// ─── Inline link parser ───
// Converts markdown-style [text](url) in strings to React elements
function renderText(text) {
  if (!text || !text.includes("[")) return text;
  const parts = [];
  let remaining = text;
  let key = 0;
  const regex = /\[([^\]]+)\]\(([^)]+)\)/g;
  let match;
  let lastIndex = 0;
  while ((match = regex.exec(text)) !== null) {
    if (match.index > lastIndex) {
      parts.push(text.slice(lastIndex, match.index));
    }
    const isExternal = match[2].startsWith("http");
    parts.push(
      React.createElement("a", {
        key: key++,
        href: match[2],
        ...(isExternal ? { target: "_blank", rel: "noopener noreferrer" } : {}),
        className: "article-link"
      }, match[1])
    );
    lastIndex = regex.lastIndex;
  }
  if (lastIndex < text.length) {
    parts.push(text.slice(lastIndex));
  }
  return parts.length > 0 ? parts : text;
}

// ─── Article Renderer ───
// Maps JSON body array to React elements

function ArticleRenderer({ body }) {
  if (!body || !body.length) return null;

  let h2Count = 0;

  return (
    <div className="article-body">
      {body.map((block, i) => {
        switch (block.type) {

          case "lead":
            return <p key={i} className="article-lead">{renderText(block.text)}</p>;

          case "p":
            return <p key={i} className="article-p">{renderText(block.text)}</p>;

          case "amber":
            return <p key={i} className="article-amber">{renderText(block.text)}</p>;

          case "h2":
            return <h2 key={i} className="article-h2" id={block.text.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/-$/, "")}>{block.text}</h2>;

          case "h2-numbered":
            return <h2 key={i} className="article-h2" id={block.text.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/-$/, "")}>{block.text}</h2>;

          case "h3":
            return <h3 key={i} className="article-h3">{block.text}</h3>;

          case "image":
            return (
              <figure key={i} className={`article-figure ${block.wide ? "article-figure-wide" : ""}`}>
                <img src={block.src} alt={block.alt || ""} className="article-img" loading="lazy" />
                {block.caption && <figcaption className="article-caption">{block.caption}</figcaption>}
              </figure>
            );

          case "callout":
            return (
              <aside key={i} className="article-callout">
                <span className="callout-dot" />
                <p>{renderText(block.text)}</p>
              </aside>
            );

          case "pullquote":
            return (
              <div key={i} className="article-pullquote">
                <blockquote>{block.text}</blockquote>
              </div>
            );

          case "blockquote":
            return (
              <blockquote key={i} className="article-blockquote">
                <p>{block.text}</p>
              </blockquote>
            );

          case "ul":
            return (
              <ul key={i} className="article-list">
                {block.items.map((item, j) => <li key={j}>{renderText(item)}</li>)}
              </ul>
            );

          case "ol":
            return (
              <ol key={i} className="article-list article-list-ol">
                {block.items.map((item, j) => <li key={j}>{renderText(item)}</li>)}
              </ol>
            );

          case "steps":
            return (
              <div key={i} className="article-steps">
                {block.items.map((item, j) => (
                  <div key={j} className="article-step">
                    <span className="step-num">{String(j + 1).padStart(2, "0")}</span>
                    <div className="step-text">{item}</div>
                  </div>
                ))}
              </div>
            );

          case "spec-table":
            return (
              <div key={i} className="article-spec-table">
                <table>
                  {block.headers && (
                    <thead>
                      <tr>{block.headers.map((h, j) => <th key={j}>{h}</th>)}</tr>
                    </thead>
                  )}
                  <tbody>
                    {block.rows.map((row, j) => (
                      <tr key={j}>{row.map((cell, k) => <td key={k}>{cell}</td>)}</tr>
                    ))}
                  </tbody>
                </table>
              </div>
            );

          case "social-proof": {
            const isReddit = block.platform === "Reddit";
            const isTwitter = block.platform === "Twitter" || block.platform === "X";
            const isTiktok = block.platform === "TikTok";
            const isYoutube = block.platform === "YouTube";
            const platformIcon = isReddit ? "↗ Reddit" : isTwitter ? "𝕏" : isTiktok ? "♪ TikTok" : isYoutube ? "▶ YouTube" : block.platform;
            const platformClass = isReddit ? "reddit" : isTwitter ? "twitter" : isTiktok ? "tiktok" : isYoutube ? "youtube" : "other";

            const inner = (
              <div className={`article-social-proof sp-${platformClass}`}>
                <div className="sp-header">
                  <span className={`sp-icon sp-icon-${platformClass}`}>{platformIcon}</span>
                  <span className="sp-author">{block.author}</span>
                </div>
                <div className="sp-body">{block.text}</div>
                {block.stats && <div className="sp-stats">{block.stats}</div>}
              </div>
            );

            return block.url
              ? <a key={i} href={block.url} target="_blank" rel="noopener noreferrer" className="sp-link">{inner}</a>
              : <div key={i}>{inner}</div>;
          }

          case "divider":
            return <hr key={i} className="article-divider" />;

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

Object.assign(window, { ArticleRenderer });
