"use client";

import { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import Image from "next/image";
import { ArrowRight, ChevronLeft, ChevronRight, Star, Briefcase, GraduationCap, ShoppingBag, BookOpen, Plane, Globe } from "lucide-react";

// ─── Types ───────────────────────────────────────────────────────────────────

export type HeroSlideItem = {
  id: string | number;
  imageUrl: string;
  badge: string;
  badgeIcon: string;
  title: string;
  highlight: string;
  description: string;
  ctaLabel: string;
  ctaHref: string;
  ctaSecondLabel: string;
  ctaSecondHref: string;
};

const BADGE_ICONS: Record<string, React.ComponentType<{ size?: number; className?: string }>> = {
  jobs: Briefcase,
  scholarships: GraduationCap,
  shop: ShoppingBag,
  journal: BookOpen,
  tours: Plane,
  visa: Globe,
};

// ─── Fallback slides (used when DB is empty) ──────────────────────────────────

const FALLBACK_SLIDES: HeroSlideItem[] = [
  {
    id: 1,
    imageUrl: "https://images.unsplash.com/photo-1521737604893-d14cc237f11d?w=1920&q=80",
    badge: "Jobs Portal",
    badgeIcon: "jobs",
    title: "Find Your",
    highlight: "Dream Career",
    description: "Connect with top employers across Malaysia and beyond. Thousands of verified job listings updated every 6 hours from live APIs.",
    ctaLabel: "Browse Jobs",
    ctaHref: "/jobs",
    ctaSecondLabel: "Learn More",
    ctaSecondHref: "/about",
  },
  {
    id: 2,
    imageUrl: "https://images.unsplash.com/photo-1541339907198-e08756dedf3f?w=1920&q=80",
    badge: "Scholarships",
    badgeIcon: "scholarships",
    title: "Fund Your",
    highlight: "Education",
    description: "Discover 500+ international scholarship opportunities. From local grants to fully-funded programmes abroad — your future starts here.",
    ctaLabel: "Find Scholarships",
    ctaHref: "/scholarships",
    ctaSecondLabel: "View Plans",
    ctaSecondHref: "/register",
  },
  {
    id: 3,
    imageUrl: "https://images.unsplash.com/photo-1607082348824-0a96f2a4b9da?w=1920&q=80",
    badge: "Online Shop",
    badgeIcon: "shop",
    title: "Shop Quality",
    highlight: "Products",
    description: "Browse our curated selection of premium products with fast delivery. Electronics, fashion, accessories and more.",
    ctaLabel: "Shop Now",
    ctaHref: "/shop",
    ctaSecondLabel: "View Catalogue",
    ctaSecondHref: "/shop",
  },
  {
    id: 4,
    imageUrl: "https://images.unsplash.com/photo-1456513080510-7bf3a84b82f8?w=1920&q=80",
    badge: "Journals",
    badgeIcon: "journal",
    title: "Share Your",
    highlight: "Knowledge",
    description: "Read in-depth articles from industry experts, or publish your own. Join a growing community of knowledge-driven professionals.",
    ctaLabel: "Read Journals",
    ctaHref: "/journal",
    ctaSecondLabel: "Start Writing",
    ctaSecondHref: "/journal/new",
  },
];

// ─── Component ────────────────────────────────────────────────────────────────

export default function HeroSlider({ slides: dbSlides }: { slides?: HeroSlideItem[] }) {
  const slides = dbSlides && dbSlides.length > 0 ? dbSlides : FALLBACK_SLIDES;
  const [current, setCurrent] = useState(0);
  const [isTransitioning, setIsTransitioning] = useState(false);

  const goTo = useCallback((index: number) => {
    if (isTransitioning) return;
    setIsTransitioning(true);
    setCurrent(index);
    setTimeout(() => setIsTransitioning(false), 600);
  }, [isTransitioning]);

  const prev = () => goTo((current - 1 + slides.length) % slides.length);
  const next = useCallback(() => goTo((current + 1) % slides.length), [current, goTo, slides.length]);

  useEffect(() => {
    const timer = setInterval(next, 5500);
    return () => clearInterval(timer);
  }, [next]);

  const slide = slides[current];

  return (
    <section className="relative h-[600px] md:h-[680px] overflow-hidden bg-navy-900">
      {/* Background images */}
      {slides.map((s, i) => (
        <div
          key={s.id}
          className="absolute inset-0 transition-opacity duration-700 ease-in-out"
          style={{ opacity: i === current ? 1 : 0 }}
        >
          <Image
            src={s.imageUrl}
            alt={s.highlight}
            fill
            priority={i === 0}
            className="object-cover"
            sizes="100vw"
          />
          {/* Dark overlay gradient */}
          <div className="absolute inset-0 bg-gradient-to-r from-navy-950/90 via-navy-900/70 to-navy-900/30" />
        </div>
      ))}

      {/* Content */}
      <div className="relative z-10 h-full flex items-center">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 w-full">
          <div className="max-w-2xl">
            {/* Badge */}
            <div
              key={`badge-${current}`}
              className="inline-flex items-center gap-2 px-3 py-1.5 bg-gold-500/20 text-gold-300 text-xs font-semibold rounded-full mb-5 border border-gold-500/30 animate-fade-in"
            >
              {(() => { const Icon = BADGE_ICONS[slide.badgeIcon] ?? Briefcase; return <Icon size={12} />; })()}
              {slide.badge}
            </div>

            {/* Headline */}
            <h1
              key={`title-${current}`}
              className="text-4xl md:text-5xl lg:text-6xl font-bold text-white leading-tight tracking-tight"
              style={{ animation: "slideUp 0.5s ease forwards" }}
            >
              {slide.title}
              <br />
              <span className="text-gold-400">{slide.highlight}</span>
            </h1>

            {/* Description */}
            <p
              key={`desc-${current}`}
              className="mt-5 text-base md:text-lg text-navy-200 leading-relaxed"
              style={{ animation: "slideUp 0.6s ease forwards" }}
            >
              {slide.description}
            </p>

            {/* CTAs */}
            <div
              key={`cta-${current}`}
              className="mt-8 flex flex-wrap gap-3"
              style={{ animation: "slideUp 0.7s ease forwards" }}
            >
              <Link
                href={slide.ctaHref}
                className="inline-flex items-center gap-2 px-6 py-3 bg-gold-500 text-white font-semibold rounded-xl hover:bg-gold-400 transition-colors shadow-lg"
              >
                {slide.ctaLabel} <ArrowRight size={16} />
              </Link>
              <Link
                href={slide.ctaSecondHref}
                className="inline-flex items-center gap-2 px-6 py-3 bg-white/10 text-white font-medium rounded-xl hover:bg-white/20 transition-colors border border-white/20"
              >
                {slide.ctaSecondLabel}
              </Link>
            </div>

            {/* Trust badge */}
            <div className="mt-8 flex items-center gap-2 text-navy-300 text-sm">
              <Star size={14} className="text-gold-400 fill-gold-400" />
              <span>Trusted by 12,000+ members across Malaysia</span>
            </div>
          </div>
        </div>
      </div>

      {/* Navigation arrows */}
      <button
        onClick={prev}
        className="absolute left-4 top-1/2 -translate-y-1/2 z-20 w-10 h-10 bg-white/10 hover:bg-white/25 border border-white/20 rounded-full flex items-center justify-center text-white transition-colors backdrop-blur-sm"
        aria-label="Previous slide"
      >
        <ChevronLeft size={20} />
      </button>
      <button
        onClick={next}
        className="absolute right-4 top-1/2 -translate-y-1/2 z-20 w-10 h-10 bg-white/10 hover:bg-white/25 border border-white/20 rounded-full flex items-center justify-center text-white transition-colors backdrop-blur-sm"
        aria-label="Next slide"
      >
        <ChevronRight size={20} />
      </button>

      {/* Dots */}
      <div className="absolute bottom-6 left-1/2 -translate-x-1/2 z-20 flex items-center gap-2">
        {slides.map((_, i) => (
          <button
            key={i}
            onClick={() => goTo(i)}
            className={`transition-all duration-300 rounded-full ${
              i === current ? "w-6 h-2 bg-gold-400" : "w-2 h-2 bg-white/40 hover:bg-white/70"
            }`}
            aria-label={`Go to slide ${i + 1}`}
          />
        ))}
      </div>

      {/* Slide counter */}
      <div className="absolute bottom-6 right-6 z-20 text-xs text-white/50 font-mono">
        {String(current + 1).padStart(2, "0")} / {String(slides.length).padStart(2, "0")}
      </div>

      <style jsx>{`
        @keyframes slideUp {
          from { opacity: 0; transform: translateY(20px); }
          to { opacity: 1; transform: translateY(0); }
        }
      `}</style>
    </section>
  );
}
