"use client";

import {
  useState,
  useEffect,
  useCallback,
  useRef,
} from "react";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { Play, Info, ChevronLeft, ChevronRight, Volume2, VolumeX } from "lucide-react";
import { useAppDispatch } from "@/store/hooks";
import { stopAll } from "@/store/slices/playerSlice";
import { useSidebar } from "@/lib/SidebarContext";
import { VideoItem } from "@/types/home";
import { usePauseOnInactivity } from "@/hooks/usePauseOnInactivity";

/* ── constants ────────────────────────────────────────────────────────────── */

const SLIDE_MS = 6500;
const FADE_MS  = 700;

/* ── types ────────────────────────────────────────────────────────────────── */

interface Props {
  items: VideoItem[];
}

/* ── helpers ──────────────────────────────────────────────────────────────── */

function Badge({ children, accent }: { children: React.ReactNode; accent?: boolean }) {
  return (
    <span
      className="inline-flex items-center text-[8px] font-black uppercase tracking-[0.24em] px-2 py-[3px] rounded-sm"
      style={
        accent
          ? { background: "var(--accent)", color: "white" }
          : {
              color: "#ffd060",
              border: "1px solid rgba(255,208,96,0.35)",
              background: "rgba(255,208,96,0.07)",
            }
      }
    >
      {children}
    </span>
  );
}

/* ── FilmstripThumb ──────────────────────────────────────────────────────── */

function FilmstripThumb({
  item,
  active,
  onClick,
}: {
  item: VideoItem;
  active: boolean;
  onClick: () => void;
}) {
  return (
    <button
      onClick={onClick}
      className="relative shrink-0 rounded-lg overflow-hidden transition-all duration-300 group/thumb"
      style={{
        width: 80,
        height: 46,
        outline: active ? "2px solid var(--accent)" : "2px solid transparent",
        outlineOffset: "1px",
        opacity: active ? 1 : 0.5,
        transform: active ? "scale(1.08)" : "scale(1)",
        boxShadow: active ? "0 4px 18px rgba(var(--accent-rgb),0.45)" : "none",
      }}
    >
      {item.thumbnail ? (
        <Image
          src={item.thumbnail}
          alt={item.title}
          fill
          className="object-cover transition-transform duration-300 group-hover/thumb:scale-110"
          unoptimized
          sizes="80px"
        />
      ) : (
        <div className="w-full h-full" style={{ background: "var(--deep)" }} />
      )}
      {/* Dark overlay on inactive */}
      {!active && (
        <div className="absolute inset-0" style={{ background: "rgba(0,0,0,0.35)" }} />
      )}
    </button>
  );
}

/* ── HeroBannerCarousel ───────────────────────────────────────────────────── */

