"use client";

import { useEffect, useState, useCallback } from "react";
import Image from "next/image";
import { Play, Plus, Star, Info, Crown } from "lucide-react";
import { useAppStore } from "@/lib/store";
import { toPersianDigits } from "@/lib/poster";
import type { PosterItem } from "./poster";

interface HeroSliderProps {
  items: PosterItem[];
}

const QUALITY_LABEL: Record<string, string> = {
  "2160p": "4K",
  "1080p": "FHD",
  "720p": "HD",
};

export function HeroSlider({ items }: HeroSliderProps) {
  const [idx, setIdx] = useState(0);
  const [paused, setPaused] = useState(false);
  const navigate = useAppStore((s) => s.navigate);
  const openDetail = useAppStore((s) => s.openDetail);

  const next = useCallback(() => {
    setIdx((p) => (p + 1) % items.length);
  }, [items.length]);

  useEffect(() => {
    if (paused || items.length <= 1) return;
    const t = setInterval(next, 7000);
    return () => clearInterval(t);
  }, [paused, items.length, next]);

  if (!items.length) return null;
  const safeIdx = Math.min(idx, items.length - 1);
  const item = items[safeIdx];
  const bg = item.backdrop ?? null;
  const gradient = `linear-gradient(135deg, ${item.gradient[0]}, ${item.gradient[1]})`;

  return (
    <section
      className="relative w-full h-[68vh] min-h-[440px] max-h-[720px] overflow-hidden"
      onMouseEnter={() => setPaused(true)}
      onMouseLeave={() => setPaused(false)}
    >
      {/* Backdrop layers (crossfade) */}
      {items.map((it, i) => (
        <div
          key={it.slug}
          className="absolute inset-0 transition-opacity duration-1000"
          style={{ opacity: i === safeIdx ? 1 : 0 }}
        >
          {it.backdrop ? (
            <Image
              src={it.backdrop}
              alt={it.persianTitle}
              fill
              unoptimized
              priority={i === 0}
              sizes="100vw"
              className="object-cover"
            />
          ) : (
            <div className="absolute inset-0" style={{ background: `linear-gradient(135deg, ${it.gradient[0]}, ${it.gradient[1]})` }} />
          )}
        </div>
      ))}

      {/* Overlays */}
      <div className="absolute inset-0 bg-gradient-to-t from-background via-background/40 to-transparent" />
      <div className="absolute inset-0 bg-gradient-to-l from-transparent via-transparent to-background/80" />

      {/* Content */}
      <div className="relative h-full flex items-end pb-10 md:pb-16">
        <div className="px-4 md:px-8 max-w-2xl">
          <div className="flex items-center gap-2 mb-3 flex-wrap">
            <span className="inline-flex items-center gap-1 rounded-md bg-gradient-brand px-2 py-0.5 text-[10px] font-bold text-white">
              <Crown className="h-3 w-3" /> ویژه PeepBox
            </span>
            <span className="rounded-md bg-black/60 backdrop-blur px-2 py-0.5 text-[10px] font-bold text-white">
              {QUALITY_LABEL[item.quality] ?? item.quality}
            </span>
            {item.isDubbed && (
              <span className="rounded-md bg-black/60 backdrop-blur px-2 py-0.5 text-[10px] font-bold text-white">دوبله فارسی</span>
            )}
            {item.hasSubtitle && !item.isDubbed && (
              <span className="rounded-md bg-black/60 backdrop-blur px-2 py-0.5 text-[10px] font-bold text-white">زیرنویس فارسی</span>
            )}
          </div>

          <h1 className="hero-title text-4xl md:text-6xl font-black text-white mb-2 leading-tight">
            {item.persianTitle}
          </h1>
          <div className="flex items-center gap-3 text-sm text-white/80 mb-3 flex-wrap">
            <span className="flex items-center gap-1 font-bold text-warning">
              <Star className="h-4 w-4 fill-warning" />
              {toPersianDigits(item.imdbRating.toFixed(1))}
            </span>
            <span>{toPersianDigits(item.releaseYear)}</span>
            {item.duration && <span>{toPersianDigits(item.duration)} دقیقه</span>}
            <span className="px-1.5 py-0.5 border border-white/30 rounded text-[10px]">{item.ageRating ?? "13+"}</span>
            {item.genres?.slice(0, 3).map((g) => (
              <span key={g.persianName} className="text-white/70">{g.persianName}</span>
            ))}
          </div>

          {item.shortDesc && (
            <p className="text-sm md:text-base text-white/80 mb-5 line-clamp-2 max-w-xl drop-shadow">
              {item.shortDesc}
            </p>
          )}

          <div className="flex items-center gap-3 flex-wrap">
            <button
              onClick={() => navigate("watch", { contentType: item.type, contentSlug: item.slug })}
              className="inline-flex items-center gap-2 rounded-xl bg-primary hover:bg-primary/90 px-6 py-3 font-bold text-white shadow-glow transition"
            >
              <Play className="h-5 w-5 fill-white" /> پخش
            </button>
            <button
              onClick={() => openDetail(item.type, item.slug)}
              className="inline-flex items-center gap-2 rounded-xl glass-strong hover:bg-white/10 px-6 py-3 font-bold text-white transition"
            >
              <Info className="h-5 w-5" /> جزئیات
            </button>
            <button
              className="inline-flex items-center justify-center h-12 w-12 rounded-xl glass-strong hover:bg-white/10 text-white transition"
              aria-label="افزودن به لیست من"
            >
              <Plus className="h-5 w-5" />
            </button>
          </div>
        </div>
      </div>

      {/* Indicators */}
      <div className="absolute bottom-4 left-1/2 -translate-x-1/2 flex gap-2">
        {items.map((_, i) => (
          <button
            key={i}
            onClick={() => setIdx(i)}
            className={`h-1.5 rounded-full transition-all ${i === safeIdx ? "w-8 bg-primary" : "w-2 bg-white/40 hover:bg-white/70"}`}
            aria-label={`اسلاید ${i + 1}`}
          />
        ))}
      </div>
    </section>
  );
}
