/* =========================================================================
   DynamicGuide.jsx — renders a DB-backed Iris guide for ANY leaf URL.
   This is the human-facing render path that was missing: content routes
   (/lane/category/topic/slug/) are rewritten to /guide.html, which loads
   this component. It reads the slug from the URL, fetches the page from the
   pages table (Supabase REST, anon key — same data the middleware prerenders
   for crawlers), and renders it with the site's guide styling + chrome.
   Falls back to a clean "not found → search" state if no row exists.
   ========================================================================= */

const SB_URL = "https://xkquhthyfqdcbktyigyu.supabase.co";
const SB_ANON = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InhrcXVodGh5ZnFkY2JrdHlpZ3l1Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzY4MDEzMjcsImV4cCI6MjA5MjM3NzMyN30.N4faHMUv_gkRzJ_okqDIoGD4uBIdpSLQ9mwDdpdZAbE";

async function sbGet(pathAndQuery) {
  const res = await fetch(`${SB_URL}/rest/v1/${pathAndQuery}`, {
    headers: { apikey: SB_ANON, Authorization: `Bearer ${SB_ANON}` },
  });
  if (!res.ok) return null;
  return res.json();
}

function toLabel(seg) {
  return (seg || "").split("-").map((w) => (w ? w[0].toUpperCase() + w.slice(1) : w)).join(" ");
}

// Parse /[lang]/lane/category/topic/slug/ → { lang, lane, category, topic, slugNoTrail }
function parseLeaf(pathname) {
  const noTrail = pathname.replace(/\/+$/, "");
  const parts = noTrail.split("/").filter(Boolean);
  let lang = "en";
  if (parts[0] === "es") { lang = "es"; parts.shift(); }
  const [lane, category, topic] = parts;
  return { lang, lane, category, topic, slug: noTrail.startsWith("/") ? noTrail : `/${noTrail}` };
}

function CONTRIBUTOR(lane) {
  return lane === "business"
    ? { name: "Isabella", role: "Business lane · operator-grade finance", img: "/contributors/isabella.png",
        bio: "Isabella has opened three businesses, closed one, and wrote the financial operating manuals for the other two. She reviews every business-lane guide for operators who already run the numbers." }
    : { name: "Johnnie", role: "Personal lane · money without the jargon", img: "/contributors/johnnie.png",
        bio: "Johnnie spent a decade on a retail trading desk before walking away to write for people who were never meant to read a 10-K. He reviews every personal-lane guide so the answer is the one you can actually use." };
}

function GBreadcrumbs({ p, content }) {
  const segs = [p.lane, p.category, p.topic].filter(Boolean);
  const base = p.lang === "es" ? "/es" : "";
  let acc = base;
  const crumbs = segs.map((s) => { acc += `/${s}`; return { label: toLabel(s).toUpperCase(), href: acc + "/" }; });
  return (
    <div className="crumbs">
      <div className="crumbs__inner">
        <a href={base + "/"} className="crumbs__item">HOME</a>
        {crumbs.map((c) => (
          <React.Fragment key={c.href}>
            <span className="crumbs__sep">/</span>
            <a href={c.href} className="crumbs__item">{c.label}</a>
          </React.Fragment>
        ))}
        <span className="crumbs__spacer" />
        <span className="crumbs__stats">
          <span>WRITTEN BY</span><span className="crumbs__val">IRIS</span>
          <span>·</span>
          <span>REVIEWED BY</span><span className="crumbs__val">{CONTRIBUTOR(p.lane).name.toUpperCase()}</span>
        </span>
      </div>
    </div>
  );
}

