"use client";

import { useState, useEffect, useCallback } from "react";
import Image from "next/image";
import Link from "next/link";
import type { HeroSlide } from "@/types";
import { getTranslations, type Translations } from "@/lib/i18n";

interface HeroSliderProps {
  slides: HeroSlide[];
  storeName: string;
  t?: Translations;
}

export default function HeroSlider({ slides, storeName, t }: HeroSliderProps) {
  const T = t ?? getTranslations("en");
  const [current, setCurrent] = useState(0);
  const [isPlaying, setIsPlaying] = useState(true);
  const [progress, setProgress] = useState(0);

  const next = useCallback(() => {
    setCurrent((c) => (c + 1) % slides.length);
    setProgress(0);
  }, [slides.length]);
  const prev = () => {
    setCurrent((c) => (c - 1 + slides.length) % slides.length);
    setProgress(0);
  };

  // Auto-advance with progress tracking
  useEffect(() => {
    if (!isPlaying || slides.length <= 1) return;
    const interval = 5000;
    const tick = 50;
    const timer = setInterval(() => {
      setProgress((p) => {
        if (p >= 100) {
          next();
          return 0;
        }
        return p + (tick / interval) * 100;
      });
    }, tick);
    return () => clearInterval(timer);
  }, [isPlaying, next, slides.length]);

  if (slides.length === 0) return null;
  if (slides.length === 1)
    return <SingleSlide slide={slides[0]} storeName={storeName} t={T} />;

  const slide = slides[current];

  return (
    <section
      className="relative overflow-hidden bg-gray-900 select-none"
      style={{ minHeight: "540px" }}
      onMouseEnter={() => setIsPlaying(false)}
      onMouseLeave={() => setIsPlaying(true)}
    >
      {/* Slides */}
      {slides.map((s, i) => (
        <div
          key={s.id}
          className={`absolute inset-0 transition-opacity duration-700 ${
            i === current ? "opacity-100 z-10" : "opacity-0 z-0"
          }`}
        >
          <SlideBackground slide={s} storeName={storeName} />
        </div>
      ))}

      {/* Overlay + content */}
      <div className="relative z-20 flex items-center min-h-[540px]">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 w-full py-20">
          <div className="max-w-2xl">
            {slide.title && (
              <h1
                className="text-4xl md:text-6xl font-bold text-white leading-tight mb-5 tracking-tight"
                style={{ textShadow: "0 2px 20px rgba(0,0,0,0.3)" }}
              >
                {slide.title}
              </h1>
            )}
            {slide.subtitle && (
              <p className="text-lg md:text-xl text-white/80 mb-10 leading-relaxed">
                {slide.subtitle}
              </p>
            )}
            {slide.cta_label && (
              <Link
                href={slide.cta_url || "/products"}
                className="inline-block px-10 py-4 rounded-full text-sm font-semibold shadow-xl text-white"
                style={{ backgroundColor: "var(--color-primary)" }}
              >
                {slide.cta_label}
              </Link>
            )}
          </div>
        </div>
      </div>

      {/* Prev / Next arrows */}
      {slides.length > 1 && (
        <>
          <button
            onClick={prev}
            className="absolute left-4 top-1/2 -translate-y-1/2 z-30 w-11 h-11 rounded-full bg-black/25 hover:bg-black/45 text-white flex items-center justify-center transition-all hover:scale-105 backdrop-blur-sm border border-white/10"
            aria-label={T.home.previousSlide}
          >
            <svg
              className="w-5 h-5"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              strokeWidth={2}
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M15 19l-7-7 7-7"
              />
            </svg>
          </button>
          <button
            onClick={next}
            className="absolute right-4 top-1/2 -translate-y-1/2 z-30 w-11 h-11 rounded-full bg-black/25 hover:bg-black/45 text-white flex items-center justify-center transition-all hover:scale-105 backdrop-blur-sm border border-white/10"
            aria-label={T.home.nextSlide}
          >
            <svg
              className="w-5 h-5"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              strokeWidth={2}
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M9 5l7 7-7 7"
              />
            </svg>
          </button>
        </>
      )}

      {/* Progress bars + dot indicators */}
      {slides.length > 1 && (
        <div className="absolute bottom-6 left-1/2 -translate-x-1/2 z-30 flex items-center gap-2">
          {slides.map((_, i) => (
            <button
              key={i}
              onClick={() => {
                setCurrent(i);
                setProgress(0);
              }}
              className="relative h-[3px] rounded-full overflow-hidden transition-all duration-300"
              style={{
                width: i === current ? "2rem" : "0.5rem",
                backgroundColor: "rgba(255,255,255,0.35)",
              }}
              aria-label={T.home.goToSlide.replace(
                /\{\{\s*n\s*\}\}/g,
                String(i + 1),
              )}
            >
              {i === current && (
                <span
                  className="absolute inset-y-0 left-0 bg-white rounded-full transition-none"
                  style={{ width: `${progress}%` }}
                />
              )}
            </button>
          ))}
        </div>
      )}
    </section>
  );
}

function SlideBackground({
  slide,
  storeName,
}: {
  slide: HeroSlide;
  storeName: string;
}) {
  const opacity = slide.overlay_opacity ?? 0.45;

  if (slide.type === "video") {
    return (
      <>
        <video
          src={slide.url}
          autoPlay
          muted
          loop
          playsInline
          className="absolute inset-0 w-full h-full object-cover"
        />
        <div
          className="absolute inset-0"
          style={{ backgroundColor: `rgba(0,0,0,${opacity})` }}
        />
      </>
    );
  }

  return (
    <>
      <Image
        src={slide.url}
        alt={slide.title || storeName}
        fill
        className="object-cover"
        sizes="100vw"
        priority
      />
      <div
        className="absolute inset-0"
        style={{ backgroundColor: `rgba(0,0,0,${opacity})` }}
      />
    </>
  );
}

function SingleSlide({
  slide,
  storeName,
  t,
}: {
  slide: HeroSlide;
  storeName: string;
  t: Translations;
}) {
  return (
    <section
      className="relative overflow-hidden bg-gray-900"
      style={{ minHeight: "540px" }}
    >
      <SlideBackground slide={slide} storeName={storeName} />
      <div className="relative z-10 flex items-center min-h-[540px]">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 w-full py-20">
          <div className="max-w-2xl">
            {slide.title && (
              <h1
                className="text-4xl md:text-6xl font-bold text-white leading-tight mb-5 tracking-tight"
                style={{ textShadow: "0 2px 20px rgba(0,0,0,0.3)" }}
              >
                {slide.title}
              </h1>
            )}
            {slide.subtitle && (
              <p className="text-lg md:text-xl text-white/80 mb-10 leading-relaxed">
                {slide.subtitle}
              </p>
            )}
            {slide.cta_label && (
              <Link
                href={slide.cta_url || "/products"}
                className="inline-block px-10 py-4 rounded-full text-sm font-semibold shadow-xl text-white"
                style={{ backgroundColor: "var(--color-primary)" }}
              >
                {slide.cta_label}
              </Link>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}
