"use client";

import { getBannerData } from "@/service/banner";
import Image from "next/image";
import { useEffect, useState } from "react";

type Banner = {
  id: number;
  title: string;
  status_id: number;
  thumbnail_url: string;
};

export default function Video() {
  const [banner, setBanner] = useState<Banner | null>(null);

  useEffect(() => {
    const fetchRandomBanner = async () => {
      try {
        const req = {
          limit: "20", // ambil agak banyak biar random lebih terasa
          page: 1,
          search: "",
        };

        const res = await getBannerData(req);

        const banners: Banner[] = res?.data?.data || [];

        const approvedBanners = banners.filter((item) => item.status_id === 2);

        if (approvedBanners.length === 0) return;

        const randomBanner =
          approvedBanners[Math.floor(Math.random() * approvedBanners.length)];

        setBanner(randomBanner);
      } catch (error) {
        console.error("Failed to fetch random banner:", error);
      }
    };

    fetchRandomBanner();
  }, []);

  return (
    <section className="pt-10 bg-white">
      <div className="relative mb-10 w-full h-[250px] sm:h-[600px] md:h-[800px]">
        <Image
          src={banner?.thumbnail_url || "/maintenance.png"}
          alt={banner?.title || "Banner"}
          fill
          className="object-cover"
          priority
        />
        s
      </div>

      <div className="relative w-full h-[500px] overflow-hidden">
        <iframe
          className="w-full h-full"
          src="https://www.youtube.com/embed/qEfjAK4gVhU?autoplay=1&mute=1&loop=1&playlist=qEfjAK4gVhU"
          title="YouTube video player"
          frameBorder="0"
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
          allowFullScreen
        />
      </div>
    </section>
  );
}
