import Image from "next/image";
import type { ArticleBlock, Locale } from "@/types/content";
import { getImageAlt, getImageUrl } from "@/lib/images";

/**
 * Renders an article's modular body (rich text / image / video blocks) as
 * authored in the CMS. Block HTML comes from Twill's constrained, RBAC-gated
 * WYSIWYG editor, so it is injected directly (same trust model as the JSON-LD
 * blocks elsewhere in the app).
 */
export function ArticleBody({ blocks, locale }: { blocks: ArticleBlock[]; locale: Locale }) {
  if (!blocks?.length) return null;

  return (
    <div className="article-body">
      {blocks.map((block, index) => {
        if (block.type === "richText") {
          const html = block.html?.[locale] || block.html?.en || "";
          if (!html.trim()) return null;
          return <div key={index} className="article-prose" dangerouslySetInnerHTML={{ __html: html }} />;
        }

        if (block.type === "image") {
          const url = getImageUrl(block.image ?? undefined);
          if (!url) return null;
          const caption = block.caption?.[locale] || block.caption?.en || "";
          return (
            <figure key={index} className="article-figure">
              <Image
                src={url}
                alt={getImageAlt(block.image ?? undefined, caption || "Article image")}
                width={1600}
                height={900}
                sizes="(max-width: 768px) 100vw, 760px"
                className="article-image"
                style={{ width: "100%", height: "auto" }}
              />
              {caption ? <figcaption>{caption}</figcaption> : null}
            </figure>
          );
        }

        if (block.type === "video") {
          return <ArticleVideo key={index} block={block} locale={locale} />;
        }

        return null;
      })}
    </div>
  );
}

function ArticleVideo({ block, locale }: { block: Extract<ArticleBlock, { type: "video" }>; locale: Locale }) {
  const caption = block.caption?.[locale] || block.caption?.en || "";
  const embed = toEmbedUrl(block.embedUrl);
  const fileUrl = block.file?.url;
  const directUrl = fileUrl || (isDirectVideo(block.embedUrl) ? block.embedUrl ?? undefined : undefined);

  if (!embed && !directUrl) return null;

  return (
    <figure className="article-figure article-video">
      {embed ? (
        <div className="article-video-frame">
          <iframe
            src={embed}
            title={caption || "Embedded video"}
            loading="lazy"
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
            allowFullScreen
          />
        </div>
      ) : (
        <video controls preload="metadata" src={directUrl} />
      )}
      {caption ? <figcaption>{caption}</figcaption> : null}
    </figure>
  );
}

function isDirectVideo(url?: string | null) {
  return Boolean(url && /\.(mp4|webm|ogg|mov)(\?.*)?$/i.test(url));
}

/** Normalise a YouTube / Vimeo watch or share link to its embed URL. */
function toEmbedUrl(url?: string | null): string | null {
  if (!url || isDirectVideo(url)) return null;

  const youtube = url.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/)|youtu\.be\/)([\w-]{6,})/i);
  if (youtube) return `https://www.youtube.com/embed/${youtube[1]}`;

  const vimeo = url.match(/vimeo\.com\/(?:video\/)?(\d+)/i);
  if (vimeo) return `https://player.vimeo.com/video/${vimeo[1]}`;

  // Already an embeddable URL (or an unknown provider we pass through).
  if (/player\.|\/embed\//i.test(url)) return url;

  return null;
}