function GuideView({ page, p }) {
  const c = page.content || {};
  const lane = p.lane || page.lane || "personal";
  const contrib = CONTRIBUTOR(lane);
  const read = c.read || "6 MIN";
  const steps = Array.isArray(c.steps) ? c.steps : (Array.isArray(c.sections) ? c.sections : []);
  const figures = Array.isArray(c.figures) ? c.figures : [];
  const takeaways = Array.isArray(c.keyTakeaways) ? c.keyTakeaways : [];
  const [related, setRelated] = React.useState([]);

  React.useEffect(() => {
    document.title = `${c.title || page.title} · HowTo: Finance Edition`;
    const prefix = (p.lang === "es" ? "/es" : "") + `/${lane}/${p.category}/`;
    sbGet(`pages?select=slug,title&slug=like.${encodeURIComponent(prefix)}*&slug=neq.${encodeURIComponent(page.slug)}&language=eq.${p.lang}&order=created_at.desc&limit=4`)
      .then((rows) => setRelated((rows || []).slice(0, 3)));
  }, []);

  return (
    <div className="site" data-lane={lane}>
      <Ticker />
      <Nav lane={lane} setLane={() => {}} />
      <GBreadcrumbs p={p} content={c} />

      <section className="ghero">
        <div className="ghero__bg" aria-hidden="true" />
        <div className="ghero__inner">
          <div className="ghero__meta">
            <span className="ghero__num">{lane === "personal" ? "01" : "02"}</span>
            <span className="ghero__bar" />
            <span className="ghero__label">{[p.lane, p.category, p.topic].filter(Boolean).map((s) => toLabel(s)).join(" · ")}</span>
            <span className="ghero__dot">·</span>
            <span>{read}</span>
            <span className="ghero__dot">·</span>
            <span>WRITTEN BY IRIS</span>
          </div>
          <h1 className="ghero__h1">{c.title || page.title}</h1>
          {c.sub ? <p className="ghero__sub">{c.sub}</p> : null}
        </div>
      </section>

      <section className="gbody">
        <div className="gbody__grid">
          <article className="gbody__main">
            <div className="gbody__kicker"><span className="bar" /> PROCEDURE · {steps.length} STEPS</div>
            {c.lead ? <p className="gbody__lead">{c.lead}</p> : null}

            <ol className="gbody__steps">
              {steps.map((s, i) => (
                <li key={i} className="gstep">
                  <div className="gstep__num">{s.number || s.heading ? (s.number || `Step ${String(i + 1).padStart(2, "0")}`) : `Step ${String(i + 1).padStart(2, "0")}`}</div>
                  <div className="gstep__body">
                    <h3 className="gstep__h">{s.headline || s.heading || ""}</h3>
                    <p className="gstep__p">{s.body || ""}</p>
                  </div>
                </li>
              ))}
            </ol>

            {takeaways.length ? (
              <div className="gbody__pull">
                <div className="gbody__pull-k">KEY TAKEAWAYS</div>
                <ul style={{ margin: 0, paddingLeft: "1.1em" }}>
                  {takeaways.map((t, i) => <li key={i} style={{ marginBottom: "0.5em" }}>{t}</li>)}
                </ul>
              </div>
            ) : (c.lead ? (
              <div className="gbody__pull">
                <div className="gbody__pull-k">THE ONE-SENTENCE ANSWER</div>
                <p>{c.lead}</p>
              </div>
            ) : null)}

            {c.disclaimer ? (
              <p style={{ fontFamily: "var(--mono, monospace)", fontSize: "12px", lineHeight: 1.7, color: "var(--mute, #6b7875)", borderTop: "1px solid var(--line, #d7dfda)", paddingTop: "18px", marginTop: "28px" }}>
                {c.disclaimer}
              </p>
            ) : null}

            <nav className="gbody__nav">
              <a href={(p.lang === "es" ? "/es" : "") + `/${p.lane}/${p.category}/${p.topic}/`} className="gbody__nav-l">
                <span className="gbody__nav-k">← BACK</span>
                <span className="gbody__nav-t">{toLabel(p.topic)}</span>
              </a>
              {related[0] ? (
                <a href={withSlash(related[0].slug)} className="gbody__nav-r">
                  <span className="gbody__nav-k">NEXT GUIDE →</span>
                  <span className="gbody__nav-t">{related[0].title}</span>
                </a>
              ) : null}
            </nav>
          </article>

          <aside className="gbody__side">
            {figures.length ? (
              <div className="gfigs">
                <div className="gfigs__k">KEY FIGURES</div>
                <div className="gfigs__sub">{toLabel(p.category)}</div>
                {figures.map((f, i) => (
                  <div key={i} className="gfig">
                    <div className="gfig__k">{f.k}</div>
                    <div className="gfig__v">{f.v}</div>
                    <div className="gfig__d">{f.d}</div>
                  </div>
                ))}
                <div className="gfigs__foot"><span>SOURCED FROM</span><span className="gfigs__foot-v">HOWTO · LIVE INDEX</span></div>
              </div>
            ) : null}

            {related.length ? (
              <div className="gside-block">
                <div className="gside-block__k">MORE IN {toLabel(p.category).toUpperCase()}</div>
                <ul>
                  {related.map((m, i) => (
                    <li key={m.slug}>
                      <a href={withSlash(m.slug)}>
                        <span className="gside-block__idx">{String(i + 1).padStart(2, "0")}</span>
                        <div><div className="gside-block__t">{m.title}</div></div>
                      </a>
                    </li>
                  ))}
                </ul>
              </div>
            ) : null}

            <div className="gside-block gside-block--mint">
              <div className="gside-block__k" style={{ color: "var(--forest-ink)" }}>SEARCH IRIS</div>
              <p>Ask anything about {lane === "business" ? "running the numbers" : "your money"}. If it doesn't exist yet, Iris builds it.</p>
              <a href="/search/" className="gside-block__cta">Search the index →</a>
            </div>
          </aside>
        </div>
      </section>

      <section className={`gauthor gauthor--${lane}`}>
        <div className="gauthor__inner">
          <div className={`gauthor__pic gauthor__pic--${lane}`} style={{ position: "relative", overflow: "hidden" }}>
            <img src={contrib.img} alt={contrib.name} style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }} onError={(e) => { e.target.style.display = "none"; }} />
          </div>
          <div className="gauthor__body">
            <div className="gauthor__kicker"><span className="bar" /> WRITTEN BY IRIS · REVIEWED BY {contrib.name.toUpperCase()}</div>
            <h3 className="gauthor__name">{contrib.name}</h3>
            <div className="gauthor__role">{contrib.role}</div>
            <p className="gauthor__bio">{contrib.bio}</p>
          </div>
        </div>
      </section>

      <NetworkBand />
      <Footer />
    </div>
  );
}

