import { useEffect, useRef } from "react";
import { ExternalLink, X } from "lucide-react";
import type { Video } from "../lib/api";
import { formatDuration, formatViews, relativeTime } from "../lib/format";

// Experiment (branch experiment/inline-player): play the video in-app via the
// YouTube IFrame Player API (not a bare embed) so we can read playback position
// and resume where the user left off. The modal closes via the header X button,
// the backdrop, or ESC (ESC only while focus is on our page, not inside the
// cross-origin player iframe — a browser security boundary we can't cross).

// --- IFrame Player API loader (singleton) ---
let apiPromise: Promise<any> | null = null;
function loadYouTubeApi(): Promise<any> {
  if (apiPromise) return apiPromise;
  apiPromise = new Promise((resolve) => {
    const w = window as any;
    if (w.YT && w.YT.Player) return resolve(w.YT);
    const prev = w.onYouTubeIframeAPIReady;
    w.onYouTubeIframeAPIReady = () => {
      if (typeof prev === "function") prev();
      resolve(w.YT);
    };
    const tag = document.createElement("script");
    tag.src = "https://www.youtube.com/iframe_api";
    document.head.appendChild(tag);
  });
  return apiPromise;
}

// --- Per-video resume position, persisted in localStorage so it survives a refresh ---
const posKey = (id: string) => `subfeed:player-pos:${id}`;
function savePos(id: string, seconds: number, duration: number): void {
  // Don't store trivially-early or near-finished positions (start fresh next time).
  if (!Number.isFinite(seconds) || seconds < 5 || (duration > 0 && seconds > duration - 10)) {
    localStorage.removeItem(posKey(id));
    return;
  }
  localStorage.setItem(posKey(id), String(Math.floor(seconds)));
}
function loadPos(id: string): number {
  const v = localStorage.getItem(posKey(id));
  const n = v ? parseInt(v, 10) : 0;
  return Number.isFinite(n) && n > 0 ? n : 0;
}

export default function PlayerModal({
  video,
  onClose,
}: {
  video: Video;
  onClose: () => void;
}) {
  const mountRef = useRef<HTMLDivElement | null>(null);
  const playerRef = useRef<any>(null);

  // ESC + background scroll lock.
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    window.addEventListener("keydown", onKey);
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = prevOverflow;
    };
  }, [onClose]);

  // Create the player, resume from the saved position, and persist progress.
  useEffect(() => {
    let cancelled = false;
    const id = video.id;
    const persist = () => {
      const p = playerRef.current;
      if (!p || typeof p.getCurrentTime !== "function") return;
      try {
        savePos(id, p.getCurrentTime(), typeof p.getDuration === "function" ? p.getDuration() : 0);
      } catch {
        /* player may be tearing down */
      }
    };

    loadYouTubeApi().then((YT) => {
      if (cancelled || !mountRef.current) return;
      playerRef.current = new YT.Player(mountRef.current, {
        width: "100%",
        height: "100%",
        videoId: id,
        playerVars: {
          autoplay: 1,
          start: loadPos(id) || undefined,
          rel: 0, // limit "related" to the same channel (full removal is no longer possible)
          enablejsapi: 1,
          origin: window.location.origin,
          playsinline: 1,
        },
      });
    });

    // Periodic checkpoint so progress survives a crash/refresh, not just a clean close.
    const timer = window.setInterval(persist, 5000);

    return () => {
      cancelled = true;
      window.clearInterval(timer);
      persist();
      const p = playerRef.current;
      if (p && typeof p.destroy === "function") {
        try {
          p.destroy();
        } catch {
          /* ignore */
        }
      }
      playerRef.current = null;
    };
  }, [video.id]);

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center p-4 sm:p-6 bg-black/80 backdrop-blur-sm"
      onClick={onClose}
      role="dialog"
      aria-modal="true"
    >
      <div
        className="glass-card relative w-full max-w-4xl max-h-full overflow-y-auto rounded-2xl shadow-2xl"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header bar — keeps our close button off the player's own top-right controls. */}
        <div className="flex items-center justify-between gap-3 px-4 h-12 border-b border-border">
          <span className="truncate text-sm font-medium text-muted">{video.title}</span>
          <button
            onClick={onClose}
            title="Close (Esc)"
            aria-label="Close"
            className="shrink-0 p-2 -mr-2 rounded-full text-muted hover:text-fg hover:bg-surface transition"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        <div className="aspect-video w-full bg-black">
          <div ref={mountRef} className="w-full h-full" />
        </div>

        <div className="p-4 sm:p-5">
          <h2 className="text-lg font-semibold leading-snug">{video.title}</h2>

          <div className="flex items-center gap-3 mt-3">
            {video.channel_thumbnail && (
              <img
                src={video.channel_thumbnail}
                alt=""
                className="w-10 h-10 rounded-full shrink-0"
              />
            )}
            <a
              href={video.channel_url}
              target="_blank"
              rel="noreferrer"
              className="font-medium hover:text-accent truncate"
            >
              {video.channel_title}
            </a>
          </div>

          <div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm text-muted mt-3">
            {video.view_count != null && <span>{formatViews(video.view_count)} views</span>}
            {video.view_count != null && <span>·</span>}
            <span>{relativeTime(video.published_at)}</span>
            {video.duration_seconds != null && (
              <>
                <span>·</span>
                <span>{formatDuration(video.duration_seconds)}</span>
              </>
            )}
            {video.live_status === "was_live" && (
              <span className="bg-accent text-accent-fg text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded">
                stream
              </span>
            )}
          </div>

          <div className="mt-4">
            <a
              href={video.watch_url}
              target="_blank"
              rel="noreferrer"
              className="inline-flex items-center gap-2 text-sm px-3 py-2 rounded-lg bg-accent text-accent-fg shadow-sm hover:opacity-90 transition"
            >
              <ExternalLink className="w-4 h-4" />
              Open on YouTube
            </a>
          </div>
        </div>
      </div>
    </div>
  );
}
