// Chapter shell, hybrid IA wrapper around existing section components.
// Cover · 5-chapter index · sticky pill strip · active chapter workspace.

const CHAPTERS = [
  { n: "01", title: "The Reality",  sub: "4 hurdles · self-check",           color: "#d4a64a" },
  { n: "02", title: "The Money",    sub: "Where every dollar goes",            color: "#b889ff" },
  { n: "03", title: "Your Numbers", sub: "Producer fee calculator",          color: "#6ab8e8" },
  { n: "04", title: "The Playbook", sub: "6 rules · per situation",          color: "#7acf99" },
  { n: "05", title: "Join",         sub: "Free · Plus",                        color: "#d4a64a" },
];

const CHAPTER_LEDE = {
  "01": "Most producers clear the first hurdle. Almost none have a map for the last three. Read the path.",
  "02": "One beat splits into four separate money streams. Most producers collect from one. Trace where every dollar goes.",
  "03": "Start with the producer fee calculator. Go deeper for net-net and the 10-year curve.",
  "04": "Pick the artist's situation. See the before/after, then read the six rules for it.",
  "05": "★ Not a course. A community with tools. Join free first, upgrade when you want to.",
};

const CHAPTER_TOOLS = {
  "01": ["Survival-rate chart", "Producer self-check"],
  "02": ["Money flow diagram", "Four pools · where to collect"],
  "03": ["Producer fee calculator", "Net-net · career curve (optional)"],
  "04": ["5 situations · before/after", "6 rules each"],
  "05": ["Free · website + Skool + YouTube", "Plus · Roadmap + weekly calls + group chat"],
};

// Inject chapter-shell scoped styles once
if (typeof document !== "undefined" && !document.getElementById("chapter-shell-styles")) {
  const s = document.createElement("style");
  s.id = "chapter-shell-styles";
  s.textContent = `
    @keyframes chapterIn {
      from { opacity: 0; transform: translateY(10px); }
      to   { opacity: 1; transform: translateY(0); }
    }
    .chapter-fade { animation: chapterIn 0.45s ease both; }
    .chapter-card {
      padding: 22px 20px;
      background: transparent;
      border: 1px solid var(--rule);
      border-radius: var(--radius-card);
      cursor: pointer;
      text-align: left;
      transition: all 0.2s ease;
      display: flex;
      flex-direction: column;
      gap: 8px;
      min-height: 160px;
      color: inherit;
      font: inherit;
    }
    .chapter-card:hover { background: rgba(255,255,255,0.015); border-color: var(--rule-strong); transform: translateY(-1px); }
    .chapter-card.active { background: rgba(212,166,74,0.06); border-color: var(--rule-gold); }
    .chapter-numeral {
      font-family: var(--serif);
      font-style: italic;
      font-weight: 400;
      line-height: 0.85;
    }
    .cover-hero {
      display: grid;
      grid-template-columns: repeat(12, 1fr);
      gap: var(--col-gap);
      align-items: start;
    }
    .cover-rail { grid-column: span 1; grid-row: 1 / span 2; }
    .cover-headline { grid-column: 2 / -1; min-width: 0; }
    .cover-meta {
      grid-column: 2 / -1;
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: clamp(32px, 4vw, 56px);
      align-items: start;
      margin-top: clamp(28px, 3.5vw, 44px);
      padding-top: clamp(28px, 3.5vw, 44px);
      border-top: 1px solid var(--rule-strong);
    }
    .cover-meta-lede {
      margin: 0;
      max-width: none;
    }
    .cover-proof {
      display: grid;
      grid-template-columns: repeat(2, minmax(0, 1fr));
      gap: clamp(20px, 2.5vw, 28px) clamp(24px, 3vw, 36px);
      padding-left: clamp(28px, 3.5vw, 48px);
      border-left: 1px solid var(--rule-strong);
    }
    .cover-proof-value {
      font-family: var(--sans);
      font-weight: 800;
      font-size: clamp(24px, 2.25vw, 30px);
      color: var(--gold);
      letter-spacing: -0.025em;
      line-height: 1;
    }
    .cover-proof-label {
      margin-top: 6px;
      font-family: var(--mono);
      font-size: 11px;
      letter-spacing: 0.12em;
      text-transform: uppercase;
      color: var(--ink-3);
    }
    .cover-index {
      margin-top: clamp(24px, 3.5vw, 40px);
      padding-top: clamp(20px, 2.5vw, 28px);
      border-top: 1px solid var(--rule-strong);
    }
    .cover-index .chapter-card { min-height: 132px; padding: 18px 16px; }
    @media (max-width: 900px) {
      .cover-rail { display: none; }
      .cover-headline { grid-column: 1 / -1; }
      .cover-meta {
        grid-column: 1 / -1;
        grid-template-columns: 1fr;
        gap: 28px;
        margin-top: 24px;
        padding-top: 24px;
      }
      .cover-proof {
        padding-left: 0;
        border-left: none;
        padding-top: 24px;
        border-top: 1px solid var(--rule);
      }
    }
    @media (max-width: 600px) {
      .chapter-grid { grid-template-columns: repeat(2, 1fr) !important; }
    }
  `;
  document.head.appendChild(s);
}