function withSlash(slug) {
  if (!slug) return "/";
  const s = slug.startsWith("/") ? slug : `/${slug}`;
  return s.endsWith("/") ? s : `${s}/`;
}

function NotFound({ p }) {
  const guess = [p.topic, p.category].filter(Boolean).map((s) => s.replace(/-/g, " "))[0] || "";
  return (
    <div className="site" data-lane={p.lane || "personal"}>
      <Ticker />
      <Nav lane={p.lane || "personal"} setLane={() => {}} />
      <section className="ghero">
        <div className="ghero__bg" aria-hidden="true" />
        <div className="ghero__inner">
          <div className="ghero__meta"><span className="ghero__num">404</span><span className="ghero__bar" /><span className="ghero__label">NO PAGE AT THIS ADDRESS</span></div>
          <h1 className="ghero__h1">Iris hasn't built this one yet.</h1>
          <p className="ghero__sub">Search what you're after — if it doesn't exist, Iris builds it on the spot, in 8 languages.</p>
          <p style={{ marginTop: "26px" }}>
            <a href={`/search/${guess ? "?q=" + encodeURIComponent(guess) : ""}`} className="btn btn--primary">SEARCH IRIS →</a>
          </p>
        </div>
      </section>
      <NetworkBand />
      <Footer />
    </div>
  );
}

function DynamicGuideApp() {
  const p = parseLeaf(window.location.pathname);
  const [state, setState] = React.useState({ loading: true, page: null });

  React.useEffect(() => {
    const tick = () => {
      const now = new Date();
      const hh = String(now.getHours()).padStart(2, "0");
      const mm = String(now.getMinutes()).padStart(2, "0");
      const ss = String(now.getSeconds()).padStart(2, "0");
      const clock = document.getElementById("tickerClock");
      if (clock) clock.textContent = `NYC · ${hh}:${mm}:${ss}`;
      const fsess = document.getElementById("fsess");
      if (fsess) fsess.textContent = `${hh}${mm}.${ss}`;
    };
    tick();
    const id = setInterval(tick, 1000);
    return () => clearInterval(id);
  }, []);

  React.useEffect(() => {
    const variants = Array.from(new Set([p.slug, p.slug + "/", p.slug.replace(/\/$/, "")]));
    (async () => {
      for (const v of variants) {
        const rows = await sbGet(`pages?select=slug,title,content,language,lane,category,hero_image&slug=eq.${encodeURIComponent(v)}&limit=1`);
        if (rows && rows[0]) { setState({ loading: false, page: rows[0] }); return; }
      }
      setState({ loading: false, page: null });
    })();
  }, []);

  if (state.loading) {
    return (
      <div className="site" data-lane={p.lane || "personal"}>
        <Ticker />
        <Nav lane={p.lane || "personal"} setLane={() => {}} />
        <section className="ghero"><div className="ghero__bg" aria-hidden="true" /><div className="ghero__inner">
          <div className="ghero__meta"><span className="ghero__num">··</span><span className="ghero__bar" /><span className="ghero__label">LOADING</span></div>
          <h1 className="ghero__h1" style={{ opacity: 0.5 }}>Loading…</h1>
        </div></section>
        <Footer />
      </div>
    );
  }
  return state.page ? <GuideView page={state.page} p={p} /> : <NotFound p={p} />;
}

ReactDOM.createRoot(document.getElementById("root")).render(<DynamicGuideApp />);
