/* global React, ReactDOM, I18N, BLOG_ARTICLES, BlogNav, BlogFooter, ArticleCard, CoverArt, useAppearance, BIcon */

const { useState, useMemo, useEffect } = React;

const ART_T = {
  en: { back: "Back to blog", source: "Source", related: "More articles", share: "Share", cta_title: "Need help building this for your stack?", cta_body: "Book a 30-minute discovery call — we'll talk through your cloud, security and AI roadmap.", cta_btn: "Book a call" },
  es: { back: "Volver al blog", source: "Fuente", related: "Más artículos", share: "Compartir", cta_title: "¿Necesitas ayuda implementando esto en tu stack?", cta_body: "Agenda una llamada de 30 minutos — hablamos de tu cloud, seguridad y roadmap de IA.", cta_btn: "Agendar llamada" },
};

/* ---------- Minimal Markdown renderer ---------- */
// Handles: ## H2, ### H3, **bold**, paragraphs, code fences, inline `code`,
// numbered/bullet lists. No links/images needed for samples.
function renderMarkdown(md) {
  const lines = md.split(/\r?\n/);
  const blocks = [];
  let i = 0;
  while (i < lines.length) {
    const ln = lines[i];
    if (ln.startsWith("```")) {
      const lang = ln.slice(3).trim();
      const code = [];
      i++;
      while (i < lines.length && !lines[i].startsWith("```")) { code.push(lines[i]); i++; }
      i++;
      blocks.push({ type: "code", lang, content: code.join("\n") });
      continue;
    }
    if (ln.startsWith("### ")) { blocks.push({ type: "h3", content: ln.slice(4) }); i++; continue; }
    if (ln.startsWith("## "))  { blocks.push({ type: "h2", content: ln.slice(3) }); i++; continue; }
    if (/^\d+\.\s/.test(ln)) {
      const items = [];
      while (i < lines.length && /^\d+\.\s/.test(lines[i])) { items.push(lines[i].replace(/^\d+\.\s/, "")); i++; }
      blocks.push({ type: "ol", items });
      continue;
    }
    if (ln.startsWith("- ")) {
      const items = [];
      while (i < lines.length && lines[i].startsWith("- ")) { items.push(lines[i].slice(2)); i++; }
      blocks.push({ type: "ul", items });
      continue;
    }
    if (ln.trim() === "") { i++; continue; }
    // paragraph: consume until blank line or special block
    const p = [ln];
    i++;
    while (i < lines.length && lines[i].trim() !== "" && !lines[i].startsWith("##") && !lines[i].startsWith("- ") && !/^\d+\.\s/.test(lines[i]) && !lines[i].startsWith("```")) {
      p.push(lines[i]); i++;
    }
    blocks.push({ type: "p", content: p.join(" ") });
  }
  return blocks;
}

function renderInline(s) {
  // Split into segments handling **bold** and `code`
  const parts = [];
  let buf = "";
  for (let i = 0; i < s.length; i++) {
    if (s.slice(i, i + 2) === "**") {
      if (buf) parts.push(buf), buf = "";
      const end = s.indexOf("**", i + 2);
      if (end === -1) { buf += s[i]; continue; }
      parts.push(<strong key={parts.length}>{s.slice(i + 2, end)}</strong>);
      i = end + 1;
    } else if (s[i] === "`") {
      if (buf) parts.push(buf), buf = "";
      const end = s.indexOf("`", i + 1);
      if (end === -1) { buf += s[i]; continue; }
      parts.push(<code key={parts.length}>{s.slice(i + 1, end)}</code>);
      i = end;
    } else {
      buf += s[i];
    }
  }
  if (buf) parts.push(buf);
  return parts;
}