function StickyNav({ active, setActive }) {
  return (
    <header
      className="sticky-glass-header"
      style={{
        position: "sticky", top: 0, zIndex: 50,
        background: "rgba(10,10,10,0.92)",
        backdropFilter: "blur(8px)", WebkitBackdropFilter: "blur(8px)",
        borderBottom: "1px solid var(--rule-strong)",
      }}
    >
      <div className="page" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "12px 0", gap: 20 }}>
        <a href="#cover" onClick={(e) => { e.preventDefault(); window.scrollTo({ top: 0, behavior: "smooth" }); }}
           style={{ fontFamily: "var(--sans)", fontWeight: 800, fontSize: 15, letterSpacing: "-0.02em", color: "var(--ink)", flex: "0 0 auto" }}>
          Producer<span style={{ color: "var(--gold)" }}>•</span>Union
        </a>

        <nav className="hide-mobile" aria-label="Chapters" style={{ display: "flex", alignItems: "center" }}>
          <GlassSegmented
            items={CHAPTERS.map((c) => ({ id: c.n, num: c.n, label: c.title }))}
            active={active}
            onChange={setActive}
            ariaLabel="Chapters"
          />
        </nav>

        <JoinCta href={PU_LINKS.free} style={{ padding: "8px 14px", fontSize: 12, flex: "0 0 auto" }}>
          Join free
        </JoinCta>
      </div>
    </header>
  );
}

function Cover({ active, setActive }) {
  return (
    <section id="cover" style={{ paddingBlock: "clamp(40px, 5vw, 64px)", borderBottom: "1px solid var(--rule-strong)" }}>
      <div className="page">
        <div className="cover-hero">
          <div className="cover-rail hide-mobile">
            <span className="vert">PROD · UNION · FIELD GUIDE</span>
          </div>
          <div className="cover-headline">
            <span className="chip gold">A 5-chapter field guide</span>
            <h1 className="display" style={{ fontSize: "clamp(52px, 8.5vw, 128px)", margin: "16px 0 0", lineHeight: 0.88 }}>
              The producer's<br/>
              <em>roadmap.</em>
            </h1>
          </div>
          <div className="cover-meta">
            <p className="lede cover-meta-lede">
              Five chapters. Each one ends in a working tool you can use today. First-time visitor reads the story. Returning user jumps straight to the calculator.
            </p>
            <div className="cover-proof">
              {[
                { v: "3B+", l: "Streams produced" },
                { v: "5×", l: "Grammy nominations" },
                { v: "400+", l: "Deals negotiated" },
                { v: "10+ yrs", l: "In the industry" },
              ].map((s) => (
                <div key={s.l}>
                  <div className="cover-proof-value">{s.v}</div>
                  <div className="cover-proof-label">{s.l}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
        <div className="cover-index">
          <ChapterIndexBody active={active} setActive={setActive} />
        </div>
      </div>
    </section>
  );
}

function ChapterIndexBody({ active, setActive }) {
  return (
    <>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 14 }}>
        <span className="caption">Index · click any chapter to jump</span>
        <span className="caption">Now viewing · <span className="gold">CH. {active}</span></span>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 14 }} className="chapter-grid">
        {CHAPTERS.map((c) => {
          const isActive = c.n === active;
          return (
            <button key={c.n}
              onClick={() => setActive(c.n)}
              className={`chapter-card ${isActive ? "active" : ""}`}>
              <span className="chapter-numeral" style={{ fontSize: "clamp(40px, 4.5vw, 56px)", color: c.color }}>{c.n}</span>
              <span style={{ fontFamily: "var(--sans)", fontWeight: 700, fontSize: 17, letterSpacing: "-0.015em", color: isActive ? "var(--ink)" : "var(--ink-2)" }}>{c.title}</span>
              <span className="caption" style={{ marginTop: "auto" }}>{c.sub}</span>
            </button>
          );
        })}
      </div>
    </>
  );
}


