// Writing: bilingual blog index (/writing) + single article (/writing/<slug>)
const LINKEDIN_URL = "https://www.linkedin.com/in/vlad-tudor-18090a1a2";

function articleBySlug(slug) {
  return (window.BLOG || []).find((a) => a.slug === slug) || null;
}
function isCoverGraphic(src) {
  return typeof src === "string" && src.endsWith(".svg");
}
// Article URLs are two-segment (/writing/<slug>), so relative "assets/..." paths
// would resolve against /writing/. Force root-absolute so images load everywhere.
function blogAsset(src) {
  return typeof src === "string" && src.indexOf("assets/") === 0 ? "/" + src : src;
}
// Writing copy in a given language, falling back to the passed copy.
function writingCopy(lang, fallback) {
  return (window.CONTENT && window.CONTENT[lang] && window.CONTENT[lang].writing) || fallback;
}
// Minimal inline **bold** rendering for body/list/table/faq text.
function renderRich(text) {
  if (typeof text !== "string" || text.indexOf("**") === -1) return text;
  return text.split("**").map((part, i) => (i % 2 === 1 ? <strong key={i}>{part}</strong> : part));
}

function ArticleMeta({ a }) {
  return (
    <div className="article__meta">
      <span>{a.dateLabel}</span>
      <span className="article__meta-sep" aria-hidden="true">·</span>
      <span>{a.readingMins} min</span>
      {a.tags && a.tags.length > 0 && (
        <React.Fragment>
          <span className="article__meta-sep" aria-hidden="true">·</span>
          <span className="article__tags">{a.tags.slice(0, 3).join(" / ")}</span>
        </React.Fragment>
      )}
    </div>);

}

function ArticleCard({ a }) {
  const href = "/writing/" + a.slug;
  return (
    <a
      href={href}
      className="wcard"
      onClick={(e) => { e.preventDefault(); goTo(href); }}>
      <div className="wcard__cover">
        <CoverArt slug={a.slug} variant="card" />
      </div>
      <div className="wcard__body">
        <div className="wcard__kicker">
          <span>{a.dateLabel}</span>
          {a.tags && a.tags[0] && <span className="wcard__tag">{a.tags[0]}</span>}
        </div>
        <h3 className="wcard__title">{a.title}</h3>
        <p className="wcard__dek">{a.dek}</p>
        <span className="wcard__cta">Read <span aria-hidden="true">→</span></span>
      </div>
    </a>);

}

function LangToggle({ lang, onPick }) {
  return (
    <div className="lang-toggle" role="group" aria-label="Language">
      {["en", "ro"].map((l) => (
        <button
          key={l}
          className={"lang-toggle__btn" + (lang === l ? " is-active" : "")}
          onClick={() => onPick(l)}
          aria-pressed={lang === l}>
          {l.toUpperCase()}
        </button>
      ))}
    </div>);

}

function FeaturedCard({ a }) {
  const href = "/writing/" + a.slug;
  return (
    <a
      href={href}
      className="wfeatured"
      onClick={(e) => { e.preventDefault(); goTo(href); }}>
      <div className="wfeatured__art">
        <CoverArt slug={a.slug} variant="feature" />
        <span className="wfeatured__badge">Latest</span>
      </div>
      <div className="wfeatured__text">
        <div className="wcard__kicker">
          <span>{a.dateLabel}</span>
          <span className="article__meta-sep" aria-hidden="true">·</span>
          <span>{a.readingMins} min</span>
          {a.tags && a.tags[0] && <span className="wcard__tag">{a.tags[0]}</span>}
        </div>
        <h2 className="wfeatured__title">{a.title}</h2>
        <p className="wfeatured__dek">{a.dek}</p>
        <span className="wcard__cta">Read the essay <span aria-hidden="true">→</span></span>
      </div>
    </a>);

}

function WritingIndex({ c }) {
  const [lang, setLang] = React.useState(() => {
    try { return localStorage.getItem("blogLang") || "en"; } catch (e) { return "en"; }
  });
  const pick = (l) => { setLang(l); try { localStorage.setItem("blogLang", l); } catch (e) {} };
  const wc = writingCopy(lang, c);
  const list = (window.BLOG || []).
    filter((a) => (a.lang || "en") === lang).
    sort((a, b) => (a.date < b.date ? 1 : -1));
  const featured = list[0] || null;
  const rest = featured ? list.slice(1) : list;

  return (
    <div className="page page--narrow-wide">
      <header className="writing-head">
        <Eyebrow>{wc.eyebrow}</Eyebrow>
        <h1 className="writing-head__title">{wc.title}</h1>
        <p className="writing-head__lead">{wc.lead}</p>
        <LangToggle lang={lang} onPick={pick} />
      </header>
      {featured && <FeaturedCard a={featured} />}
      <div className="wlist-head">
        <span className="wlist-head__label">{wc.cta_more}</span>
        <span className="wlist-head__rule" aria-hidden="true" />
        <span className="wlist-head__count">{rest.length}</span>
      </div>
      <div className="wlist">
        {rest.map((a) => <ArticleCard key={a.slug} a={a} />)}
      </div>
    </div>);

}

