"use client";

import Image from "next/image";
import { useEffect, useMemo, useState } from "react";
import type { HomepageOverviewMedia, Locale } from "@/types/content";
import { getImageUrl } from "@/lib/images";

type HomeOverviewBackgroundProps = {
  locale: Locale;
  media: HomepageOverviewMedia[];
};

const rotateIntervalMs = 7000;

export function HomeOverviewBackground({ locale, media }: HomeOverviewBackgroundProps) {
  const slides = useMemo(
    () =>
      media.filter((item) =>
        item.mediaType === "video" ? Boolean(item.video?.url) : Boolean(getImageUrl(item.image))
      ),
    [media]
  );
  const [rawIndex, setRawIndex] = useState(0);
  const hasMultiple = slides.length > 1;
  const activeIndex = slides.length > 0 ? ((rawIndex % slides.length) + slides.length) % slides.length : 0;

  useEffect(() => {
    if (!hasMultiple) return;
    const timer = window.setInterval(() => {
      setRawIndex((current) => current + 1);
    }, rotateIntervalMs);
    return () => window.clearInterval(timer);
  }, [hasMultiple, slides.length]);

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

  const goTo = (index: number) => setRawIndex((index + slides.length) % slides.length);
  const nextLabel = locale === "id" ? "Ganti background berikutnya" : "Show next background";
  const prevLabel = locale === "id" ? "Ganti background sebelumnya" : "Show previous background";

  return (
    <>
      <div className="home-overview-media" aria-hidden="true">
        {slides.map((item, index) => {
          const imageUrl = getImageUrl(item.image);
          const active = index === activeIndex;
          return (
            <div className={`home-overview-media-item ${active ? "active" : ""}`} key={item._key ?? index}>
              {item.mediaType === "video" && item.video?.url ? (
                <video
                  src={item.video.url}
                  autoPlay={active}
                  loop
                  muted
                  playsInline
                  preload={active ? "auto" : "metadata"}
                  tabIndex={-1}
                />
              ) : imageUrl ? (
                <Image src={imageUrl} alt="" fill priority={index === 0} quality={82} sizes="100vw" />
              ) : null}
            </div>
          );
        })}
      </div>
      <div className="home-overview-shade" aria-hidden="true" />
      {hasMultiple ? (
        <div className="home-overview-controls" role="group" aria-label={locale === "id" ? "Kontrol background" : "Background controls"}>
          <button type="button" className="home-overview-arrow" aria-label={prevLabel} onClick={() => goTo(activeIndex - 1)}>
            <span aria-hidden="true">‹</span>
          </button>
          <div className="home-overview-dots">
            {slides.map((item, index) => (
              <button
                key={item._key ?? `dot-${index}`}
                type="button"
                className={index === activeIndex ? "active" : ""}
                aria-label={`Background ${index + 1}`}
                aria-current={index === activeIndex ? "true" : undefined}
                onClick={() => goTo(index)}
              />
            ))}
          </div>
          <button type="button" className="home-overview-arrow" aria-label={nextLabel} onClick={() => goTo(activeIndex + 1)}>
            <span aria-hidden="true">›</span>
          </button>
        </div>
      ) : null}
    </>
  );
}
