/* Long-form article reader.
   Content comes from window.ARTICLES (articles-data.js, generated from the
   uploaded PHYOMIC.AG documents). Uses the site's --font/--colour tokens so
   it inherits Work Sans / Inter and the --teal accent tweak. */

/* ---- turn bare URLs / domains in reference lines into links ---- */
function linkify(text) {
  const parts = String(text).split(/(\bhttps?:\/\/[^\s]+|\bwww\.[^\s]+|\b[a-z0-9-]+\.(?:com|org|net|gov|edu)[^\s]*)/gi);
  return parts.map((p, i) => {
    if (/^(https?:\/\/|www\.)/i.test(p) || /^[a-z0-9-]+\.(com|org|net|gov|edu)/i.test(p)) {
      const href = p.startsWith("http") ? p : "https://" + p;
      return <a key={i} href={href} target="_blank" rel="noopener noreferrer" style={{ color: "var(--teal-deep)", wordBreak: "break-word" }}>{p}</a>;
    }
    return p;
  });
}


/* ============ ARTICLE READER ============ */
function Article({ id, onNav }) {
  const Container = window.Container;
  const narrow = window.useNarrow();
  const a = (window.ARTICLES || {})[id];
  React.useEffect(() => { window.scrollTo({ top: 0, behavior: "instant" }); }, [id]);
  const [pg, setPg] = React.useState(0);
  React.useEffect(() => { setPg(0); }, [id]);

  if (!a) {
    return (
      <main style={{ paddingBlock: 120 }}>
        <Container style={{ maxWidth: 760, textAlign: "center" }}>
          <p style={{ fontFamily: "var(--font-body)", color: "var(--stone)" }}>Article not found.</p>
          <a onClick={() => onNav("home")} style={{ color: "var(--teal-deep)", cursor: "pointer" }}>← Back to home</a>
        </Container>
      </main>
    );
  }

  const isEra = false;
  const backTo = "home";
  const backLabel = "Home";

  /* Long-form governance / legal pages (Board, Procurement, Legal) carry
     dozens of headings: several distinct documents in one page, split by
     "PAGE N" markers. Give them real hierarchy + an in-page contents rail
     so they scan instead of reading as one flat wall. */
  const hasPage = a.blocks.some((b) => b.type === "h" && /^page\b/i.test((b.text || "").trim()));
  const longForm = a.blocks.length > 30 || hasPage;
  const heads = [];
  let afterPage = false;
  const leveled = a.blocks.map((b, i) => {
    if (b.type !== "h") { afterPage = false; return { ...b, _i: i }; }
    const id = "sec-" + i;
    let level = 2;
    if (longForm) {
      if (/^page\b/i.test((b.text || "").trim())) { level = 0; afterPage = true; }
      else if (afterPage) { level = 1; afterPage = false; }
      else { level = 2; afterPage = false; }
      if (hasPage ? level === 1 : true) heads.push({ id, text: b.text, level });
    }
    return { ...b, _i: i, level, id };
  });
  /* When the page carries PAGE markers, paginate for real: one document per
     page, numbered nav at the foot. Otherwise fall back to the scroll + TOC. */
  const pages = [];
  if (hasPage) {
    leveled.forEach((b) => {
      if (b.type === "h" && b.level === 0) { pages.push({ label: b.text, title: null, blocks: [] }); }
      else if (pages.length) {
        const p = pages[pages.length - 1];
        if (b.type === "h" && b.level === 1 && !p.title) p.title = b.text;
        p.blocks.push(b);
      }
    });
  }
  const paged = pages.length >= 2;
  const curPage = paged ? Math.min(pg, pages.length - 1) : 0;
  const changePage = (n) => { setPg(n); window.scrollTo({ top: 0, behavior: "instant" }); };
  const showTOC = !paged && longForm && heads.length >= 3;
  const goTo = (id) => {
    const el = document.getElementById(id);
    if (el) window.scrollTo(0, el.getBoundingClientRect().top + window.scrollY - 96);
  };

  const hStyle = { fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 26, lineHeight: 1.25, letterSpacing: "-0.01em", color: "var(--navy)", margin: "44px 0 4px" };
  const docTitleStyle = { fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 28, lineHeight: 1.2, letterSpacing: "-0.01em", color: "var(--navy)", margin: "16px 0 6px" };
  const subStyle = { fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 20, lineHeight: 1.3, color: "var(--navy)", margin: "34px 0 2px" };
  const pStyle = { fontFamily: "var(--font-body)", fontSize: 18, lineHeight: 1.75, color: "var(--charcoal)", margin: "18px 0 0" };
  const liStyle = { fontFamily: "var(--font-body)", fontSize: 17, lineHeight: 1.6, color: "var(--charcoal)", marginBottom: 10 };

  const renderBlock = (b) => {
    const i = b._i;
    if (b.type === "h") {
      if (!longForm) return <h2 key={i} id={b.id} style={hStyle}>{b.text}</h2>;
      if (b.level === 0) return (
        <div key={i} id={b.id} style={{ margin: "76px 0 0", borderTop: "2px solid var(--gold)", paddingTop: 14 }}>
          <span style={{ fontFamily: "var(--font-body)", fontWeight: 700, fontSize: 12.5, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--gold)" }}>{b.text}</span>
        </div>
      );
      if (b.level === 1) return <h2 key={i} id={b.id} style={docTitleStyle}>{b.text}</h2>;
      return <h3 key={i} id={b.id} style={subStyle}>{b.text}</h3>;
    }
    if (b.type === "p") return <p key={i} style={pStyle}>{b.text}</p>;
    if (b.type === "ul") return (
      <ul key={i} style={{ margin: "18px 0 0", paddingLeft: 0, listStyle: "none" }}>
        {b.items.map((it, j) => (
          <li key={j} style={{ ...liStyle, position: "relative", paddingLeft: 22 }}>
            <span style={{ position: "absolute", left: 0, top: 10, width: 8, height: 8, background: "var(--teal)", borderRadius: 2 }} />
            {it}
          </li>
        ))}
      </ul>
    );
    if (b.type === "callout") return (
      <div key={i} style={{ margin: "32px 0", background: "var(--teal-mist)", borderLeft: "3px solid var(--teal)", padding: "22px 26px" }}>
        <div style={{ fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 12.5, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--teal-deep)", marginBottom: 8 }}>{b.label}</div>
        <div style={{ fontFamily: "var(--font-display)", fontWeight: 500, fontSize: 20, lineHeight: 1.4, color: "var(--navy)" }}>{b.text}</div>
      </div>
    );
    if (b.type === "sources") return (
      <div key={i} style={{ margin: "48px 0 0", borderTop: "1px solid var(--border-subtle)", paddingTop: 28 }}>
        <div style={{ fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 12.5, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--teal-grey)", marginBottom: 16 }}>Sources &amp; further reading</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {b.items.map((it, j) => (
            <p key={j} style={{ fontFamily: "var(--font-body)", fontSize: 13.5, lineHeight: 1.55, color: "var(--stone)", margin: 0 }}>{linkify(it)}</p>
          ))}
        </div>
      </div>
    );
    return null;
  };

  return (
    <main>
      <article style={{ paddingBlock: 64 }}>
        <Container style={{ maxWidth: (showTOC || paged) ? 1040 : 760 }}>
          <div style={{ maxWidth: 760 }}>
            <a onClick={() => onNav(backTo)} style={{ fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 14.5, color: "var(--teal-deep)", cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 8, marginBottom: 32 }}>
              <span style={{ fontSize: 16 }}>←</span> {backLabel}
            </a>

            <div style={{ fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 13, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--teal-grey)" }}>{a.kicker}</div>
            <h1 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: "clamp(2.25rem,3.6vw,3rem)", lineHeight: 1.12, letterSpacing: "-0.02em", color: "var(--navy)", margin: "16px 0 0" }}>{a.title}</h1>
            {a.dek && <p style={{ fontFamily: "var(--font-body)", fontSize: 20, lineHeight: 1.55, color: "var(--charcoal)", margin: "18px 0 0", maxWidth: "62ch" }}>{a.dek}</p>}
            <div style={{ width: 56, height: 2, background: "var(--gold)", margin: "26px 0 0" }} />
            {a.byline && <div style={{ fontFamily: "var(--font-body)", fontSize: 13.5, color: "var(--stone)", margin: "22px 0 0" }}>{a.byline}</div>}
          </div>

          {paged ? (
            <div style={{ display: "grid", gridTemplateColumns: narrow ? "1fr" : "minmax(0,1fr) 220px", gap: narrow ? 32 : 48, alignItems: "start", marginTop: 8 }}>
              <div style={{ minWidth: 0, maxWidth: 760 }}>
                <div style={{ fontFamily: "var(--font-body)", fontWeight: 700, fontSize: 12.5, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--gold)", borderTop: "2px solid var(--gold)", paddingTop: 14, marginTop: 8 }}>
                  Page {curPage + 1} of {pages.length}
                </div>
                {pages[curPage].blocks.map(renderBlock)}
                {/* bottom page-number nav */}
                <div style={{ marginTop: 56, borderTop: "1px solid var(--border-subtle)", paddingTop: 24, display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, flexWrap: "wrap" }}>
                  <a onClick={() => curPage > 0 && changePage(curPage - 1)} style={{ cursor: curPage > 0 ? "pointer" : "default", fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 14.5, color: curPage > 0 ? "var(--teal-deep)" : "var(--stone)", opacity: curPage > 0 ? 1 : 0.4, display: "inline-flex", alignItems: "center", gap: 8 }}>
                    <span style={{ fontSize: 16 }}>←</span> Previous
                  </a>
                  <div style={{ display: "flex", gap: 8 }}>
                    {pages.map((p, n) => (
                      <a key={n} onClick={() => changePage(n)} style={{ cursor: "pointer", width: 36, height: 36, borderRadius: 4, display: "inline-flex", alignItems: "center", justifyContent: "center", fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 14.5, color: n === curPage ? "#fff" : "var(--navy)", background: n === curPage ? "var(--teal)" : "transparent", border: n === curPage ? "none" : "1px solid var(--border-subtle)" }}>{n + 1}</a>
                    ))}
                  </div>
                  <a onClick={() => curPage < pages.length - 1 && changePage(curPage + 1)} style={{ cursor: curPage < pages.length - 1 ? "pointer" : "default", fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 14.5, color: curPage < pages.length - 1 ? "var(--teal-deep)" : "var(--stone)", opacity: curPage < pages.length - 1 ? 1 : 0.4, display: "inline-flex", alignItems: "center", gap: 8 }}>
                    Next <span style={{ fontSize: 16 }}>→</span>
                  </a>
                </div>
              </div>
              <nav style={{ position: "sticky", top: 100, alignSelf: "start", display: narrow ? "none" : "block" }}>
                <div style={{ fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 12, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--teal-grey)", marginBottom: 14 }}>Contents</div>
                <div style={{ display: "flex", flexDirection: "column", gap: 9, borderLeft: "1px solid var(--border-subtle)" }}>
                  {pages.map((p, n) => (
                    <a key={n} onClick={() => changePage(n)} style={{ cursor: "pointer", fontFamily: "var(--font-body)", fontSize: 13.5, lineHeight: 1.4, color: n === curPage ? "var(--navy)" : "var(--teal-grey)", fontWeight: n === curPage ? 600 : 400, paddingLeft: 14, marginLeft: -1, borderLeft: n === curPage ? "2px solid var(--teal)" : "2px solid transparent" }}>{p.title || p.label}</a>
                  ))}
                </div>
              </nav>
            </div>
          ) : showTOC ? (
            <div style={{ display: "grid", gridTemplateColumns: narrow ? "1fr" : "minmax(0,1fr) 220px", gap: narrow ? 32 : 48, alignItems: "start", marginTop: 8 }}>
              <div style={{ minWidth: 0, maxWidth: 760 }}>{leveled.map(renderBlock)}</div>
              <nav style={{ position: "sticky", top: 100, alignSelf: "start", display: narrow ? "none" : "block" }}>
                <div style={{ fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 12, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--teal-grey)", marginBottom: 14 }}>On this page</div>
                <div style={{ display: "flex", flexDirection: "column", gap: 9, borderLeft: "1px solid var(--border-subtle)" }}>
                  {heads.map((h) => (
                    <a key={h.id} onClick={() => goTo(h.id)} style={{ cursor: "pointer", fontFamily: "var(--font-body)", fontSize: 13.5, lineHeight: 1.4, color: h.level <= 1 ? "var(--navy)" : "var(--teal-grey)", fontWeight: h.level <= 1 ? 600 : 400, paddingLeft: 14, marginLeft: -1, borderLeft: "2px solid transparent" }}>{h.text}</a>
                  ))}
                </div>
              </nav>
            </div>
          ) : (
            <div style={{ marginTop: 8 }}>
              {leveled.map(renderBlock)}
            </div>
          )}

          {/* footer CTA */}
          <div style={{ marginTop: 56, borderTop: "1px solid var(--border-subtle)", paddingTop: 28, display: "flex", gap: 14, flexWrap: "wrap" }}>
            <a onClick={() => onNav(backTo)} style={{ cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 8, fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 15, color: "#fff", background: "var(--teal)", padding: "13px 26px", borderRadius: 50 }}>
              {isEra ? "More articles" : "Back to home"} <span style={{ fontSize: 16 }}>→</span>
            </a>
            <a onClick={() => onNav("contact")} style={{ cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 8, fontFamily: "var(--font-body)", fontWeight: 600, fontSize: 15, color: "var(--navy)", border: "1px solid var(--navy)", padding: "13px 26px", borderRadius: 50 }}>
              Talk to an agronomist
            </a>
          </div>
        </Container>
      </article>
    </main>
  );
}
window.Article = Article;