function ArticleBlock({ b }) {
  switch (b.t) {
    case "h":
    case "h2":
      return <h2 className="article__h">{b.x}</h2>;
    case "h3":
      return <h3 className="article__h3">{b.x}</h3>;
    case "ul":
      return (
        <ul className="article__ul">
          {b.items.map((it, i) => <li key={i}>{renderRich(it)}</li>)}
        </ul>);

    case "table":
      return (
        <div className="article__table-wrap">
          <table className="article__table">
            <thead>
              <tr>{b.headers.map((h, i) => <th key={i}>{renderRich(h)}</th>)}</tr>
            </thead>
            <tbody>
              {b.rows.map((r, ri) => <tr key={ri}>{r.map((cell, ci) => <td key={ci}>{renderRich(cell)}</td>)}</tr>)}
            </tbody>
          </table>
        </div>);

    case "img":
      return (
        <figure className="article__fig">
          <img src={blogAsset(b.src)} alt={b.alt || ""} loading="lazy" />
          {b.cap && <figcaption className="article__cap">{b.cap}</figcaption>}
        </figure>);

    case "quote":
      return <PullQuote quote={b.x} variant="inline" />;
    default:
      return <p className="article__p">{renderRich(b.x)}</p>;
  }
}

function ReadingProgress() {
  const [p, setP] = React.useState(0);
  React.useEffect(() => {
    const onScroll = () => {
      const h = document.documentElement;
      const max = (h.scrollHeight - h.clientHeight) || 1;
      setP(Math.min(1, Math.max(0, (h.scrollTop || window.scrollY || 0) / max)));
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    onScroll();
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
    };
  }, []);
  return (
    <div className="reading-bar" aria-hidden="true">
      <div className="reading-bar__fill" style={{ transform: "scaleX(" + p + ")" }} />
    </div>);

}

function ArticleView({ a, c }) {
  const cw = writingCopy(a.lang || "en", c);
  return (
    <article className="page page--article">
      <ReadingProgress />
      <div className="article__top">
        <a
          href="/writing"
          className="article__back"
          onClick={(e) => { e.preventDefault(); goTo("/writing"); }}>
          ← {cw.title}
        </a>
        {a.alt && (
          <div className="lang-toggle lang-toggle--sm" role="group" aria-label="Language">
            <span className="lang-toggle__btn is-active">{(a.lang || "en").toUpperCase()}</span>
            <a
              className="lang-toggle__btn"
              href={"/writing/" + a.alt}
              onClick={(e) => { e.preventDefault(); goTo("/writing/" + a.alt); }}>
              {(a.lang === "ro" ? "EN" : "RO")}
            </a>
          </div>
        )}
      </div>

      <header className="article__header">
        {a.tags && a.tags[0] && <Eyebrow>{a.tags[0]}</Eyebrow>}
        <h1 className="article__title">{a.title}</h1>
        <p className="article__dek">{a.dek}</p>
        <ArticleMeta a={a} />
      </header>

      <div className="article__cover">
        <CoverArt slug={a.slug} variant="hero" />
      </div>

      <div className="article__body">
        {a.body.map((b, i) => <ArticleBlock key={i} b={b} />)}
      </div>

      {a.faq && a.faq.length > 0 && (
        <section className="article__faq">
          <h2 className="article__h">{cw.faq_title}</h2>
          {a.faq.map((f, i) => (
            <div className="faq-item" key={i}>
              <h3 className="faq-item__q">{f.q}</h3>
              <div className="faq-item__a">{renderRich(f.a)}</div>
            </div>
          ))}
        </section>
      )}

      <footer className="article__foot">
        <div className="consult-cta">
          <span className="consult-cta__label">{cw.cta_consult_label}</span>
          <h2 className="consult-cta__title">{cw.cta_consult_title}</h2>
          <p className="consult-cta__body">{cw.cta_consult_body}</p>
          <div className="cta-row" style={{ marginTop: 22 }}>
            <Btn kind="primary" href={cw.cta_consult_href}>{cw.cta_consult_button}</Btn>
            <Btn kind="ghost" href="/writing">{cw.cta_more}</Btn>
          </div>
        </div>
      </footer>
    </article>);

}

function WritingNotFound({ c }) {
  return (
    <div className="page page--narrow" style={{ paddingTop: 120, paddingBottom: 120 }}>
      <Eyebrow>404</Eyebrow>
      <h1 className="writing-head__title">{c.notfound}</h1>
      <div className="cta-row" style={{ marginTop: 24 }}>
        <Btn kind="primary" href="/writing">{c.cta_more}</Btn>
      </div>
    </div>);

}

function WritingPage({ copy, slug }) {
  const c = copy.writing;
  if (slug) {
    const a = articleBySlug(slug);
    if (!a) return <section className="section"><WritingNotFound c={c} /></section>;
    return <section className="section"><ArticleView a={a} c={c} /></section>;
  }
  return <section className="section"><WritingIndex c={c} /></section>;
}

Object.assign(window, { WritingPage });
