// Chapter shell, hybrid IA wrapper around existing section components.
// Cover · 6-chapter index · sticky nav dropdowns · active chapter workspace.

const CHAPTERS = [
  { n: "01", title: "The Reality",  sub: "4 hurdles · self-check",           color: "#ece6da" },
  { 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 free",    sub: "Free · Plus",                        color: "#d4a64a" },
  { n: "06", title: "Resources",    sub: "The toolbelt · daily stack",         color: "#c0392b" },
];

// Toggle to re-enable Ch.06 in nav when the toolbelt is ready to ship.
const HIDDEN_CHAPTERS = new Set(["06"]);
const NAV_CHAPTERS = CHAPTERS.filter((c) => !HIDDEN_CHAPTERS.has(c.n));

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.",
  "06": "Tools I actually use: storefront, notes, AI, money, focus. No affiliate list.",
};

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"],
  "06": ["5 lanes · 18 tools", "Produce · think · AI · money · life"],
};

// Deep-link targets for sticky nav dropdowns
const CHAPTER_NAV = {
  "01": {
    items: [
      { label: "Four Hurdles", target: { chapter: "01", scrollTo: "hurdles" } },
      { label: "Talent", sub: "Hurdle 01", target: { chapter: "01", hurdle: 0 } },
      { label: "Attention", sub: "Hurdle 02", target: { chapter: "01", hurdle: 1 } },
      { label: "Release", sub: "Hurdle 03", target: { chapter: "01", hurdle: 2 } },
      { label: "Payment", sub: "Hurdle 04", target: { chapter: "01", hurdle: 3 } },
      { label: "Producer Self-Check", target: { chapter: "01", action: "assessment" } },
    ],
  },
  "02": {
    items: [
      { label: "Money Flow Diagram", target: { chapter: "02", scrollTo: "flow" } },
      { label: "Four pools · where to collect", target: { chapter: "02", scrollTo: "flow" } },
    ],
  },
  "03": {
    items: [
      {
        label: "Fee Calculator",
        sub: "What to charge",
        target: { chapter: "03", tool: "fee", calcTab: "fee" },
      },
      { label: "Net-Net Take-Home", sub: "After splits & taxes", target: { chapter: "03", tool: "netnet" } },
      { label: "10-Year Curve", sub: "Career projection", target: { chapter: "03", tool: "curve" } },
    ],
  },
  "04": {
    items: [
      { label: "Six Rules", target: { chapter: "04", scrollTo: "rules" } },
      { label: "No Deal", target: { chapter: "04", situation: "nodeal" } },
      { label: "Indie, No Distro", target: { chapter: "04", situation: "indie-no" } },
      { label: "Indie with Distro", target: { chapter: "04", situation: "indie" } },
      { label: "Signed, Indie Label", target: { chapter: "04", situation: "signed-indie" } },
      { label: "Major Label", target: { chapter: "04", situation: "major" } },
    ],
  },
  "05": {
    items: [
      { label: "Membership", target: { chapter: "05", scrollTo: "pricing" } },
      { label: "Free community", target: { chapter: "05", scrollTo: "pricing" } },
      { label: "Producer Union Plus", target: { chapter: "05", scrollTo: "pricing" } },
      { label: "Producer Self-Check", target: { chapter: "05", action: "assessment" } },
    ],
  },
  "06": {
    items: [
      { label: "Daily stack map", target: { chapter: "06", scrollTo: "resources-map" } },
      { label: "Reading loop", target: { chapter: "06", story: "reading", scrollTo: "resources-map" } },
      { label: "The toolbelt", target: { chapter: "06", scrollTo: "resources" } },
      { label: "Produce & community", target: { chapter: "06", lane: "produce" } },
      { label: "Monetize", target: { chapter: "06", lane: "monetize" } },
      { label: "Credits & accolades", target: { chapter: "06", lane: "credits" } },
      { label: "Studio & sounds", target: { chapter: "06", lane: "studio" } },
      { label: "Think & capture", target: { chapter: "06", lane: "think" } },
      { label: "Build with AI", target: { chapter: "06", lane: "ai" } },
      { label: "Money & security", target: { chapter: "06", lane: "money" } },
      { label: "Focus & life", target: { chapter: "06", lane: "life" } },
      { label: "Soundpage", target: { chapter: "06", tool: "soundpage" } },
      { label: "Obsidian", target: { chapter: "06", tool: "obsidian" } },
      { label: "Claude", target: { chapter: "06", tool: "claude" } },
    ],
  },
};

function scrollToSectionId(id, offset = 84) {
  const el = document.getElementById(id);
  if (!el) return;
  const y = el.getBoundingClientRect().top + window.scrollY - offset;
  window.scrollTo({ top: y, behavior: "smooth" });
}

