// Guide leaf page — both lanes, structural twins

/* ========== LIVE LEAF URLS ==========
   Only these two guides are live. Everything else renders as text, no href. */
const LEAF_URLS = {
  "How to Build a 3-Month Emergency Fund": "/personal/foundations/emergency-savings/build-a-3-month-emergency-fund/",
  "How to Calculate Your Real Profit Margin (Most People Get This Wrong)": "/business/benchmarks/margins-profitability/calculate-your-real-profit-margin/",
  "How to Calculate Your Real Profit Margin": "/business/benchmarks/margins-profitability/calculate-your-real-profit-margin/",
};
const leafUrl = (title) => LEAF_URLS[title] || null;

const GUIDE_META = {
  "emergency-fund": {
    lane: "personal",
    breadcrumb: ["PERSONAL", "FOUNDATIONS", "EMERGENCY SAVINGS"],
    breadcrumbHrefs: ["/personal/", "/personal/foundations/", "/personal/foundations/emergency-savings/"],
    subcatPath: "/personal/foundations/emergency-savings/",
    subcatName: "Emergency Savings",
    read: "6 MIN",
    title: "How to Build a 3-Month Emergency Fund",
    sub: "The exact steps to get there, with numbers.",
    lead: "Three months of essential spend, parked in a high-yield account, contributed to automatically — that's the whole thing. Everything below is how to actually do it.",
    steps: [
      ["Step 01", "Frame the goal in a dollar figure, not a feeling.", "Add up one month of essential spend — rent, utilities, groceries, insurance, minimum debt payments. Multiply by three. That's your target."],
      ["Step 02", "Pull the three statements that show where you are today.", "Current savings, monthly take-home, monthly essential spend. Write them on one line. If the gap is less than 6 months of automation, skip to Step 04."],
      ["Step 03", "Open a separate high-yield savings account (HYSA).", "Not the same bank as checking. The separation is the point — friction is a feature. Aim for ≥ 4% APY in 2026."],
      ["Step 04", "Automate the boring 80%. Review the other 20% monthly.", "Schedule the transfer the day after payday. Check the balance at the end of the month, not the end of the week."],
      ["Step 05", "Re-check against your plan every 90 days.", "Life changes. Rent goes up, jobs change, the target moves. Recalculate once a quarter and adjust the automation."],
    ],
    figures: [
      { k: "TARGET", v: "$12,400", d: "3 months essential spend" },
      { k: "TIMELINE", v: "18 MO", d: "at $689/mo, automated" },
      { k: "RATE", v: "4.35%", d: "HYSA, 26-wk avg" },
    ],
    author: "Johnnie",
    authorRole: "Personal finance — formerly retail trading desk, Chicago",
    authorBio: "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 answers the money questions you're a little embarrassed to ask.",
    more: [
      { t: "How to Automate Your Savings (Set It and Forget It)", read: "4 MIN" },
      { t: "How to Choose a Checking Account in 2026", read: "6 MIN" },
      { t: "How to Pair a HYSA With Your Main Bank", read: "4 MIN" },
    ],
    prev: { t: "How to Build a Budget You'll Actually Follow", href: "#" },
    next: { t: "How to Automate Your Savings (Set It and Forget It)", href: "#" },
  },
  "profit-margin": {
    lane: "business",
    breadcrumb: ["BUSINESS", "BENCHMARKS", "MARGINS & PROFITABILITY"],
    breadcrumbHrefs: ["/business/", "/business/benchmarks/", "/business/benchmarks/margins-profitability/"],
    subcatPath: "/business/benchmarks/margins-profitability/",
    subcatName: "Margins & Profitability",
    read: "8 MIN",
    title: "How to Calculate Your Real Profit Margin (Most People Get This Wrong)",
    sub: "The formula that changes your pricing strategy.",
    lead: "Most operators confuse markup with margin and set prices that leak cash every month. The fix is one formula, applied honestly to real numbers from your books — not the numbers you wish were in your books.",
    steps: [
      ["Step 01", "Gross Profit = Revenue minus Cost of Goods Sold (COGS).", "Revenue is what landed in the bank, net of refunds. COGS is every direct cost to produce what you sold — materials, direct labor, freight in. Nothing else."],
      ["Step 02", "Pull your quarterly revenue and actual COGS from your books.", "Not your best guess. Not last year's number × 1.1. Run the P&L for the quarter and use those exact figures."],
      ["Step 03", "Divide Gross Profit by Revenue. Multiply by 100 for percentage.", "That's your gross margin. Write it down. This is the only margin you should quote in pricing conversations."],
      ["Step 04", "Benchmark against your industry — not your gut.", "A healthy product business runs 35–50%. A healthy services business runs 50–70%. If you're below, the problem is pricing or COGS, not sales volume."],
      ["Step 05", "Track this monthly. Watch for seasonal swings and cost creep.", "Margins drift. A supplier raises prices 3%, a shipping lane adds a fee, a new hire is coded to COGS. Monthly tracking catches this before it compounds."],
    ],
    figures: [
      { k: "BENCHMARK", v: "22–35%", d: "healthy range, product biz" },
      { k: "FORMULA", v: "(R − C) / R", d: "Revenue, COGS" },
      { k: "WATCH", v: "±3%", d: "seasonal variance tolerance" },
    ],
    author: "Isabella",
    authorRole: "Small business — operator, three founded, two still running",
    authorBio: "Isabella has opened three businesses, closed one, and wrote the financial operating manuals for the other two. She's the person founders text at 11pm when the books don't tie.",
    more: [
      { t: "How to Price Your Services Without Leaving Money on the Table", read: "8 MIN" },
      { t: "How to Read Financial Statements Like a Founder", read: "9 MIN" },
      { t: "How to Benchmark Your Margin Against Your Industry", read: "7 MIN" },
    ],
    prev: { t: "How to Price Your Services Without Leaving Money on the Table", href: "#" },
    next: { t: "How to Set Up Accounting for Your Solo Business", href: "#" },
  },
};

