"use client";

import Image from "next/image";
import { useState } from "react";
import type { FileAsset, ImageAsset } from "@/types/content";
import { getImageAlt, getImageUrl } from "@/lib/images";

type DetailHeroMediaProps = {
  label: string;
  video?: FileAsset;
  images?: ImageAsset[];
};

export function DetailHeroMedia({ label, video, images = [] }: DetailHeroMediaProps) {
  const validImages = images.filter((image) => Boolean(getImageUrl(image)));
  const [activeIndex, setActiveIndex] = useState(0);
  const activeImage = validImages[activeIndex];

  if (video?.url) {
    return (
      <div className="detail-hero-media" aria-label={label}>
        <video autoPlay loop muted playsInline preload="metadata" src={video.url} />
      </div>
    );
  }

  if (!activeImage) return null;

  const imageUrl = getImageUrl(activeImage);
  const hasCarousel = validImages.length > 1;

  return (
    <div className="detail-hero-media" role="img" aria-label={label}>
      {imageUrl ? <Image key={imageUrl} src={imageUrl} alt={getImageAlt(activeImage, label)} fill sizes="100vw" priority className="detail-hero-media-image" /> : null}
      {hasCarousel ? (
        <div className="detail-media-controls" aria-label="Media carousel controls">
          <button type="button" onClick={() => setActiveIndex((activeIndex - 1 + validImages.length) % validImages.length)} aria-label="Previous image">
            ←
          </button>
          <span>
            {activeIndex + 1}/{validImages.length}
          </span>
          <button type="button" onClick={() => setActiveIndex((activeIndex + 1) % validImages.length)} aria-label="Next image">
            →
          </button>
        </div>
      ) : null}
    </div>
  );
}