function ChapterContent({ chapter }) {
  switch (chapter) {
    case "01": return <><Hurdles /><AssessmentPrompt /></>;
    case "02": return <MoneyFlow />;
    case "03": return <YourNumbers />;
    case "04": return <Rules />;
    case "05": return <><Pricing /><Bio /></>;
    default: return null;
  }
}

function ChapterNav({ chapter, setActive }) {
  const idx = CHAPTERS.findIndex((c) => c.n === chapter);
  const prev = idx > 0 ? CHAPTERS[idx - 1] : null;
  const next = idx < CHAPTERS.length - 1 ? CHAPTERS[idx + 1] : null;
  return (
    <section style={{ paddingBlock: 48, borderTop: "1px solid var(--rule-strong)" }}>
      <div className="page" style={{ display: "flex", justifyContent: "space-between", alignItems: "stretch", gap: 16, flexWrap: "wrap" }}>
        {prev ? (
          <button onClick={() => setActive(prev.n)} className="btn btn-ghost" style={{ flexDirection: "row", padding: "16px 22px", minWidth: 280, justifyContent: "flex-start" }}>
            <Arrow d="left" />
            <span style={{ textAlign: "left" }}>
              <div className="caption" style={{ marginBottom: 4 }}>PREVIOUS · {prev.n}</div>
              <div style={{ fontFamily: "var(--sans)", fontWeight: 700, fontSize: 20, letterSpacing: "-0.02em" }}>{prev.title}</div>
            </span>
          </button>
        ) : <span style={{ minWidth: 280 }}></span>}
        {next ? (
          <button onClick={() => setActive(next.n)} className="btn btn-primary" style={{ padding: "16px 22px", minWidth: 280, justifyContent: "space-between" }}>
            <span style={{ textAlign: "left" }}>
              <div className="caption" style={{ marginBottom: 4, color: "rgba(22,17,10,0.6)", letterSpacing: "0.14em" }}>NEXT · {next.n}</div>
              <div style={{ fontFamily: "var(--sans)", fontWeight: 700, fontSize: 20, letterSpacing: "-0.02em" }}>{next.title}</div>
            </span>
            <Arrow d="right" />
          </button>
        ) : (
          <a
            href={PU_LINKS.free}
            target="_blank"
            rel="noopener noreferrer"
            className="btn btn-primary"
            style={{ padding: "16px 22px", minWidth: 280, justifyContent: "space-between", textDecoration: "none" }}
          >
            <span style={{ textAlign: "left" }}>
              <span className="caption" style={{ display: "block", marginBottom: 4, color: "rgba(22,17,10,0.6)", letterSpacing: "0.14em" }}>END · 05</span>
              <span style={{ fontFamily: "var(--sans)", fontWeight: 700, fontSize: 20, letterSpacing: "-0.02em" }}>Join free on Skool</span>
            </span>
            <Arrow d="right" />
          </a>
        )}
      </div>
    </section>
  );
}

function ChapteredApp() {
  const [active, setActive] = React.useState("01");

  const changeChapter = React.useCallback((n) => {
    setActive(n);
    // Scroll the workspace into view without using scrollIntoView
    requestAnimationFrame(() => {
      const el = document.getElementById("chapter-workspace");
      if (el) {
        const y = el.getBoundingClientRect().top + window.scrollY - 84;
        window.scrollTo({ top: y, behavior: "smooth" });
      }
    });
  }, []);

  return (
    <>
      <StickyNav active={active} setActive={changeChapter} />
      <Cover active={active} setActive={changeChapter} />
      <main id="chapter-workspace" style={{ minHeight: "60vh" }}>
        <div key={active} className="chapter-fade">
          <ChapterContent chapter={active} />
          <ChapterNav chapter={active} setActive={changeChapter} />
        </div>
      </main>
      <Footer />
    </>
  );
}

window.ChapteredApp = ChapteredApp;
