"use client";

import { useEffect, useRef, useState } from "react";
import Link from "next/link";
import SiteNav from "@/components/site-nav";
import type { HeroSlide, HomeVideo } from "@/lib/types";

const SLIDE_MS = 6000;

const TAGLINE = "The vibe you need.";

// Accepts a bare 11-char ID or any common YouTube URL shape (watch?v=,
// youtu.be/, embed/, shorts/) and returns just the ID, or null if it
// doesn't look like YouTube at all (e.g. blank, or someone pasted a bad
// value) so the caller can fall back cleanly.
function toYouTubeId(input: string): string | null {
  const trimmed = input.trim();
  if (!trimmed) return null;
  if (/^[\w-]{11}$/.test(trimmed)) return trimmed;
  const match = trimmed.match(
    /(?:youtu\.be\/|youtube\.com\/(?:watch\?v=|embed\/|shorts\/))([\w-]{11})/
  );
  return match ? match[1] : null;
}

export default function Hero({
  slides,
  video,
  featuredHref,
  browseHref = "/events",
}: {
  /** Curated from /admin/settings/homepage; always non-empty (see getHomeSlides). */
  slides: HeroSlide[];
  /** Optional promo video, curated from /admin/settings/homepage. */
  video?: HomeVideo;
  featuredHref: string;
  /** Where "Browse events" points. */
  browseHref?: string;
}) {
  const [active, setActive] = useState(0);
  const [videoOpen, setVideoOpen] = useState(false);
  const count = slides.length;

  const youtubeId = video ? toYouTubeId(video.youtubeId) : null;
  const useBackgroundVideo = !!video?.enabled && !!video.background && !!video.fileUrl;
  // The lightbox button is redundant once the video is already playing as
  // the backdrop, so background mode suppresses it.
  const showVideoButton = !!video?.enabled && !video.background && !!(video.fileUrl || youtubeId);

  // Respect reduced-motion: skip the auto-advancing carousel entirely.
  const reduceRef = useRef(false);
  useEffect(() => {
    reduceRef.current =
      typeof window !== "undefined" &&
      window.matchMedia("(prefers-reduced-motion: reduce)").matches;
  }, []);

  // Auto-advance, paused while the video lightbox is open.
  useEffect(() => {
    if (videoOpen || reduceRef.current || count < 2) return;
    const id = setInterval(() => setActive((i) => (i + 1) % count), SLIDE_MS);
    return () => clearInterval(id);
  }, [videoOpen, count]);

  const slide = slides[active];

  return (
    <section className="relative overflow-hidden">
      {/* Backdrop: a single looping muted video when background mode is on,
          otherwise the usual cross-fading slide photos. Either way, the
          slide captions/headline above keep rotating on their own timer. */}
      {useBackgroundVideo ? (
        <video
          key={video!.fileUrl}
          src={video!.fileUrl}
          autoPlay
          muted
          loop
          playsInline
          aria-hidden="true"
          className="absolute inset-0 w-full h-full object-cover opacity-40"
        />
      ) : (
        <div className="absolute inset-0">
          {slides.map((s, i) => (
            // eslint-disable-next-line @next/next/no-img-element
            <img
              key={s.image}
              src={s.image}
              alt=""
              aria-hidden="true"
              className={`absolute inset-0 w-full h-full object-cover transition-opacity duration-1000 ease-in-out ${
                i === active ? "opacity-40" : "opacity-0"
              }`}
            />
          ))}
        </div>
      )}
      <div className="absolute inset-0 bg-gradient-to-t from-bg via-bg/85 to-bg/50" />
      <div
        className="absolute inset-0 opacity-60"
        style={{
          backgroundImage:
            "radial-gradient(circle at 15% 30%, rgba(31, 157, 122,0.35), transparent 45%)",
        }}
      />

      <div className="relative">
        <SiteNav transparent />
        <div className="max-w-6xl mx-auto px-4 pt-16 pb-24">
          {/* Rotating caption — keyed so it re-animates on each slide */}
          <div key={active} className="hero-caption">
            <p className="text-xs font-semibold uppercase tracking-[0.3em] text-brand-green-h">
              {slide.eyebrow}
            </p>
            <h1 className="mt-5 text-5xl sm:text-7xl font-black leading-[0.95] tracking-tight text-white">
              {slide.titleTop}
              <br />
              {slide.titleBottom}
            </h1>
            <p className="mt-6 max-w-xl text-lg text-ink/80">{slide.body}</p>
          </div>

          <div className="mt-9 flex flex-wrap items-center gap-4">
            <Link
              href={featuredHref}
              className="rounded-full bg-brand-green px-7 py-3 text-base font-semibold text-white hover:bg-brand-green-h"
            >
              Get tickets
            </Link>
            <Link
              href={browseHref}
              className="rounded-full border border-white/30 px-7 py-3 text-base font-semibold text-white hover:bg-white/10"
            >
              Browse events
            </Link>
            {showVideoButton && (
              <button
                type="button"
                onClick={() => setVideoOpen(true)}
                className="group inline-flex items-center gap-3 rounded-full border border-white/30 px-6 py-3 text-base font-semibold text-white hover:bg-white/10"
              >
                <span className="inline-flex h-7 w-7 items-center justify-center rounded-full bg-white/15 transition-colors group-hover:bg-brand-green">
                  <svg viewBox="0 0 24 24" className="h-3.5 w-3.5 translate-x-px" aria-hidden="true">
                    <path d="M6 4l14 8-14 8V4Z" fill="currentColor" />
                  </svg>
                </span>
                {video?.label || "Watch video"}
              </button>
            )}
            <span className="text-sm font-semibold uppercase tracking-[0.15em] text-white/60">
              {TAGLINE}
            </span>
          </div>

          {/* Slide indicators */}
          {count > 1 && (
            <div className="mt-8 flex items-center gap-2" role="tablist" aria-label="Hero slides">
              {slides.map((s, i) => (
                <button
                  key={s.image}
                  type="button"
                  role="tab"
                  aria-selected={i === active}
                  aria-label={`Show ${s.titleTop} ${s.titleBottom}`}
                  onClick={() => setActive(i)}
                  className={`h-1.5 rounded-full transition-all duration-300 ${
                    i === active
                      ? "w-8 bg-brand-green-h"
                      : "w-3 bg-white/30 hover:bg-white/60"
                  }`}
                />
              ))}
            </div>
          )}

          <p className="mt-6 text-sm text-ink/70">Pay with M-Pesa — ticket arrives instantly.</p>
        </div>
      </div>

      {showVideoButton && videoOpen && (
        <VideoModal
          fileUrl={video!.fileUrl || null}
          youtubeId={youtubeId}
          label={video!.label || "Video"}
          onClose={() => setVideoOpen(false)}
        />
      )}
    </section>
  );
}

