"use client";

import { useState } from "react";
import { Play } from "lucide-react";
import { parseVideoEmbed, type AwarenessVideo } from "@/lib/awareness-videos";

/** Alto fijo para embeds que traen cabecera/pie propios (Instagram, TikTok). */
const FRAME_HEIGHT: Partial<Record<string, string>> = {
  instagram: "h-[600px]",
  tiktok: "h-[740px]",
};

export default function AwarenessVideoCard({ video }: { video: AwarenessVideo }) {
  const embed = parseVideoEmbed(video.url);
  const [playing, setPlaying] = useState(false);
  if (!embed) return null;

  const title = video.title || "Video de la fundación";
  const fixedHeight = FRAME_HEIGHT[embed.provider];
  const boxClass = fixedHeight
    ? `${fixedHeight} w-full`
    : embed.vertical
      ? "mx-auto aspect-[9/16] w-full max-w-[360px]"
      : "aspect-video w-full";

  let player: React.ReactNode;
  if (embed.provider === "file") {
    player = (
      <video src={embed.src} controls playsInline preload="metadata" className="h-full w-full bg-black object-contain" />
    );
  } else if (embed.provider === "youtube" && !playing) {
    // Fachada: solo carga el reproductor de YouTube al hacer clic (página más liviana)
    player = (
      <button
        type="button"
        onClick={() => setPlaying(true)}
        className="group relative block h-full w-full bg-brand-ink"
        aria-label={`Reproducir: ${title}`}
      >
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img src={embed.thumbnail} alt="" loading="lazy" className="h-full w-full object-cover opacity-90 transition group-hover:opacity-100" />
        <span className="absolute inset-0 flex items-center justify-center">
          <span className="flex h-16 w-16 items-center justify-center rounded-full bg-white/95 text-brand-purple shadow-xl transition group-hover:scale-110">
            <Play className="ml-1 h-7 w-7 fill-current" aria-hidden />
          </span>
        </span>
      </button>
    );
  } else {
    const src = embed.provider === "youtube" ? `${embed.src}&autoplay=1` : embed.src;
    player = (
      <iframe
        src={src}
        title={title}
        loading="lazy"
        allow="autoplay; encrypted-media; picture-in-picture; fullscreen"
        allowFullScreen
        scrolling="no"
        className="h-full w-full border-0 bg-white"
      />
    );
  }

  return (
    <figure className="card-soft h-full overflow-hidden bg-white">
      <div className={`${boxClass} overflow-hidden`}>{player}</div>
      {(video.title || video.caption) && (
        <figcaption className="p-5">
          {video.title && <p className="font-serif text-lg font-bold text-brand-ink">{video.title}</p>}
          {video.caption && <p className="mt-1.5 text-sm leading-relaxed text-brand-muted">{video.caption}</p>}
        </figcaption>
      )}
    </figure>
  );
}
