"use client";
import { useMemo } from "react";
import AdImage from "./AdImage";
import { pickAds } from "@/lib/ads";

/**
 * Article body renderer: splits the supplied HTML at paragraph boundaries
 * and splices a 300×250 ad after every Nth paragraph (default 4).
 *
 * `excludeSrcs` lets the caller forbid creatives already used in the
 * sidebar so the same page never shows a banner twice.
 */
export default function ArticleBody({
  html,
  everyN = 4,
  excludeSrcs = [],
  className = "",
}: {
  html: string;
  everyN?: number;
  excludeSrcs?: string[];
  className?: string;
}) {
  const { chunks, ads } = useMemo(() => {
    // Split keeping the closing </p> tags so each chunk is one paragraph block.
    const parts = (html || "").split(/(<\/p>)/i);
    const grouped: string[] = [];
    let buf = "";
    for (const p of parts) {
      buf += p;
      if (p.toLowerCase() === "</p>") {
        grouped.push(buf);
        buf = "";
      }
    }
    if (buf.trim()) grouped.push(buf);

    const slotsNeeded = Math.max(0, Math.floor((grouped.length - 1) / everyN));
    const ads = pickAds("300x250", slotsNeeded, new Set(excludeSrcs));
    return { chunks: grouped, ads };
  }, [html, everyN, excludeSrcs.join("|")]);

  const out: React.ReactNode[] = [];
  let adCursor = 0;
  for (let i = 0; i < chunks.length; i++) {
    out.push(
      <div
        key={`p-${i}`}
        // eslint-disable-next-line react/no-danger
        dangerouslySetInnerHTML={{ __html: chunks[i] }}
      />,
    );
    // Insert ad after this chunk if it's at an everyN boundary and not the last
    if ((i + 1) % everyN === 0 && i < chunks.length - 1 && adCursor < ads.length) {
      const ad = ads[adCursor++];
      out.push(
        <div
          key={`ad-${i}`}
          className="my-6 flex justify-center"
          data-ad-zone="article-inline">
          <AdImage ad={ad} />
        </div>,
      );
    }
  }

  return <div className={`article-body ${className}`}>{out}</div>;
}
