"use client";

import Link from "next/link";
import Image from "next/image";
import { useEffect, useState } from "react";

type Slide = {
  id: string;
  title: string;
  subtitle: string;
  imageUrl: string;
  ctaLabel: string | null;
  ctaHref: string | null;
};

export function HomeSlider({ slides }: { slides: Slide[] }) {
  const [index, setIndex] = useState(0);
  const activeSlide = slides[index];

  useEffect(() => {
    if (slides.length <= 1) {
      return;
    }

    const timer = window.setInterval(() => {
      setIndex((current) => (current + 1) % slides.length);
    }, 2000);

    return () => window.clearInterval(timer);
  }, [slides.length]);

  if (!activeSlide) {
    return (
      <div className="slider-frame">
        <div className="slider-empty">
          <span className="pill">Admin Slider</span>
          <h2>Add homepage images from admin panel.</h2>
          <p className="muted">Upload image, title and subtitle from Admin &gt; Home Page.</p>
        </div>
      </div>
    );
  }

  return (
    <div className="slider-frame">
      {slides.map((slide, slideIndex) => (
        <article className={`slide${slideIndex === index ? " active" : ""}`} key={slide.id}>
          <Image alt={slide.title} fill priority sizes="100vw" src={slide.imageUrl} unoptimized />
          <div className="slide-content">
            <span className="pill">Featured Transmission</span>
            <h2>{slide.title}</h2>
            <p>{slide.subtitle}</p>
            {slide.ctaHref ? (
              <Link className="btn" href={slide.ctaHref}>
                {slide.ctaLabel ?? "Explore"}
              </Link>
            ) : null}
          </div>
        </article>
      ))}
      <div className="slider-dots">
        {slides.map((slide, slideIndex) => (
          <button
            aria-label={`Show slide ${slideIndex + 1}`}
            className={slideIndex === index ? "active" : ""}
            key={slide.id}
            onClick={() => setIndex(slideIndex)}
            type="button"
          />
        ))}
      </div>
    </div>
  );
}
