// Printable action plan — 14 sections, AC-Conti Output Protocol v6.1
const { useState: useStatePlan } = React;

// Per-domain labels for the package tables AND the surrounding section
// headers. The schema field names stay generic (base/signOn/bonus/assignment);
// the rendered headers adapt to the domain. Falls back to corporate.
const PACKAGE_LABELS = {
  corporate:  { base: "Base",           signOn: "Sign-on",              bonus: "Bonus",              assignment: "Role / Location",    total: "Total comp",           counterpart: "recruiter",       boss: "their HR partner" },
  academic:   { base: "Annual base",    signOn: "One-time support",     bonus: "Research budget",    assignment: "Teaching load",      total: "Total package value",  counterpart: "Dean",            boss: "the provost" },
  executive:  { base: "Base",           signOn: "Sign-on / make-whole", bonus: "LTI / target bonus", assignment: "Title / scope",      total: "Total comp",           counterpart: "board",           boss: "the board chair" },
  startup:    { base: "Base",           signOn: "Sign-on",              bonus: "Equity %",           assignment: "Role / vesting",     total: "Total package",        counterpart: "founder",         boss: "their co-founder" },
  sales:      { base: "Base",           signOn: "Sign-on / draw",       bonus: "OTE / commission",   assignment: "Quota / territory",  total: "Total OTE",            counterpart: "sales leader",    boss: "their VP" },
  procurement:{ base: "Headline price", signOn: "One-time concession",  bonus: "Recurring extras",   assignment: "Non-price terms",    total: "Total contract value", counterpart: "supplier",        boss: "their CFO" },
  other:      { base: "Headline",       signOn: "One-time",             bonus: "Recurring extras",   assignment: "Non-monetary terms", total: "Total",                counterpart: "counterpart",     boss: "their leadership" },
};

function getPackageLabels(plan) {
  const d = plan?.domain;
  return PACKAGE_LABELS[d] || PACKAGE_LABELS.corporate;
}

// Color tone per ZOPA zone — cool/green → red.
const ZOPA_TONE = {
  Aspirational: "zopa-aspire",
  Good:         "zopa-good",
  Acceptable:   "zopa-ok",
  Painful:      "zopa-warn",
  "Walk-Away":  "zopa-walk",
};

// Map readiness statuses to a visual checkbox tone.
const READY_TONE = {
  Ready:    { icon: "check", cls: "rdy-ready",   label: "Ready" },
  Partial:  { icon: "circle", cls: "rdy-partial", label: "Partial" },
  "Not yet":{ icon: "x", cls: "rdy-not",     label: "Not yet" },
};

// The upstream StrategIQ strategic-sourcing read, shown as an intelligence
// callout above the plan. Only the user-facing fields (briefSummary, topActions)
// plus a few orienting facts — the full 9-element analysis already shaped the
// plan body below; this panel tells the user WHERE the plan's strategy came from.
function StrategicSourcingPanel({ brief }) {
  if (!brief || !brief.element1_strategicContext) return null;
  const e1 = brief.element1_strategicContext || {};
  const e4 = brief.element4_counterpartIntelligence || {};
  const e9 = brief.element9_strategicOptions || {};
  const cp = brief.canProceed || {};
  const options = Array.isArray(e9.options) ? [...e9.options].sort((a, b) => (a.priority || 9) - (b.priority || 9)) : [];
  const kraljic = e1.kraljicPosition && e1.kraljicPosition !== "unknown"
    ? e1.kraljicPosition.charAt(0).toUpperCase() + e1.kraljicPosition.slice(1)
    : null;

  return (
    <details className="plan-sourcing-aside no-print" open style={{ margin: "0 0 28px", padding: "20px 24px", border: "1px solid #E3E3EA", borderLeft: "4px solid #1E1E5A", borderRadius: 10, background: "#FAFAFC" }}>
      <summary style={{ cursor: "pointer", listStyle: "none", fontWeight: 600, color: "#1E1E5A", display: "flex", alignItems: "center", gap: 10 }}>
        <span className="kicker" style={{ margin: 0 }}>Strategic sourcing read</span>
        {cp.status && <span style={{ fontSize: 11, fontWeight: 600, padding: "2px 8px", borderRadius: 999, background: cp.status === "CAN_PROCEED" ? "#E6F4EA" : cp.status === "BLOCKED" ? "#FBE9E7" : "#FFF4E5", color: cp.status === "CAN_PROCEED" ? "#1B7A3D" : cp.status === "BLOCKED" ? "#B3261E" : "#9A6A00" }}>{cp.status.replace(/_/g, " ")}</span>}
      </summary>

      {brief.briefSummary && <p style={{ margin: "12px 0 14px", color: "#33333A", lineHeight: 1.5 }}>{brief.briefSummary}</p>}

      <div style={{ display: "flex", flexWrap: "wrap", gap: "8px 18px", fontSize: 13, color: "#55555F", marginBottom: 14 }}>
        {kraljic && <span><strong>Category:</strong> {kraljic}</span>}
        {(e4.buyerBatnaStrength && e4.buyerBatnaStrength !== "UNKNOWN") && <span><strong>Your BATNA:</strong> {e4.buyerBatnaStrength}</span>}
        {(e4.supplierBatnaStrength && e4.supplierBatnaStrength !== "UNKNOWN") && <span><strong>Their BATNA:</strong> {e4.supplierBatnaStrength}</span>}
      </div>

      {Array.isArray(brief.topActions) && brief.topActions.length > 0 && (
        <div style={{ marginBottom: options.length ? 14 : 0 }}>
          <div className="kicker" style={{ marginBottom: 6 }}>Do these first</div>
          <ul style={{ margin: 0, paddingLeft: 20, color: "#33333A", lineHeight: 1.55 }}>
            {brief.topActions.map((a, i) => <li key={i}>{a}</li>)}
          </ul>
        </div>
      )}

      {options.length > 0 && (
        <div>
          <div className="kicker" style={{ marginBottom: 6 }}>Strategic options carried into the plan</div>
          <ul style={{ margin: 0, paddingLeft: 20, color: "#33333A", lineHeight: 1.55 }}>
            {options.map((o, i) => <li key={i}><strong>{o.title}</strong>{o.description ? " — " + o.description : ""}</li>)}
          </ul>
        </div>
      )}
    </details>
  );
}