function GuideBreadcrumbs({ g }) {
  const hrefs = g.breadcrumbHrefs || [];
  return (
    <div className="crumbs">
      <div className="crumbs__inner">
        <a href="/" className="crumbs__item">HOME</a>
        {g.breadcrumb.map((label, i) => (
          <React.Fragment key={label}>
            <span className="crumbs__sep">/</span>
            <a href={hrefs[i] || "#"} className="crumbs__item">{label}</a>
          </React.Fragment>
        ))}
        <span className="crumbs__sep">/</span>
        <a className="crumbs__item" style={{color: "var(--forest-ink)"}}>{g.read}</a>
        <span className="crumbs__spacer" />
        <span className="crumbs__stats">
          <span>ISSUE</span><span className="crumbs__val">038</span>
          <span>·</span>
          <span>FILED</span><span className="crumbs__val">04.18.26</span>
          <span>·</span>
          <span>BY</span><span className="crumbs__val">{g.author.toUpperCase()}</span>
        </span>
      </div>
    </div>
  );
}

function GuideHero({ g }) {
  return (
    <section className="ghero">
      <div className="ghero__bg" aria-hidden="true" />
      <div className="ghero__inner">
        <div className="ghero__meta">
          <span className="ghero__num">{g.lane === "personal" ? "01" : "02"}</span>
          <span className="ghero__bar" />
          <span className="ghero__label">{g.breadcrumb.join(" · ")}</span>
          <span className="ghero__dot">·</span>
          <span>{g.read}</span>
          <span className="ghero__dot">·</span>
          <span>FILED BY {g.author.toUpperCase()}</span>
        </div>
        <h1 className="ghero__h1">{g.title}</h1>
        <p className="ghero__sub">{g.sub}</p>
      </div>
    </section>
  );
}

