"use client";
import { useEffect, useState } from "react";

type Banner = { id: string; title: string; imageUrl: string; linkUrl?: string | null };

export function HeroBanner() {
  const [banners, setBanners] = useState<Banner[]>([]);
  const [idx, setIdx] = useState(0);
  useEffect(() => {
    fetch("/api/banners").then((r) => r.json()).then((d) => setBanners(d.banners ?? []));
  }, []);
  useEffect(() => {
    if ((banners?.length ?? 0) < 2) return;
    const t = setInterval(() => setIdx((i) => (i + 1) % banners.length), 3000);
    return () => clearInterval(t);
  }, [banners]);
  const slide = banners[idx];
  if (!slide) return null;
  const content = (
    <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
      <img src={slide.imageUrl} alt={slide.title} style={{ width: 72, height: 48, objectFit: "cover", borderRadius: 6 }} />
      <h1 style={{ margin: 0 }}>{slide.title}</h1>
    </div>
  );
  return (
    <section style={{ padding: 16, background: "#f5f5f5", borderRadius: 12, marginBottom: 16 }}>
      {slide.linkUrl ? <a href={slide.linkUrl}>{content}</a> : content}
    </section>
  );
}


