// MATTER-LEVEL WAR ROOM v2 — 20 opportunity components (MW1–MW20) + 5 hubs
// Shares the dark WarRoom theme (window.W / window.wr) and hooks into window.MatterWarRoomStore
(function () {
  const W = window.W;
  const wr = window.wr;
  const mw = window.mw;

  // ── Shared primitives ─────────────────────────────────────────────
  const useStore = (topics) => window.useMatterWarRoomStore(topics);
  const S = window.MatterWarRoomStore;

  const Flash = ({ msg, tone='green' }) => msg ? (
    <div style={{ padding:'8px 12px', borderRadius:'6px',
      background: tone==='green'?W.green.bg: tone==='amber'?W.amber.bg: W.red.bg,
      border: `1px solid ${tone==='green'?W.green.base:tone==='amber'?W.amber.base:W.red.base}55`,
      color: tone==='green'?W.green.text:tone==='amber'?W.amber.text:W.red.text,
      fontSize:'11px', fontWeight:600, textTransform:'uppercase', letterSpacing:'0.06em',
      marginBottom:'12px' }}>{msg}</div>
  ) : null;

  const Pill = ({ tone, children }) => {
    const c = tone === 'green' ? W.green : tone === 'amber' ? W.amber : tone === 'red' ? W.red
            : tone === 'blue' ? W.blue : tone === 'purple' ? W.purple : tone === 'cyan' ? W.cyan
            : { bg: W.bg.tertiary, text: W.text.secondary, base: W.border.medium };
    return (
      <span style={{ ...wr.tag, background: c.bg, color: c.text, border: `1px solid ${c.base}33`,
        textTransform:'uppercase', fontSize:'9px', letterSpacing:'0.08em' }}>{children}</span>
    );
  };

  const statusTone = (s) => {
    if (['done','complete','filed','stipulated','follow-form'].includes(s)) return 'green';
    if (['in-progress','scheduled','drafting','on-track','disclosed','monitoring','accepted-with-rov'].includes(s)) return 'blue';
    if (['pending','research','queued','draft','due-today','preliminary','inquiry','stayed'].includes(s)) return 'amber';
    if (['overdue','denied','contested','rejected','active'].includes(s)) return 'red';
    if (['defended'].includes(s)) return 'purple';
    return 'default';
  };

  const Btn = ({ onClick, tone='default', children, title }) => {
    const bg = tone==='primary' ? W.red.bg : tone==='accent' ? W.blue.bg : W.bg.elevated;
    const border = tone==='primary' ? W.red.base : tone==='accent' ? W.blue.base : W.border.medium;
    const color = tone==='primary' ? W.red.text : tone==='accent' ? W.blue.text : W.text.secondary;
    return (
      <button onClick={onClick} title={title} style={{
        padding:'6px 12px', borderRadius:'6px', border:`1px solid ${border}`,
        background: bg, color, fontSize:'10px', fontWeight:700,
        textTransform:'uppercase', letterSpacing:'0.08em', cursor:'pointer',
        fontFamily: W.font.family }}>{children}</button>
    );
  };

  const KPI = ({ label, value, sub, tone='default' }) => {
    const color = tone==='green' ? W.green.text : tone==='amber' ? W.amber.text
                : tone==='red' ? W.red.text : tone==='blue' ? W.blue.text
                : tone==='purple' ? W.purple.text : W.text.primary;
    return (
      <div style={{ ...wr.stat, flex:1 }}>
        <div style={wr.statLabel}>{label}</div>
        <div style={{ ...wr.statValue, color, fontFamily: W.font.mono }}>{value}</div>
        {sub && <div style={{ fontSize:'10px', color: W.text.tertiary, marginTop:'2px' }}>{sub}</div>}
      </div>
    );
  };

  const Card = ({ title, right, children }) => (
    <div style={wr.card}>
      <div style={wr.cardH}>
        <span>{title}</span>
        {right && <span>{right}</span>}
      </div>
      <div style={wr.cardBody}>{children}</div>
    </div>
  );

  const TH = ({ children, align='left', width }) => (
    <th style={{ padding:'8px 10px', fontSize:'9px', fontWeight:600, color: W.text.tertiary,
      textTransform:'uppercase', letterSpacing:'0.08em', textAlign: align,
      borderBottom:`1px solid ${W.border.subtle}`, whiteSpace:'nowrap', width }}>{children}</th>
  );
  const TD = ({ children, align='left', mono=false, color, width }) => (
    <td style={{ padding:'8px 10px', fontSize:'12px', color: color || W.text.primary,
      borderBottom:`1px solid ${W.border.subtle}`, textAlign: align,
      fontFamily: mono ? W.font.mono : W.font.family, width }}>{children}</td>
  );

  const Bar = ({ pct, tone='blue' }) => {
    const color = tone==='green' ? W.green.base : tone==='amber' ? W.amber.base
                : tone==='red' ? W.red.base : tone==='purple' ? W.purple.base : W.blue.base;
    return (
      <div style={wr.meterContainer}>
        <div style={{ height:'100%', width:`${Math.max(0,Math.min(100,pct))}%`,
          background: color, transition:'width .4s ease' }}/>
      </div>
    );
  };

  const SubTabs = ({ tabs, active, onChange }) => (
    <div style={{ display:'flex', gap:'8px', marginBottom:'16px', flexWrap:'wrap' }}>
      {tabs.map(t => (
        <button key={t.id} onClick={() => onChange(t.id)} style={{
          padding:'7px 12px', fontSize:'10px', fontWeight: active===t.id?700:500,
          color: active===t.id ? '#fff' : W.text.tertiary,
          background: active===t.id ? W.red.base : 'transparent',
          border:`1px solid ${active===t.id ? W.red.base : W.border.medium}`,
          borderRadius:'6px', cursor:'pointer', textTransform:'uppercase',
          letterSpacing:'0.08em', fontFamily: W.font.family }}>{t.label}</button>
      ))}
    </div>
  );

  // ══════════════════════════════════════════════════════════════════
  // MW1 — Motion Strategy Orchestrator
  // ══════════════════════════════════════════════════════════════════
  function MW1MotionOrchestrator() {
    const st = useStore(['motion.status','calendar.push','audit.logged']);
    const [flash, setFlash] = React.useState('');
    const critical = st.motions.filter(m => m.priority === 'critical' || m.priority === 'high').length;
    const avgWin   = Math.round(st.motions.reduce((s,m)=>s+m.winPct,0) / (st.motions.length||1));
    const totalCost= st.motions.reduce((s,m)=>s+m.costUsd, 0);

    const onAdvance = (m) => {
      const order = ['queued','research','drafting','filed','argued','decided'];
      const next = order[Math.min(order.indexOf(m.status)+1, order.length-1)];
      S.advanceMotion(m.id, next, 'You');
      setFlash(`${m.title} → ${next}`);
    };
    const onPushCal = (m) => {
      S.pushMotionToCalendar({ motionId:m.id, milestone:`${m.title} filing`, dueDate:m.filingTarget });
      setFlash(`Pushed ${m.id} to Calendar`);
    };

    return (
      <div>
        <Flash msg={flash} tone="green"/>
        <div style={{ display:'flex', gap:'12px', marginBottom:'16px' }}>
          <KPI label="Active Motions" value={st.motions.length} />
          <KPI label="Critical / High" value={critical} tone={critical>0?'amber':'green'}/>
          <KPI label="Avg Win Probability" value={`${avgWin}%`} tone={avgWin>=60?'green':'amber'}/>
          <KPI label="Committed Spend" value={mw.money(totalCost)} />
        </div>
        <Card title="Motion Docket — filing strategy, cost, win probability">
          <table style={{ width:'100%' }}>
            <thead><tr>
              <TH>Motion</TH><TH>Type</TH><TH>Status</TH><TH>Priority</TH>
              <TH align="right">Win%</TH><TH align="right">Cost</TH>
              <TH>File By</TH><TH>Lead</TH><TH align="right">Actions</TH>
            </tr></thead>
            <tbody>
              {st.motions.map(m => (
                <tr key={m.id}>
                  <TD><div style={{fontWeight:600}}>{m.title}</div>
                    <div style={{ fontSize:'10px', color:W.text.tertiary }}>{m.basis.join(' · ')}</div></TD>
                  <TD>{m.type}</TD>
                  <TD><Pill tone={statusTone(m.status)}>{m.status}</Pill></TD>
                  <TD><Pill tone={m.priority==='critical'?'red':m.priority==='high'?'amber':'blue'}>{m.priority}</Pill></TD>
                  <TD align="right" mono color={m.winPct>=60?W.green.text:m.winPct>=40?W.amber.text:W.red.text}>{m.winPct}%</TD>
                  <TD align="right" mono>{mw.money(m.costUsd)}</TD>
                  <TD mono>{m.filingTarget}</TD>
                  <TD>{m.leadAtty}</TD>
                  <TD align="right">
                    <div style={{ display:'flex', gap:'6px', justifyContent:'flex-end' }}>
                      <Btn onClick={() => onAdvance(m)}>Advance</Btn>
                      <Btn onClick={() => onPushCal(m)} tone="accent">Calendar</Btn>
                    </div>
                  </TD>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      </div>
    );
  }

  // ══════════════════════════════════════════════════════════════════
  // MW2 — Motion-in-Limine Battleground
  // ══════════════════════════════════════════════════════════════════
  function MW2MotionInLimine() {
    const st = useStore(['mil.forecast']);
    const [flash, setFlash] = React.useState('');
    const net = st.motionsInLimine.reduce((s,m)=>s+(m.grantOdds/100)*m.caseStrengthDelta, 0);
    const evNet= st.motionsInLimine.reduce((s,m)=>s+(m.grantOdds/100)*m.evShift, 0);

    return (
      <div>
        <Flash msg={flash}/>
        <div style={{ display:'flex', gap:'12px', marginBottom:'16px' }}>
          <KPI label="MILs on the Board" value={st.motionsInLimine.length}/>
          <KPI label="Expected Case Strength Δ" value={`${net>=0?'+':''}${net.toFixed(1)} pts`} tone={net>=0?'green':'red'}/>
          <KPI label="Expected EV Shift" value={mw.money(evNet)} tone={evNet>=0?'green':'red'}/>
          <KPI label="Plaintiff MILs" value={st.motionsInLimine.filter(m=>m.filedBy==='Plaintiff').length} tone="blue"/>
        </div>
        <Card title="Motions in Limine — grant odds × impact">
          <table style={{ width:'100%' }}>
            <thead><tr>
              <TH>Issue</TH><TH>Filed By</TH><TH align="right">Grant Odds</TH>
              <TH>Impact</TH><TH align="right">Strength Δ</TH><TH align="right">EV Shift</TH>
              <TH align="right">Forecast</TH>
            </tr></thead>
            <tbody>
              {st.motionsInLimine.map(m => (
                <tr key={m.id}>
                  <TD><div style={{ fontWeight:600 }}>{m.issue}</div>
                    <div style={{ fontSize:'10px', color:W.text.tertiary, marginTop:'2px' }}>{m.rationale}</div></TD>
                  <TD><Pill tone={m.filedBy==='Plaintiff'?'blue':'red'}>{m.filedBy}</Pill></TD>
                  <TD align="right" mono color={m.grantOdds>=60?W.green.text:m.grantOdds>=40?W.amber.text:W.red.text}>{m.grantOdds}%</TD>
                  <TD><Pill tone={m.impact==='high'?'red':m.impact==='medium'?'amber':'green'}>{m.impact}</Pill></TD>
                  <TD align="right" mono color={m.caseStrengthDelta>=0?W.green.text:W.red.text}>
                    {m.caseStrengthDelta>=0?'+':''}{m.caseStrengthDelta}</TD>
                  <TD align="right" mono color={m.evShift>=0?W.green.text:W.red.text}>{mw.money(m.evShift)}</TD>
                  <TD align="right">
                    <Btn tone="accent" onClick={() => {
                      const newOdds = Math.min(95, m.grantOdds + 5);
                      S.forecastMil(m.id, newOdds, 'You');
                      setFlash(`${m.id} forecast: ${m.grantOdds}% → ${newOdds}%`);
                    }}>+5% prep</Btn>
                  </TD>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      </div>
    );
  }

  // ══════════════════════════════════════════════════════════════════
  // MW3 — Discovery Workflow & Burden Map
  // ══════════════════════════════════════════════════════════════════
  function MW3DiscoveryBurden() {
    const st = useStore(['discovery.mc','discovery.complete']);
    const [flash, setFlash] = React.useState('');
    const overdue = st.discoveryRequests.filter(r => r.status === 'overdue').length;
    const avgComplete = Math.round(st.discoveryRequests.reduce((s,r)=>s+r.completenessPct,0) / (st.discoveryRequests.length||1));
    const totalDocs = st.discoveryRequests.reduce((s,r)=>s+r.docsProduced, 0);

    return (
      <div>
        <Flash msg={flash}/>
        <div style={{ display:'flex', gap:'12px', marginBottom:'16px' }}>
          <KPI label="Outstanding Requests" value={st.discoveryRequests.length}/>
          <KPI label="Overdue" value={overdue} tone={overdue>0?'red':'green'}/>
          <KPI label="Avg Completeness" value={`${avgComplete}%`} tone={avgComplete>=70?'green':'amber'}/>
          <KPI label="Docs Produced" value={totalDocs.toLocaleString()} />
        </div>
        <Card title="Discovery Requests — burden, completeness, meet-and-confer">
          <table style={{ width:'100%' }}>
            <thead><tr>
              <TH>ID</TH><TH>Type</TH><TH>Status</TH><TH>Due</TH>
              <TH>Completeness</TH><TH align="right">Docs</TH><TH align="right">Obj.</TH>
              <TH>M&C</TH><TH align="right">Action</TH>
            </tr></thead>
            <tbody>
              {st.discoveryRequests.map(r => (
                <tr key={r.id}>
                  <TD mono>{r.id}</TD>
                  <TD>{r.type}</TD>
                  <TD><Pill tone={statusTone(r.status)}>{r.status}</Pill></TD>
                  <TD mono>{r.due}</TD>
                  <TD><div style={{ width:'120px' }}>
                    <Bar pct={r.completenessPct} tone={r.completenessPct>=70?'green':r.completenessPct>=40?'amber':'red'}/>
                    <div style={{ fontSize:'10px', marginTop:'2px', color:W.text.tertiary }}>{r.completenessPct}% · {r.docsProduced}/{r.docsExpected}</div>
                  </div></TD>
                  <TD align="right" mono>{r.docsProduced}</TD>
                  <TD align="right" mono color={r.objections>3?W.red.text:W.text.primary}>{r.objections}</TD>
                  <TD><Pill tone={r.metAndConferHeld?'green':'amber'}>{r.metAndConferHeld?'Held':'Needed'}</Pill></TD>
                  <TD align="right">
                    {!r.metAndConferHeld && (
                      <Btn tone="accent" onClick={() => {
                        S.logMeetAndConfer(r.id, 'You');
                        setFlash(`Logged meet & confer for ${r.id}`);
                      }}>Log M&C</Btn>
                    )}
                  </TD>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      </div>
    );
  }

  // ══════════════════════════════════════════════════════════════════
  // MW4 — eDiscovery / TAR Performance
  // ══════════════════════════════════════════════════════════════════
  function MW4TarPerformance() {
    const st = useStore(['tar.round']);
    const [flash, setFlash] = React.useState('');
    const t = st.tar;
    const pctReviewed = Math.round(100 * t.reviewed / t.totalDocs);

    return (
      <div>
        <Flash msg={flash}/>
        <div style={{ display:'flex', gap:'12px', marginBottom:'16px' }}>
          <KPI label="Total Docs" value={t.totalDocs.toLocaleString()} sub={`${pctReviewed}% reviewed`}/>
          <KPI label="Precision" value={`${t.precisionPct}%`} tone={t.precisionPct>=80?'green':'amber'}/>
          <KPI label="Recall" value={`${t.recallPct}%`} tone={t.recallPct>=75?'green':'amber'}/>
          <KPI label="F1 Score" value={t.f1.toFixed(3)} tone={t.f1>=0.8?'green':'amber'}/>
          <KPI label="Spend" value={mw.money(t.costToDate)} sub={`proj ${mw.money(t.costProjected)}`}/>
        </div>
        <Card title="TAR Training Rounds" right={<Btn tone="primary" onClick={() => {
          const r = S.runTarRound('You'); setFlash(`TAR round ${r.round}: P=${r.precision}% R=${r.recall}%`);
        }}>Run next round</Btn>}>
          <table style={{ width:'100%' }}>
            <thead><tr>
              <TH>Round</TH><TH align="right">Docs Trained</TH>
              <TH align="right">Precision</TH><TH align="right">Recall</TH>
              <TH>Performance</TH>
            </tr></thead>
            <tbody>
              {t.rounds.map(r => (
                <tr key={r.round}>
                  <TD mono>#{r.round}</TD>
                  <TD align="right" mono>{r.trained.toLocaleString()}</TD>
                  <TD align="right" mono color={W.green.text}>{r.precision}%</TD>
                  <TD align="right" mono color={W.blue.text}>{r.recall}%</TD>
                  <TD><div style={{ width:'200px' }}>
                    <Bar pct={(r.precision + r.recall)/2} tone="green"/>
                  </div></TD>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
        <Card title="Review Economics">
          <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:'12px' }}>
            <KPI label="Hot Docs" value={t.hot.toLocaleString()} tone="red"/>
            <KPI label="Privileged" value={t.privileged.toLocaleString()} tone="purple"/>
            <KPI label="Relevant" value={t.relevant.toLocaleString()} tone="blue"/>
            <KPI label="Cost / GB" value={mw.money(t.costPerGb)} />
          </div>
        </Card>
      </div>
    );
  }

  // ══════════════════════════════════════════════════════════════════
  // MW5 — Privilege & Waiver Exposure
  // ══════════════════════════════════════════════════════════════════
  function MW5Privilege() {
    const st = useStore(['privilege.dispute','rulebook.push']);
    const [flash, setFlash] = React.useState('');
    const disputed = st.privilegeLog.filter(p => p.disputed).length;
    const avgRisk = (st.privilegeLog.reduce((s,p)=>s+p.waiverRisk,0) / (st.privilegeLog.length||1));
    const high = st.privilegeLog.filter(p => p.waiverRisk >= 0.6).length;

    return (
      <div>
        <Flash msg={flash}/>
        <div style={{ display:'flex', gap:'12px', marginBottom:'16px' }}>
          <KPI label="Log Entries" value={st.privilegeLog.length}/>
          <KPI label="Disputed" value={disputed} tone="amber"/>
          <KPI label="Avg Waiver Risk" value={mw.pct(avgRisk,1)} tone={avgRisk<0.4?'green':'amber'}/>
          <KPI label="High-Risk Entries" value={high} tone={high>2?'red':'amber'}/>
        </div>
        <Card title="Privilege Log — disputed entries and waiver exposure">
          <table style={{ width:'100%' }}>
            <thead><tr>
              <TH>ID</TH><TH>Custodian</TH><TH>Type</TH><TH>Basis</TH>
              <TH align="right">Waiver Risk</TH><TH>Reason</TH>
              <TH>Status</TH><TH align="right">Action</TH>
            </tr></thead>
            <tbody>
              {st.privilegeLog.map(p => (
                <tr key={p.id}>
                  <TD mono>{p.id}</TD>
                  <TD>{p.custodian}</TD>
                  <TD>{p.type}</TD>
                  <TD>{p.basis}</TD>
                  <TD align="right" mono color={p.waiverRisk>=0.6?W.red.text:p.waiverRisk>=0.4?W.amber.text:W.green.text}>
                    {mw.pct(p.waiverRisk, 0)}</TD>
                  <TD>{p.reason}</TD>
                  <TD><Pill tone={p.disputed?'amber':'green'}>{p.disputed?'Disputed':'Clear'}</Pill></TD>
                  <TD align="right">
                    <div style={{ display:'flex', gap:'6px', justifyContent:'flex-end' }}>
                      {!p.disputed && <Btn onClick={() => {
                        S.disputePrivilege(p.id,'You');
                        setFlash(`${p.id} marked disputed`);
                      }}>Dispute</Btn>}
                      <Btn tone="accent" onClick={() => {
                        S.pushPrivilegeToRulebook({ privId:p.id, basis:p.basis });
                        setFlash(`${p.id} → Rulebook`);
                      }}>Rulebook</Btn>
                    </div>
                  </TD>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      </div>
    );
  }

  // ══════════════════════════════════════════════════════════════════
  // MW6 — Deposition Strategy Board
  // ══════════════════════════════════════════════════════════════════
  function MW6Depositions() {
    const st = useStore(['depo.goal']);
    const [flash, setFlash] = React.useState('');
    const complete = st.depositions.filter(d=>d.status==='complete').length;
    const pages = st.depositions.reduce((s,d)=>s+d.pages, 0);
    const goalsHit = st.depositions.reduce((s,d)=>s+(d.goalsHit||0),0);
    const goalsTotal= st.depositions.reduce((s,d)=>s+d.goals.length,0);

    return (
      <div>
        <Flash msg={flash}/>
        <div style={{ display:'flex', gap:'12px', marginBottom:'16px' }}>
          <KPI label="Depositions" value={st.depositions.length}/>
          <KPI label="Complete" value={complete} tone="green"/>
          <KPI label="Transcript Pages" value={pages.toLocaleString()}/>
          <KPI label="Goals Hit" value={`${goalsHit}/${goalsTotal}`} tone={goalsHit/goalsTotal>=0.6?'green':'amber'}/>
        </div>
        {st.depositions.map(d => (
          <Card key={d.id} title={`${d.deponent} · ${d.role}`} right={
            <div style={{display:'flex',gap:'8px',alignItems:'center'}}>
              <Pill tone={statusTone(d.status)}>{d.status}</Pill>
              <span style={{ fontSize:'10px', color:W.text.tertiary }}>{d.scheduled} · {d.duration}h · {d.pages||0} pp</span>
            </div>}>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'12px' }}>
              <div>
                <div style={{ fontSize:'10px', fontWeight:600, color:W.text.tertiary, textTransform:'uppercase', letterSpacing:'0.08em', marginBottom:'6px' }}>
                  Goals ({d.goalsHit||0} / {d.goals.length} hit)</div>
                {d.goals.map((g, i) => (
                  <div key={i} style={{ display:'flex', alignItems:'center', gap:'8px', padding:'4px 0',
                    fontSize:'12px', color: i<(d.goalsHit||0) ? W.green.text : W.text.secondary }}>
                    <div style={{ width:'10px', height:'10px', borderRadius:'50%',
                      background: i<(d.goalsHit||0) ? W.green.base : W.bg.tertiary }}/>
                    <span>{g}</span>
                    {d.status==='complete' && i >= (d.goalsHit||0) && (
                      <Btn onClick={()=>{ S.recordDepoGoalHit(d.id, i, 'You'); setFlash(`${d.deponent} — goal hit`); }}>Mark hit</Btn>
                    )}
                  </div>
                ))}
              </div>
              <div>
                <div style={{ fontSize:'10px', fontWeight:600, color:W.text.tertiary, textTransform:'uppercase', letterSpacing:'0.08em', marginBottom:'6px' }}>
                  Pivotal Exchanges</div>
                {d.pivotalExchanges.length === 0 ? (
                  <div style={{ fontSize:'12px', color:W.text.tertiary, fontStyle:'italic' }}>Not yet deposed.</div>
                ) : d.pivotalExchanges.map((e,i) => (
                  <div key={i} style={{ padding:'6px 8px', marginBottom:'4px', background:W.bg.tertiary, borderRadius:'4px' }}>
                    <div style={{ display:'flex', justifyContent:'space-between', fontSize:'10px', color:W.text.tertiary }}>
                      <span>p.{e.page}</span>
                      <span style={{ color:e.impact>=8?W.green.text:W.amber.text }}>Impact {e.impact}/10</span>
                    </div>
                    <div style={{ fontSize:'12px', color:W.text.primary, marginTop:'2px' }}>{e.summary}</div>
                  </div>
                ))}
              </div>
            </div>
          </Card>
        ))}
      </div>
    );
  }

  // ══════════════════════════════════════════════════════════════════
  // MW7 — Expert Witness Command Center
  // ══════════════════════════════════════════════════════════════════
  function MW7Experts() {
    const st = useStore(['expert.retain']);
    const [flash, setFlash] = React.useState('');

    return (
      <div>
        <Flash msg={flash}/>
        <div style={{ display:'flex', gap:'12px', marginBottom:'16px' }}>
          <KPI label="Experts" value={st.experts.length}/>
          <KPI label="Plaintiff" value={st.experts.filter(e=>e.side==='plaintiff').length} tone="blue"/>
          <KPI label="Defense" value={st.experts.filter(e=>e.side==='defense').length} tone="red"/>
          <KPI label="Avg Daubert Risk" value={mw.pct(st.experts.reduce((s,e)=>s+e.daubertRisk,0)/st.experts.length,1)} tone="amber"/>
        </div>
        <Card title="Expert Roster — credentials, Daubert exposure, report cadence">
          <table style={{ width:'100%' }}>
            <thead><tr>
              <TH>Expert</TH><TH>Side</TH><TH>Domain</TH>
              <TH align="right">Rate</TH><TH align="right">Hours</TH>
              <TH align="right">Strength</TH><TH align="right">Daubert Risk</TH>
              <TH>Opening / Rebuttal</TH><TH align="right">Action</TH>
            </tr></thead>
            <tbody>
              {st.experts.map(e => (
                <tr key={e.id}>
                  <TD><div style={{ fontWeight:600 }}>{e.name}</div>
                    <div style={{ fontSize:'10px', color:W.text.tertiary }}>{e.priorCases} prior cases · {e.priorDaubertExclusions} exclusions</div></TD>
                  <TD><Pill tone={e.side==='plaintiff'?'blue':'red'}>{e.side}</Pill></TD>
                  <TD>{e.domain}</TD>
                  <TD align="right" mono>{e.hourlyRate?`$${e.hourlyRate}/h`:'—'}</TD>
                  <TD align="right" mono>{e.hoursBilled}</TD>
                  <TD align="right" mono color={e.strengthScore>=80?W.green.text:e.strengthScore>=60?W.amber.text:W.red.text}>{e.strengthScore}/100</TD>
                  <TD align="right" mono color={e.daubertRisk<0.25?W.green.text:e.daubertRisk<0.5?W.amber.text:W.red.text}>
                    {mw.pct(e.daubertRisk,0)}</TD>
                  <TD mono style={{fontSize:'10px'}}>{e.reportDueDates.opening}<br/>{e.reportDueDates.rebuttal}</TD>
                  <TD align="right">
                    {e.side==='plaintiff' && e.reportStatus==='pending' && (
                      <Btn tone="primary" onClick={()=>{
                        S.retainExpert(e.id, 75000, 'You'); setFlash(`${e.name} retained`);
                      }}>Retain</Btn>
                    )}
                    <Pill tone={statusTone(e.reportStatus)}>{e.reportStatus}</Pill>
                  </TD>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      </div>
    );
  }

  // ══════════════════════════════════════════════════════════════════
  // MW8 — Cross-Examination Playbook
  // ══════════════════════════════════════════════════════════════════
  function MW8CrossExam() {
    const st = useStore(['cross.rehearse']);
    const [flash, setFlash] = React.useState('');
    const avg = Math.round(st.crossExam.reduce((s,c)=>s+c.controlScore,0) / (st.crossExam.length||1));

    return (
      <div>
        <Flash msg={flash}/>
        <div style={{ display:'flex', gap:'12px', marginBottom:'16px' }}>
          <KPI label="Cross Plans" value={st.crossExam.length}/>
          <KPI label="Avg Control Score" value={`${avg}%`} tone={avg>=75?'green':'amber'}/>
        </div>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'12px' }}>
          {st.crossExam.map(c => (
            <Card key={c.id} title={`${c.witness} — ${c.topic}`} right={
              <span style={{ fontSize:'11px', color: c.controlScore>=75?W.green.text:W.amber.text,
                fontFamily: W.font.mono, fontWeight:700 }}>{c.controlScore}%</span>}>
              <div style={{ fontSize:'10px', color:W.text.tertiary, textTransform:'uppercase', letterSpacing:'0.08em', marginBottom:'4px' }}>Loop</div>
              <ol style={{ paddingLeft:'18px', marginBottom:'10px' }}>
                {c.loop.map((q,i)=>(
                  <li key={i} style={{ fontSize:'12px', color:W.text.primary, marginBottom:'2px' }}>{q}</li>
                ))}
              </ol>
              <div style={{ fontSize:'10px', color:W.text.tertiary, textTransform:'uppercase', letterSpacing:'0.08em', marginBottom:'4px' }}>Impeachment ammo</div>
              <div style={{ display:'flex', gap:'6px', flexWrap:'wrap', marginBottom:'10px' }}>
                {c.impeachmentAmmo.map((a,i)=><Pill key={i} tone="blue">{a}</Pill>)}
              </div>
              <div style={{ fontSize:'11px', color:W.text.secondary, fontStyle:'italic', marginBottom:'10px' }}>
                Expected answer: {c.expectedAnswer}</div>
              <Btn tone="primary" onClick={()=>{
                const next = Math.min(95, c.controlScore + 4);
                S.rehearseCross(c.id, next, 'You');
                setFlash(`${c.witness} rehearsed: ${c.controlScore}% → ${next}%`);
              }}>Rehearse (+4%)</Btn>
            </Card>
          ))}
        </div>
      </div>
    );
  }

  // ══════════════════════════════════════════════════════════════════
  // MW9 — Trial Narrative Storyboard
  // ══════════════════════════════════════════════════════════════════
  function MW9Narrative() {
    const st = useStore(['*']);
    const n = st.narrative;
    const openTotal = n.openingBeats.reduce((s,b)=>s+b.sec,0);
    const closeTotal= n.closingBeats.reduce((s,b)=>s+b.sec,0);

    const BeatBar = ({ beats, total }) => (
      <div style={{ display:'flex', borderRadius:'6px', overflow:'hidden', height:'32px', marginBottom:'8px' }}>
        {beats.map((b,i) => (
          <div key={i} title={`${b.title} — ${b.sec}s, strength ${b.strength}`}
            style={{ flex: b.sec / total,
              background: b.strength>=90?W.green.base : b.strength>=80?W.blue.base : W.amber.base,
              display:'flex', alignItems:'center', justifyContent:'center',
              fontSize:'10px', fontWeight:700, color:'#fff',
              borderRight: i<beats.length-1?`1px solid ${W.bg.primary}`:'none' }}>
            {b.title}
          </div>
        ))}
      </div>
    );

    return (
      <div>
        <Card title="Trial theme">
          <div style={{ fontSize:'14px', fontWeight:600, color:W.text.primary, fontStyle:'italic' }}>
            "{n.theme}"</div>
        </Card>
        <div style={{ display:'flex', gap:'12px', marginBottom:'16px' }}>
          <KPI label="Opening Runtime" value={`${Math.round(openTotal/60)}m ${openTotal%60}s`}/>
          <KPI label="Closing Runtime" value={`${Math.round(closeTotal/60)}m ${closeTotal%60}s`}/>
          <KPI label="Exhibits" value={n.exhibits}/>
          <KPI label="Demonstratives" value={n.demonstratives}/>
          <KPI label="Video Clips" value={n.videoClips}/>
        </div>
        <Card title="Opening Statement Storyboard">
          <BeatBar beats={n.openingBeats} total={openTotal}/>
          <table style={{ width:'100%' }}>
            <thead><tr>
              <TH>Beat</TH><TH>Title</TH><TH>Anchor</TH><TH>Exhibit</TH>
              <TH align="right">Runtime</TH><TH align="right">Strength</TH>
            </tr></thead>
            <tbody>
              {n.openingBeats.map((b,i)=>(
                <tr key={i}>
                  <TD mono>#{b.beat}</TD><TD><b>{b.title}</b></TD>
                  <TD>{b.anchor}</TD><TD mono>{b.exhibit}</TD>
                  <TD align="right" mono>{b.sec}s</TD>
                  <TD align="right" mono color={b.strength>=90?W.green.text:b.strength>=80?W.blue.text:W.amber.text}>{b.strength}</TD>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
        <Card title="Closing Argument Storyboard">
          <BeatBar beats={n.closingBeats} total={closeTotal}/>
          <table style={{ width:'100%' }}>
            <thead><tr>
              <TH>Beat</TH><TH>Title</TH><TH align="right">Runtime</TH><TH align="right">Strength</TH>
            </tr></thead>
            <tbody>
              {n.closingBeats.map((b,i)=>(
                <tr key={i}>
                  <TD mono>#{b.beat}</TD><TD><b>{b.title}</b></TD>
                  <TD align="right" mono>{b.sec}s</TD>
                  <TD align="right" mono color={b.strength>=90?W.green.text:b.strength>=80?W.blue.text:W.amber.text}>{b.strength}</TD>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      </div>
    );
  }

  // ══════════════════════════════════════════════════════════════════
  // MW10 — Mock Trial & Focus Group Analytics
  // ══════════════════════════════════════════════════════════════════
  function MW10MockTrial() {
    const st = useStore(['mock.panel']);
    const [flash, setFlash] = React.useState('');
    const m = st.mockTrial;

    return (
      <div>
        <Flash msg={flash}/>
        <div style={{ display:'flex', gap:'12px', marginBottom:'16px' }}>
          <KPI label="Mock Panels" value={m.panels}/>
          <KPI label="Respondents" value={m.totalRespondents}/>
          <KPI label="Liability Finding" value={`${m.liabilityFinding}%`} tone={m.liabilityFinding>=65?'green':'amber'}/>
          <KPI label="Avg Award" value={mw.money(m.avgAward)} tone="green"/>
          <KPI label="Median Award" value={mw.money(m.medianAward)}/>
        </div>
        <Card title="Theme Performance" right={<Btn tone="accent" onClick={()=>{
          S.addMockPanel('You'); setFlash('Mock panel scheduled');
        }}>Add panel</Btn>}>
          <table style={{ width:'100%' }}>
            <thead><tr>
              <TH>Theme</TH><TH>Favorability</TH><TH>Recall</TH>
            </tr></thead>
            <tbody>
              {m.themeReactions.map((t,i) => (
                <tr key={i}>
                  <TD>{t.theme}</TD>
                  <TD><div style={{ width:'240px' }}>
                    <Bar pct={t.favorability} tone={t.favorability>=75?'green':t.favorability>=50?'amber':'red'}/>
                    <div style={{ fontSize:'10px', marginTop:'2px', color:W.text.tertiary }}>{t.favorability}%</div>
                  </div></TD>
                  <TD><div style={{ width:'240px' }}>
                    <Bar pct={t.recall} tone="blue"/>
                    <div style={{ fontSize:'10px', marginTop:'2px', color:W.text.tertiary }}>{t.recall}%</div>
                  </div></TD>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'12px' }}>
          <Card title="Juror Profiles">
            <table style={{ width:'100%' }}>
              <thead><tr><TH>Persona</TH><TH>Bias</TH><TH align="right">Award</TH></tr></thead>
              <tbody>
                {m.juroProfiles.map((j,i) => (
                  <tr key={i}>
                    <TD><div>{j.persona}</div><div style={{ fontSize:'10px', color:W.text.tertiary }}>{j.notes}</div></TD>
                    <TD><Pill tone={j.bias==='Plaintiff'?'blue':'red'}>{j.bias}</Pill></TD>
                    <TD align="right" mono>{mw.money(j.award)}</TD>
                  </tr>
                ))}
              </tbody>
            </table>
          </Card>
          <Card title="Key Exhibit Impact (0–10)">
            {m.keyExhibitReactions.map((e,i) => (
              <div key={i} style={{ marginBottom:'10px' }}>
                <div style={{ display:'flex', justifyContent:'space-between', fontSize:'11px', color:W.text.secondary }}>
                  <span>{e.exhibit}</span>
                  <span style={{ color: W.green.text, fontFamily:W.font.mono, fontWeight:700 }}>{e.impact.toFixed(1)}</span>
                </div>
                <div style={{ marginTop:'4px' }}>
                  <Bar pct={e.impact*10} tone={e.impact>=8?'green':'amber'}/>
                </div>
              </div>
            ))}
          </Card>
        </div>
      </div>
    );
  }

  // ══════════════════════════════════════════════════════════════════
  // MW11 — Courtroom Ops & Tech Logistics
  // ══════════════════════════════════════════════════════════════════
  function MW11CourtroomOps() {
    const st = useStore(['courtroom.item']);
    const [flash, setFlash] = React.useState('');
    const c = st.courtroomOps;
    const done = c.checklist.filter(i=>i.status==='done').length;
    const totalBudget = c.techSupport.onsiteCost + c.techSupport.remoteCost + c.travelCost + c.meals;

    return (
      <div>
        <Flash msg={flash}/>
        <div style={{ display:'flex', gap:'12px', marginBottom:'16px' }}>
          <KPI label="Checklist Done" value={`${done}/${c.checklist.length}`} tone={done===c.checklist.length?'green':'amber'}/>
          <KPI label="Tech Support" value={mw.money(c.techSupport.onsiteCost+c.techSupport.remoteCost)}/>
          <KPI label="Travel" value={mw.money(c.travelCost)} sub={`${c.hotelNights} hotel nights`}/>
          <KPI label="Meals" value={mw.money(c.meals)}/>
          <KPI label="Total Trial Ops" value={mw.money(totalBudget)} tone="amber"/>
        </div>
        <Card title={`${c.courthouse} — Courtroom ${c.courtroom} · Judge ${c.judge}`}>
          <table style={{ width:'100%' }}>
            <thead><tr>
              <TH>Item</TH><TH>Owner</TH><TH>Status</TH><TH align="right">Action</TH>
            </tr></thead>
            <tbody>
              {c.checklist.map((item, idx) => (
                <tr key={idx}>
                  <TD>{item.item}</TD>
                  <TD>{item.owner}</TD>
                  <TD><Pill tone={statusTone(item.status)}>{item.status}</Pill></TD>
                  <TD align="right">
                    {item.status !== 'done' && (
                      <Btn tone="accent" onClick={()=>{
                        const r = S.advanceChecklistItem(idx, 'You');
                        setFlash(`${r.item} → ${r.status}`);
                      }}>Advance</Btn>
                    )}
                  </TD>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      </div>
    );
  }

  // ══════════════════════════════════════════════════════════════════
  // MW12 — Document Authentication Tracker
  // ══════════════════════════════════════════════════════════════════
  function MW12Authentication() {
    const st = useStore(['auth.status']);
    const [flash, setFlash] = React.useState('');
    const stip = st.authentications.filter(a=>a.status==='stipulated').length;
    const contested = st.authentications.filter(a=>a.status==='contested').length;

    return (
      <div>
        <Flash msg={flash}/>
        <div style={{ display:'flex', gap:'12px', marginBottom:'16px' }}>
          <KPI label="Exhibits to Auth" value={st.authentications.length}/>
          <KPI label="Stipulated" value={stip} tone="green"/>
          <KPI label="Contested" value={contested} tone={contested>0?'red':'green'}/>
          <KPI label="Pending" value={st.authentications.length - stip - contested} tone="amber"/>
        </div>
        <Card title="Authentication Foundation Paths">
          <table style={{ width:'100%' }}>
            <thead><tr>
              <TH>Exhibit</TH><TH>Description</TH><TH>Foundation Path</TH>
              <TH>Status</TH><TH>Risk</TH><TH align="right">Action</TH>
            </tr></thead>
            <tbody>
              {st.authentications.map(a => (
                <tr key={a.exhibit}>
                  <TD mono>{a.exhibit}</TD>
                  <TD>{a.description}</TD>
                  <TD style={{ fontSize:'11px', color:W.text.secondary }}>{a.path}</TD>
                  <TD><Pill tone={statusTone(a.status)}>{a.status}</Pill></TD>
                  <TD><Pill tone={a.risk==='low'?'green':a.risk==='medium'?'amber':'red'}>{a.risk}</Pill></TD>
                  <TD align="right">
                    {a.status==='pending' && (
                      <Btn tone="accent" onClick={()=>{
                        S.advanceAuthentication(a.exhibit, 'stipulated', 'You');
                        setFlash(`${a.exhibit} stipulated`);
                      }}>Stipulate</Btn>
                    )}
                  </TD>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      </div>
    );
  }

  // ══════════════════════════════════════════════════════════════════
  // MW13 — Parallel Proceedings Tracker
  // ══════════════════════════════════════════════════════════════════
  function MW13ParallelProceedings() {
    const st = useStore(['parallel.status']);
    const [flash, setFlash] = React.useState('');
    const active = st.parallelProceedings.filter(p=>p.status==='active'||p.status==='preliminary').length;

    return (
      <div>
        <Flash msg={flash}/>
        <div style={{ display:'flex', gap:'12px', marginBottom:'16px' }}>
          <KPI label="Parallel Forums" value={st.parallelProceedings.length}/>
          <KPI label="Active / Preliminary" value={active} tone={active>1?'red':'amber'}/>
          <KPI label="High Risk" value={st.parallelProceedings.filter(p=>p.risk==='high').length} tone="red"/>
        </div>
        {st.parallelProceedings.map(p => (
          <Card key={p.id} title={p.forum} right={
            <div style={{display:'flex',gap:'8px'}}>
              <Pill tone={p.risk==='high'?'red':p.risk==='medium'?'amber':'green'}>{p.risk}</Pill>
              <Pill tone={statusTone(p.status)}>{p.status}</Pill>
            </div>}>
            <div style={{ fontSize:'12px', color:W.text.primary, marginBottom:'8px' }}>{p.summary}</div>
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'12px' }}>
              <div>
                <div style={{ fontSize:'9px', fontWeight:600, color:W.text.tertiary, textTransform:'uppercase', letterSpacing:'0.08em', marginBottom:'4px' }}>Impact</div>
                <div style={{ fontSize:'11px', color:W.text.secondary }}>{p.impact}</div>
              </div>
              <div>
                <div style={{ fontSize:'9px', fontWeight:600, color:W.text.tertiary, textTransform:'uppercase', letterSpacing:'0.08em', marginBottom:'4px' }}>Coordination</div>
                <div style={{ fontSize:'11px', color:W.text.secondary }}>{p.coordination}</div>
              </div>
            </div>
            <div style={{ marginTop:'10px' }}>
              <Btn tone="accent" onClick={()=>{
                const next = p.status==='active' ? 'stayed' : p.status==='preliminary' ? 'active' : 'dormant';
                S.updateParallel(p.id, next, 'You');
                setFlash(`${p.forum}: ${p.status} → ${next}`);
              }}>Advance status</Btn>
            </div>
          </Card>
        ))}
      </div>
    );
  }

  // ══════════════════════════════════════════════════════════════════
  // MW14 — Regulatory & Congressional Risk
  // ══════════════════════════════════════════════════════════════════
  function MW14Regulatory() {
    const st = useStore(['reg.stage']);
    const [flash, setFlash] = React.useState('');
    const exposure = st.regulatory.reduce((s,r)=>s+r.likelihood*((r.penaltyRange[1]+r.disgorgementRange[1])/2),0);

    return (
      <div>
        <Flash msg={flash}/>
        <div style={{ display:'flex', gap:'12px', marginBottom:'16px' }}>
          <KPI label="Regulatory Fronts" value={st.regulatory.length}/>
          <KPI label="Expected Exposure" value={mw.money(exposure)} tone="red"/>
          <KPI label="Severe Threats" value={st.regulatory.filter(r=>r.severity==='severe').length} tone="red"/>
        </div>
        <Card title="Regulatory & Congressional Exposure">
          <table style={{ width:'100%' }}>
            <thead><tr>
              <TH>Agency</TH><TH>Stage</TH><TH align="right">Likelihood</TH>
              <TH>Severity</TH><TH align="right">Penalty Range</TH><TH align="right">Disgorge Range</TH>
              <TH>Next Milestone</TH><TH align="right">Action</TH>
            </tr></thead>
            <tbody>
              {st.regulatory.map(r => (
                <tr key={r.id}>
                  <TD><b>{r.agency}</b></TD>
                  <TD><Pill tone={statusTone(r.stage)}>{r.stage}</Pill></TD>
                  <TD align="right" mono>{mw.pct(r.likelihood,0)}</TD>
                  <TD><Pill tone={r.severity==='severe'?'red':r.severity==='material'?'amber':'blue'}>{r.severity}</Pill></TD>
                  <TD align="right" mono>{mw.money(r.penaltyRange[0])}–{mw.money(r.penaltyRange[1])}</TD>
                  <TD align="right" mono>{mw.money(r.disgorgementRange[0])}–{mw.money(r.disgorgementRange[1])}</TD>
                  <TD style={{ fontSize:'11px' }}>{r.nextMilestone}</TD>
                  <TD align="right">
                    <Btn tone="accent" onClick={()=>{
                      const order = ['monitoring','inquiry','preliminary','investigation','enforcement'];
                      const next = order[Math.min(order.indexOf(r.stage)+1, order.length-1)];
                      S.advanceRegulatory(r.id, next, 'You');
                      setFlash(`${r.agency} → ${next}`);
                    }}>Escalate</Btn>
                  </TD>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      </div>
    );
  }

  // ══════════════════════════════════════════════════════════════════
  // MW15 — Media & Reputational War Map
  // ══════════════════════════════════════════════════════════════════
  function MW15Media() {
    const st = useStore(['*']);
    const m = st.media;

    return (
      <div>
        <div style={{ display:'flex', gap:'12px', marginBottom:'16px' }}>
          <KPI label="Articles" value={m.articleCount}/>
          <KPI label="Broadcast" value={m.broadcastSegments}/>
          <KPI label="Reach" value={(m.reach/1e6).toFixed(1)+'M'}/>
          <KPI label="Social Mentions" value={(m.socialMentions/1000).toFixed(1)+'K'}/>
          <KPI label="PR Spend YTD" value={mw.money(m.prSpendYtd)}/>
        </div>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'12px' }}>
          <Card title="Sentiment Distribution">
            <div style={{ display:'flex', borderRadius:'6px', overflow:'hidden', height:'40px', marginBottom:'10px' }}>
              <div style={{ flex: m.sentiment.positive, background:W.green.base, display:'flex', alignItems:'center', justifyContent:'center', fontSize:'11px', fontWeight:700, color:'#fff' }}>{m.sentiment.positive}% +</div>
              <div style={{ flex: m.sentiment.neutral, background:W.blue.base, display:'flex', alignItems:'center', justifyContent:'center', fontSize:'11px', fontWeight:700, color:'#fff' }}>{m.sentiment.neutral}% ·</div>
              <div style={{ flex: m.sentiment.negative, background:W.red.base, display:'flex', alignItems:'center', justifyContent:'center', fontSize:'11px', fontWeight:700, color:'#fff' }}>{m.sentiment.negative}% −</div>
            </div>
            <table style={{ width:'100%' }}>
              <thead><tr><TH>Outlet</TH><TH>Tone</TH><TH align="right">Reach</TH><TH>Last</TH></tr></thead>
              <tbody>
                {m.keyOutlets.map((o,i)=>(
                  <tr key={i}>
                    <TD><b>{o.outlet}</b></TD>
                    <TD><Pill tone={o.tone.includes('negative')?'red':o.tone.includes('positive')?'green':'blue'}>{o.tone}</Pill></TD>
                    <TD align="right" mono>{(o.reach/1e6).toFixed(1)}M</TD>
                    <TD mono>{o.lastArticle}</TD>
                  </tr>
                ))}
              </tbody>
            </table>
          </Card>
          <Card title="Narrative Risks & Mitigation">
            {m.narrativeRisks.map((r,i) => (
              <div key={i} style={{ padding:'8px 0', borderBottom:`1px solid ${W.border.subtle}` }}>
                <div style={{ display:'flex', justifyContent:'space-between', marginBottom:'4px' }}>
                  <span style={{ fontSize:'12px', fontWeight:600, color:W.text.primary }}>{r.risk}</span>
                  <Pill tone={r.level==='high'?'red':r.level==='medium'?'amber':'green'}>{r.level}</Pill>
                </div>
                <div style={{ fontSize:'11px', color:W.text.tertiary }}>Mitigation: {r.mitigation}</div>
              </div>
            ))}
          </Card>
        </div>
      </div>
    );
  }

  // ══════════════════════════════════════════════════════════════════
  // MW16 — Adverse Precedent Watcher
  // ══════════════════════════════════════════════════════════════════
  function MW16Precedents() {
    const st = useStore(['*']);
    const friendly = st.precedents.filter(p=>p.alignment>0).length;
    const adverse = st.precedents.filter(p=>p.alignment<0).length;

    return (
      <div>
        <div style={{ display:'flex', gap:'12px', marginBottom:'16px' }}>
          <KPI label="Precedents Tracked" value={st.precedents.length}/>
          <KPI label="Favorable" value={friendly} tone="green"/>
          <KPI label="Adverse" value={adverse} tone="red"/>
          <KPI label="Emerging" value={st.precedents.filter(p=>p.changeSinceFiling==='emerging').length} tone="amber"/>
        </div>
        <Card title="Adverse & Favorable Precedent Watch">
          <table style={{ width:'100%' }}>
            <thead><tr>
              <TH>Case</TH><TH>Jurisdiction</TH><TH>Year</TH>
              <TH>Area</TH><TH align="right">Alignment</TH><TH>Change</TH><TH>Holding</TH>
            </tr></thead>
            <tbody>
              {st.precedents.map(p => (
                <tr key={p.id}>
                  <TD><i>{p.caseName}</i><div style={{ fontSize:'10px', color:W.text.tertiary }}>{p.citation}</div></TD>
                  <TD>{p.jurisdiction}</TD>
                  <TD mono>{p.year}</TD>
                  <TD>{p.impactArea}</TD>
                  <TD align="right" mono color={p.alignment>=0?W.green.text:W.red.text}>
                    {p.alignment>=0?'+':''}{p.alignment.toFixed(2)}</TD>
                  <TD><Pill tone={p.changeSinceFiling==='emerging'?'amber':p.changeSinceFiling==='reinforced'?'green':'blue'}>{p.changeSinceFiling}</Pill></TD>
                  <TD style={{ fontSize:'11px', color:W.text.secondary }}>{p.holding}</TD>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      </div>
    );
  }

  // ══════════════════════════════════════════════════════════════════
  // MW17 — Damages Monte Carlo Modeler
  // ══════════════════════════════════════════════════════════════════
  function MW17Damages() {
    const st = useStore(['damages.mc']);
    const [flash, setFlash] = React.useState('');
    const d = st.damagesModel;

    return (
      <div>
        <Flash msg={flash}/>
        <div style={{ display:'flex', gap:'12px', marginBottom:'16px' }}>
          <KPI label="Base Case" value={mw.money(d.baseCase)} />
          <KPI label="EV (Monte Carlo)" value={mw.money(d.evUsd)} tone="green"/>
          <KPI label="Range" value={`${mw.money(d.rangeLow)} – ${mw.money(d.rangeHigh)}`}/>
          <KPI label="MC Runs" value={d.monteCarloRuns.toLocaleString()}/>
        </div>
        <Card title="Damages Components — central estimate, range, certainty"
          right={<Btn tone="primary" onClick={()=>{
            S.runMonteCarlo('You');
            setFlash('Re-ran Monte Carlo (10K paths)');
          }}>Re-run MC</Btn>}>
          <table style={{ width:'100%' }}>
            <thead><tr>
              <TH>Component</TH><TH align="right">Central</TH><TH align="right">Low</TH>
              <TH align="right">High</TH><TH align="right">Certainty</TH>
            </tr></thead>
            <tbody>
              {d.components.map((c,i) => (
                <tr key={i}>
                  <TD><b>{c.name}</b></TD>
                  <TD align="right" mono color={W.green.text}>{mw.money(c.central)}</TD>
                  <TD align="right" mono>{mw.money(c.range[0])}</TD>
                  <TD align="right" mono>{mw.money(c.range[1])}</TD>
                  <TD align="right" mono color={c.certainty>=0.8?W.green.text:c.certainty>=0.5?W.amber.text:W.red.text}>
                    {mw.pct(c.certainty,0)}</TD>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
        <Card title="Percentile Distribution (10K simulations)">
          <table style={{ width:'100%' }}>
            <thead><tr>
              <TH>Percentile</TH><TH align="right">Award</TH><TH>Scenario</TH>
            </tr></thead>
            <tbody>
              {Object.entries(d.distributions).map(([k,v],i) => (
                <tr key={i}>
                  <TD mono>{k.toUpperCase()}</TD>
                  <TD align="right" mono color={k==='p50'?W.green.text:W.text.primary}>{mw.money(v)}</TD>
                  <TD style={{ fontSize:'11px', color:W.text.tertiary }}>
                    {k==='p10'?'Pessimistic — defense wins most issues':
                     k==='p25'?'Below central — partial liability':
                     k==='p50'?'Central / median — expected outcome':
                     k==='p75'?'Above central — most claims succeed':
                     'Optimistic — includes punitives'}
                  </TD>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      </div>
    );
  }

  // ══════════════════════════════════════════════════════════════════
  // MW18 — Settlement Decision Tree EV
  // ══════════════════════════════════════════════════════════════════
  function MW18Settlement() {
    const st = useStore(['settle.model']);
    const [flash, setFlash] = React.useState('');
    const [offer, setOffer] = React.useState(st.settlementTree.summary.settleNowEv);
    const t = st.settlementTree;

    return (
      <div>
        <Flash msg={flash}/>
        <div style={{ display:'flex', gap:'12px', marginBottom:'16px' }}>
          <KPI label="Settle Now EV" value={mw.money(t.summary.settleNowEv)} tone="blue"/>
          <KPI label="Trial EV (net costs)" value={mw.money(t.summary.trialEvNet)} tone="green"/>
          <KPI label="Delta" value={mw.money(t.summary.trialEvNet - t.summary.settleNowEv)}
            tone={t.summary.trialEvNet > t.summary.settleNowEv?'green':'red'}/>
        </div>
        <Card title="Recommendation">
          <div style={{ fontSize:'13px', color:W.text.primary, fontStyle:'italic' }}>
            {t.summary.recommendation}</div>
        </Card>
        <Card title="Decision Tree — probability-weighted payoffs">
          <table style={{ width:'100%' }}>
            <thead><tr>
              <TH>Node</TH><TH>Kind</TH><TH align="right">Probability</TH>
              <TH align="right">Outcome EV</TH><TH align="right">Cost</TH>
            </tr></thead>
            <tbody>
              {t.nodes.map(n => (
                <tr key={n.id}>
                  <TD style={{ paddingLeft: n.parent==='trial-branch' || n.parent==='appeal-branch' ? '32px' : '10px' }}>
                    <b>{n.label}</b></TD>
                  <TD><Pill tone={n.kind==='decision'?'purple':n.kind==='chance'?'amber':'blue'}>{n.kind}</Pill></TD>
                  <TD align="right" mono>{n.prob!=null ? mw.pct(n.prob,0) : '—'}</TD>
                  <TD align="right" mono color={W.green.text}>{n.ev!=null?mw.money(n.ev):'—'}</TD>
                  <TD align="right" mono color={n.cost?W.red.text:W.text.tertiary}>{n.cost?mw.money(n.cost):'—'}</TD>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
        <Card title="Model alternative settlement offers">
          <div style={{ display:'flex', gap:'12px', alignItems:'center' }}>
            <input type="range" min={4000000} max={20000000} step={500000}
              value={offer} onChange={e => setOffer(Number(e.target.value))}
              style={{ flex:1 }}/>
            <div style={{ minWidth:'120px', fontFamily:W.font.mono, fontSize:'14px', fontWeight:700, color:W.green.text }}>
              {mw.money(offer)}</div>
            <Btn tone="primary" onClick={()=>{
              S.modelSettlementOffer(offer,'You');
              setFlash(`Settle-now node → ${mw.money(offer)}`);
            }}>Model offer</Btn>
          </div>
        </Card>
      </div>
    );
  }

  // ══════════════════════════════════════════════════════════════════
  // MW19 — Litigation Finance & Budget Cockpit
  // ══════════════════════════════════════════════════════════════════
  function MW19Budget() {
    const st = useStore(['budget.draw','billing.push']);
    const [flash, setFlash] = React.useState('');
    const b = st.budget;
    const pctSpent = Math.round(100 * b.spentToDate / b.totalAuthorized);
    const runway = (b.remaining / (b.burnRatePerMonth||1)).toFixed(1);

    return (
      <div>
        <Flash msg={flash}/>
        <div style={{ display:'flex', gap:'12px', marginBottom:'16px' }}>
          <KPI label="Authorized" value={mw.money(b.totalAuthorized)}/>
          <KPI label="Spent" value={mw.money(b.spentToDate)} sub={`${pctSpent}%`} tone={pctSpent>70?'amber':'blue'}/>
          <KPI label="Remaining" value={mw.money(b.remaining)} tone="green"/>
          <KPI label="Burn/Mo" value={mw.money(b.burnRatePerMonth)}/>
          <KPI label="Runway" value={`${runway} mo`} tone={runway<6?'amber':'green'}/>
        </div>
        <Card title="Phase Budget vs Spend">
          <table style={{ width:'100%' }}>
            <thead><tr>
              <TH>Phase</TH><TH align="right">Budget</TH><TH align="right">Spent</TH>
              <TH align="right">Variance</TH><TH>Progress</TH>
              <TH align="right">Action</TH>
            </tr></thead>
            <tbody>
              {b.phases.map((p,i) => {
                const pct = Math.min(100, Math.round(100 * p.spent / (p.budget||1)));
                return (
                  <tr key={i}>
                    <TD><b>{p.phase}</b></TD>
                    <TD align="right" mono>{mw.money(p.budget)}</TD>
                    <TD align="right" mono>{mw.money(p.spent)}</TD>
                    <TD align="right" mono color={p.variance>=0?W.green.text:W.red.text}>
                      {p.variance>=0?'+':''}{mw.money(p.variance)}</TD>
                    <TD><div style={{ width:'120px' }}>
                      <Bar pct={pct} tone={pct>100?'red':pct>80?'amber':'blue'}/>
                      <div style={{ fontSize:'10px', marginTop:'2px', color:W.text.tertiary }}>{pct}%</div>
                    </div></TD>
                    <TD align="right">
                      <Btn tone="accent" onClick={()=>{
                        S.pushBudgetToBilling({ phase:p.phase, spendUsd:p.spent });
                        setFlash(`${p.phase} → Billing`);
                      }}>Billing</Btn>
                    </TD>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </Card>
        <Card title={`Litigation Finance — ${b.litigationFinance.provider}`}>
          <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:'12px', marginBottom:'12px' }}>
            <KPI label="Facility" value={mw.money(b.litigationFinance.facilityUsd)}/>
            <KPI label="Drawn" value={mw.money(b.litigationFinance.drawnUsd)} tone="amber"/>
            <KPI label="Undrawn" value={mw.money(b.litigationFinance.undrawnUsd)} tone="green"/>
            <KPI label="Cost of Capital" value={mw.pct(b.litigationFinance.costOfCapital,0)}/>
          </div>
          <div style={{ display:'flex', gap:'8px', alignItems:'center' }}>
            <Btn tone="primary" onClick={()=>{
              S.drawLitigationFinance(500000,'You');
              setFlash('Drew $500K from facility');
            }}>Draw $500K</Btn>
            <span style={{ fontSize:'11px', color:W.text.tertiary }}>
              Success multiple {b.litigationFinance.successMultiple}× · Waterfall rank {b.litigationFinance.waterfallRank}</span>
          </div>
        </Card>
      </div>
    );
  }

  // ══════════════════════════════════════════════════════════════════
  // MW20 — Insurance Coverage Cockpit
  // ══════════════════════════════════════════════════════════════════
  function MW20Coverage() {
    const st = useStore(['coverage.tender']);
    const [flash, setFlash] = React.useState('');
    const c = st.coverage;

    return (
      <div>
        <Flash msg={flash}/>
        <div style={{ display:'flex', gap:'12px', marginBottom:'16px' }}>
          <KPI label="Coverage Tower" value={mw.money(c.totalTowerUsd)} tone="green"/>
          <KPI label="Defense Costs Billed" value={mw.money(c.defenseCostsBilledToCarrier)}/>
          <KPI label="Pending Reimbursement" value={mw.money(c.defenseCostsPending)} tone="amber"/>
          <KPI label="Coverage Score" value={`${c.coveragePositionScore}/100`}
            tone={c.coveragePositionScore>=70?'green':c.coveragePositionScore>=50?'amber':'red'}/>
        </div>
        <Card title={`Insurance Tower — Coverage Counsel: ${c.coverageCounsel}`}>
          <table style={{ width:'100%' }}>
            <thead><tr>
              <TH>Policy</TH><TH>Type</TH><TH>Carrier</TH>
              <TH align="right">Limit</TH><TH align="right">Retention</TH>
              <TH align="right">Attaches At</TH><TH>Status</TH><TH align="right">Action</TH>
            </tr></thead>
            <tbody>
              {c.policies.map(p => (
                <tr key={p.id}>
                  <TD mono>{p.id}</TD>
                  <TD>{p.type}</TD>
                  <TD>{p.carrier}</TD>
                  <TD align="right" mono>{mw.money(p.limit)}</TD>
                  <TD align="right" mono>{mw.money(p.retention)}</TD>
                  <TD align="right" mono>{mw.money(p.attachmentPoint)}</TD>
                  <TD><Pill tone={statusTone(p.coverageStatus)}>{p.coverageStatus}</Pill></TD>
                  <TD align="right">
                    {p.coverageStatus!=='tendered' && (
                      <Btn tone="accent" onClick={()=>{
                        S.tenderToCarrier(p.id,'You');
                        setFlash(`${p.carrier} tendered`);
                      }}>Tender</Btn>
                    )}
                  </TD>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
        <Card title="Coverage Disputes">
          <table style={{ width:'100%' }}>
            <thead><tr>
              <TH>ID</TH><TH>Carrier</TH><TH>Issue</TH>
              <TH>Status</TH><TH align="right">Exposure</TH>
            </tr></thead>
            <tbody>
              {c.disputes.map(d => (
                <tr key={d.id}>
                  <TD mono>{d.id}</TD>
                  <TD>{d.carrier}</TD>
                  <TD>{d.issue}</TD>
                  <TD><Pill tone={d.status==='filed'?'amber':'blue'}>{d.status}</Pill></TD>
                  <TD align="right" mono color={W.red.text}>{mw.money(d.exposureUsd)}</TD>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      </div>
    );
  }

  // ══════════════════════════════════════════════════════════════════
  // HUBS — 5 consolidated navigation surfaces
  // ══════════════════════════════════════════════════════════════════
  const HubShell = ({ title, subtitle, tabs, active, setActive, children }) => (
    <div>
      <div style={{ padding:'16px 20px', marginBottom:'16px',
        background:'linear-gradient(135deg,#1E2740 0%,#111827 100%)',
        border:`1px solid ${W.border.medium}`, borderRadius:'8px' }}>
        <div style={{ fontSize:'16px', fontWeight:700, color:W.text.primary, letterSpacing:'-0.02em' }}>{title}</div>
        <div style={{ fontSize:'12px', color:W.text.tertiary, marginTop:'2px' }}>{subtitle}</div>
      </div>
      <SubTabs tabs={tabs} active={active} onChange={setActive}/>
      {children}
    </div>
  );

  // HUB 1 — Motions & Discovery
  function MotionsDiscoveryHub() {
    const [active, setActive] = React.useState('motions');
    const tabs = [
      { id:'motions',    label:'Motion Orchestrator' },
      { id:'mil',        label:'Motions in Limine' },
      { id:'discovery',  label:'Discovery Burden' },
      { id:'tar',        label:'TAR Performance' },
      { id:'privilege',  label:'Privilege & Waiver' },
    ];
    return (
      <HubShell title="Motions & Discovery"
        subtitle="Orchestrate motion practice, evidentiary fights, and discovery burden in one surface."
        tabs={tabs} active={active} setActive={setActive}>
        {active==='motions'   && <MW1MotionOrchestrator />}
        {active==='mil'       && <MW2MotionInLimine />}
        {active==='discovery' && <MW3DiscoveryBurden />}
        {active==='tar'       && <MW4TarPerformance />}
        {active==='privilege' && <MW5Privilege />}
      </HubShell>
    );
  }

  // HUB 2 — Depositions & Experts
  function DepositionsExpertsHub() {
    const [active, setActive] = React.useState('depos');
    const tabs = [
      { id:'depos',  label:'Deposition Board' },
      { id:'experts',label:'Expert Command' },
      { id:'cross',  label:'Cross-Exam Playbook' },
    ];
    return (
      <HubShell title="Depositions & Experts"
        subtitle="Depose strategically, retain the right experts, and rehearse crosses with measured control."
        tabs={tabs} active={active} setActive={setActive}>
        {active==='depos'   && <MW6Depositions />}
        {active==='experts' && <MW7Experts />}
        {active==='cross'   && <MW8CrossExam />}
      </HubShell>
    );
  }

  // HUB 3 — Trial Preparation
  function TrialPrepHub() {
    const [active, setActive] = React.useState('narrative');
    const tabs = [
      { id:'narrative', label:'Trial Narrative' },
      { id:'mock',      label:'Mock Trial' },
      { id:'ops',       label:'Courtroom Ops' },
      { id:'auth',      label:'Authentication' },
    ];
    return (
      <HubShell title="Trial Preparation"
        subtitle="Storyboard the trial, validate with jurors, run courtroom logistics, foundation every exhibit."
        tabs={tabs} active={active} setActive={setActive}>
        {active==='narrative' && <MW9Narrative />}
        {active==='mock'      && <MW10MockTrial />}
        {active==='ops'       && <MW11CourtroomOps />}
        {active==='auth'      && <MW12Authentication />}
      </HubShell>
    );
  }

  // HUB 4 — Parallel Risk
  function ParallelRiskHub() {
    const [active, setActive] = React.useState('parallel');
    const tabs = [
      { id:'parallel',   label:'Parallel Proceedings' },
      { id:'regulatory', label:'Regulatory Risk' },
      { id:'media',      label:'Media & Reputation' },
      { id:'precedent',  label:'Precedent Watcher' },
    ];
    return (
      <HubShell title="Parallel Risk"
        subtitle="Track parallel forums, regulatory fronts, media narrative, and live precedent as they move."
        tabs={tabs} active={active} setActive={setActive}>
        {active==='parallel'   && <MW13ParallelProceedings />}
        {active==='regulatory' && <MW14Regulatory />}
        {active==='media'      && <MW15Media />}
        {active==='precedent'  && <MW16Precedents />}
      </HubShell>
    );
  }

  // HUB 5 — Decision Economics
  function DecisionEconomicsHub() {
    const [active, setActive] = React.useState('damages');
    const tabs = [
      { id:'damages',  label:'Damages MC' },
      { id:'settle',   label:'Settlement EV Tree' },
      { id:'budget',   label:'Budget & Finance' },
      { id:'coverage', label:'Insurance Coverage' },
    ];
    return (
      <HubShell title="Decision Economics"
        subtitle="Quantify damages, price settlement, govern budget, and optimize insurance coverage."
        tabs={tabs} active={active} setActive={setActive}>
        {active==='damages'  && <MW17Damages />}
        {active==='settle'   && <MW18Settlement />}
        {active==='budget'   && <MW19Budget />}
        {active==='coverage' && <MW20Coverage />}
      </HubShell>
    );
  }

  // Expose 5 hubs on window for WarRoom.jsx integration
  window.MotionsDiscoveryHub  = MotionsDiscoveryHub;
  window.DepositionsExpertsHub= DepositionsExpertsHub;
  window.TrialPrepHub         = TrialPrepHub;
  window.ParallelRiskHub      = ParallelRiskHub;
  window.DecisionEconomicsHub = DecisionEconomicsHub;

  // Also expose individual opportunities for ad-hoc reuse
  window.MW1MotionOrchestrator = MW1MotionOrchestrator;
  window.MW2MotionInLimine     = MW2MotionInLimine;
  window.MW3DiscoveryBurden    = MW3DiscoveryBurden;
  window.MW4TarPerformance     = MW4TarPerformance;
  window.MW5Privilege          = MW5Privilege;
  window.MW6Depositions        = MW6Depositions;
  window.MW7Experts            = MW7Experts;
  window.MW8CrossExam          = MW8CrossExam;
  window.MW9Narrative          = MW9Narrative;
  window.MW10MockTrial         = MW10MockTrial;
  window.MW11CourtroomOps      = MW11CourtroomOps;
  window.MW12Authentication    = MW12Authentication;
  window.MW13ParallelProceedings = MW13ParallelProceedings;
  window.MW14Regulatory        = MW14Regulatory;
  window.MW15Media             = MW15Media;
  window.MW16Precedents        = MW16Precedents;
  window.MW17Damages           = MW17Damages;
  window.MW18Settlement        = MW18Settlement;
  window.MW19Budget            = MW19Budget;
  window.MW20Coverage          = MW20Coverage;
})();
