"use client";

import Image from "next/image";
import { useCallback, useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { ChevronLeft, ChevronRight, X } from "lucide-react";
import { ScrollSmoother } from "./gsap-setup";

/** One screenshot in a gallery. Shared by the tour rail and this viewer. */
export type Shot = {
  id: string;
  /** Two-digit ordinal shown in the rail and the viewer's counter. */
  number: string;
  label: string;
  /** One line for the rail — what this screen answers. */
  blurb: string;
  /** Path shown in the window chrome, so the screen is placed in the product. */
  route: string;
  src: string;
  width: number;
  height: number;
};

type LightboxProps = {
  shots: Shot[];
  index: number;
  onIndex: (index: number) => void;
  onClose: () => void;
};

/**
 * Full-screen viewer for a product screenshot.
 *
 * Rendered through a portal rather than in place: the landing page's sections
 * live inside ScrollSmoother's transformed #smooth-content, and a `position:
 * fixed` element inside a transformed ancestor is positioned against that
 * ancestor — it would scroll away with the page instead of covering it.
 *
 * The portal host is the `.immersive` wrapper, not <body>: that element is
 * untransformed (so fixed works) and it is where `immersive--light` puts the
 * light palette, so the viewer follows the visitor's theme. <body> would give
 * correct positioning but a permanently dark viewer on the light landing.
 *
 * Freezing the page behind it takes both halves of the HUD menu's approach:
 * the smoother owns the scroll position, so it is paused, and `overflow:
 * hidden` covers the reduced-motion visitors who never got a smoother.
 */
export default function Lightbox({ shots, index, onIndex, onClose }: LightboxProps) {
  const [host, setHost] = useState<HTMLElement | null>(null);
  const closeRef = useRef<HTMLButtonElement>(null);
  const restoreFocusRef = useRef<Element | null>(null);

  const shot = shots[index];
  const count = shots.length;

  const step = useCallback(
    (delta: number) => onIndex((index + delta + count) % count),
    [index, count, onIndex]
  );

  useEffect(() => {
    setHost(document.querySelector<HTMLElement>(".immersive") ?? document.body);
  }, []);

  useEffect(() => {
    restoreFocusRef.current = document.activeElement;
    const smoother = ScrollSmoother.get();
    smoother?.paused(true);
    document.body.style.overflow = "hidden";
    closeRef.current?.focus();

    return () => {
      smoother?.paused(false);
      document.body.style.overflow = "";
      // Send focus back to whatever opened the viewer, not to the top of the page.
      if (restoreFocusRef.current instanceof HTMLElement) restoreFocusRef.current.focus();
    };
  }, []);

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
      else if (e.key === "ArrowRight") step(1);
      else if (e.key === "ArrowLeft") step(-1);
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose, step]);

  if (!host || !shot) return null;

  return createPortal(
    <div
      role="dialog"
      aria-modal="true"
      aria-label={`${shot.label} — full size`}
      // Above the HUD (z-90) and its menu (z-110); the preloader (z-120) has
      // already lifted by the time anything on the page is clickable.
      className="fixed inset-0 z-[115] flex flex-col bg-[hsl(var(--background))]/95 backdrop-blur-xl"
    >
      {/* Backdrop click target, behind the panel's own content. */}
      <button
        type="button"
        aria-label="Close viewer"
        tabIndex={-1}
        onClick={onClose}
        className="absolute inset-0 cursor-zoom-out"
      />

      <div className="relative flex items-center justify-between gap-4 px-6 py-5 lg:px-10">
        <div className="min-w-0">
          <p className="immersive-label immersive-tour-route truncate">{shot.route}</p>
          <p className="font-heading mt-1 truncate text-lg font-medium tracking-tight">
            {shot.label}
          </p>
        </div>
        <button
          ref={closeRef}
          type="button"
          onClick={onClose}
          aria-label="Close viewer"
          className="inline-flex size-10 shrink-0 items-center justify-center rounded-lg border border-white/15 text-[hsl(var(--foreground))] transition-colors hover:border-white/35 hover:bg-white/[0.06]"
        >
          <X className="size-5" aria-hidden />
        </button>
      </div>

      {/* The frame is the only clickable thing in this row; the space around it
          passes clicks through to the backdrop, so clicking beside the image
          closes the viewer like clicking anywhere else outside it. */}
      <div className="pointer-events-none relative flex min-h-0 flex-1 items-center justify-center px-4 pb-4 lg:px-10">
        <div className="pointer-events-auto max-h-full w-full max-w-[86rem] overflow-hidden rounded-xl border border-white/12 bg-white shadow-2xl">
          <Image
            key={shot.id}
            src={shot.src}
            alt={`${shot.label} — ${shot.blurb}`}
            width={shot.width}
            height={shot.height}
            sizes="100vw"
            className="h-auto max-h-[72vh] w-full object-contain object-top"
          />
        </div>
      </div>

      <div className="relative flex items-center justify-center gap-4 px-6 pb-7 lg:pb-9">
        <button
          type="button"
          onClick={() => step(-1)}
          aria-label="Previous screen"
          className="inline-flex size-10 items-center justify-center rounded-lg border border-white/15 transition-colors hover:border-white/35 hover:bg-white/[0.06]"
        >
          <ChevronLeft className="size-5" aria-hidden />
        </button>
        <span className="immersive-label tabular-nums">
          {shot.number} / {String(count).padStart(2, "0")}
        </span>
        <button
          type="button"
          onClick={() => step(1)}
          aria-label="Next screen"
          className="inline-flex size-10 items-center justify-center rounded-lg border border-white/15 transition-colors hover:border-white/35 hover:bg-white/[0.06]"
        >
          <ChevronRight className="size-5" aria-hidden />
        </button>
      </div>
    </div>,
    host
  );
}
