"use client";

import { useCallback, useEffect, useRef } from "react";
import { AnimatePresence, motion, useReducedMotion } from "framer-motion";
import { X } from "lucide-react";
import type { WelcomeVideoData } from "@/lib/homeBroadcast";

interface Props {
  open: boolean;
  video: WelcomeVideoData | null;
  onClose: () => void;
}

const FOCUSABLE = 'a[href], button:not([disabled]), iframe, [tabindex]:not([tabindex="-1"])';

// WelcomeModal — the first-run welcome video. Accessible by contract:
// focus is trapped inside, Esc closes, focus returns to whatever opened it,
// and reduced-motion users get an instant fade instead of a spring.
export default function WelcomeModal({ open, video, onClose }: Props) {
  const dialogRef = useRef<HTMLDivElement>(null);
  const lastActiveRef = useRef<HTMLElement | null>(null);
  const reduceMotion = useReducedMotion();

  const trapFocus = useCallback((e: KeyboardEvent) => {
    if (e.key === "Escape") { e.preventDefault(); onClose(); return; }
    if (e.key !== "Tab" || !dialogRef.current) return;
    const nodes = Array.from(dialogRef.current.querySelectorAll<HTMLElement>(FOCUSABLE));
    if (nodes.length === 0) return;
    const first = nodes[0];
    const last = nodes[nodes.length - 1];
    const active = document.activeElement as HTMLElement | null;
    if (e.shiftKey && (active === first || !dialogRef.current.contains(active))) {
      e.preventDefault(); last.focus();
    } else if (!e.shiftKey && active === last) {
      e.preventDefault(); first.focus();
    }
  }, [onClose]);

  useEffect(() => {
    if (!open) return;
    lastActiveRef.current = document.activeElement as HTMLElement | null;
    document.addEventListener("keydown", trapFocus);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    // Move focus into the dialog once it exists.
    const focusTimer = window.setTimeout(() => {
      dialogRef.current?.querySelector<HTMLElement>("button")?.focus();
    }, 30);
    return () => {
      document.removeEventListener("keydown", trapFocus);
      document.body.style.overflow = prevOverflow;
      window.clearTimeout(focusTimer);
      lastActiveRef.current?.focus?.();
    };
  }, [open, trapFocus]);

  const show = open && Boolean(video);
  const fade = reduceMotion ? { duration: 0.01 } : { duration: 0.25 };
  const spring = reduceMotion
    ? { duration: 0.01 }
    : { type: "spring" as const, stiffness: 320, damping: 30 };

  return (
    <AnimatePresence>
      {show && video && (
        <motion.div
          key="mm-welcome"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          transition={fade}
          className="fixed inset-0 z-[70] grid place-items-center p-4 sm:p-6"
          style={{ background: "color-mix(in srgb, var(--bg-deep) 80%, transparent)", backdropFilter: "blur(8px)" }}
          onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}
        >
          <motion.div
            ref={dialogRef}
            role="dialog"
            aria-modal="true"
            aria-labelledby="mm-welcome-title"
            aria-describedby="mm-welcome-subtitle"
            initial={reduceMotion ? { opacity: 0 } : { opacity: 0, y: 18, scale: 0.97 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={reduceMotion ? { opacity: 0 } : { opacity: 0, y: 10, scale: 0.98 }}
            transition={spring}
            className="w-full max-w-[880px] max-h-[92dvh] overflow-y-auto scroll rounded-xl border p-5 sm:p-8"
            style={{
              background: "linear-gradient(180deg, var(--bg-elev), var(--bg-card))",
              borderColor: "var(--line)",
              boxShadow: "var(--shadow-2), 0 0 90px -30px color-mix(in srgb, var(--gold) 35%, transparent)",
            }}
          >
            <div className="flex items-start justify-between gap-4 mb-4">
              <div className="min-w-0">
                <div className="action-tag mb-2" style={{ color: "var(--gold)" }}>Welcome aboard</div>
                <h2 id="mm-welcome-title" className="text-[24px] sm:text-[30px] leading-tight" style={{ letterSpacing: "-0.025em" }}>
                  {video.title ?? "Welcome to MissionMate"}
                </h2>
                {video.subtitle && (
                  <p id="mm-welcome-subtitle" className="mt-1.5 text-[14px] leading-relaxed" style={{ color: "var(--cream-dim)" }}>
                    {video.subtitle}
                  </p>
                )}
              </div>
              <button
                onClick={onClose}
                aria-label="Close welcome video"
                className="focus-ring shrink-0 grid place-items-center w-9 h-9 rounded-lg border transition-colors"
                style={{ borderColor: "var(--line-soft)", color: "var(--cream-dim)", background: "color-mix(in srgb, var(--cream) 3%, transparent)" }}
              >
                <X size={16} />
              </button>
            </div>

            <div
              className="relative w-full overflow-hidden rounded-lg border"
              style={{ aspectRatio: "16 / 9", borderColor: "var(--line-soft)", background: "var(--bg-deep)" }}
            >
              {video.embedUrl ? (
                <iframe
                  src={video.embedUrl}
                  title={video.title ?? "Welcome video"}
                  className="absolute inset-0 w-full h-full"
                  allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                  allowFullScreen
                  referrerPolicy="strict-origin-when-cross-origin"
                />
              ) : (
                <div className="absolute inset-0 grid place-items-center text-[13px]" style={{ color: "var(--cream-mute)" }}>
                  Video coming soon.
                </div>
              )}
            </div>

            <div className="mt-5 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
              <p className="text-[12.5px]" style={{ color: "var(--cream-mute)" }}>
                You can rewatch any time with the Watch intro button up top.
              </p>
              <button onClick={onClose} className="copy-btn focus-ring w-full sm:w-auto">
                Got it, let&apos;s go
              </button>
            </div>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  );
}
