import { useEffect, useRef, useState } from "react";
import { X } from "lucide-react";

type Proof = { id: string; caption: string | null; url: string };

export function StudentProofs({ proofs }: { proofs: Proof[] }) {
  const [lightbox, setLightbox] = useState<Proof | null>(null);
  const trackRef = useRef<HTMLDivElement>(null);

  if (!proofs.length) return null;
  // Duplicate for seamless infinite scroll
  const loop = [...proofs, ...proofs];

  return (
    <section id="proofs" className="border-t border-border/40 bg-card/30 py-16 md:py-20">
      <div className="mx-auto max-w-6xl px-4">
        <div className="mb-3 text-center">
          <span className="inline-flex items-center gap-2 rounded-full border border-success/30 bg-success/10 px-3 py-1 text-xs font-semibold text-success">
            ✓ Verified Student Inboxes
          </span>
        </div>
        <div className="mb-10 text-center">
          <h2 className="font-display text-3xl font-bold md:text-4xl">Real Results From Real Students</h2>
          <p className="mt-2 text-muted-foreground">See what our students are saying after joining the course.</p>
          <p className="mt-1 text-xs uppercase tracking-wider text-muted-foreground">Real Student Inbox Proofs</p>
        </div>
      </div>

      <div
        className="group relative overflow-hidden"
        onMouseEnter={() => trackRef.current?.style.setProperty("animation-play-state", "paused")}
        onMouseLeave={() => trackRef.current?.style.setProperty("animation-play-state", "running")}
        onTouchStart={() => trackRef.current?.style.setProperty("animation-play-state", "paused")}
        onTouchEnd={() => trackRef.current?.style.setProperty("animation-play-state", "running")}
      >
        <div className="pointer-events-none absolute inset-y-0 left-0 z-10 w-16 bg-gradient-to-r from-background to-transparent md:w-32" />
        <div className="pointer-events-none absolute inset-y-0 right-0 z-10 w-16 bg-gradient-to-l from-background to-transparent md:w-32" />

        <div
          ref={trackRef}
          className="flex w-max gap-4 px-4 animate-marquee md:gap-6"
          style={{ animationDuration: `${Math.max(20, proofs.length * 6)}s` }}
        >
          {loop.map((p, i) => (
            <button
              key={`${p.id}-${i}`}
              onClick={() => setLightbox(p)}
              className="group/card relative w-[150px] shrink-0 sm:w-[180px] md:w-[220px]"
              aria-label={p.caption ?? "Student proof screenshot"}
            >
              {/* Phone mockup frame */}
              <div className="relative rounded-[2rem] border-[6px] border-foreground/80 bg-foreground/80 p-1 shadow-card transition group-hover/card:scale-[1.03] group-hover/card:shadow-glow">
                <div className="absolute left-1/2 top-2 z-10 h-1.5 w-12 -translate-x-1/2 rounded-full bg-background/40" />
                <div className="overflow-hidden rounded-[1.6rem] bg-background">
                  <img
                    src={p.url}
                    alt={p.caption ?? "Student proof"}
                    loading="lazy"
                    decoding="async"
                    className="aspect-[9/16] w-full object-cover"
                  />
                </div>
              </div>
              {p.caption && (
                <p className="mt-2 line-clamp-2 px-1 text-center text-xs text-muted-foreground">{p.caption}</p>
              )}
            </button>
          ))}
        </div>
      </div>

      {lightbox && <Lightbox proof={lightbox} onClose={() => setLightbox(null)} />}
    </section>
  );
}

function Lightbox({ proof, onClose }: { proof: Proof; onClose: () => void }) {
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { window.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, [onClose]);

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-background/95 p-4 backdrop-blur" onClick={onClose}>
      <button onClick={onClose} className="absolute right-4 top-4 grid h-10 w-10 place-items-center rounded-full border border-border bg-card text-foreground hover:bg-muted">
        <X className="h-5 w-5" />
      </button>
      <div className="relative max-h-[90vh] max-w-md" onClick={(e) => e.stopPropagation()}>
        <img src={proof.url} alt={proof.caption ?? ""} className="max-h-[90vh] w-auto rounded-2xl object-contain shadow-glow" />
        {proof.caption && <p className="mt-3 text-center text-sm text-muted-foreground">{proof.caption}</p>}
      </div>
    </div>
  );
}