function VideoModal({
  fileUrl,
  youtubeId,
  label,
  onClose,
}: {
  fileUrl: string | null;
  youtubeId: string | null;
  label: string;
  onClose: () => void;
}) {
  // Close on Escape, lock background scroll while open.
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
    document.addEventListener("keydown", onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = prev;
    };
  }, [onClose]);

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 p-4 backdrop-blur-sm"
      role="dialog"
      aria-modal="true"
      aria-label={label}
      onClick={onClose}
    >
      <div className="relative w-full max-w-4xl" onClick={(e) => e.stopPropagation()}>
        <button
          type="button"
          onClick={onClose}
          aria-label="Close video"
          className="absolute -top-11 right-0 inline-flex h-9 w-9 items-center justify-center rounded-full border border-white/30 text-white hover:bg-white/10"
        >
          <svg viewBox="0 0 24 24" className="h-5 w-5" fill="none" aria-hidden="true">
            <path
              d="M6 6l12 12M18 6L6 18"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
            />
          </svg>
        </button>
        <div className="aspect-video w-full overflow-hidden rounded-2xl border border-white/10 bg-black shadow-2xl">
          {fileUrl ? (
            <video className="h-full w-full" src={fileUrl} controls autoPlay playsInline />
          ) : youtubeId ? (
            <iframe
              className="h-full w-full"
              src={`https://www.youtube.com/embed/${youtubeId}?autoplay=1&rel=0&modestbranding=1`}
              title={label}
              allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
              allowFullScreen
            />
          ) : null}
        </div>
      </div>
    </div>
  );
}
