"use client";

import Image from "next/image";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { CSSProperties } from "react";

export interface SliderPhoto {
  src: string;
  alt: string;
  id?: string | number;
}

const ROTATE_MS = 5500;

// --- 1. SLIDE COMPONENT ---
interface SlideProps {
  photo: SliderPhoto;
}

function PromoStripSingleSlide({ photo }: SlideProps) {
  return (
    <div className="relative h-full w-full">
      <Image
        src={photo.src}
        alt={photo.alt}
        fill
        priority
        className="object-cover object-center"
        sizes="100vw"
      />
    </div>
  );
}

// --- 2. DATA HOOK ---
function useSliderPhotos(): { photos: SliderPhoto[]; loading: boolean } {
  const [photos, setPhotos] = useState<SliderPhoto[]>([]);
  const [loading, setLoading] = useState<boolean>(true);

  useEffect(() => {
    let cancelled = false;
    fetch("/api/slider-photos", { cache: "no-store" })
      .then((r) => (r.ok ? r.json() : []))
      .then((data: unknown) => {
        if (cancelled) return;
        if (Array.isArray(data)) {
          const validated = data.filter(
            (x): x is SliderPhoto =>
              typeof x === "object" && x !== null && "src" in x && "alt" in x
          );
          setPhotos(validated);
        }
      })
      .catch(() => {
        if (!cancelled) setPhotos([]);
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });
    return () => { cancelled = true; };
  }, []);

  return { photos, loading };
}

// --- 3. MAIN COMPONENT ---
export function TvonePromoStrip() {
  const { photos, loading } = useSliderPhotos();
  const [index, setIndex] = useState<number>(0);
  const [reduceMotion, setReduceMotion] = useState<boolean>(false);

  // Constants for the 4.8:1 ratio
  const FIXED_RATIO = 4.8 / 1;

  useEffect(() => {
    const mq = window.matchMedia("(prefers-reduced-motion: reduce)");
    const sync = () => setReduceMotion(mq.matches);
    sync();
    mq.addEventListener("change", sync);
    return () => mq.removeEventListener("change", sync);
  }, []);

  const advance = useCallback(() => {
    if (photos.length <= 1) return;
    setIndex((i: number) => (i + 1) % photos.length);
  }, [photos.length]);

  useEffect(() => {
    if (photos.length <= 1 || reduceMotion) return;
    const id = window.setInterval(advance, ROTATE_MS);
    return () => window.clearInterval(id);
  }, [photos.length, reduceMotion, advance]);

  // Loading state with fixed ratio
  if (loading && photos.length === 0) {
    return (
      <div 
        className="w-full animate-pulse bg-neutral-100 dark:bg-neutral-800" 
        style={{ aspectRatio: "4.8 / 1" }}
      />
    );
  }

  if (photos.length === 0) return null;

  return (
    <section 
      className="relative w-full overflow-hidden bg-neutral-100 dark:bg-neutral-900 transition-all duration-700 ease-[cubic-bezier(0.32,0.72,0,1)]"
      style={{ aspectRatio: "4.8 / 1" }} // Locked to 4.8:1
      role="region"
      aria-roledescription="carrossel"
    >
      {/* THE TRACK */}
      <div 
        className="flex h-full w-full transition-transform duration-1000 ease-[cubic-bezier(0.32,0.72,0,1)]"
        style={{ transform: `translateX(-${index * 100}%)` }}
      >
        {photos.map((photo: SliderPhoto, i: number) => (
          <div key={photo.src || i} className="h-full w-full flex-shrink-0">
            <PromoStripSingleSlide photo={photo} />
          </div>
        ))}
      </div>

      {/* INDICATORS */}
      {photos.length > 1 && (
        <div className="absolute bottom-4 left-1/2 flex -translate-x-1/2 gap-2 z-20">
          {photos.map((_, i: number) => (
            <button
              key={i}
              onClick={() => setIndex(i)}
              className={`h-1 transition-all duration-500 ${
                index === i ? "w-6 bg-white" : "w-1.5 bg-white/30 hover:bg-white/60"
              }`}
              aria-label={`Ir para slide ${i + 1}`}
            />
          ))}
        </div>
      )}
    </section>
  );
}