function MarkdownBody({ source }) {
  const blocks = useMemo(() => renderMarkdown(source), [source]);
  return (
    <div className="article-body">
      {blocks.map((b, i) => {
        switch (b.type) {
          case "h2": return <h2 key={i}>{renderInline(b.content)}</h2>;
          case "h3": return <h3 key={i}>{renderInline(b.content)}</h3>;
          case "p":  return <p key={i}>{renderInline(b.content)}</p>;
          case "ul": return <ul key={i}>{b.items.map((it, j) => <li key={j}>{renderInline(it)}</li>)}</ul>;
          case "ol": return <ol key={i}>{b.items.map((it, j) => <li key={j}>{renderInline(it)}</li>)}</ol>;
          case "code": return <pre key={i}><code>{b.content}</code></pre>;
          default: return null;
        }
      })}
    </div>
  );
}

function ArticlePage({ slug }) {
  const { theme, setTheme, lang, setLang } = useAppearance();
  const t = ART_T[lang];
  const article = window.BLOG_ARTICLES.find(a => a.slug === slug);

  useEffect(() => {
    if (article) document.title = `${article.title} — ClowdSecOps Blog`;
  }, [article]);

  if (!article) {
    return (
      <>
        <BlogNav lang={lang} setLang={setLang} theme={theme} setTheme={setTheme} />
        <main><div className="wrap" style={{ padding: "120px 0" }}><h1>404 — article not found</h1><a href="blog" className="btn btn-ghost btn-lg" style={{ marginTop: 24 }}>{t.back}</a></div></main>
      </>
    );
  }

  const dateLabel = new Date(article.published_at).toLocaleDateString(lang === "es" ? "es-ES" : "en-US", { day: "numeric", month: "long", year: "numeric" });
  const minLabel = lang === "es" ? `${article.reading_time_min} min` : `${article.reading_time_min} min read`;
  const related = window.BLOG_ARTICLES.filter(a => a.slug !== article.slug).slice(0, 3);

  return (
    <>
      <BlogNav lang={lang} setLang={setLang} theme={theme} setTheme={setTheme} />
      <main>
        <article className="article-page">
          <div className="wrap article-wrap">
            <a href="blog" className="article-back"><span><BIcon.back /></span>{t.back}</a>

            <header className="article-header">
              <div className="article-tags">
                {article.tags.map((t) => <span key={t}>{t}</span>)}
                <span className="lang-pill">{article.language.toUpperCase()}</span>
              </div>
              <h1 className="article-title">{article.title}</h1>
              <p className="article-deck">{article.excerpt}</p>
              <div className="article-meta">
                <span>{dateLabel}</span>
                <span>·</span>
                <span>{minLabel}</span>
                {article.source && (
                  <>
                    <span>·</span>
                    <span>{t.source}: <a href={article.source.url} target="_blank" rel="noreferrer">{article.source.name} <BIcon.external /></a></span>
                  </>
                )}
              </div>
            </header>

            <div className="article-cover" style={{ background: `color-mix(in oklab, ${article.cover_color} 14%, var(--bg-elev))` }}>
              <CoverArt color={article.cover_color} pattern={article.cover_pattern} />
            </div>

            <MarkdownBody source={article.body} />

            <div className="article-cta">
              <h3>{t.cta_title}</h3>
              <p>{t.cta_body}</p>
              <a href={window.BOOKING_URL} target="_blank" rel="noreferrer" className="btn btn-primary btn-lg">{t.cta_btn}<span className="arrow"><BIcon.arrow /></span></a>
            </div>
          </div>

          {related.length > 0 && (
            <section className="related">
              <div className="wrap">
                <span className="eyebrow">{t.related}</span>
                <div className="article-grid" style={{ marginTop: 28 }}>
                  {related.map((a) => <ArticleCard key={a.slug} a={a} />)}
                </div>
              </div>
            </section>
          )}
        </article>
      </main>
      <BlogFooter lang={lang} />
    </>
  );
}

// Slug is set by each per-article HTML page on window.__SLUG before this script runs
const slug = window.__SLUG;
ReactDOM.createRoot(document.getElementById("root")).render(<ArticlePage slug={slug} />);
