"use client";

import LinkifyPlainText from "@/components/LinkifyPlainText";

/**
 * Forum body renderer that splits markdown image syntax out of the
 * plain-text body, renders inline `![alt](url)` images as a <picture>
 * element with AVIF source (when the URL is from our bb-media bucket,
 * we derive the .avif sibling), and hands the rest of the prose to
 * LinkifyPlainText for company auto-linking.
 *
 * Why a custom mini-parser instead of react-markdown? The body is
 * 99% plain text with the occasional attached image. Pulling in a
 * full markdown lib + sanitizer chain for one feature triples the
 * client bundle for negligible gain.
 */
const IMG_RE = /!\[([^\]]*)\]\((https?:\/\/[^\s)]+)\)/g;

function deriveAvifFromWebp(url: string): string | null {
  // Our /api/upload/image writes both .webp and .avif to the same path.
  // If the URL ends in .webp on the bb-media bucket, the .avif sibling
  // is at the same path with the extension swapped.
  if (!/\/bb-media\/.+\.webp(\?.*)?$/i.test(url)) return null;
  return url.replace(/\.webp(\?.*)?$/i, ".avif$1");
}

export default function RichBody({ body }: { body: string }) {
  if (!body) return null;

  // Walk the body, splitting on image markdown.
  const segments: Array<
    | { type: "text"; text: string }
    | { type: "image"; alt: string; url: string }
  > = [];
  let cursor = 0;
  IMG_RE.lastIndex = 0;
  for (let m = IMG_RE.exec(body); m; m = IMG_RE.exec(body)) {
    if (m.index > cursor) {
      segments.push({ type: "text", text: body.slice(cursor, m.index) });
    }
    segments.push({ type: "image", alt: m[1] || "", url: m[2] });
    cursor = m.index + m[0].length;
  }
  if (cursor < body.length) {
    segments.push({ type: "text", text: body.slice(cursor) });
  }
  if (segments.length === 0) {
    segments.push({ type: "text", text: body });
  }

  return (
    <div className="space-y-3">
      {segments.map((seg, i) => {
        if (seg.type === "image") {
          const avif = deriveAvifFromWebp(seg.url);
          return (
            <figure key={i} className="my-2">
              <picture>
                {avif && <source srcSet={avif} type="image/avif" />}
                <source srcSet={seg.url} type="image/webp" />
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img
                  src={seg.url}
                  alt={seg.alt}
                  loading="lazy"
                  decoding="async"
                  className="max-w-full h-auto rounded-md border border-[#DCE6F2] bg-[#F8FAFC]"
                />
              </picture>
              {seg.alt && (
                <figcaption className="text-[11px] text-[#666] mt-1 italic">{seg.alt}</figcaption>
              )}
            </figure>
          );
        }
        // For text segments, drop into LinkifyPlainText (company links)
        return seg.text.trim()
          ? <LinkifyPlainText key={i} body={seg.text} />
          : null;
      })}
    </div>
  );
}
