/* MyAds. — Blog components (BlogTeaser, BlogIndex, BlogArticle) */
const {
  useState: useStateBlog,
  useEffect: useEffectBlog,
  useMemo: useMemoBlog,
} = React;

const TBlog = (lang) => window.MYADS_I18N[lang];
const PostT = (post, lang) =>
  post[lang] ||
  (lang === "es" ? post.en || post.fr : post.fr || post.en) ||
  post.nl;

/* ---------- date formatting ---------- */
function fmtDate(iso, lang) {
  try {
    const d = new Date(iso + "T00:00:00");
    return new Intl.DateTimeFormat(
      lang === "en" ? "en-GB" : lang === "nl" ? "nl-BE" : "fr-BE",
      {
        day: "numeric",
        month: "long",
        year: "numeric",
      },
    ).format(d);
  } catch (e) {
    return iso;
  }
}

/* ---------- tiny markdown renderer ---------- */
function renderInline(s) {
  // images first to avoid clashing with links
  s = s.replace(
    /!\[([^\]]*)\]\(([^)]+)\)/g,
    '<img src="$2" alt="$1" loading="lazy"/>',
  );
  // links
  s = s.replace(
    /\[([^\]]+)\]\(([^)]+)\)/g,
    '<a href="$2" target="_blank" rel="noopener">$1</a>',
  );
  // code
  s = s.replace(/`([^`]+)`/g, "<code>$1</code>");
  // bold then italic
  s = s.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
  s = s.replace(/\*([^*]+)\*/g, "<em>$1</em>");
  return s;
}

function MD({ source }) {
  if (!source) return null;
  const lines = source.replace(/\r\n/g, "\n").split("\n");
  const blocks = [];
  let i = 0;
  while (i < lines.length) {
    const line = lines[i];
    // blank
    if (!line.trim()) {
      i++;
      continue;
    }
    // hr
    if (/^---+$/.test(line.trim())) {
      blocks.push({ t: "hr" });
      i++;
      continue;
    }
    // heading
    const h = /^(#{1,3})\s+(.+)$/.exec(line);
    if (h) {
      blocks.push({ t: "h" + h[1].length, c: h[2] });
      i++;
      continue;
    }
    // quote
    if (/^>\s+/.test(line)) {
      let q = [];
      while (i < lines.length && /^>\s+/.test(lines[i])) {
        q.push(lines[i].replace(/^>\s+/, ""));
        i++;
      }
      blocks.push({ t: "quote", c: q.join(" ") });
      continue;
    }
    // list
    if (/^[-*]\s+/.test(line)) {
      let items = [];
      while (i < lines.length && /^[-*]\s+/.test(lines[i])) {
        items.push(lines[i].replace(/^[-*]\s+/, ""));
        i++;
      }
      blocks.push({ t: "ul", items });
      continue;
    }
    // table
    if (
      /^\|.*\|$/.test(line) &&
      i + 1 < lines.length &&
      /^\|[-:\s|]+\|$/.test(lines[i + 1])
    ) {
      const head = line
        .split("|")
        .slice(1, -1)
        .map((s) => s.trim());
      i += 2;
      const rows = [];
      while (i < lines.length && /^\|.*\|$/.test(lines[i])) {
        rows.push(
          lines[i]
            .split("|")
            .slice(1, -1)
            .map((s) => s.trim()),
        );
        i++;
      }
      blocks.push({ t: "table", head, rows });
      continue;
    }
    // paragraph (consume until blank)
    let p = [line];
    i++;
    while (
      i < lines.length &&
      lines[i].trim() &&
      !/^(#{1,3}\s+|>\s+|[-*]\s+|---+$|\|.*\|$)/.test(lines[i])
    ) {
      p.push(lines[i]);
      i++;
    }
    blocks.push({ t: "p", c: p.join(" ") });
  }
  return (
    <>
      {blocks.map((b, k) => {
        if (b.t === "hr") return <hr key={k} />;
        if (b.t === "h1")
          return (
            <h1
              key={k}
              dangerouslySetInnerHTML={{ __html: renderInline(b.c) }}
            />
          );
        if (b.t === "h2")
          return (
            <h2
              key={k}
              dangerouslySetInnerHTML={{ __html: renderInline(b.c) }}
            />
          );
        if (b.t === "h3")
          return (
            <h3
              key={k}
              dangerouslySetInnerHTML={{ __html: renderInline(b.c) }}
            />
          );
        if (b.t === "quote")
          return (
            <blockquote
              key={k}
              dangerouslySetInnerHTML={{ __html: renderInline(b.c) }}
            />
          );
        if (b.t === "ul")
          return (
            <ul key={k}>
              {b.items.map((it, j) => (
                <li
                  key={j}
                  dangerouslySetInnerHTML={{ __html: renderInline(it) }}
                />
              ))}
            </ul>
          );
        if (b.t === "table")
          return (
            <div className="md-table-wrap" key={k}>
              <table className="md-table">
                <thead>
                  <tr>
                    {b.head.map((c, j) => (
                      <th
                        key={j}
                        dangerouslySetInnerHTML={{ __html: renderInline(c) }}
                      />
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {b.rows.map((row, ri) => (
                    <tr key={ri}>
                      {row.map((c, ci) => (
                        <td
                          key={ci}
                          dangerouslySetInnerHTML={{ __html: renderInline(c) }}
                        />
                      ))}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          );
        return (
          <p key={k} dangerouslySetInnerHTML={{ __html: renderInline(b.c) }} />
        );
      })}
    </>
  );
}

/* ---------- author avatar (initials) ---------- */
function AuthorAvatar({ name }) {
  const initials = (name || "??")
    .split(" ")
    .map((p) => p[0])
    .slice(0, 2)
    .join("")
    .toUpperCase();
  // hash to color
  let h = 0;
  for (let i = 0; i < name.length; i++) h = (h * 31 + name.charCodeAt(i)) >>> 0;
  const hue = h % 360;
  return (
    <span
      className="author-avatar"
      style={{ background: `oklch(0.65 0.10 ${hue})` }}
      aria-hidden="true"
    >
      {initials}
    </span>
  );
}

/* ---------- cover placeholder ---------- */
function CoverPlaceholder({ post, lang }) {
  // deterministic color based on category
  const palette = {
    industry: ["oklch(0.32 0.06 220)", "oklch(0.52 0.08 200)"],
    product: ["oklch(0.30 0.05 160)", "oklch(0.50 0.09 165)"],
    data: ["oklch(0.28 0.07 280)", "oklch(0.48 0.10 295)"],
    "case-study": ["oklch(0.30 0.07 30)", "oklch(0.52 0.10 45)"],
    sustainability: ["oklch(0.28 0.06 145)", "oklch(0.48 0.09 150)"],
  };
  const [a, b] = palette[post.category] || palette.industry;
  const t = PostT(post, lang);
  return (
    <div
      className="blog-cover-ph"
      style={{ background: `linear-gradient(135deg, ${a}, ${b})` }}
      aria-hidden="true"
    >
      <div className="bcph-grid">
        {Array.from({ length: 36 }).map((_, i) => (
          <span key={i} />
        ))}
      </div>
      <div className="bcph-tag">{(t.tags || [post.category])[0]}</div>
    </div>
  );
}

/* ---------- card ---------- */
function PostCard({ post, lang, featured }) {
  const t = PostT(post, lang);
  const cats =
    window.MYADS_BLOG_CATEGORIES[lang] || window.MYADS_BLOG_CATEGORIES.fr;
  const readLabel =
    lang === "fr"
      ? "min de lecture"
      : lang === "nl"
        ? "min lezen"
        : lang === "es"
          ? "min de lectura"
          : "min read";
  return (
    <a
      href={"#blog/" + post.slug}
      className={"post-card" + (featured ? " featured" : "")}
    >
      {post.cover ? (
        <div
          className="post-cover"
          style={{ backgroundImage: `url('${post.cover}')` }}
        />
      ) : (
        <CoverPlaceholder post={post} lang={lang} />
      )}
      <div className="post-meta">
        <span className="post-cat">{cats[post.category] || post.category}</span>
        <span className="post-dot">·</span>
        <span>{fmtDate(post.date, lang)}</span>
        <span className="post-dot">·</span>
        <span>
          {t.read} {readLabel}
        </span>
      </div>
      <h3 className="post-title">{t.title}</h3>
      <p className="post-excerpt">{t.excerpt}</p>
      <div className="post-foot">
        <AuthorAvatar name={post.author.name} />
        <div className="post-author">
          <div className="pa-name">{post.author.name}</div>
        </div>
        <span className="post-arrow" aria-hidden="true">
          →
        </span>
      </div>
    </a>
  );
}

/* ---------- Home blog teaser (3 latest) ---------- */
function BlogTeaser({ lang }) {
  const posts = useMemoBlog(
    () =>
      [...window.MYADS_BLOG_POSTS]
        .sort((a, b) => b.date.localeCompare(a.date))
        .slice(0, 3),
    [],
  );
  const t = TBlog(lang);
  if (posts.length === 0) return null;
  const heading =
    lang === "fr"
      ? "Lectures"
      : lang === "nl"
        ? "Inzichten"
        : lang === "es"
          ? "Lecturas"
          : "Reads";
  const sub =
    lang === "fr"
      ? "Notes, analyses et cas concrets de notre équipe."
      : lang === "nl"
        ? "Notities, analyses en concrete cases van ons team."
        : lang === "es"
          ? "Notas, análisis y casos concretos de nuestro equipo."
          : "Notes, analysis and field cases from our team.";
  const all =
    lang === "fr"
      ? "Voir tous les articles"
      : lang === "nl"
        ? "Alle artikelen"
        : lang === "es"
          ? "Ver todos los artículos"
          : "All articles";
  return (
    <section
      id="blog-teaser"
      className="section-pad blog-teaser-section"
      data-screen-label="11 Blog teaser"
    >
      <div className="container">
        <div className="blog-teaser-head">
          <div>
            <div className="kicker">{heading.toUpperCase()}</div>
            <h2 className="section-h2">
              {lang === "fr" ? (
                <>
                  Le terrain, <em>en clair.</em>
                </>
              ) : lang === "nl" ? (
                <>
                  Het veld, <em>helder.</em>
                </>
              ) : lang === "es" ? (
                <>
                  El terreno, <em>claro.</em>
                </>
              ) : (
                <>
                  The field, <em>in plain terms.</em>
                </>
              )}
            </h2>
            <p className="section-sub">{sub}</p>
          </div>
          <a href="#blog" className="btn btn-ghost btn-sm">
            {all} <span className="arrow">→</span>
          </a>
        </div>
        <div className="blog-grid">
          {posts.map((p) => (
            <PostCard key={p.slug} post={p} lang={lang} />
          ))}
        </div>
        <div className="models-cta reveal">
          <p>
            {lang === "fr"
              ? "Envie d'appliquer ces idées à vos campagnes ?"
              : lang === "nl"
                ? "Klaar om deze inzichten op uw campagnes toe te passen?"
                : lang === "es"
                  ? "¿Quieres aplicar estas ideas a tus campañas?"
                  : "Ready to apply these ideas to your campaigns?"}
          </p>
          <a className="btn btn-primary" href="#contact">
            {lang === "fr"
              ? "Parlons de votre projet"
              : lang === "nl"
                ? "Praat over uw project"
                : lang === "es"
                  ? "Hablemos de tu proyecto"
                  : "Let's talk about your project"}{" "}
            <span className="arrow">→</span>
          </a>
        </div>
      </div>
    </section>
  );
}

/* ---------- Full blog index page ---------- */
function BlogIndex({ lang }) {
  const cats =
    window.MYADS_BLOG_CATEGORIES[lang] || window.MYADS_BLOG_CATEGORIES.fr;
  const allPosts = useMemoBlog(
    () =>
      [...window.MYADS_BLOG_POSTS].sort((a, b) => b.date.localeCompare(a.date)),
    [],
  );
  const [active, setActive] = useStateBlog("all");
  const [q, setQ] = useStateBlog("");

  const filtered = useMemoBlog(() => {
    return allPosts.filter((p) => {
      if (active !== "all" && p.category !== active) return false;
      if (q.trim()) {
        const t = PostT(p, lang);
        const hay = (
          t.title +
          " " +
          t.excerpt +
          " " +
          (t.tags || []).join(" ") +
          " " +
          p.author.name
        ).toLowerCase();
        if (!hay.includes(q.toLowerCase())) return false;
      }
      return true;
    });
  }, [active, q, lang]);

  const featured = filtered[0];
  const rest = filtered.slice(1);

  const searchPh =
    lang === "fr"
      ? "Rechercher un article…"
      : lang === "nl"
        ? "Zoek een artikel…"
        : lang === "es"
          ? "Buscar un artículo…"
          : "Search articles…";
  const empties =
    lang === "fr"
      ? "Aucun article pour l'instant. Les nouveaux articles publiés apparaîtront ici."
      : lang === "nl"
        ? "Nog geen artikelen. Nieuw gepubliceerde artikelen verschijnen hier."
        : lang === "es"
          ? "Aún no hay artículos. Los nuevos artículos publicados aparecerán aquí."
          : "No articles yet. Newly published articles will appear here.";
  const noRes =
    allPosts.length === 0
      ? empties
      : lang === "fr"
        ? "Aucun article ne correspond."
        : lang === "nl"
          ? "Geen artikelen gevonden."
          : lang === "es"
            ? "Ningún artículo coincide."
            : "No matching articles.";
  const heroKicker = lang === "fr" ? "BLOG MYADS" : "MYADS BLOG";
  const heroH2 =
    lang === "fr" ? (
      <>
        Le marché belge, <em>analysé.</em>
      </>
    ) : lang === "nl" ? (
      <>
        De Belgische markt, <em>geanalyseerd.</em>
      </>
    ) : lang === "es" ? (
      <>
        El mercado belga, <em>analizado.</em>
      </>
    ) : (
      <>
        The Belgian market, <em>analysed.</em>
      </>
    );
  const heroSub =
    lang === "fr"
      ? "Industrie, produits, data, IA, cas clients, durabilité — sans jargon."
      : lang === "nl"
        ? "Industrie, producten, data, AI, klantcases, duurzaamheid — zonder jargon."
        : lang === "es"
          ? "Industria, producto, data, IA, casos de éxito, sostenibilidad — sin jerga."
          : "Industry, product, data, AI, case studies, sustainability — no jargon.";

  return (
    <main className="blog-page">
      <section className="blog-hero" data-screen-label="01 Blog hero">
        <div className="container">
          <a href="#top" className="blog-back">
            ←{" "}
            {lang === "fr"
              ? "Retour à l'accueil"
              : lang === "nl"
                ? "Terug naar home"
                : lang === "es"
                  ? "Volver al inicio"
                  : "Back to home"}
          </a>
          <div className="kicker">{heroKicker}</div>
          <h1 className="blog-h1">{heroH2}</h1>
          <p className="blog-sub">{heroSub}</p>
        </div>
      </section>

      <section className="blog-toolbar">
        <div className="container">
          <div className="blog-cats" role="tablist">
            {Object.entries(cats).map(([k, label]) => (
              <button
                key={k}
                role="tab"
                aria-selected={active === k}
                className={"blog-cat" + (active === k ? " active" : "")}
                onClick={() => setActive(k)}
              >
                {label}
              </button>
            ))}
          </div>
          <div className="blog-search">
            <span className="bs-icon" aria-hidden="true">
              ⌕
            </span>
            <input
              type="search"
              value={q}
              onChange={(e) => setQ(e.target.value)}
              placeholder={searchPh}
              aria-label={searchPh}
            />
          </div>
        </div>
      </section>

      <section className="blog-list section-pad">
        <div className="container">
          {filtered.length === 0 ? (
            <div className="blog-empty">{noRes}</div>
          ) : (
            <>
              {featured && (
                <div className="blog-featured">
                  <PostCard post={featured} lang={lang} featured />
                </div>
              )}
              {rest.length > 0 && (
                <div className="blog-grid">
                  {rest.map((p) => (
                    <PostCard key={p.slug} post={p} lang={lang} />
                  ))}
                </div>
              )}
            </>
          )}
        </div>
      </section>
    </main>
  );
}

/* ---------- Single article ---------- */
function BlogArticle({ slug, lang, onCta }) {
  const post = window.MYADS_BLOG_POSTS.find((p) => p.slug === slug);
  useEffectBlog(() => {
    window.scrollTo({ top: 0, behavior: "instant" });
  }, [slug]);

  if (!post) {
    return (
      <main className="blog-page">
        <section className="blog-hero">
          <div className="container">
            <a href="#blog" className="blog-back">
              ← Blog
            </a>
            <h1 className="blog-h1">404</h1>
            <p className="blog-sub">
              {lang === "fr"
                ? "Article introuvable."
                : lang === "nl"
                  ? "Artikel niet gevonden."
                  : lang === "es"
                    ? "Artículo no encontrado."
                    : "Article not found."}
            </p>
          </div>
        </section>
      </main>
    );
  }

  const t = PostT(post, lang);
  const cats =
    window.MYADS_BLOG_CATEGORIES[lang] || window.MYADS_BLOG_CATEGORIES.fr;
  const readLabel =
    lang === "fr"
      ? "min de lecture"
      : lang === "nl"
        ? "min lezen"
        : lang === "es"
          ? "min de lectura"
          : "min read";

  // related: same category, exclude self, latest 3
  const related = [...window.MYADS_BLOG_POSTS]
    .filter((p) => p.slug !== slug && p.category === post.category)
    .sort((a, b) => b.date.localeCompare(a.date))
    .slice(0, 3);
  const relatedFallback = [...window.MYADS_BLOG_POSTS]
    .filter((p) => p.slug !== slug)
    .sort((a, b) => b.date.localeCompare(a.date))
    .slice(0, 3);
  const finalRelated = related.length > 0 ? related : relatedFallback;

  const ctaH =
    lang === "fr"
      ? "Envie d'en discuter ?"
      : lang === "nl"
        ? "Zin om te praten?"
        : lang === "es"
          ? "¿Quieres hablarlo?"
          : "Want to discuss?";
  const ctaP =
    lang === "fr"
      ? "Un de nos experts MyAds revient vers vous sous 24h ouvrées avec une recommandation média sur mesure."
      : lang === "nl"
        ? "Een MyAds-expert komt binnen 24 werkuren bij u terug met een advies op maat."
        : lang === "es"
          ? "Un experto de MyAds te contactará en 24h laborables con una recomendación de medios a medida."
          : "A MyAds expert will reach out within 24 business hours with a tailor-made recommendation.";
  const ctaB =
    lang === "fr"
      ? "Réserver une démo"
      : lang === "nl"
        ? "Demo boeken"
        : lang === "es"
          ? "Reservar una demo"
          : "Book a demo";
  const relTitle =
    lang === "fr"
      ? "À lire aussi"
      : lang === "nl"
        ? "Lees ook"
        : lang === "es"
          ? "También para leer"
          : "Read also";
  const shareLabel =
    lang === "fr"
      ? "Partager"
      : lang === "nl"
        ? "Delen"
        : lang === "es"
          ? "Compartir"
          : "Share";

  return (
    <main className="blog-page article-page">
      <article>
        <header className="article-hero" data-screen-label="01 Article hero">
          <div className="container article-container">
            <a href="#blog" className="blog-back">
              ←{" "}
              {lang === "fr"
                ? "Tous les articles"
                : lang === "nl"
                  ? "Alle artikelen"
                  : lang === "es"
                    ? "Todos los artículos"
                    : "All articles"}
            </a>
            <div className="article-meta-top">
              <span className="post-cat">
                {cats[post.category] || post.category}
              </span>
              <span className="post-dot">·</span>
              <span>{fmtDate(post.date, lang)}</span>
              <span className="post-dot">·</span>
              <span>
                {t.read} {readLabel}
              </span>
            </div>
            <h1 className="article-title">{t.title}</h1>
            <p className="article-excerpt">{t.excerpt}</p>
            <div className="article-author">
              <AuthorAvatar name={post.author.name} />
              <div>
                <div className="pa-name">{post.author.name}</div>
              </div>
              <div className="article-share" aria-label={shareLabel}>
                <button
                  className="share-btn"
                  onClick={() =>
                    navigator.clipboard?.writeText(window.location.href)
                  }
                >
                  ⧉ {shareLabel}
                </button>
              </div>
            </div>
          </div>
        </header>

        <div className="article-body">
          <div className="container article-container">
            <MD source={t.body} />
            <div className="article-tags">
              {(t.tags || []).map((tag) => (
                <span key={tag} className="tag">
                  #{tag}
                </span>
              ))}
            </div>
          </div>
        </div>

        <section className="article-cta">
          <div className="container article-container">
            <div className="acta-card">
              <div>
                <h3>{ctaH}</h3>
                <p>{ctaP}</p>
              </div>
              <button className="btn btn-primary" onClick={onCta}>
                {ctaB} <span className="arrow">→</span>
              </button>
            </div>
          </div>
        </section>

        <section className="article-related section-pad">
          <div className="container">
            <h2 className="section-h2 small">{relTitle}</h2>
            <div className="blog-grid">
              {finalRelated.map((p) => (
                <PostCard key={p.slug} post={p} lang={lang} />
              ))}
            </div>
          </div>
        </section>
      </article>
    </main>
  );
}

// expose to window for app.jsx
Object.assign(window, {
  BlogTeaser,
  BlogIndex,
  BlogArticle,
  LegalPage,
  MD,
  PostCard,
  fmtDate,
});

/* ---------- Legal pages (Belgium) ---------- */
function LegalPage({ slug, lang }) {
  const all =
    (window.MYADS_LEGAL && window.MYADS_LEGAL[lang]) ||
    (window.MYADS_LEGAL && window.MYADS_LEGAL.fr) ||
    {};
  const page = all[slug];
  useEffectBlog(() => {
    window.scrollTo({ top: 0, behavior: "instant" });
  }, [slug]);

  const i18n = {
    fr: {
      home: "Accueil",
      legal: "Légal",
      updated: "Dernière mise à jour",
      notFound: "Page non trouvée",
      back: "← Retour à l'accueil",
    },
    nl: {
      home: "Home",
      legal: "Juridisch",
      updated: "Laatst bijgewerkt",
      notFound: "Pagina niet gevonden",
      back: "← Terug naar home",
    },
    en: {
      home: "Home",
      legal: "Legal",
      updated: "Last updated",
      notFound: "Page not found",
      back: "← Back to home",
    },
    es: {
      home: "Inicio",
      legal: "Legal",
      updated: "Última actualización",
      notFound: "Página no encontrada",
      back: "← Volver al inicio",
    },
  };
  const L = i18n[lang] || i18n.fr;

  if (!page) {
    return (
      <main className="legal-shell">
        <div className="container" style={{ padding: "120px 0 80px" }}>
          <h1 style={{ fontFamily: "var(--serif)", fontSize: 48 }}>
            {L.notFound}
          </h1>
          <p style={{ marginTop: 16 }}>
            <a href="#" style={{ color: "var(--accent)" }}>
              {L.back}
            </a>
          </p>
        </div>
      </main>
    );
  }

  const dateFmt = (d) => {
    try {
      return new Date(d).toLocaleDateString(
        lang === "fr"
          ? "fr-BE"
          : lang === "nl"
            ? "nl-BE"
            : lang === "es"
              ? "es-ES"
              : "en-GB",
        { year: "numeric", month: "long", day: "numeric" },
      );
    } catch (e) {
      return d;
    }
  };

  const otherSlugs = Object.keys(all).filter((s) => s !== slug);

  return (
    <main className="legal-shell">
      <div className="legal-hero">
        <div className="container">
          <div className="legal-crumbs">
            <a href="#">{L.home}</a> <span>›</span> <span>{L.legal}</span>{" "}
            <span>›</span> <span className="curr">{page.title}</span>
          </div>
          <h1 className="legal-title">{page.title}</h1>
          <div className="legal-meta">
            {L.updated} · <time>{dateFmt(page.updated)}</time>
          </div>
        </div>
      </div>
      <div className="article-body">
        <div className="container article-container">
          <MD source={page.body} />
          <hr
            style={{
              border: "none",
              borderTop: "1px solid var(--line)",
              margin: "60px 0 30px",
            }}
          />
          <div className="legal-other">
            {otherSlugs.map((s) => (
              <a key={s} href={`#legal/${s}`} className="legal-other-link">
                {all[s].title} →
              </a>
            ))}
          </div>
        </div>
      </div>
    </main>
  );
}