function GuideBody({ g }) {
  return (
    <section className="gbody">
      <div className="gbody__grid">
        <article className="gbody__main">
          <div className="gbody__kicker">
            <span className="bar"/> ARTICLE PREVIEW · PROCEDURE
          </div>
          <p className="gbody__lead">{g.lead}</p>

          <ol className="gbody__steps">
            {g.steps.map((s, i) => (
              <li key={i} className="gstep">
                <div className="gstep__num">{s[0]}</div>
                <div className="gstep__body">
                  <h3 className="gstep__h">{s[1]}</h3>
                  <p className="gstep__p">{s[2]}</p>
                </div>
              </li>
            ))}
          </ol>

          <div className="gbody__pull">
            <div className="gbody__pull-k">THE ONE-SENTENCE ANSWER</div>
            <p>{g.lead}</p>
          </div>

          <div className="gbody__actions">
            <button className="btn btn--primary">READ FULL GUIDE →</button>
            <button className="btn btn--ghost">SAVE TO LIBRARY</button>
            <span className="gbody__sharekey">SHARE · ⌘ S</span>
          </div>

          <div className="gbody__strip">
            <div className="gbody__strip-l">
              <span className="gbody__strip-k">ALSO IN THIS PROCEDURE</span>
              <span className="gbody__strip-v">05 STEPS · {g.figures.length} KEY FIGURES · {g.read}</span>
            </div>
            <div className="gbody__strip-r">
              <span className="gbody__strip-k">WRITER</span>
              <span className="gbody__strip-v">{g.author.toUpperCase()}</span>
            </div>
          </div>

          <nav className="gbody__nav">
            {leafUrl(g.prev.t) ? (
              <a href={leafUrl(g.prev.t)} className="gbody__nav-l">
                <span className="gbody__nav-k">← PREVIOUS</span>
                <span className="gbody__nav-t">{g.prev.t}</span>
              </a>
            ) : (
              <div className="gbody__nav-l">
                <span className="gbody__nav-k">← PREVIOUS</span>
                <span className="gbody__nav-t">{g.prev.t}</span>
              </div>
            )}
            {leafUrl(g.next.t) ? (
              <a href={leafUrl(g.next.t)} className="gbody__nav-r">
                <span className="gbody__nav-k">NEXT GUIDE →</span>
                <span className="gbody__nav-t">{g.next.t}</span>
              </a>
            ) : (
              <div className="gbody__nav-r">
                <span className="gbody__nav-k">NEXT GUIDE →</span>
                <span className="gbody__nav-t">{g.next.t}</span>
              </div>
            )}
          </nav>
        </article>

        <aside className="gbody__side">
          <div className="gfigs">
            <div className="gfigs__k">KEY FIGURES</div>
            <div className="gfigs__sub">04.18.26 · {g.breadcrumb[1]}</div>
            {g.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>

          <div className="gside-block">
            <div className="gside-block__k">MORE FROM {g.author.toUpperCase()} THIS WEEK</div>
            <ul>
              {g.more.map((m, i) => {
                const url = leafUrl(m.t);
                const Inner = url ? "a" : "div";
                const innerProps = url ? { href: url } : {};
                return (
                  <li key={m.t}>
                    <Inner {...innerProps}>
                      <span className="gside-block__idx">{String(i + 1).padStart(2, "0")}</span>
                      <div>
                        <div className="gside-block__t">{m.t}</div>
                        <div className="gside-block__r">{m.read}</div>
                      </div>
                    </Inner>
                  </li>
                );
              })}
            </ul>
          </div>

          <div className="gside-block gside-block--mint">
            <div className="gside-block__k" style={{color: "var(--forest-ink)"}}>NEXT STEP</div>
            <p>Think you've got it? Run the procedure once, then hit the next guide.</p>
            {leafUrl(g.next.t) ? (
              <a href={leafUrl(g.next.t)} className="gside-block__cta">{g.next.t} →</a>
            ) : (
              <span className="gside-block__cta">{g.next.t} →</span>
            )}
          </div>
        </aside>
      </div>
    </section>
  );
}

function GuideAuthor({ g }) {
  const isP = g.lane === "personal";
  return (
    <section className={`gauthor gauthor--${g.lane}`}>
      <div className="gauthor__inner">
        <div className={`gauthor__pic gauthor__pic--${g.lane}`} style={{position: "relative", overflow: "hidden"}}>
          <img src={`/contributors/${g.author.toLowerCase()}.png`} alt={g.author} style={{position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover"}} />
        </div>
        <div className="gauthor__body">
          <div className="gauthor__kicker">
            <span className="bar"/> ABOUT THE WRITER · {g.lane.toUpperCase()} LANE
          </div>
          <h3 className="gauthor__name">{g.author}</h3>
          <div className="gauthor__role">{g.authorRole}</div>
          <p className="gauthor__bio">{g.authorBio}</p>
          <dl className="gauthor__creds">
            <div><dt>GUIDES</dt><dd>{isP ? "312" : "218"}</dd></div>
            <div><dt>YEARS</dt><dd>{isP ? "12" : "9"}</dd></div>
            <div><dt>REVIEWED</dt><dd>{isP ? "1,284" : "864"}</dd></div>
            <div><dt>LANE</dt><dd>{g.lane.toUpperCase()}</dd></div>
          </dl>
          <div className="gauthor__actions">
            <button className="btn btn--primary">
              VIEW ALL GUIDES BY {g.author.toUpperCase()} →
            </button>
            <button className="btn btn--ghost">{g.author.toUpperCase()}'S PROFILE</button>
          </div>
        </div>
      </div>
    </section>
  );
}

function GuideNav({ g }) {
  const nextUrl = leafUrl(g.next.t);
  return (
    <section className="gnav">
      <div className="gnav__inner">
        <a href={g.subcatPath} className="gnav__back">
          <span className="gnav__arr">←</span> BACK TO {g.subcatName.toUpperCase()}
        </a>
        {nextUrl ? (
          <a href={nextUrl} className="gnav__next">
            NEXT GUIDE: {g.next.t} <span className="gnav__arr">→</span>
          </a>
        ) : (
          <span className="gnav__next">
            NEXT GUIDE: {g.next.t} <span className="gnav__arr">→</span>
          </span>
        )}
      </div>
    </section>
  );
}

function GuideApp() {
  const key = window.GUIDE || "emergency-fund";
  const g = GUIDE_META[key];
  const [tweaksOpen, setTweaksOpen] = React.useState(false);

  React.useEffect(() => {
    const handler = (e) => {
      if (!e.data) return;
      if (e.data.type === "__activate_edit_mode") setTweaksOpen(true);
      if (e.data.type === "__deactivate_edit_mode") setTweaksOpen(false);
    };
    window.addEventListener("message", handler);
    window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", handler);
  }, []);

  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);
  }, []);

  return (
    <div className="site" data-lane={g.lane}>
      <Ticker />
      <Nav lane={g.lane} setLane={() => {}} />
      <GuideBreadcrumbs g={g} />
      <GuideHero g={g} />
      <GuideBody g={g} />
      <GuideAuthor g={g} />
      <GuideNav g={g} />
      <NetworkBand />
      <Footer />

      <div className={`tweaks ${tweaksOpen ? "is-open" : ""}`}>
        <div className="tweaks__head">
          <span>GUIDE · {g.lane.toUpperCase()}</span>
          <button onClick={() => setTweaksOpen(false)} style={{color: "var(--pistachio)"}}>✕</button>
        </div>
        <div className="tweaks__body">
          <div>
            <span className="tweaks__k">THIS IS A LEAF PAGE</span>
            <p style={{fontSize: "10px", color: "var(--pistachio)", margin: 0, lineHeight: 1.5, letterSpacing: "0.08em"}}>
              SWITCH FILES TO VIEW THE OTHER LANE · PERSONAL = EMERGENCY FUND · BUSINESS = PROFIT MARGIN
            </p>
          </div>
        </div>
        <div className="tweaks__foot">FINANCE · GUIDE</div>
      </div>
    </div>
  );
}

Object.assign(window, { GUIDE_META, GuideBreadcrumbs, GuideHero, GuideBody, GuideAuthor, GuideNav });
ReactDOM.createRoot(document.getElementById("root")).render(<GuideApp />);