export function HeroBannerCarousel({ items }: Props) {
  const router   = useRouter();
  const dispatch = useAppDispatch();
  const { collapse } = useSidebar();

  const [activeIdx, setActiveIdx]   = useState(0);
  const [contentKey, setContentKey] = useState(0); // drives content re-animation
  const [paused, setPaused]         = useState(false);
  const [animKey, setAnimKey]       = useState(0); // increments to reset CSS progress animation
  const [muted, setMuted]           = useState(true);
  const stripRef                    = useRef<HTMLDivElement>(null);

  const n = items.length;

  /* ── navigation ──────────────────────────────────────────────────────── */

  const goTo = useCallback(
    (i: number) => {
      setActiveIdx(i);
      setContentKey((k) => k + 1);
      setAnimKey((k) => k + 1);
    },
    [],
  );

  const prev = useCallback(() => goTo((activeIdx - 1 + n) % n), [activeIdx, n, goTo]);
  const next = useCallback(() => goTo((activeIdx + 1) % n), [activeIdx, n, goTo]);

  /* ── auto-advance ─────────────────────────────────────────────────────── */
  // Single timeout per slide — no 50ms polling. CSS animation handles the progress bar.

  useEffect(() => {
    if (n <= 1 || paused) return;
    const id = setTimeout(() => {
      setActiveIdx((prev) => (prev + 1) % n);
      setContentKey((k) => k + 1);
      setAnimKey((k) => k + 1);
    }, SLIDE_MS);
    return () => clearTimeout(id);
  }, [paused, n, activeIdx]);

  /* ── pause when tab is hidden ─────────────────────────────────────────── */

  useEffect(() => {
    const onVisibility = () => setPaused(document.hidden);
    document.addEventListener("visibilitychange", onVisibility);
    return () => document.removeEventListener("visibilitychange", onVisibility);
  }, []);

  /* ── pause when user is inactive for 10 minutes ───────────────────────── */
  usePauseOnInactivity(setPaused);

  /* ── scroll active thumb into view ──────────────────────────────────── */

  useEffect(() => {
    const strip = stripRef.current;
    if (!strip) return;
    const el = strip.children[activeIdx] as HTMLElement | undefined;
    el?.scrollIntoView({ behavior: "smooth", block: "nearest", inline: "center" });
  }, [activeIdx]);

  /* ── keyboard navigation ─────────────────────────────────────────────── */

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "ArrowLeft")  prev();
      if (e.key === "ArrowRight") next();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [prev, next]);

  if (!n) return null;

  const current = items[activeIdx];

  /* ── render ──────────────────────────────────────────────────────────── */

  return (
    <div
      className="relative w-full overflow-hidden group"
      style={{ height: "clamp(240px, 40vw, 420px)" }}
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}
    >
      {/* ════════════════════════════════════════════════════════════════
          BACKGROUND SLIDES — crossfade + Ken Burns
      ════════════════════════════════════════════════════════════════ */}
      {items.map((item, i) => {
        const isActive = i === activeIdx;
        return (
          <div
            key={item.id}
            className="absolute inset-0"
            style={{
              opacity: isActive ? 1 : 0,
              transition: `opacity ${FADE_MS}ms ease`,
              zIndex: isActive ? 1 : 0,
            }}
          >
            {item.thumbnail && (
              <div
                className="absolute inset-0"
                style={{
                  transform: isActive ? "scale(1.07) translate(-1.5%, -0.8%)" : "scale(1)",
                  transition: isActive
                    ? `transform ${SLIDE_MS}ms ease-out`
                    : `transform ${FADE_MS}ms ease`,
                  willChange: "transform",
                }}
              >
                <Image
                  src={item.thumbnail}
                  alt={item.title}
                  fill
                  className="object-cover"
                  unoptimized
                  sizes="100vw"
                  priority={i < 2}
                />
              </div>
            )}
          </div>
        );
      })}

      {/* ════════════════════════════════════════════════════════════════
          GRADIENT OVERLAYS — multi-layer cinematic scrim
      ════════════════════════════════════════════════════════════════ */}

      {/* Left scrim — anchors content readability */}
      <div
        className="absolute inset-0 z-10 pointer-events-none"
        style={{
          background:
            "linear-gradient(to right, rgba(8,8,20,0.97) 0%, rgba(8,8,20,0.82) 25%, rgba(8,8,20,0.45) 50%, rgba(8,8,20,0.12) 70%, rgba(8,8,20,0.0) 85%)",
        }}
      />
      {/* Bottom scrim */}
      <div
        className="absolute inset-x-0 bottom-0 z-10 pointer-events-none"
        style={{
          height: "65%",
          background:
            "linear-gradient(to top, rgba(8,8,20,0.95) 0%, rgba(8,8,20,0.55) 35%, transparent 70%)",
        }}
      />
      {/* Top vignette */}
      <div
        className="absolute inset-x-0 top-0 z-10 pointer-events-none"
        style={{
          height: "28%",
          background: "linear-gradient(to bottom, rgba(0,0,0,0.35) 0%, transparent 100%)",
        }}
      />

      {/* ════════════════════════════════════════════════════════════════
          CONTENT PANEL — animated in on every slide change
      ════════════════════════════════════════════════════════════════ */}
      <div
        key={contentKey}
        className="absolute inset-0 z-20 flex flex-col justify-end sm:justify-center px-5 sm:px-8 pb-14 sm:pb-6"
        style={{ animation: "hero-content-rise 0.55s ease both" }}
      >
        {/* Badges row */}
        <div className="flex items-center gap-2 mb-2 sm:mb-3 flex-wrap">
          <Badge accent>{current.category || "Featured"}</Badge>
          {current.isPremium && <Badge>Premium</Badge>}
          {current.isNew && (
            <Badge>
              <span className="mr-0.5" style={{ color: "var(--accent)" }}>●</span> New
            </Badge>
          )}
        </div>

        {/* Title */}
        <h2
          className="text-[#ffffff] font-black leading-tight line-clamp-2 mb-2 sm:mb-3"
          style={{
            fontSize: "clamp(15px, 2.8vw, 30px)",
            maxWidth: "min(75%, 500px)",
            textShadow: "0 2px 24px rgba(0,0,0,0.9)",
            letterSpacing: "-0.025em",
          }}
        >
          {current.title}
        </h2>

        {/* Meta */}
        <div className="flex items-center gap-2 mb-3 sm:mb-4 flex-wrap">
          {current.channelName && (
            <span
              className="text-[10px] sm:text-[11px] font-semibold"
              style={{ color: "rgba(255,255,255,0.7)" }}
            >
              {current.channelName}
            </span>
          )}
          {current.views && (
            <>
              <span style={{ color: "rgba(255,255,255,0.25)", fontSize: 10 }}>•</span>
              <span
                className="text-[10px] sm:text-[11px]"
                style={{ color: "rgba(255,255,255,0.5)" }}
              >
                {current.views}
              </span>
            </>
          )}
          {current.duration && (
            <>
              <span style={{ color: "rgba(255,255,255,0.25)", fontSize: 10 }}>•</span>
              <span
                className="text-[10px] sm:text-[11px] font-mono"
                style={{ color: "rgba(255,255,255,0.5)" }}
              >
                {current.duration}
              </span>
            </>
          )}
          {current.uploadedAt && (
            <>
              <span style={{ color: "rgba(255,255,255,0.25)", fontSize: 10 }}>•</span>
              <span
                className="text-[10px] sm:text-[11px]"
                style={{ color: "rgba(255,255,255,0.4)" }}
              >
                {current.uploadedAt}
              </span>
            </>
          )}
        </div>

        {/* Action buttons */}
        <div className="flex items-center gap-2.5">
          <button
            className="flex items-center gap-2 px-4 sm:px-5 py-2 sm:py-2.5 rounded-full text-[11px] sm:text-[12px] font-bold text-[#ffffff] transition-all duration-150 active:scale-95 hover:brightness-110"
            style={{
              background: "var(--accent)",
              boxShadow: "0 4px 24px rgba(var(--accent-rgb),0.6)",
            }}
            onClick={() => {
              dispatch(stopAll());
              collapse();
              const href = current.type === "short" ? `/reel/${current.id}` : `/video/${current.id}`;
              router.push(href);
            }}
          >
            <Play size={12} fill="white" strokeWidth={0} className="shrink-0" />
            Play Now
          </button>

          <button
            className="flex items-center gap-1.5 px-4 sm:px-5 py-2 sm:py-2.5 rounded-full text-[11px] sm:text-[12px] font-semibold text-[#ffffff] transition-all duration-150 active:scale-95"
            style={{
              background: "rgba(255,255,255,0.10)",
              border: "1px solid rgba(255,255,255,0.16)",
              backdropFilter: "blur(10px)",
            }}
            onClick={() => {
              dispatch(stopAll());
              collapse();
              router.push(`/video/${current.id}`);
            }}
          >
            <Info size={12} strokeWidth={2} className="shrink-0" />
            <span className="hidden sm:inline">More Info</span>
          </button>

          {/* Mute toggle — decorative */}
          <button
            className="w-8 h-8 rounded-full flex items-center justify-center transition-all duration-150 active:scale-95 ml-1 hidden sm:flex"
            style={{
              background: "rgba(255,255,255,0.08)",
              border: "1px solid rgba(255,255,255,0.12)",
            }}
            onClick={(e) => { e.stopPropagation(); setMuted((m) => !m); }}
          >
            {muted
              ? <VolumeX size={12} color="rgba(255,255,255,0.6)" strokeWidth={1.8} />
              : <Volume2 size={12} color="rgba(255,255,255,0.6)" strokeWidth={1.8} />
            }
          </button>
        </div>
      </div>

      {/* ════════════════════════════════════════════════════════════════
          PREV / NEXT ARROWS — visible only on hover (desktop)
      ════════════════════════════════════════════════════════════════ */}
      {n > 1 && (
        <>
          <button
            className="absolute left-3 top-1/2 -translate-y-1/2 z-30 w-10 h-10 rounded-full
                       hidden sm:flex items-center justify-center
                       transition-all duration-200
                       opacity-0 group-hover:opacity-100 hover:scale-110"
            style={{
              background: "rgba(0,0,0,0.55)",
              border: "1px solid rgba(255,255,255,0.12)",
              backdropFilter: "blur(10px)",
              boxShadow: "0 2px 12px rgba(0,0,0,0.5)",
            }}
            onClick={prev}
          >
            <ChevronLeft size={18} color="white" strokeWidth={2} />
          </button>

          <button
            className="absolute right-3 top-1/2 -translate-y-1/2 z-30 w-10 h-10 rounded-full
                       hidden sm:flex items-center justify-center
                       transition-all duration-200
                       opacity-0 group-hover:opacity-100 hover:scale-110"
            style={{
              background: "rgba(0,0,0,0.55)",
              border: "1px solid rgba(255,255,255,0.12)",
              backdropFilter: "blur(10px)",
              boxShadow: "0 2px 12px rgba(0,0,0,0.5)",
            }}
            onClick={next}
          >
            <ChevronRight size={18} color="white" strokeWidth={2} />
          </button>
        </>
      )}

      {/* ════════════════════════════════════════════════════════════════
          BOTTOM CONTROL BAR
      ════════════════════════════════════════════════════════════════ */}
      {n > 1 && (
        <div
          className="absolute bottom-3 left-0 right-0 z-30 flex items-end justify-between px-5 sm:px-8"
        >
          {/* Left: slide counter */}
          <div
            className="hidden sm:flex items-center gap-1.5 text-[10px] font-bold tabular-nums"
            style={{ color: "rgba(255,255,255,0.35)" }}
          >
            <span style={{ color: "rgba(255,255,255,0.7)", fontSize: 13 }}>
              {String(activeIdx + 1).padStart(2, "0")}
            </span>
            <span style={{ color: "rgba(255,255,255,0.25)" }}>/</span>
            <span>{String(n).padStart(2, "0")}</span>
          </div>

          {/* Mobile: dot indicators */}
          <div className="flex sm:hidden items-center gap-1.5">
            {items.map((_, i) => (
              <button
                key={i}
                onClick={() => goTo(i)}
                className="rounded-full transition-all duration-300"
                style={{
                  width: i === activeIdx ? 20 : 6,
                  height: 6,
                  background:
                    i === activeIdx ? "var(--accent)" : "rgba(255,255,255,0.28)",
                }}
              />
            ))}
          </div>

          {/* Right: filmstrip thumbnails (desktop) */}
          <div className="hidden sm:flex items-center gap-2">
            {/* Dot indicators alongside thumbnails */}
            <div className="flex items-center gap-1 mr-2">
              {items.map((_, i) => (
                <div
                  key={i}
                  className="rounded-full transition-all duration-300"
                  style={{
                    width: i === activeIdx ? 14 : 5,
                    height: 5,
                    background:
                      i === activeIdx ? "var(--accent)" : "rgba(255,255,255,0.22)",
                  }}
                />
              ))}
            </div>

            <div
              ref={stripRef}
              className="flex gap-2 overflow-x-auto scrollbar-hide"
              style={{ maxWidth: 340 }}
            >
              {items.map((item, i) => (
                <FilmstripThumb
                  key={item.id}
                  item={item}
                  active={i === activeIdx}
                  onClick={() => goTo(i)}
                />
              ))}
            </div>
          </div>
        </div>
      )}

      {/* ════════════════════════════════════════════════════════════════
          PROGRESS BAR — CSS animation (no JS polling)
      ════════════════════════════════════════════════════════════════ */}
      {n > 1 && (
        <div
          className="absolute bottom-0 left-0 right-0 z-40"
          style={{ height: 3, background: "rgba(255,255,255,0.06)" }}
        >
          <div
            key={animKey}
            style={{
              height: "100%",
              background: "var(--accent)",
              boxShadow: "0 0 10px rgba(var(--accent-rgb),0.8), 0 0 4px rgba(var(--accent-rgb),0.4)",
              animation: `banner-prog ${SLIDE_MS}ms linear forwards`,
              animationPlayState: paused ? "paused" : "running",
            }}
          />
        </div>
      )}
    </div>
  );
}