function ActionPlan({ situation, coach, plan, user, byoKeyStatus, creditStatus, onBack, onRestart, onOpenSettings, onSignOut }) {
  // Live mode passes plan from /api/plan. Demo mode (and any fallback) uses PLAN_DATA.
  const D = plan || PLAN_DATA;
  const L = getPackageLabels(D);

  const handlePrint = () => window.print();

  return (
    <div className="screen plan-screen">
      {user && (
        <AppTopBar
          user={user}
          active="plan"
          onNewCase={null}
          onOpenWorkspace={onRestart}
          onOpenSettings={onOpenSettings}
          onSignOut={onSignOut}
          byoKeyStatus={byoKeyStatus}
          creditStatus={creditStatus}
        />
      )}
      <div className="plan-action-bar no-print">
        <button className="btn-ghost" onClick={onBack}>
          <IconText name="arrow-left">Back to conversation</IconText>
        </button>
        <div className="plan-action-bar-r">
          <button className="btn-ghost" onClick={onRestart}>
            <IconText name="home">Workspace</IconText>
          </button>
          <button className="btn-primary" onClick={handlePrint}>
            <IconText name="printer">Print or save as PDF</IconText>
          </button>
        </div>
      </div>

      <div className="plan-page">
        {/* Header */}
        <header className="plan-header">
          <div className="plan-header-l">
            <div className="kicker">Negotiation preparation plan</div>
            <h1 className="plan-title display">{D.title}</h1>
            <div className="plan-byline">CABL Procurement Lab · {D.date}</div>
            {D.recommendedPosture && (
              <div className="plan-posture-row">
                <span className="plan-posture-label">Recommended stance</span>
                <span className="plan-posture-badge">{D.recommendedPosture}</span>
              </div>
            )}
          </div>
          <div className="plan-header-r">
            <img src="assets/cabl-logo.png" alt="CABL" className="plan-header-logo"/>
            <div className="plan-stamp">Prepared for {D.generatedFor}</div>
          </div>
        </header>

        {/* Upstream strategic-sourcing read (only on cases where StrategIQ ran) */}
        <StrategicSourcingPanel brief={D.strategiqBrief}/>

        {/* Table of contents */}
        <nav className="plan-toc">
          <div className="kicker">In this plan</div>
          <ol className="plan-toc-list">
            <li>The quick read</li>
            <li>Who you're talking to</li>
            <li>What's on the table — both sides</li>
            <li>Your goal numbers</li>
            <li>What you've got going for you</li>
            <li>Your three opening offers</li>
            <li>Your opening lines + questions</li>
            <li>How you'll move</li>
            <li>The call itself</li>
            <li>Things to watch out for</li>
            <li>Do these next</li>
            <li>How you'll describe this win to your team</li>
            <li>How they'll defend this deal to {L.boss}</li>
            <li>Ready to walk in?</li>
          </ol>
        </nav>

        {/* 1. Snapshot — mirrored */}
        <Section num="01" title="The quick read">
          <div className="plan-grid-2">
            <div className="plan-block">
              <div className="kicker">Your side</div>
              <p>{D.snapshot.situation}</p>
              <p><strong>What you're aiming for:</strong> {D.snapshot.objective}</p>
            </div>
            <div className="plan-block plan-block-mirror">
              <div className="kicker">Their side (estimated)</div>
              <p>{D.snapshot.counterpartLens}</p>
            </div>
          </div>
          <div className="plan-callout plan-callout-insight">
            <div className="kicker">The move that makes this plan</div>
            <blockquote>"{D.snapshot.recommendation}"</blockquote>
          </div>
        </Section>

        {/* 2. Counterpart diagnosis — mirror + scenarios + hidden + relationship */}
        <Section num="02" title="Who you're talking to">
          {/* 2.0 Counterpart Mapping */}
          <h3 className="plan-h3">Side-by-side: where you stand vs. where they stand</h3>
          <table className="plan-table plan-mirror">
            <thead>
              <tr>
                <th>What we're mapping</th>
                <th>You</th>
                <th>Them (estimated)</th>
                <th>Confidence</th>
              </tr>
            </thead>
            <tbody>
              {D.counterpartMirror?.map((r, i) => (
                <tr key={i}>
                  <td><strong>{r.field}</strong></td>
                  <td>{r.ourSide}</td>
                  <td className="cell-counter">{r.counterpartSide}</td>
                  <td><span className={`conf-pill conf-${r.confidence.toLowerCase()}`}>{r.confidence}</span></td>
                </tr>
              ))}
            </tbody>
          </table>

          <h3 className="plan-h3" style={{ marginTop: "32px" }}>What we know (and what we're guessing)</h3>
          <div className="plan-grid-4">
            <InfoCol tag="We know"    tone="ok"      items={D.diagnosis.confirmed}/>
            <InfoCol tag="We assume"  tone="warn"    items={D.diagnosis.assumptions}/>
            <InfoCol tag="We suspect" tone="neutral" items={D.diagnosis.hypotheses}/>
            <InfoCol tag="Still TBD"  tone="bad"     items={D.diagnosis.unknowns}/>
          </div>

          <h3 className="plan-h3" style={{ marginTop: "32px" }}>How the {L.counterpart} might be playing this</h3>
          <div className="plan-scenarios">
            {D.scenarios.map(s => (
              <div key={s.letter} className="plan-scenario">
                <div className="plan-scenario-letter">{s.letter}</div>
                <div className="plan-scenario-title">{s.title}</div>
                <dl>
                  <dt>Driver</dt><dd>{s.driver}</dd>
                  <dt>Signals</dt><dd>{s.signals}</dd>
                  <dt>Best response</dt><dd>{s.response}</dd>
                </dl>
                <div className="plan-scenario-foot">Confidence · <strong>{s.confidence}</strong></div>
              </div>
            ))}
          </div>

          {D.hiddenStakeholders && D.hiddenStakeholders.length > 0 && (
            <>
              <h3 className="plan-h3" style={{ marginTop: "32px" }}>Who's behind the room</h3>
              <p className="plan-lede">The people who shape this deal but aren't in the conversation. Plan for them.</p>
              <table className="plan-table">
                <thead>
                  <tr><th>Person / role</th><th>How visible</th><th>How they influence</th><th>What to do</th></tr>
                </thead>
                <tbody>
                  {D.hiddenStakeholders.map((r, i) => (
                    <tr key={i}>
                      <td><strong>{r.stakeholder}</strong></td>
                      <td><span className={`vis-pill vis-${r.visibility.toLowerCase().replace(/[^a-z]/g, "")}`}>{r.visibility}</span></td>
                      <td>{r.influence}</td>
                      <td className="cell-note">{r.action}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </>
          )}

          {D.relationshipStrategy && (
            <>
              <h3 className="plan-h3" style={{ marginTop: "32px" }}>The relationship mode for this round</h3>
              <div className="plan-relationship">
                <div className="plan-relationship-states">
                  <div className="rel-state">
                    <div className="kicker">Today</div>
                    <div className="rel-state-label">{D.relationshipStrategy.currentState}</div>
                  </div>
                  <div className="rel-arrow"><Icon name="arrow-right" size={32}/></div>
                  <div className="rel-state">
                    <div className="kicker">This round</div>
                    <div className="rel-state-label rel-state-target">{D.relationshipStrategy.desiredState}</div>
                  </div>
                </div>
                <p className="plan-rel-rationale">{D.relationshipStrategy.shiftRationale}</p>
                <div className="kicker">How you'll execute the shift</div>
                <ul className="plan-rel-actions">
                  {D.relationshipStrategy.actionSteps.map((s, i) => (
                    <li key={i}>
                      <Icon name="arrow-right" size={14}/>
                      <span>{s}</span>
                    </li>
                  ))}
                </ul>
              </div>
            </>
          )}
        </Section>

        {/* 3. Issues — both sides */}
        <Section num="03" title="What's on the table — both sides">
          <h3 className="plan-h3">What you actually want</h3>
          <table className="plan-table">
            <thead>
              <tr>
                <th>What</th>
                <th>Right now</th>
                <th>Aim for</th>
                <th>Okay with</th>
                <th>Walk away</th>
                <th>Why it matters</th>
              </tr>
            </thead>
            <tbody>
              {D.issues.map((r, i) => (
                <tr key={i}>
                  <td><strong>{r.issue}</strong></td>
                  <td>{r.current}</td>
                  <td className="cell-target">{r.target}</td>
                  <td>{r.acceptable}</td>
                  <td className="cell-walk">{r.walkAway}</td>
                  <td className="cell-note">{r.note}</td>
                </tr>
              ))}
            </tbody>
          </table>

          {D.theirIssues && D.theirIssues.length > 0 && (
            <>
              <h3 className="plan-h3" style={{ marginTop: "28px" }}>What they probably want</h3>
              <table className="plan-table">
                <thead>
                  <tr><th>Their likely issue</th><th>Priority + confidence</th><th>Likely target</th></tr>
                </thead>
                <tbody>
                  {D.theirIssues.map((r, i) => (
                    <tr key={i}>
                      <td><strong>{r.issue}</strong></td>
                      <td>{r.priority}</td>
                      <td className="cell-note">{r.likelyTarget}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </>
          )}

          <div className="plan-grid-2" style={{ marginTop: "28px" }}>
            <div className="plan-block plan-block-ok">
              <div className="kicker">Common ground (use for trades)</div>
              <ul className="plan-bullets">
                {(D.commonGround || []).map((c, i) => <li key={i}>{c}</li>)}
              </ul>
            </div>
            <div className="plan-block plan-block-warn">
              <div className="kicker">Real conflicts (plan for impasse)</div>
              <ul className="plan-bullets">
                {(D.conflictingIssues || []).map((c, i) => <li key={i}>{c}</li>)}
              </ul>
            </div>
          </div>
        </Section>

        {/* 4. Goal matrix + ZOPA zones */}
        <Section num="04" title="Your goal numbers">
          <p className="plan-lede">
            Four columns — your floor, your real target, your ambitious ask, and the ceiling worth testing.
            Anchor to <em>these</em> numbers in your head, not to their opening.
          </p>
          <table className="plan-table">
            <thead>
              <tr>
                <th>Variable</th>
                <th>Floor (your fallback)</th>
                <th>Target</th>
                <th>Ambitious</th>
                <th>Worth testing</th>
              </tr>
            </thead>
            <tbody>
              {D.goalMatrix.map((r, i) => (
                <tr key={i}>
                  <td><strong>{r.variable}</strong></td>
                  <td className="cell-walk">{r.floor}</td>
                  <td>{r.target}</td>
                  <td className="cell-target">{r.ambitious}</td>
                  <td className="cell-target">{r.ceiling}</td>
                </tr>
              ))}
            </tbody>
          </table>
          <div className="plan-note">
            <span className="plan-note-tag">A note from your coach</span>
            <p>{D.goalMatrixNote}</p>
          </div>

          {D.zopaZones && D.zopaZones.length > 0 && (
            <>
              <h3 className="plan-h3" style={{ marginTop: "32px" }}>What landing in each zone actually means</h3>
              <p className="plan-lede">A landing-zone map for the main number. The walk-away row stays with you only.</p>
              <div className="plan-zopa">
                {D.zopaZones.map((z, i) => (
                  <div key={i} className={`plan-zopa-row ${ZOPA_TONE[z.zone] || ""}`}>
                    <div className="zopa-zone">
                      <div className="zopa-zone-name">{z.zone}</div>
                      {z.zone === "Walk-Away" && (
                        <div className="zopa-confidential">Confidential · do not share</div>
                      )}
                    </div>
                    <div className="zopa-range">{z.range}</div>
                    <div className="zopa-meaning">{z.meaning}</div>
                    <div className="zopa-guidance">{z.guidance}</div>
                  </div>
                ))}
              </div>
              {D.zopaNote && <p className="plan-equivalency-note">{D.zopaNote}</p>}
            </>
          )}
        </Section>

        {/* 5. Leverage + BATNA timeline */}
        <Section num="05" title="What you've got going for you">
          {D.licensingEconomics?.applicable && <LicensingEconomics data={D.licensingEconomics}/>}

          {D.shouldCostTable && D.shouldCostTable.length > 0 && (
            <>
              <h3 className="plan-h3">Your reconstructed cost view</h3>
              <p className="plan-lede">
                This is what their cost actually looks like, broken down — built from your data plus market sources.
                The bottom row is the justified range. You'll anchor on <em>this</em>, not their headline number.
              </p>
              <table className="plan-table plan-shouldcost">
                <thead>
                  <tr>
                    <th>Cost element</th>
                    <th>Share of their cost</th>
                    <th>Market movement</th>
                    <th>Weighted effect</th>
                  </tr>
                </thead>
                <tbody>
                  {D.shouldCostTable.map((r, i) => (
                    <tr key={i}>
                      <td><strong>{r.element}</strong></td>
                      <td>{r.share}</td>
                      <td className="cell-note">{r.movement}</td>
                      <td className="cell-target">{r.weightedEffect}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
              {D.shouldCostNote && (
                <div className="plan-note">
                  <span className="plan-note-tag">Range &amp; sources</span>
                  <p>{D.shouldCostNote}</p>
                </div>
              )}
              <h3 className="plan-h3" style={{ marginTop: "32px" }}>Your other levers</h3>
            </>
          )}

          <p className="plan-lede">Levers you already hold. Some are stronger than others — know which is which.</p>
          <div className="plan-leverage">
            {D.leverage.map((l, i) => (
              <div key={i} className={`plan-leverage-row plan-leverage-${l.strength.toLowerCase()}`}>
                <div className="plan-leverage-name">{l.lever}</div>
                <div className="plan-leverage-strength"><span>{l.strength}</span></div>
                <div className="plan-leverage-how">{l.how}</div>
              </div>
            ))}
          </div>

          {D.batnaTimeline && D.batnaTimeline.length > 0 && (
            <>
              <h3 className="plan-h3" style={{ marginTop: "32px" }}>Your fallback over time</h3>
              <p className="plan-lede">Real alternatives by when they'd actually be available. Honest about what's theoretical vs. actionable.</p>
              <table className="plan-table">
                <thead>
                  <tr>
                    <th>Timeframe</th>
                    <th>Alternative(s)</th>
                    <th>Coverage</th>
                    <th>Status</th>
                    <th>Credibility</th>
                    <th>Switching cost</th>
                  </tr>
                </thead>
                <tbody>
                  {D.batnaTimeline.map((r, i) => (
                    <tr key={i}>
                      <td><strong>{r.timeframe}</strong></td>
                      <td>{r.alternatives}</td>
                      <td>{r.capacity}</td>
                      <td>{r.qualification}</td>
                      <td><span className={`conf-pill conf-${r.credibility.toLowerCase()}`}>{r.credibility}</span></td>
                      <td className="cell-note">{r.switchingCost}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
              {D.batnaTrajectory && (
                <div className="plan-note">
                  <span className="plan-note-tag">Timing</span>
                  <p>{D.batnaTrajectory}</p>
                </div>
              )}
            </>
          )}
        </Section>

        {/* 6. Packages */}
        <Section num="06" title="Your three opening offers">
          <p className="plan-lede">
            Bring all three to the same conversation. Each one tests a different thing.
            How they react to <em>which</em> one tells you more than which one they say yes to.
          </p>

          <h3 className="plan-h3">Opening packages — find out where there's give</h3>
          <div className="plan-packages">
            {D.packages.map(p => (
              <div key={p.label} className="plan-package">
                <div className="plan-package-head">
                  <div className="plan-package-letter">{p.label}</div>
                  <div className="plan-package-tag">{p.tag}</div>
                </div>
                <dl className="plan-package-dl">
                  <div><dt>{L.base}</dt><dd className="big-num">{p.base}</dd></div>
                  <div><dt>{L.signOn}</dt><dd>{p.signOn}</dd></div>
                  <div><dt>{L.bonus}</dt><dd>{p.bonus}</dd></div>
                  <div><dt>{L.assignment}</dt><dd>{p.assignment}</dd></div>
                  <div className="plan-package-total"><dt>{L.total}</dt><dd>{p.total}</dd></div>
                </dl>
                <div className="plan-package-purpose">
                  <div className="kicker">Diagnostic purpose</div>
                  <p>{p.purpose}</p>
                </div>
              </div>
            ))}
          </div>

          {D.packageIntro && (
            <div className="plan-callout">
              <div className="kicker">How to bring it up</div>
              <blockquote>"{D.packageIntro}"</blockquote>
            </div>
          )}

          <h3 className="plan-h3" style={{ marginTop: "32px" }}>Narrowing packages — once they've shown the room</h3>
          <p className="plan-lede">{D.phase2Note}</p>
          <div className="plan-packages">
            {D.phase2.map(p => (
              <div key={p.label} className="plan-package plan-package-p2">
                <div className="plan-package-head">
                  <div className="plan-package-letter">{p.label}</div>
                  <div className="plan-package-tag">{p.tag}</div>
                </div>
                <dl className="plan-package-dl">
                  <div><dt>{L.base}</dt><dd className="big-num">{p.base}</dd></div>
                  <div><dt>{L.signOn}</dt><dd>{p.signOn}</dd></div>
                  <div><dt>{L.bonus}</dt><dd>{p.bonus}</dd></div>
                  <div><dt>{L.assignment}</dt><dd>{p.assignment}</dd></div>
                  <div><dt>Year 1</dt><dd>{p.year1}</dd></div>
                  <div className="plan-package-total"><dt>Year 2+</dt><dd>{p.year2}</dd></div>
                </dl>
                <div className="plan-package-purpose">
                  <div className="kicker">Why this works</div>
                  <p>{p.pitch}</p>
                </div>
              </div>
            ))}
          </div>

          <div className="plan-equivalency">
            <div className="kicker">Are these actually equivalent?</div>
            <table className="plan-table">
              <thead>
                <tr><th>Package</th><th>Year 1 total cash</th><th>Difference from A</th><th>Within 20%?</th></tr>
              </thead>
              <tbody>
                {D.equivalency.map((e, i) => (
                  <tr key={i}>
                    <td><strong>{e.p}</strong></td>
                    <td>{e.y1}</td>
                    <td>{e.diff}</td>
                    <td className="cell-target">{e.ok}</td>
                  </tr>
                ))}
              </tbody>
            </table>
            {D.equivalencyNote && (
              <p className="plan-equivalency-note">{D.equivalencyNote}</p>
            )}
          </div>
        </Section>

        {/* 7. Opening script + question plan + their questions */}
        <Section num="07" title="Your opening lines + questions">
          {D.openingScript && (
            <>
              <h3 className="plan-h3">Your opening script — what to say in the first three minutes</h3>
              <p className="plan-lede">Read it once, then put it away. Don't read it verbatim — it'll sound rehearsed.</p>
              <div className="plan-script">
                <div className="plan-script-block">
                  <div className="plan-script-tag">1 · Set the relationship + your right to negotiate</div>
                  <p>{D.openingScript.frame}</p>
                </div>
                <div className="plan-script-block plan-script-block-assert">
                  <div className="plan-script-tag">2 · Plant your anchor before they plant theirs</div>
                  <p>{D.openingScript.assert}</p>
                </div>
                <div className="plan-script-block">
                  <div className="plan-script-tag">3 · Hand them the burden of explanation</div>
                  <p>{D.openingScript.invite}</p>
                </div>
              </div>
            </>
          )}

          <h3 className="plan-h3" style={{ marginTop: "32px" }}>Your questions for them</h3>
          <table className="plan-table">
            <thead><tr><th>What to ask</th><th>Why it helps</th><th>When</th></tr></thead>
            <tbody>
              {D.questions.map((q, i) => (
                <tr key={i}>
                  <td className="cell-q">"{q.q}"</td>
                  <td>{q.purpose}</td>
                  <td className="cell-when">{q.when}</td>
                </tr>
              ))}
            </tbody>
          </table>

          {D.theirQuestions && D.theirQuestions.length > 0 && (
            <>
              <h3 className="plan-h3" style={{ marginTop: "32px" }}>What they'll probably ask — and how to answer</h3>
              <table className="plan-table">
                <thead>
                  <tr><th>Their likely question</th><th>How to answer</th><th>What you must not reveal</th></tr>
                </thead>
                <tbody>
                  {D.theirQuestions.map((q, i) => (
                    <tr key={i}>
                      <td className="cell-q">"{q.question}"</td>
                      <td>{q.answerLogic}</td>
                      <td className="cell-walk">{q.infoAtRisk}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </>
          )}
        </Section>

        {/* 8. Concession plan — give-get + moves + hard protect */}
        <Section num="08" title="How you'll move">
          {D.giveGet && D.giveGet.length > 0 && (
            <>
              <h3 className="plan-h3">Trade map — what to give, what to require in return</h3>
              <table className="plan-table">
                <thead>
                  <tr><th>You offer</th><th>Cost to you</th><th>You require</th><th>Value to you</th><th>When</th></tr>
                </thead>
                <tbody>
                  {D.giveGet.map((r, i) => (
                    <tr key={i}>
                      <td>{r.give}</td>
                      <td className="cell-walk">{r.costToUs}</td>
                      <td className="cell-target">{r.get}</td>
                      <td>{r.valueToUs}</td>
                      <td className="cell-when">{r.stage}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </>
          )}

          <h3 className="plan-h3" style={{ marginTop: "28px" }}>Sequenced moves</h3>
          <div className="plan-moves">
            {D.moves.map(m => (
              <div key={m.n} className="plan-move">
                <div className="plan-move-n">Step {m.n}</div>
                <div className="plan-move-what">{m.what}</div>
                <dl>
                  <div><dt>You give</dt><dd>{m.gives}</dd></div>
                  <div><dt>You get</dt><dd>{m.gets}</dd></div>
                </dl>
              </div>
            ))}
          </div>
          <div className="plan-protect">
            <div className="kicker">Hard protect — do not give these up</div>
            <ul>
              {D.hardProtect.map((p, i) => (
                <li key={i}>
                  <Icon name="shield" size={15}/>
                  <span>{p}</span>
                </li>
              ))}
            </ul>
          </div>
        </Section>

        {/* 9. Meeting plan + team roles + phrase bank + anti-patterns */}
        <Section num="09" title="The call itself">
          <dl className="plan-meeting">
            <div><dt>You lead</dt><dd>{D.meeting.leads}</dd></div>
            <div><dt>How to open (one-liner)</dt><dd>{D.meeting.open}</dd></div>
            <div><dt>Try not to</dt><dd>{D.meeting.avoid}</dd></div>
            <div><dt>If they push for a number</dt><dd>{D.meeting.ifPushed}</dd></div>
            <div><dt>If they say "this is our best"</dt><dd>{D.meeting.ifFinal}</dd></div>
            <div><dt>When you're ready to close</dt><dd>{D.meeting.close}</dd></div>
          </dl>

          {D.teamRoles && D.teamRoles.length > 0 && (
            <>
              <h3 className="plan-h3" style={{ marginTop: "28px" }}>Who plays what role</h3>
              <p className="plan-lede">Role discipline before, during, and after the meeting. Even solo, knowing the roles helps you spot when you're trying to do too much at once.</p>
              <table className="plan-table">
                <thead><tr><th>Role</th><th>Who</th><th>What they do</th><th>What they don't do</th></tr></thead>
                <tbody>
                  {D.teamRoles.map((r, i) => (
                    <tr key={i}>
                      <td><strong>{r.role}</strong></td>
                      <td>{r.person}</td>
                      <td>{r.responsibility}</td>
                      <td className="cell-walk">{r.doNotDo}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </>
          )}

          {D.phraseBank && D.phraseBank.length > 0 && (
            <>
              <h3 className="plan-h3" style={{ marginTop: "28px" }}>Lines to have ready</h3>
              <p className="plan-lede">Plain phrases you can use in the moment. No need to memorize — just know they exist.</p>
              <div className="plan-phrasebank">
                {D.phraseBank.map((p, i) => (
                  <div key={i} className="plan-phrase">
                    <div className="plan-phrase-tag">{p.purpose}</div>
                    <div className="plan-phrase-text">"{p.phrase}"</div>
                  </div>
                ))}
              </div>
            </>
          )}

          {D.antiPatterns && D.antiPatterns.length > 0 && (
            <>
              <h3 className="plan-h3" style={{ marginTop: "28px" }}>Things to catch yourself doing</h3>
              <ul className="plan-antipatterns">
                {D.antiPatterns.map((p, i) => (
                  <li key={i}><span className="anti-x"><Icon name="x" size={14}/></span>{p}</li>
                ))}
              </ul>
            </>
          )}
        </Section>

        {/* 10. Risks + verification register */}
        <Section num="10" title="Things to watch out for">
          <h3 className="plan-h3">Your own biases — and how to push back on them</h3>
          <table className="plan-table plan-table-risks">
            <thead><tr><th>The pull</th><th>What it does</th><th>How to push back</th></tr></thead>
            <tbody>
              {D.risks.map((r, i) => (
                <tr key={i}>
                  <td><strong>{r.bias}</strong></td>
                  <td>{r.risk}</td>
                  <td>{r.action}</td>
                </tr>
              ))}
            </tbody>
          </table>

          {D.verificationRegister && D.verificationRegister.length > 0 && (
            <>
              <h3 className="plan-h3" style={{ marginTop: "28px" }}>What you need to verify before you commit</h3>
              <p className="plan-lede">Don't take these on faith. Each one moves the deal if it turns out to be wrong.</p>
              <table className="plan-table">
                <thead>
                  <tr><th>Claim</th><th>Why it matters</th><th>What changes if it's wrong</th></tr>
                </thead>
                <tbody>
                  {D.verificationRegister.map((r, i) => (
                    <tr key={i}>
                      <td><strong>{r.claim}</strong></td>
                      <td>{r.whyMatters}</td>
                      <td className="cell-walk">{r.impactIfFalse}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </>
          )}
        </Section>

        {/* 11. Next moves — pre-positioning + main next */}
        <Section num="11" title="Do these next">
          {D.prepositioning && (
            <>
              <h3 className="plan-h3">Before the meeting — shape the frame they arrive with</h3>
              <div className="plan-grid-3">
                <div className="plan-block">
                  <div className="kicker">Set the process</div>
                  <ul className="plan-bullets">
                    {(D.prepositioning.processControl || []).map((s, i) => <li key={i}>{s}</li>)}
                  </ul>
                </div>
                <div className="plan-block">
                  <div className="kicker">Gather intelligence</div>
                  <ul className="plan-bullets">
                    {(D.prepositioning.intelligence || []).map((s, i) => <li key={i}>{s}</li>)}
                  </ul>
                </div>
                <div className="plan-block">
                  <div className="kicker">Position the relationship</div>
                  <ul className="plan-bullets">
                    {(D.prepositioning.networkPositioning || []).map((s, i) => <li key={i}>{s}</li>)}
                  </ul>
                </div>
              </div>
            </>
          )}

          <h3 className="plan-h3" style={{ marginTop: "32px" }}>Your action list</h3>
          <ol className="plan-next">
            {D.next.map((n, i) => (
              <li key={i}>
                <span className="plan-next-n">{String(i + 1).padStart(2, "0")}</span>
                <span>{n}</span>
              </li>
            ))}
          </ol>
        </Section>

        {/* 12. Victory speech */}
        {D.victorySpeech && (
          <Section num="12" title="How you'll describe this win to your team">
            <p className="plan-lede">If this deal closes the way you've designed it, here's the story you'll tell internally.</p>
            <blockquote className="plan-victory">{D.victorySpeech}</blockquote>
          </Section>
        )}

        {/* 13. Counterpart story */}
        {D.counterpartStory && (
          <Section num="13" title={`How they'll defend this deal to ${L.boss}`}>
            <p className="plan-lede">
              This is the version of the deal the {L.counterpart} can carry upward. Giving it to them — or letting it shape your packaging — is the single highest-leverage move you can make for free.
            </p>
            <blockquote className="plan-counterstory">{D.counterpartStory}</blockquote>
          </Section>
        )}

        {/* 14. Readiness check */}
        {D.readinessCheck && D.readinessCheck.length > 0 && (
          <Section num="14" title="Ready to walk in?">
            <p className="plan-lede">Run through this list the morning of. Anything not "ready" — fix it before the call.</p>
            <div className="plan-readiness">
              {D.readinessCheck.map((r, i) => {
                const tone = READY_TONE[r.status] || READY_TONE["Not yet"];
                return (
                  <div key={i} className={`rdy-row ${tone.cls}`}>
                    <span className="rdy-mark"><Icon name={tone.icon} size={18}/></span>
                    <span className="rdy-item">{r.item}</span>
                    <span className="rdy-status">{tone.label}</span>
                  </div>
                );
              })}
            </div>
          </Section>
        )}

        <footer className="plan-footer">
          <div className="plan-footer-l">
            <img src="assets/cabl-logo.png" alt="CABL"/>
            <div>
              <div className="plan-footer-meta">Plan generated {D.date} · Private workspace</div>
            </div>
          </div>
          <div className="plan-footer-r">
            Private workspace. Saved cases are encrypted; uploaded files are not stored. This is coaching, not legal or financial advice.
          </div>
        </footer>
      </div>
    </div>
  );
}

function Section({ num, title, children }) {
  return (
    <section className="plan-section">
      <header className="plan-section-head">
        <div className="plan-section-num">{num}</div>
        <h2 className="plan-section-title">{title}</h2>
        <div className="plan-section-rule"/>
      </header>
      <div className="plan-section-body">{children}</div>
    </section>
  );
}

// Technology/IP licensing render block. Shown only when
// plan.licensingEconomics.applicable is true. Renders the denominator lock
// (§9.1 spec gate), the continuity floor held constant across packages, and
// the all-in cost stack.
function LicensingEconomics({ data }) {
  const lock = data.denominatorLock || {};
  const floor = data.continuityFloor || {};
  const stack = Array.isArray(data.costStack) ? data.costStack : [];
  const lockAspirational = lock.status === "ASPIRATIONAL";
  return (
    <div className="plan-licensing">
      {data.dealArchetype && data.dealArchetype !== "N/A" && (
        <div className="plan-licensing-archetype">{data.dealArchetype}</div>
      )}

      {(lock.unit || lock.lockMechanism) && (
        <div className={`plan-licensing-lock ${lockAspirational ? "is-open" : "is-locked"}`}>
          <div className="plan-licensing-lock-head">
            <span className="plan-licensing-lock-mark">
              <Icon name={lockAspirational ? "alert-triangle" : "lock"} size={19}/>
            </span>
            <strong>
              {lockAspirational
                ? "Lock what the royalty is charged on — before you agree any rate"
                : "What the royalty is charged on is fixed"}
            </strong>
          </div>
          {lock.unit && <p><span className="plan-licensing-label">Basis:</span> {lock.unit}</p>}
          {lock.lockMechanism && <p><span className="plan-licensing-label">How to lock it:</span> {lock.lockMechanism}</p>}
          {lock.note && <p className="plan-licensing-note">{lock.note}</p>}
        </div>
      )}

      {floor.required === "YES" && (
        <div className="plan-licensing-floor">
          <div className="plan-licensing-lock-head">
            <span className="plan-licensing-lock-mark"><Icon name="life-buoy" size={19}/></span>
            <strong>Continuity protection — keep this in every package</strong>
          </div>
          {floor.floorTerms && <p>{floor.floorTerms}</p>}
          {floor.heldConstantNote && <p className="plan-licensing-note">{floor.heldConstantNote}</p>}
        </div>
      )}

      {stack.length > 0 && (
        <>
          <h3 className="plan-h3">The all-in cost of this licence</h3>
          <p className="plan-lede">
            The headline royalty is only one layer. Here's the true cost stacked up — so a low rate with heavy milestones can't hide a worse deal.
          </p>
          <table className="plan-table">
            <thead>
              <tr><th>Cost layer</th><th>Amount</th><th>Basis</th><th>Notes</th></tr>
            </thead>
            <tbody>
              {stack.map((r, i) => (
                <tr key={i}>
                  <td><strong>{r.layer}</strong></td>
                  <td className="cell-target">{r.amount}</td>
                  <td>{r.basis}</td>
                  <td className="cell-note">{r.note}</td>
                </tr>
              ))}
            </tbody>
          </table>
          {data.costStackNote && (
            <div className="plan-note">
              <span className="plan-note-tag">All-in cost</span>
              <p>{data.costStackNote}</p>
            </div>
          )}
          <h3 className="plan-h3" style={{ marginTop: "32px" }}>Your other levers</h3>
        </>
      )}
    </div>
  );
}

function InfoCol({ tag, tone, items }) {
  return (
    <div className={`info-col info-col-${tone}`}>
      <div className="info-col-tag">{tag}</div>
      <ul>{items.map((x, i) => <li key={i}>{x}</li>)}</ul>
    </div>
  );
}

window.ActionPlan = ActionPlan;