function scrollTargetForNav(target) {
  if (target.scrollTo) return target.scrollTo;
  if (target.chapter === "03") {
    if (target.tool === "netnet") return "netnet";
    if (target.tool === "curve") return "career";
    if (target.tool === "fee" || target.calcTab) return "calculator";
  }
  if (target.chapter === "01" && target.hurdle != null) return "hurdles";
  if (target.chapter === "04" && target.situation) return "rules";
  if (target.chapter === "06") {
    if (target.scrollTo === "resources-map") return "resources-map";
    if (target.tool) return `resources-${target.tool}`;
    return "resources";
  }
  return null;
}

// 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); }
    }
    @keyframes sheetIn {
      from { opacity: 0; transform: translateY(100%); }
      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: 132px;
      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); }
    @media (max-width: 1100px) {
      .chapter-grid { grid-template-columns: repeat(3, 1fr) !important; }
    }
    @media (max-width: 600px) {
      .chapter-grid { grid-template-columns: repeat(2, 1fr) !important; }
    }

    /* ---- Mobile chapter sheet ---- */
    .mobile-ch-btn {
      display: none;
      align-items: center;
      gap: 8px;
      padding: 8px 14px;
      background: rgba(255,255,255,0.04);
      border: 1px solid var(--rule-strong);
      border-radius: var(--radius-pill);
      color: var(--ink-2);
      font-family: var(--sans);
      font-weight: 600;
      font-size: 13px;
      cursor: pointer;
      white-space: nowrap;
      -webkit-tap-highlight-color: transparent;
      min-height: 44px;
    }
    @media (max-width: 900px) { .mobile-ch-btn { display: inline-flex; } }

    .mobile-ch-sheet {
      position: fixed;
      inset: 0;
      z-index: 300;
      background: rgba(0,0,0,0.88);
      backdrop-filter: blur(10px);
      -webkit-backdrop-filter: blur(10px);
      display: flex;
      flex-direction: column;
      padding: env(safe-area-inset-top, 0) 0 env(safe-area-inset-bottom, 0);
      animation: sheetIn 0.28s cubic-bezier(0.34, 1.2, 0.64, 1) both;
      overflow-y: auto;
    }
    .mobile-ch-sheet-head {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px var(--page-pad) 16px;
      border-bottom: 1px solid var(--rule-strong);
      flex-shrink: 0;
    }
    .mobile-ch-sheet-close {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 44px;
      height: 44px;
      background: rgba(255,255,255,0.04);
      border: 1px solid var(--rule-strong);
      border-radius: var(--radius-pill);
      color: var(--ink-2);
      font-size: 20px;
      line-height: 1;
      cursor: pointer;
    }
    .mobile-ch-sheet-list {
      display: flex;
      flex-direction: column;
      gap: 10px;
      padding: 20px var(--page-pad);
    }
    .mobile-ch-sheet .chapter-card {
      min-height: 80px;
      padding: 18px 20px;
    }

    /* ---- Sticky bottom CTA (mobile only) ---- */
    .mobile-cta-bar {
      display: none;
      position: fixed;
      bottom: 0;
      left: 0;
      right: 0;
      z-index: 100;
      box-sizing: border-box;
      width: 100%;
      max-width: 100vw;
      padding: 12px var(--page-pad) calc(12px + env(safe-area-inset-bottom, 0px));
      background: rgba(10,10,10,0.96);
      backdrop-filter: blur(8px);
      -webkit-backdrop-filter: blur(8px);
      border-top: 1px solid var(--rule-strong);
      align-items: center;
      justify-content: space-between;
      gap: 12px;
    }
    .mobile-cta-bar > div:first-child {
      flex: 1;
      min-width: 0;
    }
    @media (max-width: 900px) { .mobile-cta-bar { display: flex; } }
    @media (max-width: 900px) { body { padding-bottom: calc(80px + env(safe-area-inset-bottom, 0px)); } }
    /* Push content above sticky bottom bar on mobile */
    @media (max-width: 900px) { #chapter-workspace { padding-bottom: 80px; } }

    .chapter-numeral {
      font-family: var(--display);
      font-style: normal;
      font-weight: 400;
      line-height: 0.85;
    }
    .cover-hero {
      position: relative;
      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 { position: relative; z-index: 1; 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 {
      border-bottom: 1px solid var(--rule-strong);
    }
    .cover-index {
      position: relative;
      z-index: 4;
      margin-top: clamp(20px, 3vw, 32px);
      padding-top: clamp(16px, 2vw, 24px);
      border-top: none;
    }
    .cover-index::before {
      content: "";
      display: block;
      height: 1px;
      margin-bottom: clamp(16px, 2vw, 24px);
      background: linear-gradient(
        to right,
        transparent,
        var(--rule-strong) 18%,
        var(--rule-strong) 82%,
        transparent
      );
    }
    .cover-index .chapter-card { min-height: 132px; padding: 18px 16px; }

    /* ---- Noise -> Signal cover stage + floating artifact cards ---- */
    .cover-stage {
      position: relative;
      padding-top: clamp(6px, 1.2vw, 13px);
      padding-bottom: clamp(13px, 2vw, 22px);
      overflow: visible;
    }
    .cover-stage::after {
      content: "";
      position: absolute;
      left: 0;
      right: 0;
      bottom: -1px;
      height: clamp(38px, 6.4vh, 64px);
      background: linear-gradient(to bottom, transparent, var(--bg));
      pointer-events: none;
      z-index: 3;
    }
    .cover-grid {
      position: relative;
      z-index: 4;
      display: grid;
      grid-template-columns: minmax(0, 1fr) minmax(368px, 1.28fr) minmax(0, 1fr);
      align-items: center;
      gap: clamp(37px, 6.3vw, 83px);
      width: 100%;
      min-height: inherit;
    }
    .cover-col {
      display: flex;
      flex-direction: column;
      gap: clamp(4px, 0.58vw, 9px);
      pointer-events: none;
    }
    .cover-col--noise {
      align-items: flex-start;
      text-align: left;
      padding-left: clamp(4px, 1.5vw, 20px);
      padding-right: clamp(16px, 3vw, 40px);
    }
    .cover-col--signal {
      align-items: flex-end;
      text-align: right;
      padding-right: clamp(4px, 1.5vw, 20px);
      padding-left: clamp(16px, 3vw, 40px);
    }
    .cover-pole {
      font-family: var(--sans);
      font-weight: 800;
      font-size: clamp(16px, 1.5vw, 21px);
      letter-spacing: 0.28em;
      text-transform: uppercase;
      margin-bottom: clamp(10px, 1.4vw, 17px);
    }
    .cover-pole--noise { color: rgba(192, 57, 43, 0.95); }
    .cover-pole--signal { color: var(--gold); }
    .cover-stage .hero-funnel {
      inset: -16px -12px -29px -12px;
      -webkit-mask-image:
        linear-gradient(to right, transparent 0%, rgba(0,0,0,0.35) 5%, #000 14%, #000 86%, rgba(0,0,0,0.35) 95%, transparent 100%),
        linear-gradient(to bottom, transparent 0%, rgba(0,0,0,0.4) 8%, #000 18%, #000 78%, rgba(0,0,0,0.45) 90%, transparent 100%);
      mask-image:
        linear-gradient(to right, transparent 0%, rgba(0,0,0,0.35) 5%, #000 14%, #000 86%, rgba(0,0,0,0.35) 95%, transparent 100%),
        linear-gradient(to bottom, transparent 0%, rgba(0,0,0,0.4) 8%, #000 18%, #000 78%, rgba(0,0,0,0.45) 90%, transparent 100%);
      -webkit-mask-composite: source-in;
      mask-composite: intersect;
    }
    .word-before, .word-after {
      font-family: var(--display); font-style: normal; font-weight: 400;
      font-size: clamp(16px, 2vw, 28px); line-height: 1.08;
    }
    .word-before {
      color: var(--ink-2);
      opacity: 0.88;
      text-shadow: 0 0 18px rgba(0, 0, 0, 0.85), 0 1px 3px rgba(0, 0, 0, 0.6);
    }
    .word-after {
      color: var(--gold);
      text-shadow: 0 0 18px rgba(212, 166, 74, 0.3);
      opacity: 1;
    }

    .cover-center {
      position: relative; text-align: center;
      padding: clamp(11px, 1.84vw, 22px) clamp(9px, 1.75vw, 18px);
    }
    .cover-eyebrow {
      display: inline-block; font-family: var(--mono); font-size: 13px;
      letter-spacing: 0.24em; text-transform: uppercase; color: var(--gold); margin-bottom: 14px;
    }
    .cover-title {
      margin: 0;
      font-size: clamp(37px, 5.75vw, 87px);
      line-height: 0.95;
      text-align: center;
      text-wrap: normal;
    }
    .cover-lede {
      margin: 17px auto 0;
      max-width: min(44ch, 100%);
      font-family: var(--sans);
      font-size: clamp(16px, 1.38vw, 20px); font-weight: 400; font-style: normal;
      line-height: 1.45; letter-spacing: -0.01em; color: var(--ink-2);
      text-align: center; text-wrap: pretty;
      overflow-wrap: break-word;
    }
    .cover-cta { margin-top: 22px; display: flex; justify-content: center; }

    .sticky-nav-inner {
      padding-block: 12px;
      min-width: 0;
    }
    @media (max-width: 900px) {
      .sticky-glass-header {
        max-width: 100vw;
        overflow-x: clip;
      }
      .sticky-nav-inner {
        gap: 8px;
      }
      .sticky-nav-inner > a:first-child {
        font-size: 14px;
      }
      .sticky-nav-inner .mobile-ch-btn {
        flex: 1;
        min-width: 0;
        max-width: none;
      }
      .sticky-nav-inner .mobile-ch-btn > span:nth-child(2) {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        min-width: 0;
      }
      .sticky-nav-join { display: none !important; }
    }

    /* ---- Chapter nav dropdowns (desktop) ---- */
    .chapter-nav-dd-strip {
      display: inline-flex;
      align-items: center;
      flex-wrap: wrap;
      justify-content: center;
      gap: 3px;
      padding: 4px;
      border-radius: var(--radius-pill);
      background: rgba(255,255,255,0.04);
      border: 1px solid var(--rule-strong);
      box-shadow: inset 0 1px 0 rgba(255,255,255,0.04);
      max-width: 100%;
    }
    .chapter-nav-dd {
      position: relative;
    }
    .chapter-nav-dd-trigger {
      display: inline-flex;
      align-items: center;
      gap: 6px;
      padding: 7px 10px 7px 8px;
      border: 1px solid transparent;
      border-radius: var(--radius-pill);
      background: transparent;
      color: var(--ink-3);
      font-family: var(--mono);
      font-size: 11px;
      letter-spacing: 0.08em;
      cursor: pointer;
      transition: color 0.18s ease, background 0.18s ease, border-color 0.18s ease;
      white-space: nowrap;
    }
    .chapter-nav-dd-trigger:hover,
    .chapter-nav-dd.open .chapter-nav-dd-trigger {
      color: var(--ink-2);
      background: rgba(255,255,255,0.03);
    }
    .chapter-nav-dd.active .chapter-nav-dd-trigger {
      color: var(--dd-accent, var(--gold));
      background: color-mix(in srgb, var(--dd-accent, var(--gold)) 12%, transparent);
      border-color: color-mix(in srgb, var(--dd-accent, var(--gold)) 28%, transparent);
      font-weight: 600;
    }
    .chapter-nav-dd-num { opacity: 0.72; }
    .chapter-nav-dd-label { font-family: var(--sans); font-weight: 600; font-size: 11px; letter-spacing: -0.01em; }
    .chapter-nav-dd-chevron { font-size: 9px; opacity: 0.55; margin-left: 1px; }
    .chapter-nav-dd-menu {
      position: absolute;
      top: calc(100% + 8px);
      left: 50%;
      transform: translateX(-50%);
      min-width: 220px;
      max-width: 280px;
      padding: 8px;
      background: rgba(14,14,14,0.98);
      border: 1px solid var(--rule-strong);
      border-radius: 12px;
      box-shadow: 0 16px 40px rgba(0,0,0,0.55);
      overflow: visible;
      z-index: 80;
    }
    .chapter-nav-dd-item {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      gap: 2px;
      width: 100%;
      padding: 10px 12px;
      border: none;
      border-radius: 8px;
      background: transparent;
      color: var(--ink-2);
      text-align: left;
      cursor: pointer;
      transition: background 0.15s ease;
    }
    .chapter-nav-dd-item:hover { background: rgba(255,255,255,0.05); }
    .chapter-nav-dd-item-label {
      font-family: var(--sans);
      font-weight: 600;
      font-size: 13px;
      letter-spacing: -0.01em;
      color: var(--ink);
    }
    .chapter-nav-dd-item-sub {
      font-family: var(--mono);
      font-size: 10px;
      letter-spacing: 0.1em;
      color: var(--ink-4);
      text-transform: uppercase;
    }
    .chapter-nav-dd-divider {
      height: 1px;
      margin: 6px 8px;
      background: var(--rule);
    }
    .chapter-nav-dd-flyout-parent {
      position: relative;
    }
    .chapter-nav-dd-flyout-parent > .chapter-nav-dd-item {
      padding-right: 28px;
    }
    .chapter-nav-dd-flyout-arrow {
      position: absolute;
      right: 12px;
      top: 50%;
      transform: translateY(-50%);
      font-size: 10px;
      color: var(--ink-4);
      pointer-events: none;
    }
    .chapter-nav-dd-flyout {
      position: absolute;
      left: calc(100% + 4px);
      top: -4px;
      min-width: 200px;
      padding: 6px;
      background: rgba(14,14,14,0.98);
      border: 1px solid var(--rule-strong);
      border-radius: 10px;
      box-shadow: 0 12px 32px rgba(0,0,0,0.5);
      opacity: 0;
      visibility: hidden;
      pointer-events: none;
      transition: opacity 0.15s ease, visibility 0.15s ease;
      z-index: 90;
    }
    .chapter-nav-dd-flyout-parent:hover .chapter-nav-dd-flyout,
    .chapter-nav-dd-flyout-parent:focus-within .chapter-nav-dd-flyout {
      opacity: 1;
      visibility: visible;
      pointer-events: auto;
    }
    .chapter-nav-dd-flyout .chapter-nav-dd-item-label { font-size: 12px; }
    .chapter-nav-dd-plain .chapter-nav-dd-trigger .chapter-nav-dd-chevron { display: none; }

    /* Mobile nested nav in chapter sheet */
    .mobile-ch-nested {
      display: flex;
      flex-direction: column;
      gap: 4px;
      padding: 0 0 8px 12px;
      margin-top: -4px;
      margin-bottom: 4px;
      border-left: 1px solid var(--rule);
      margin-left: 8px;
    }
    .mobile-ch-nested-btn {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      gap: 2px;
      padding: 10px 12px;
      border: 1px solid transparent;
      border-radius: 8px;
      background: transparent;
      color: var(--ink-2);
      text-align: left;
      cursor: pointer;
      width: 100%;
    }
    .mobile-ch-nested-btn:hover { background: rgba(255,255,255,0.04); }
    .mobile-ch-nested-group {
      font-family: var(--mono);
      font-size: 10px;
      letter-spacing: 0.12em;
      color: var(--ink-4);
      text-transform: uppercase;
      padding: 8px 12px 4px;
    }
    .mobile-ch-nested-child { padding-left: 10px; }

    /* Desktop: one viewport - hero centered, chapter cards + rule pinned to bottom */
    @media (min-width: 901px) {
      #cover {
        --cover-header: 57px;
        min-height: calc(100svh - var(--cover-header));
        display: flex;
        flex-direction: column;
        padding-top: clamp(10px, 1.6vw, 19px);
        padding-bottom: 0;
        box-sizing: border-box;
      }
      #cover > .page {
        flex: 1;
        display: flex;
        flex-direction: column;
        min-height: 0;
      }
      .cover-stage {
        flex: 1;
        min-height: 0;
        display: flex;
        flex-direction: column;
        justify-content: center;
        padding-top: 0;
        padding-bottom: clamp(3px, 0.8vw, 10px);
      }
      .cover-grid {
        flex: 0 0 auto;
        margin-block: clamp(-22px, -2vh, -40px);
      }
      .cover-index {
        margin-top: auto;
        padding-top: clamp(8px, 0.96vw, 13px);
        padding-bottom: 0;
      }
      .cover-index::before {
        margin-bottom: clamp(8px, 0.96vw, 13px);
      }
    }

    @media (max-width: 900px) {
      #cover {
        min-height: 0;
        padding-top: clamp(24px, 3.5vw, 40px);
        padding-bottom: clamp(20px, 3vw, 32px);
        overflow-x: clip;
      }
      .cover-stage {
        min-height: 0;
        padding-bottom: 8px;
        overflow: hidden;
      }
      .cover-stage .hero-funnel {
        inset: 0;
      }
      .cover-grid { display: none; }
      .cover-center {
        background: none;
        padding: 8px 0 16px;
        width: 100%;
        max-width: 100%;
        box-sizing: border-box;
      }
      .show-mobile.cover-center {
        position: relative;
        z-index: 4;
        padding-inline: max(4px, env(safe-area-inset-left, 0px)) max(4px, env(safe-area-inset-right, 0px));
      }
      .show-mobile.cover-center .cover-cta { display: none; }
      .show-mobile.cover-center .cover-title {
        font-size: clamp(32px, 9.8vw, 48px);
        max-width: 100%;
        overflow-wrap: break-word;
      }
      .show-mobile.cover-center .cover-lede {
        margin-top: 23px;
        margin-bottom: 0;
        max-width: min(36ch, 100%);
        width: auto;
        padding-inline: 0;
        font-size: clamp(15px, 4vw, 17px);
        line-height: 1.5;
        text-wrap: pretty;
        overflow-wrap: break-word;
        white-space: normal;
      }
    }
    @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: 1fr !important; }
      /* Cover hero: single column on phones */
      .cover-hero { grid-template-columns: 1fr !important; }
      .cover-headline, .cover-meta { grid-column: 1 / -1 !important; }
    }
  `;
  document.head.appendChild(s);
}

function ChapterNavMenuItems({ chapter, onPick, onClose }) {
  const nav = CHAPTER_NAV[chapter];
  if (!nav) return null;

  const pick = (target) => {
    onPick(target);
    onClose?.();
  };

  return nav.items.map((item, idx) => (
    <React.Fragment key={`${chapter}-${item.label}-${idx}`}>
      {idx > 0 ? <div className="chapter-nav-dd-divider" aria-hidden="true" /> : null}
      {item.children?.length ? (
        <div className="chapter-nav-dd-flyout-parent">
          <button type="button" className="chapter-nav-dd-item" onClick={() => pick(item.target)}>
            <span className="chapter-nav-dd-item-label">{item.label}</span>
            {item.sub ? <span className="chapter-nav-dd-item-sub">{item.sub}</span> : null}
          </button>
          <span className="chapter-nav-dd-flyout-arrow" aria-hidden="true">▸</span>
          <div className="chapter-nav-dd-flyout" role="menu">
            {item.children.map((child) => (
              <button
                key={child.label}
                type="button"
                className="chapter-nav-dd-item"
                onClick={() => pick(child.target)}
              >
                <span className="chapter-nav-dd-item-label">{child.label}</span>
                {child.sub ? <span className="chapter-nav-dd-item-sub">{child.sub}</span> : null}
              </button>
            ))}
          </div>
        </div>
      ) : (
        <button type="button" className="chapter-nav-dd-item" onClick={() => pick(item.target)}>
          <span className="chapter-nav-dd-item-label">{item.label}</span>
          {item.sub ? <span className="chapter-nav-dd-item-sub">{item.sub}</span> : null}
        </button>
      )}
    </React.Fragment>
  ));
}

function ChapterNavDropdowns({ active, onNavigate }) {
  const [openChapter, setOpenChapter] = React.useState(null);
  const closeTimer = React.useRef(null);

  const open = (n) => {
    if (closeTimer.current) clearTimeout(closeTimer.current);
    setOpenChapter(n);
  };
  const scheduleClose = () => {
    closeTimer.current = setTimeout(() => setOpenChapter(null), 120);
  };

  React.useEffect(() => () => { if (closeTimer.current) clearTimeout(closeTimer.current); }, []);

  return (
    <div className="chapter-nav-dd-strip" role="navigation" aria-label="Chapters">
      {NAV_CHAPTERS.map((c) => {
        const isActive = c.n === active;
        const hasDropdown = c.n === "03";
        const isOpen = hasDropdown && openChapter === c.n;
        const chapterTarget = { chapter: c.n };
        return (
          <div
            key={c.n}
            className={`chapter-nav-dd${isActive ? " active" : ""}${isOpen ? " open" : ""}${hasDropdown ? "" : " chapter-nav-dd-plain"}`}
            style={{ "--dd-accent": c.color }}
            onMouseEnter={hasDropdown ? () => open(c.n) : undefined}
            onMouseLeave={hasDropdown ? scheduleClose : undefined}
          >
            <button
              type="button"
              className="chapter-nav-dd-trigger"
              aria-haspopup={hasDropdown ? "true" : undefined}
              aria-expanded={hasDropdown ? isOpen : undefined}
              onClick={() => onNavigate(chapterTarget)}
            >
              <span className="chapter-nav-dd-num">{c.n}</span>
              <span className="chapter-nav-dd-label">{c.title}</span>
              {hasDropdown ? <span className="chapter-nav-dd-chevron" aria-hidden="true">▾</span> : null}
            </button>
            {isOpen && (
              <div className="chapter-nav-dd-menu" role="menu" onMouseEnter={() => open(c.n)} onMouseLeave={scheduleClose}>
                <ChapterNavMenuItems chapter={c.n} onPick={onNavigate} />
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

function MobileChapterSheet({ active, onNavigate, onClose }) {
  const [expanded, setExpanded] = React.useState(active);

  return (
    <div className="mobile-ch-sheet" role="dialog" aria-modal="true" aria-label="Select chapter">
      <div className="mobile-ch-sheet-head">
        <span style={{ fontFamily: "var(--sans)", fontWeight: 800, fontSize: 15, letterSpacing: "-0.02em", color: "var(--ink)" }}>
          Producer<span style={{ color: "var(--gold)" }}>•</span>Union
        </span>
        <button className="mobile-ch-sheet-close" onClick={onClose} aria-label="Close chapter menu">×</button>
      </div>
      <div className="mobile-ch-sheet-list">
        <span className="caption" style={{ marginBottom: 4 }}>Jump to a section</span>
        {NAV_CHAPTERS.map((c) => {
          const isActive = c.n === active;
          const hasSubnav = c.n === "03";
          const isExpanded = hasSubnav && expanded === c.n;
          const nav = hasSubnav ? CHAPTER_NAV[c.n] : null;
          return (
            <div key={c.n}>
              <button
                className={`chapter-card ${isActive ? "active" : ""}`}
                onClick={() => {
                  if (hasSubnav) setExpanded(isExpanded ? null : c.n);
                  else { onNavigate({ chapter: c.n }); onClose(); }
                }}
                style={{ width: "100%" }}
              >
                <span className="chapter-numeral" style={{ fontSize: "clamp(28px, 4.2vw, 36px)", color: c.color }}>{c.n}</span>
                <span style={{ fontFamily: "var(--sans)", fontWeight: 700, fontSize: 15, letterSpacing: "-0.015em", color: isActive ? "var(--ink)" : "var(--ink-2)" }}>{c.title}</span>
                <span className="caption" style={{ marginTop: 2 }}>{c.sub}</span>
                {hasSubnav ? (
                  <span className="caption" style={{ marginTop: 6, color: "var(--ink-4)" }}>{isExpanded ? "▴ hide tools" : "▾ tools"}</span>
                ) : null}
              </button>
              {isExpanded && nav && (
                <div className="mobile-ch-nested">
                  {nav.items.map((item, idx) => (
                    <React.Fragment key={`${c.n}-m-${idx}`}>
                      {idx > 0 ? <div style={{ height: 1, margin: "6px 12px", background: "var(--rule)" }} aria-hidden="true" /> : null}
                      <button
                        type="button"
                        className="mobile-ch-nested-btn"
                        onClick={() => { onNavigate(item.target); onClose(); }}
                      >
                        <span style={{ fontFamily: "var(--sans)", fontWeight: 600, fontSize: 14, color: "var(--ink)" }}>{item.label}</span>
                        {item.sub ? <span className="caption">{item.sub}</span> : null}
                      </button>
                      {item.children?.map((child) => (
                        <button
                          key={child.label}
                          type="button"
                          className="mobile-ch-nested-btn mobile-ch-nested-child"
                          onClick={() => { onNavigate(child.target); onClose(); }}
                        >
                          <span style={{ fontFamily: "var(--sans)", fontWeight: 600, fontSize: 13, color: "var(--ink-2)" }}>{child.label}</span>
                          {child.sub ? <span className="caption">{child.sub}</span> : null}
                        </button>
                      ))}
                    </React.Fragment>
                  ))}
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

function StickyNav({ active, onNavigate }) {
  const [sheetOpen, setSheetOpen] = React.useState(false);
  const activeChapter = CHAPTERS.find((c) => c.n === active);

  // Close sheet on Escape
  React.useEffect(() => {
    if (!sheetOpen) return;
    const handler = (e) => { if (e.key === "Escape") setSheetOpen(false); };
    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, [sheetOpen]);

  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 sticky-nav-inner" style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12 }}>
          <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", flex: 1, justifyContent: "center", minWidth: 0 }}>
            <ChapterNavDropdowns active={active} onNavigate={onNavigate} />
          </nav>

          <button
            className="mobile-ch-btn"
            onClick={() => setSheetOpen(true)}
            aria-haspopup="dialog"
            aria-expanded={sheetOpen}
          >
            <span style={{ color: activeChapter?.color || "var(--gold)", fontFamily: "var(--mono)", fontSize: 11, letterSpacing: "0.1em" }}>
              {active}
            </span>
            <span style={{ color: "var(--ink-2)" }}>{activeChapter?.title}</span>
            <span style={{ color: "var(--ink-3)", fontSize: 10 }}>▾</span>
          </button>

          <JoinCta
            href={PU_LINKS.free}
            className="sticky-nav-join"
            style={{ padding: "8px 14px", fontSize: 12, flex: "0 0 auto" }}
          >
            Join free
          </JoinCta>
        </div>
      </header>

      {sheetOpen && (
        <MobileChapterSheet
          active={active}
          onNavigate={onNavigate}
          onClose={() => setSheetOpen(false)}
        />
      )}
    </>
  );
}

const COVER_BEFORE = ["Broke", "Overlooked", "Guessing", "Underpaid", "Frustrated"];
const COVER_AFTER = ["Records", "Fame", "Royalties", "Leverage", "Paid"];

function Cover({ active, setActive }) {
  return (
    <section id="cover">
      <div className="page">
        <div className="cover-stage">
          <HeroFunnel />

          <div className="cover-grid hide-mobile">
            <div className="cover-col cover-col--noise" aria-hidden="true">
              <div className="cover-pole cover-pole--noise">Before</div>
              {COVER_BEFORE.map((w) => (
                <span key={w} className="word-before">{w}</span>
              ))}
            </div>

            <div className="cover-center">
              <span className="cover-eyebrow">From noise to signal</span>
              <h1 className="display cover-title">
                The<br />
                producer's<br />
                roadmap.
              </h1>
              <p className="cover-lede">
                What to focus on, how to land more records, and how to build a sustainable career.
              </p>
              <div className="cover-cta">
                <JoinCta href={PU_LINKS.free}>Join free on Skool</JoinCta>
              </div>
            </div>

            <div className="cover-col cover-col--signal" aria-hidden="true">
              <div className="cover-pole cover-pole--signal">After</div>
              {COVER_AFTER.map((w) => (
                <span key={w} className="word-after">{w}</span>
              ))}
            </div>
          </div>

          <div
            className="show-mobile cover-center"
            style={{ width: "100%", maxWidth: "100%", boxSizing: "border-box", textAlign: "center" }}
          >
            <span className="cover-eyebrow">From noise to signal</span>
            <h1 className="display cover-title">
              The<br />
              producer's<br />
              roadmap.
            </h1>
            <p
              className="cover-lede"
              style={{
                maxWidth: "min(36ch, 100%)",
                margin: "23px auto 0",
                whiteSpace: "normal",
                overflowWrap: "break-word",
              }}
            >
              What to focus on, how to land more records, and how to build a sustainable career.
            </p>
            <div className="cover-cta">
              <JoinCta href={PU_LINKS.free}>Join free on Skool</JoinCta>
            </div>
          </div>
        </div>
        <div className="cover-index">
          <ChapterIndexBody active={active} setActive={setActive} />
        </div>
      </div>
    </section>
  );
}

function ChapterIndexBody({ active, setActive }) {
  return (
    <>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 14 }} className="chapter-grid">
        {NAV_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(34px, 4vw, 46px)", color: c.color }}>{c.n}</span>
              <span style={{ fontFamily: "var(--sans)", fontWeight: 700, fontSize: 15, 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, navTarget }) {
  switch (chapter) {
    case "01": return <><Hurdles navTarget={navTarget} /><AssessmentPrompt /></>;
    case "02": return <MoneyFlow />;
    case "03": return <YourNumbers navTarget={navTarget} />;
    case "04": return <Rules navTarget={navTarget} />;
    case "05": return <><Pricing /><Bio /></>;
    case "06": return <Resources navTarget={navTarget} />;
    default: return null;
  }
}

function ChapterNav({ chapter, setActive }) {
  const idx = NAV_CHAPTERS.findIndex((c) => c.n === chapter);
  const prev = idx > 0 ? NAV_CHAPTERS[idx - 1] : null;
  const next = idx < NAV_CHAPTERS.length - 1 ? NAV_CHAPTERS[idx + 1] : null;
  const btnBase = { flex: "1 1 240px", padding: "16px 22px", justifyContent: "space-between" };
  return (
    <section style={{ paddingBlock: 48, borderTop: "1px solid var(--rule-strong)" }}>
      <div className="page" style={{ display: "flex", justifyContent: "space-between", alignItems: "stretch", gap: 12, flexWrap: "wrap" }}>
        {prev ? (
          <button onClick={() => setActive(prev.n)} className="btn btn-ghost" style={{ ...btnBase, 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: 17, letterSpacing: "-0.02em" }}>{prev.title}</div>
            </span>
          </button>
        ) : <span style={{ flex: "1 1 240px" }}></span>}
        {next ? (
          <button onClick={() => setActive(next.n)} className="btn btn-primary" style={btnBase}>
            <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: 17, 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={{ ...btnBase, 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 · {chapter}</span>
              <span style={{ fontFamily: "var(--sans)", fontWeight: 700, fontSize: 17, letterSpacing: "-0.02em" }}>Join free on Skool</span>
            </span>
            <Arrow d="right" />
          </a>
        )}
      </div>
    </section>
  );
}

function MobileCtaBar() {
  return (
    <div className="mobile-cta-bar" aria-label="Join Producer Union">
      <div>
        <div style={{ fontFamily: "var(--sans)", fontWeight: 700, fontSize: 13, color: "var(--ink)", letterSpacing: "-0.01em" }}>
          Producer Union
        </div>
        <div style={{ fontFamily: "var(--mono)", fontSize: 10, color: "var(--ink-3)", letterSpacing: "0.08em", marginTop: 1 }}>
          Free community · No card needed
        </div>
      </div>
      <JoinCta href={PU_LINKS.free} style={{ padding: "10px 16px", fontSize: 13, flex: "0 0 auto" }}>
        Join free
      </JoinCta>
    </div>
  );
}

function ChapteredApp() {
  const [active, setActive] = React.useState("01");
  const [navTarget, setNavTarget] = React.useState({ chapter: "01", key: 0 });

  const navigateTo = React.useCallback((target) => {
    if (HIDDEN_CHAPTERS.has(target.chapter)) return;
    const next = { ...target, key: Date.now() };
    setActive(target.chapter);
    setNavTarget(next);

    requestAnimationFrame(() => {
      const workspace = document.getElementById("chapter-workspace");
      if (workspace) {
        const y = workspace.getBoundingClientRect().top + window.scrollY - 84;
        window.scrollTo({ top: y, behavior: "smooth" });
      }

      const sectionId = scrollTargetForNav(target);
      if (sectionId) {
        setTimeout(() => scrollToSectionId(sectionId), target.chapter === active ? 80 : 320);
      }

      if (target.action === "assessment") {
        setTimeout(() => document.dispatchEvent(new CustomEvent("openAssessment")), 400);
      }
    });
  }, [active]);

  const changeChapter = React.useCallback((n) => {
    if (HIDDEN_CHAPTERS.has(n)) return;
    const defaultTarget = CHAPTER_NAV[n]?.items?.[0]?.target || { chapter: n };
    navigateTo(defaultTarget);
  }, [navigateTo]);

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

window.ChapteredApp = ChapteredApp;
