"use client";

import Image from "next/image";
import Link from "next/link";
import { motion, AnimatePresence } from "framer-motion";
import { useEffect, useState, useCallback } from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";

import { heroSlides as staticSlides } from "@/lib/data";
import { fetchHeroSlides, type ApiHeroSlide } from "@/lib/api";
import { Button } from "@/components/ui/button";

export function HeroSlider() {
  const [slides, setSlides] = useState<ApiHeroSlide[]>(staticSlides);
  const [index,     setIndex]     = useState(0);
  const [showIntro, setShowIntro] = useState(true);
  const [direction, setDirection] = useState(1);

  useEffect(() => {
    fetchHeroSlides().then((data) => setSlides(data));
  }, []);

  const navigate = useCallback((dir: 1 | -1) => {
    setDirection(dir);
    setIndex((prev) => (prev + dir + slides.length) % slides.length);
  }, [slides.length]);

  useEffect(() => {
    const timer = setInterval(() => navigate(1), 5000);
    return () => clearInterval(timer);
  }, [navigate]);

  useEffect(() => {
    const timer = window.setTimeout(() => setShowIntro(false), 1600);
    return () => window.clearTimeout(timer);
  }, []);

  const active = slides[index] ?? slides[0];
  const isGraphic = active?.image?.includes("slide_");

  const slideVariants = {
    enter:  (d: number) => ({ opacity: 0, scale: 1.06, x: d > 0 ? 40 : -40 }),
    center: { opacity: 1, scale: 1, x: 0 },
    exit:   (d: number) => ({ opacity: 0, scale: 0.98, x: d > 0 ? -40 : 40 })
  };

  return (
    <section className="px-4 pt-6 sm:px-6 lg:px-8">
      <div className="group/hero relative mx-auto h-[64vh] max-w-7xl overflow-hidden sm:h-[72vh]"
        style={{ borderRadius: "1.5rem" }}>

        {/* Slides */}
        <AnimatePresence mode="wait" custom={direction}>
          <motion.div
            key={active.id}
            custom={direction}
            variants={slideVariants}
            initial="enter"
            animate="center"
            exit="exit"
            transition={{ duration: 0.8, ease: [0.25, 0.46, 0.45, 0.94] }}
            className="hero-mask absolute inset-0"
          >
            <Image
              src={active.image}
              alt={active.title}
              fill
              className="object-cover"
              priority
            />
          </motion.div>
        </AnimatePresence>

        {/* Entire Slide Link for Pre-designed Graphics */}
        {isGraphic && (
          <Link href="/collections" className="absolute inset-0 z-20 cursor-pointer flex flex-col justify-end p-6 sm:p-10">
            <div
              className="w-fit h-11 px-8 rounded-full font-bold tracking-wider text-[#05040f] transition-all duration-300 hover:scale-105 hover:shadow-[0_0_28px_rgba(201,162,80,0.5)] flex items-center justify-center text-sm"
              style={{
                background: "linear-gradient(90deg, #c9a250, #f0d080, #c9a250)",
                backgroundSize: "200% 100%",
                animation: "shimmer-text 4s linear infinite"
              }}
            >
              Shop Now
            </div>
          </Link>
        )}

        {/* Gradient overlay — bottom-heavy for text legibility — only for standard text slides */}
        {!isGraphic && (
          <>
            <div
              className="pointer-events-none absolute inset-0 z-10"
              style={{
                background:
                  "linear-gradient(180deg, rgba(5,4,18,0.15) 0%, rgba(5,4,18,0.08) 40%, rgba(5,4,18,0.78) 80%, rgba(5,4,18,0.92) 100%)"
              }}
            />
            {/* Side vignette */}
            <div
              className="pointer-events-none absolute inset-0 z-10"
              style={{
                background:
                  "linear-gradient(90deg, rgba(5,4,18,0.45) 0%, transparent 20%, transparent 80%, rgba(5,4,18,0.30) 100%)"
              }}
            />
          </>
        )}

        {/* Slide text content */}
        {!isGraphic && (
          <div className="relative z-20 flex h-full flex-col justify-end gap-4 p-6 sm:p-10">
            <motion.p
              key={`tag-${active.id}`}
              initial={{ opacity: 0, y: 12 }}
              animate={{ opacity: showIntro ? 0 : 1, y: showIntro ? 12 : 0 }}
              transition={{ delay: 0.1, duration: 0.5 }}
              className="max-w-xs text-[10px] font-bold uppercase tracking-[0.4em]"
              style={{ color: "rgba(201,162,80,0.9)" }}
            >
              ✦ New Season 2026
            </motion.p>

            <motion.h1
              key={`title-${active.id}`}
              initial={{ opacity: 0, y: 18 }}
              animate={{ opacity: showIntro ? 0 : 1, y: showIntro ? 18 : 0 }}
              transition={{ delay: 0.2, duration: 0.55 }}
              className="max-w-xl text-3xl font-extrabold leading-tight tracking-tight text-white drop-shadow-[0_2px_8px_rgba(0,0,0,0.5)] sm:text-5xl"
            >
              {active.title}
            </motion.h1>

            <motion.p
              key={`sub-${active.id}`}
              initial={{ opacity: 0, y: 14 }}
              animate={{ opacity: showIntro ? 0 : 1, y: showIntro ? 14 : 0 }}
              transition={{ delay: 0.3, duration: 0.5 }}
              className="max-w-md text-sm leading-relaxed text-white/70 sm:text-base"
            >
              {active.subtitle}
            </motion.p>

            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: showIntro ? 0 : 1 }}
              transition={{ delay: 0.42 }}
              className="flex items-center gap-3"
            >
              <Link href="/collections">
                <Button
                  className="group relative h-11 overflow-hidden rounded-full px-8 font-bold tracking-wider text-[#05040f] transition-all duration-300 hover:scale-105 hover:shadow-[0_0_28px_rgba(201,162,80,0.5)]"
                  style={{
                    background: "linear-gradient(90deg, #c9a250, #f0d080, #c9a250)",
                    backgroundSize: "200% 100%",
                    animation: "shimmer-text 4s linear infinite"
                  }}
                >
                  {active.cta}
                </Button>
              </Link>
              <Link href="/about">
                <button
                  className="h-11 rounded-full px-6 text-sm font-semibold text-white/70 transition-all hover:text-white"
                  style={{
                    background: "rgba(255,255,255,0.07)",
                    border: "1px solid rgba(255,255,255,0.12)",
                    backdropFilter: "blur(8px)"
                  }}
                >
                  View Our Story
                </button>
              </Link>
            </motion.div>
          </div>
        )}

        {/* Arrow controls */}
        {[
          { dir: -1 as const, side: "left-3 sm:left-5",  Icon: ChevronLeft },
          { dir:  1 as const, side: "right-3 sm:right-5", Icon: ChevronRight },
        ].map(({ dir, side, Icon }) => (
          <button
            key={dir}
            type="button"
            onClick={() => navigate(dir)}
            className={`absolute top-1/2 z-30 -translate-y-1/2 ${side} flex h-10 w-10 items-center justify-center rounded-full opacity-0 transition-all duration-300 group-hover/hero:opacity-100 hover:scale-110`}
            style={{
              background: "rgba(15,12,35,0.65)",
              border: "1px solid rgba(201,162,80,0.25)",
              backdropFilter: "blur(12px)"
            }}
          >
            <Icon className="h-5 w-5 text-white/80" />
          </button>
        ))}

        {/* Dot indicators */}
        <div className="absolute bottom-5 right-6 z-30 flex gap-2">
          {slides.map((slide, i) => (
            <button
              key={slide.id}
              type="button"
              onClick={() => { setDirection(i > index ? 1 : -1); setIndex(i); }}
              className="h-1.5 rounded-full transition-all duration-300"
              style={{
                width: i === index ? 28 : 6,
                background: i === index
                  ? "linear-gradient(90deg, #c9a250, #f0d080)"
                  : "rgba(255,255,255,0.3)"
              }}
              aria-label={`Go to ${slide.title}`}
            />
          ))}
        </div>

        {/* Slide counter */}
        <div
          className="absolute bottom-5 left-6 z-30 font-mono text-xs text-white/40"
        >
          <span className="text-amber-400/80 font-bold">{String(index + 1).padStart(2, "0")}</span>
          {" / "}
          {String(slides.length).padStart(2, "0")}
        </div>
      </div>
    </section>
  );
}

