/* Operating Attorney screens. Case theory, strength & outcomes, pleadings & briefs, discovery.
   Each screen has 2-3 layout/density variants exposed via Tweaks (variant prop).
   These attorneys do FULL representation (vs. Reviewing = limited-scope).
   Threads through MATTERS dataset. Chen as the focused matter, full caseload listed.
*/

const _opTabs = (active, setActive, items) => (
  <TabStrip tabs={items} value={active} onChange={setActive} padded={false}/>
);

/* ============================================================
   1. CASE THEORY. Case-strategy workspace (the operating side of "legal theory")
   ============================================================ */
const OperatingTheoryScreen = ({ variant = 'split' }) => {
  const [matterId, setMatterId] = React.useState('chen');
  const [activeTheory, setActiveTheory] = React.useState('breach-contract');
  const m = MATTERS[matterId];

  const matters = OPERATING_CASELOAD.map(id => MATTERS[id]);
  const theories = [
    { id: 'breach-contract', label: 'Breach of contract', strength: 86, primary: true,
      strengths: ['Signed agreement with clear scope', 'Documented partial performance', 'Three independent successor bids'],
      weaknesses: ['No liquidated-damages clause', 'Disputed completion percentage'],
      cite: 'Harris v. Seward Park Hous. Corp., 79 A.D.3d 425 (1st Dep\'t 2010)',
    },
    { id: 'unjust-enrichment', label: 'Unjust enrichment (alt.)', strength: 62, primary: false,
      strengths: ['Deposit retained without performance', 'Material on-site abandoned'],
      weaknesses: ['Cumulative recovery barred if breach-contract succeeds', 'Equitable defense exposure'],
      cite: 'Mandarin Trading Ltd. v. Wildenstein, 16 N.Y.3d 173 (2011)',
    },
    { id: 'consumer-fraud', label: 'GBL § 349 (deceptive practices)', strength: 41, primary: false,
      strengths: ['Misrepresentation of license held', 'Public-impact element arguable'],
      weaknesses: ['Reliance proof thin', 'Treble cap may be lower than contract recovery'],
      cite: 'Karlin v. IVF Am., 93 N.Y.2d 282 (1999)',
    },
  ];
  const t = theories.find(x => x.id === activeTheory);

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      <PageHeader
        eyebrow={<>Section C · Operating attorney <span style={{opacity:0.5}}>·</span> Case theory</>}
        title="Theory & strategy workspace"
        subtitle="Side-by-side comparison of viable theories, with element coverage, precedent matches, and weakness flags. Pick a primary, keep alternates live until pleading lock."
        right={<>
          <Btn icon={Icons.book}>Precedent search</Btn>
          <Btn kind="primary" icon={Icons.sparkle}>Draft pleading</Btn>
        </>}
      >
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 14 }}>
          <span style={{ fontSize: 11, color: THEME.textMute, letterSpacing: 1, fontWeight: 600, textTransform: 'uppercase' }}>Active matter</span>
          <Segmented dense
            value={matterId}
            onChange={setMatterId}
            options={matters.slice(0, 5).map(mm => ({ value: mm.id, label: mm.short || mm.title.split(' ')[0] }))}
          />
          <div style={{ flex: 1 }}/>
          <JurisdictionPill jx={m.jurisdiction || 'ny'}/>
          <Pill soft tone={THEME.warn} dense>{m.stage || 'Filing prep'}</Pill>
        </div>
      </PageHeader>

      <div style={{ flex: 1, overflowY: 'auto', padding: '20px 32px' }}>
        {/* Matter snapshot strip */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 12, marginBottom: 18 }}>
          <Stat label="Theory leaders" value="3" sub="ranked below" tone={THEME.blue}/>
          <Stat label="Damages claimed" value={m.amountLabel || '-'} sub="under SC cap" tone={THEME.success}/>
          <Stat label="Precedents" value="14" sub="2nd Dep't, last 6 yrs" tone={THEME.accent}/>
          <Stat label="Days to file" value="3" sub="hard deadline" tone={THEME.danger}/>
        </div>

        {variant === 'split' && (
          <div style={{ display: 'grid', gridTemplateColumns: '320px 1fr', gap: 16 }}>
            {/* Theory list */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              <SectionLabel>Viable theories</SectionLabel>
              {theories.map(th => {
                const a = activeTheory === th.id;
                return (
                  <Card key={th.id} onClick={() => setActiveTheory(th.id)}
                    accent={a ? THEME.blue : null}
                    style={{
                      background: a ? THEME.blueSoft : (THEME.mode === 'dark' ? 'rgba(255,255,255,0.025)' : 'rgba(255,255,255,0.55)'),
                      borderColor: a ? THEME.blue + '60' : THEME.line,
                    }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                      <div style={{ fontFamily: 'Fraunces', fontSize: 14.5, color: THEME.text, fontWeight: 500, flex: 1 }}>{th.label}</div>
                      {th.primary && <Pill tone={THEME.success} soft dense>PRIMARY</Pill>}
                    </div>
                    <Progress pct={th.strength} tone={th.strength > 70 ? THEME.success : th.strength > 50 ? THEME.warn : THEME.danger} height={5}/>
                    <div style={{ fontSize: 10.5, color: THEME.textMute, marginTop: 6, letterSpacing: 0.4 }}>STRENGTH · {th.strength}/100</div>
                  </Card>
                );
              })}
              <Card style={{ borderStyle: 'dashed' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, color: THEME.textDim, fontSize: 12.5 }}>
                  <Icon d={Icons.plus} size={14} stroke={THEME.textDim}/>
                  <span>Add alternate theory</span>
                </div>
              </Card>
            </div>

            {/* Theory detail */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <Card padding="18px 20px">
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
                  <div style={{ fontFamily: 'Fraunces', fontSize: 22, color: THEME.text, fontWeight: 500, letterSpacing: -0.3 }}>{t.label}</div>
                  <Pill tone={t.strength > 70 ? THEME.success : THEME.warn} soft dense>{t.strength}% STRENGTH</Pill>
                  <div style={{ flex: 1 }}/>
                  <Btn kind="soft" tone={THEME.success} icon={Icons.check}>Set as primary</Btn>
                </div>
                <div style={{ fontSize: 12, color: THEME.textMute, fontStyle: 'italic' }}>{t.cite}</div>
              </Card>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <Card accent={THEME.success} padding="14px 16px">
                  <SectionLabel>Strengths</SectionLabel>
                  {t.strengths.map((s, i) => (
                    <div key={i} style={{ display: 'flex', gap: 8, padding: '5px 0', fontSize: 12.5, color: THEME.text }}>
                      <Icon d={Icons.check} size={12} stroke={THEME.success} sw={3}/>
                      <span style={{ flex: 1, lineHeight: 1.45 }}>{s}</span>
                    </div>
                  ))}
                </Card>
                <Card accent={THEME.danger} padding="14px 16px">
                  <SectionLabel>Weaknesses & risks</SectionLabel>
                  {t.weaknesses.map((s, i) => (
                    <div key={i} style={{ display: 'flex', gap: 8, padding: '5px 0', fontSize: 12.5, color: THEME.text }}>
                      <Icon d={Icons.alert} size={12} stroke={THEME.danger}/>
                      <span style={{ flex: 1, lineHeight: 1.45 }}>{s}</span>
                    </div>
                  ))}
                </Card>
              </div>

              <Card padding="14px 16px">
                <SectionLabel right={<span style={{ fontSize: 11, color: THEME.blue, fontWeight: 600, cursor: 'pointer' }}>View all 14 →</span>}>Top precedents</SectionLabel>
                {[
                  { name: 'Brandon v. Meridian Construction', cite: '92 Cal.App.5th 1184 (2023)', tag: 'On point', tone: THEME.success },
                  { name: 'Ortega v. Sunwest Builders', cite: '78 Cal.App.5th 221 (2022)', tag: 'Counter-arg', tone: THEME.warn },
                  { name: 'Ramos v. Atlas Renovation', cite: '12 N.Y.3d 414 (2009)', tag: 'On point', tone: THEME.success },
                ].map((p, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0', borderTop: i ? `1px solid ${THEME.lineSoft}` : 'none' }}>
                    <Icon d={Icons.book} size={13} stroke={THEME.textDim}/>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 12.5, color: THEME.text, fontWeight: 500, fontFamily: 'Fraunces' }}>{p.name}</div>
                      <div style={{ fontSize: 11, color: THEME.textMute }}>{p.cite}</div>
                    </div>
                    <Pill tone={p.tone} soft dense>{p.tag}</Pill>
                  </div>
                ))}
              </Card>
            </div>
          </div>
        )}

        {variant === 'matrix' && (
          <Card padding="18px 20px">
            <SectionLabel>Theory comparison matrix</SectionLabel>
            <div style={{ overflowX: 'auto' }}>
              <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 12.5 }}>
                <thead>
                  <tr style={{ color: THEME.textMute, fontSize: 10.5, letterSpacing: 0.6, textTransform: 'uppercase' }}>
                    <th style={{ textAlign: 'left', padding: '10px 12px', fontWeight: 600 }}>Theory</th>
                    <th style={{ textAlign: 'left', padding: '10px 12px', fontWeight: 600 }}>Strength</th>
                    <th style={{ textAlign: 'left', padding: '10px 12px', fontWeight: 600 }}>Max recovery</th>
                    <th style={{ textAlign: 'left', padding: '10px 12px', fontWeight: 600 }}>Burden</th>
                    <th style={{ textAlign: 'left', padding: '10px 12px', fontWeight: 600 }}>Defenses</th>
                    <th style={{ textAlign: 'left', padding: '10px 12px', fontWeight: 600 }}>Time-to-judgment</th>
                  </tr>
                </thead>
                <tbody>
                  {[
                    { th: 'Breach of contract', s: 86, max: '$8,420', burden: 'Preponderance', def: 'Performance dispute', t: '~90d' },
                    { th: 'Unjust enrichment', s: 62, max: '$4,200', burden: 'Preponderance', def: 'Election of remedies', t: '~120d' },
                    { th: 'GBL § 349', s: 41, max: '$1,000 +fees', burden: 'Preponderance', def: 'No public impact', t: '~180d' },
                  ].map((r, i) => (
                    <tr key={i} style={{ borderTop: `1px solid ${THEME.lineSoft}` }}>
                      <td style={{ padding: '12px', color: THEME.text, fontWeight: 600 }}>{r.th}</td>
                      <td style={{ padding: '12px' }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                          <div style={{ width: 60 }}>
                            <Progress pct={r.s} tone={r.s>70?THEME.success:r.s>50?THEME.warn:THEME.danger} height={4}/>
                          </div>
                          <span style={{ color: THEME.text, fontWeight: 600, fontVariantNumeric: 'tabular-nums' }}>{r.s}%</span>
                        </div>
                      </td>
                      <td style={{ padding: '12px', color: THEME.text, fontVariantNumeric: 'tabular-nums' }}>{r.max}</td>
                      <td style={{ padding: '12px', color: THEME.textDim }}>{r.burden}</td>
                      <td style={{ padding: '12px', color: THEME.textDim }}>{r.def}</td>
                      <td style={{ padding: '12px', color: THEME.textDim }}>{r.t}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </Card>
        )}
      </div>
    </div>
  );
};

/* ============================================================
   2. STRENGTH & OUTCOMES. Outcome modeling, judge analytics
   ============================================================ */
const OperatingStrengthScreen = ({ variant = 'forecast' }) => {
  const [matterId, setMatterId] = React.useState('chen');
  const m = MATTERS[matterId];
  const scenarios = [
    { name: 'Settle pre-trial', pct: 42, recovery: 5500, days: 35, cost: 1200, tone: THEME.success },
    { name: 'Default judgment', pct: 18, recovery: 8420, days: 75, cost: 800, tone: THEME.blue },
    { name: 'Bench trial · win', pct: 24, recovery: 8420, days: 110, cost: 3200, tone: THEME.accent },
    { name: 'Bench trial · partial', pct: 11, recovery: 4800, days: 110, cost: 3200, tone: THEME.warn },
    { name: 'Bench trial · loss', pct: 5, recovery: 0, days: 110, cost: 3200, tone: THEME.danger },
  ];
  const expectedValue = scenarios.reduce((s, x) => s + (x.pct/100) * (x.recovery - x.cost), 0);

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      <PageHeader
        eyebrow={<>Section C · Operating <span style={{opacity:0.5}}>·</span> Strength & outcomes</>}
        title="Outcome modeling"
        subtitle="Probability-weighted scenarios using your matter's posture, judge data, and historical outcomes for similar cases. Methodology disclosed; not a guarantee."
        right={<>
          <Btn icon={Icons.eye}>Methodology</Btn>
          <Btn kind="primary" icon={Icons.download}>Share with client</Btn>
        </>}
      >
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 14 }}>
          <Segmented dense value={matterId} onChange={setMatterId}
            options={OPERATING_CASELOAD.slice(0,5).map(id => ({ value: id, label: MATTERS[id].short || MATTERS[id].title.split(' ')[0] }))}/>
        </div>
      </PageHeader>

      <div style={{ flex: 1, overflowY: 'auto', padding: '20px 32px' }}>
        {/* EV header */}
        <Card padding="20px 22px" style={{ marginBottom: 16, background: `linear-gradient(135deg, ${THEME.blueSoft}, transparent)`, borderColor: THEME.blue + '40' }}>
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 24 }}>
            <div style={{ flex: 1 }}>
              <SectionLabel>Probability-weighted expected value</SectionLabel>
              <div style={{ fontFamily: 'Fraunces', fontSize: 44, color: THEME.text, fontWeight: 500, letterSpacing: -1, lineHeight: 1 }}>
                ${Math.round(expectedValue).toLocaleString()}
              </div>
              <div style={{ fontSize: 12, color: THEME.textDim, marginTop: 6 }}>
                Net of estimated costs · {scenarios.length} scenarios modeled · Confidence band ±$1,200
              </div>
            </div>
            <div style={{ display: 'flex', gap: 18 }}>
              <div>
                <div style={{ fontSize: 10.5, color: THEME.textMute, letterSpacing: 1, textTransform: 'uppercase', fontWeight: 600 }}>P(any recovery)</div>
                <div style={{ fontFamily: 'Fraunces', fontSize: 24, color: THEME.success, fontWeight: 500 }}>95%</div>
              </div>
              <div>
                <div style={{ fontSize: 10.5, color: THEME.textMute, letterSpacing: 1, textTransform: 'uppercase', fontWeight: 600 }}>P(full recovery)</div>
                <div style={{ fontFamily: 'Fraunces', fontSize: 24, color: THEME.text, fontWeight: 500 }}>42%</div>
              </div>
              <div>
                <div style={{ fontSize: 10.5, color: THEME.textMute, letterSpacing: 1, textTransform: 'uppercase', fontWeight: 600 }}>Median time</div>
                <div style={{ fontFamily: 'Fraunces', fontSize: 24, color: THEME.text, fontWeight: 500 }}>62d</div>
              </div>
            </div>
          </div>
        </Card>

        {variant === 'forecast' && (
          <>
            <SectionLabel>Outcome distribution</SectionLabel>
            <Card padding="18px 20px" style={{ marginBottom: 14 }}>
              {/* Stacked horizontal probability bar */}
              <div style={{ display: 'flex', height: 32, borderRadius: 8, overflow: 'hidden', marginBottom: 10 }}>
                {scenarios.map((s, i) => (
                  <div key={i} title={`${s.name} · ${s.pct}%`} style={{ width: s.pct + '%', background: s.tone, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontSize: 11, fontWeight: 700 }}>
                    {s.pct >= 8 && `${s.pct}%`}
                  </div>
                ))}
              </div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 12, fontSize: 11 }}>
                {scenarios.map((s, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <div style={{ width: 9, height: 9, borderRadius: 2, background: s.tone }}/>
                    <span style={{ color: THEME.textDim }}>{s.name}</span>
                  </div>
                ))}
              </div>
            </Card>

            <SectionLabel>Scenario ladder</SectionLabel>
            <Card padding="6px 0">
              {scenarios.map((s, i) => (
                <div key={i} style={{ display: 'grid', gridTemplateColumns: '24px 1fr 90px 110px 90px 110px', gap: 10, alignItems: 'center', padding: '12px 18px', borderTop: i ? `1px solid ${THEME.lineSoft}` : 'none' }}>
                  <div style={{ width: 8, height: 30, borderRadius: 3, background: s.tone }}/>
                  <div>
                    <div style={{ fontSize: 13, color: THEME.text, fontWeight: 600 }}>{s.name}</div>
                    <div style={{ fontSize: 11, color: THEME.textMute, marginTop: 2 }}>~{s.days} days · est. cost ${s.cost.toLocaleString()}</div>
                  </div>
                  <div>
                    <div style={{ fontSize: 10, color: THEME.textMute, letterSpacing: 0.5, fontWeight: 600 }}>PROBABILITY</div>
                    <div style={{ fontSize: 14, color: THEME.text, fontWeight: 600, fontVariantNumeric: 'tabular-nums' }}>{s.pct}%</div>
                  </div>
                  <div>
                    <div style={{ fontSize: 10, color: THEME.textMute, letterSpacing: 0.5, fontWeight: 600 }}>GROSS RECOVERY</div>
                    <div style={{ fontSize: 14, color: THEME.text, fontWeight: 600, fontVariantNumeric: 'tabular-nums' }}>${s.recovery.toLocaleString()}</div>
                  </div>
                  <div>
                    <div style={{ fontSize: 10, color: THEME.textMute, letterSpacing: 0.5, fontWeight: 600 }}>NET</div>
                    <div style={{ fontSize: 14, color: s.recovery - s.cost > 0 ? THEME.success : THEME.danger, fontWeight: 600, fontVariantNumeric: 'tabular-nums' }}>${(s.recovery - s.cost).toLocaleString()}</div>
                  </div>
                  <Btn kind="ghost" style={{ padding: '5px 10px', fontSize: 11 }}>Plan for this</Btn>
                </div>
              ))}
            </Card>
          </>
        )}

        {variant === 'judge' && (
          <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 14 }}>
            <Card padding="18px 20px">
              <SectionLabel>Judge analytics · Hon. Helena Vasquez</SectionLabel>
              <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 16 }}>
                <Avatar initials="HV" size={48} tone={`linear-gradient(135deg, #8b5cf6, ${THEME.accent})`}/>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: 'Fraunces', fontSize: 20, color: THEME.text, fontWeight: 500 }}>Hon. Helena Vasquez</div>
                  <div style={{ fontSize: 11.5, color: THEME.textMute }}>Kings County Civil · 14 yrs · 2,840 cases analyzed</div>
                </div>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 10 }}>
                {[
                  { label: 'Plaintiff win rate', v: '64%', sub: 'small claims · breach' },
                  { label: 'Avg recovery', v: '78¢/$', sub: 'of damages claimed' },
                  { label: 'Median to judgment', v: '54d', sub: 'from filing' },
                  { label: 'Settlement nudges', v: 'High', sub: 'pre-trial conference' },
                ].map((s, i) => (
                  <Card key={i}>
                    <div style={{ fontSize: 10, color: THEME.textMute, letterSpacing: 0.6, textTransform: 'uppercase', fontWeight: 600 }}>{s.label}</div>
                    <div style={{ fontFamily: 'Fraunces', fontSize: 22, color: THEME.text, fontWeight: 500, marginTop: 4 }}>{s.v}</div>
                    <div style={{ fontSize: 11, color: THEME.textMute, marginTop: 2 }}>{s.sub}</div>
                  </Card>
                ))}
              </div>
            </Card>
            <Card padding="18px 20px">
              <SectionLabel>Tendencies</SectionLabel>
              {[
                { label: 'Favors detailed exhibit indexes', v: 'Strong' },
                { label: 'Penalizes inflammatory language', v: 'Strong' },
                { label: 'Awards statutory fees when requested', v: 'Moderate' },
                { label: 'Schedules in-person hearings', v: '92%' },
              ].map((r, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '9px 0', borderTop: i ? `1px solid ${THEME.lineSoft}` : 'none', fontSize: 12.5 }}>
                  <Icon d={Icons.sparkle} size={11} stroke={THEME.accent}/>
                  <span style={{ flex: 1, color: THEME.text }}>{r.label}</span>
                  <Pill tone={THEME.accent} soft dense>{r.v}</Pill>
                </div>
              ))}
            </Card>
          </div>
        )}
      </div>
    </div>
  );
};

/* ============================================================
   3. PLEADINGS & BRIEFS. Drafting workspace, document library
   ============================================================ */
const OperatingPleadingsScreen = ({ variant = 'editor' }) => {
  const [matterId, setMatterId] = React.useState('chen');
  const [docId, setDocId] = React.useState('complaint');
  const m = MATTERS[matterId];

  const docs = [
    { id: 'complaint', name: 'Statement of Claim', status: 'Draft · v3', updated: '2h ago', ai: true, words: 1240 },
    { id: 'exhibits', name: 'Exhibit Index (14 items)', status: 'Ready', updated: 'Yesterday', ai: false, words: 380 },
    { id: 'damages', name: 'Damages Calculation', status: 'Draft · v2', updated: '4h ago', ai: true, words: 720 },
    { id: 'service', name: 'Affidavit of Service', status: 'Pending', updated: '-', ai: false, words: 0 },
    { id: 'memo', name: 'Memorandum of Law', status: 'Draft · v1', updated: '3d ago', ai: true, words: 2840 },
  ];

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      <PageHeader
        eyebrow={<>Section C · Pleadings & briefs</>}
        title="Drafting workspace"
        subtitle="Side-by-side drafting with precedent matches, citation auto-format, and tone flagging. AI suggests; you approve every change."
        right={<>
          <Btn icon={Icons.book}>Templates</Btn>
          <Btn kind="primary" icon={Icons.sparkle}>New brief</Btn>
        </>}
      >
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 14 }}>
          <Segmented dense value={matterId} onChange={setMatterId}
            options={OPERATING_CASELOAD.slice(0,5).map(id => ({ value: id, label: MATTERS[id].short || MATTERS[id].title.split(' ')[0] }))}/>
        </div>
      </PageHeader>

      <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
        {/* Document tree */}
        <div style={{ width: 280, borderRight: `1px solid ${THEME.line}`, padding: '14px 12px', overflowY: 'auto', flexShrink: 0 }}>
          <SectionLabel right={<Icon d={Icons.plus} size={14} stroke={THEME.textMute}/>}>Documents</SectionLabel>
          {docs.map(d => {
            const a = docId === d.id;
            return (
              <div key={d.id} onClick={() => setDocId(d.id)} style={{
                padding: '10px 12px', borderRadius: 8, cursor: 'pointer', marginBottom: 4,
                background: a ? THEME.blueSoft : 'transparent',
                borderLeft: `2px solid ${a ? THEME.blue : 'transparent'}`,
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 3 }}>
                  <Icon d={Icons.doc} size={13} stroke={a ? THEME.blue : THEME.textDim}/>
                  <span style={{ fontSize: 12.5, color: THEME.text, fontWeight: a ? 600 : 500, flex: 1 }}>{d.name}</span>
                  {d.ai && <Icon d={Icons.sparkle} size={10} stroke={THEME.accent} fill={THEME.accent}/>}
                </div>
                <div style={{ display: 'flex', gap: 6, fontSize: 10.5, color: THEME.textMute, paddingLeft: 21 }}>
                  <span>{d.status}</span>
                  <span>·</span>
                  <span>{d.updated}</span>
                </div>
              </div>
            );
          })}
        </div>

        {/* Editor */}
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
          <div style={{ padding: '10px 18px', borderBottom: `1px solid ${THEME.line}`, display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ fontSize: 12, color: THEME.textMute }}>Chen v. Northbay /</span>
              <span style={{ fontSize: 13, color: THEME.text, fontWeight: 600 }}>Statement of Claim</span>
              <Pill tone={THEME.warn} soft dense>v3 · DRAFT</Pill>
            </div>
            <Btn kind="ghost" icon={Icons.eye} style={{ padding: '5px 10px', fontSize: 11 }}>Preview</Btn>
            <Btn kind="ghost" icon={Icons.book} style={{ padding: '5px 10px', fontSize: 11 }}>Compare</Btn>
            <Btn kind="primary" icon={Icons.send} style={{ padding: '5px 12px', fontSize: 11 }}>Send to review</Btn>
          </div>

          <div style={{ flex: 1, overflowY: 'auto', padding: '24px 32px', display: 'grid', gridTemplateColumns: '1fr 320px', gap: 20 }}>
            {/* Document body */}
            <div style={{
              fontFamily: 'Fraunces', fontSize: 13.5, color: THEME.text, lineHeight: 1.7,
              padding: '24px 28px', borderRadius: 10,
              background: THEME.mode === 'dark' ? 'rgba(255,255,255,0.02)' : '#fff',
              border: `1px solid ${THEME.line}`, minHeight: 600,
            }}>
              <div style={{ textAlign: 'center', textTransform: 'uppercase', letterSpacing: 1.5, fontWeight: 600, fontSize: 11, color: THEME.textDim, marginBottom: 4 }}>Civil Court of the City of New York</div>
              <div style={{ textAlign: 'center', textTransform: 'uppercase', letterSpacing: 1.5, fontWeight: 600, fontSize: 11, color: THEME.textDim, marginBottom: 16 }}>County of Kings · Small Claims Part</div>
              <div style={{ borderTop: `1px solid ${THEME.line}`, borderBottom: `1px solid ${THEME.line}`, padding: '10px 0', marginBottom: 16, fontSize: 11.5, color: THEME.text, fontFamily: 'Inter' }}>
                <div><strong>Marcus Chen</strong>, Plaintiff,</div>
                <div style={{ paddingLeft: 16 }}>v.</div>
                <div><strong>Northbay Contracting LLC</strong>, Defendant.</div>
                <div style={{ marginTop: 6, color: THEME.textMute }}>Index No. ____________</div>
              </div>
              <div style={{ textAlign: 'center', fontFamily: 'Inter', fontWeight: 600, fontSize: 12.5, marginBottom: 18 }}>STATEMENT OF CLAIM</div>
              <p style={{ margin: '0 0 10px' }}>1. Plaintiff Marcus Chen, residing at 414 Bergen Street, Brooklyn, NY 11217, brings this action against Defendant Northbay Contracting LLC for breach of a written home-improvement contract.</p>
              <p style={{ margin: '0 0 10px' }}>2. On or about <span style={{ background: 'rgba(217,144,54,0.20)', padding: '0 3px', borderRadius: 3 }}>January 14, 2026</span>, the parties executed a written agreement (Exhibit A) under which Defendant agreed to perform kitchen-renovation work for a contract sum of $11,200, with a deposit of $4,200 paid on signing.</p>
              <p style={{ margin: '0 0 10px' }}>3. Defendant performed partial demolition during the week of January 20–25, 2026 (Exhibits B–D), then ceased communication and abandoned the work site.</p>
              <p style={{ margin: '0 0 10px', background: 'rgba(217,144,54,0.10)', borderLeft: `2px solid ${THEME.danger}`, padding: '6px 10px' }}>
                4. After repeated demands for performance or refund (Exhibits E–H), <span style={{ background: 'rgba(217,144,54,0.30)', padding: '0 3px', borderRadius: 3, color: THEME.danger, fontWeight: 600 }}>Defendant ripped off Plaintiff and refused to even respond to basic communications</span>, leaving Plaintiff with a partially demolished kitchen.
              </p>
            </div>

            {/* Right rail: AI suggestions */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              <Card accent={THEME.warn} padding="12px 14px">
                <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 6 }}>
                  <Icon d={Icons.alert} size={13} stroke={THEME.warn}/>
                  <span style={{ fontSize: 11, color: THEME.warn, fontWeight: 700, letterSpacing: 0.6, textTransform: 'uppercase' }}>Tone flag · ¶4</span>
                </div>
                <div style={{ fontSize: 12, color: THEME.textDim, lineHeight: 1.5, marginBottom: 8 }}>
                  "ripped off" reads emotive. Suggest: "failed to perform contracted work or refund the deposit despite repeated demand."
                </div>
                <div style={{ display: 'flex', gap: 6 }}>
                  <Btn kind="soft" tone={THEME.warn} style={{ padding: '4px 10px', fontSize: 11 }}>Accept</Btn>
                  <Btn kind="ghost" style={{ padding: '4px 10px', fontSize: 11 }}>Dismiss</Btn>
                </div>
              </Card>

              <Card accent={THEME.blue} padding="12px 14px">
                <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 6 }}>
                  <Icon d={Icons.book} size={13} stroke={THEME.blue}/>
                  <span style={{ fontSize: 11, color: THEME.blue, fontWeight: 700, letterSpacing: 0.6, textTransform: 'uppercase' }}>Citation suggestion</span>
                </div>
                <div style={{ fontSize: 12, color: THEME.textDim, lineHeight: 1.5, marginBottom: 8 }}>
                  Add citation for successor-cost recovery: <em>Brandon v. Meridian Construction</em>, 92 Cal.App.5th 1184 (2023).
                </div>
                <Btn kind="soft" tone={THEME.blue} style={{ padding: '4px 10px', fontSize: 11 }}>Insert citation</Btn>
              </Card>

              <Card accent={THEME.accent} padding="12px 14px">
                <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 6 }}>
                  <Icon d={Icons.sparkle} size={13} stroke={THEME.accent} fill={THEME.accent}/>
                  <span style={{ fontSize: 11, color: THEME.accent, fontWeight: 700, letterSpacing: 0.6, textTransform: 'uppercase' }}>Strengthen ¶3</span>
                </div>
                <div style={{ fontSize: 12, color: THEME.textDim, lineHeight: 1.5, marginBottom: 8 }}>
                  Add specificity: which days? Reference photos with EXIF dates already in Exhibit Index.
                </div>
                <Btn kind="soft" tone={THEME.accent} style={{ padding: '4px 10px', fontSize: 11 }}>Apply suggestion</Btn>
              </Card>

              <Card padding="12px 14px">
                <SectionLabel>Document health</SectionLabel>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6, fontSize: 11.5 }}>
                  <div style={{ display: 'flex', gap: 6 }}><Icon d={Icons.check} size={11} stroke={THEME.success} sw={3}/><span style={{ color: THEME.text }}>Caption complete</span></div>
                  <div style={{ display: 'flex', gap: 6 }}><Icon d={Icons.check} size={11} stroke={THEME.success} sw={3}/><span style={{ color: THEME.text }}>All elements pleaded</span></div>
                  <div style={{ display: 'flex', gap: 6 }}><Icon d={Icons.alert} size={11} stroke={THEME.warn}/><span style={{ color: THEME.textDim }}>1 tone flag pending</span></div>
                  <div style={{ display: 'flex', gap: 6 }}><Icon d={Icons.alert} size={11} stroke={THEME.warn}/><span style={{ color: THEME.textDim }}>Exhibit refs need verifying</span></div>
                </div>
              </Card>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

/* ============================================================
   4. DISCOVERY. Requests, responses, document review
   ============================================================ */
const OperatingDiscoveryScreen = ({ variant = 'kanban' }) => {
  const [matterId, setMatterId] = React.useState('alvarez');
  const m = MATTERS[matterId];
  const [tab, setTab] = React.useState('outgoing');

  const requests = {
    outgoing: [
      { id: 'rfp1', kind: 'RFP', title: 'Maintenance records 2023–2025', sent: 'Apr 3', due: 'Apr 24', status: 'awaiting', items: 14 },
      { id: 'rog1', kind: 'ROG', title: 'Identification of building staff', sent: 'Apr 3', due: 'Apr 24', status: 'awaiting', items: 8 },
      { id: 'rfa1', kind: 'RFA', title: 'Admissions re lease addenda', sent: 'Apr 5', due: 'May 5', status: 'served', items: 6 },
    ],
    incoming: [
      { id: 'rfp2', kind: 'RFP', title: 'Plaintiff\'s communications log', received: 'Mar 28', due: 'Apr 22', status: 'drafting', items: 22, complete: 14 },
      { id: 'rog2', kind: 'ROG', title: 'Damages computation', received: 'Mar 28', due: 'Apr 22', status: 'drafting', items: 11, complete: 7 },
    ],
    productions: [
      { id: 'p1', name: 'Bates 0001-0247', from: 'Cypress Realty', received: 'Apr 8', size: '247 pp', priv: 12, hot: 3 },
      { id: 'p2', name: 'Email batch · Q1 2024', from: 'Cypress Realty', received: 'Apr 10', size: '1,840 msgs', priv: 84, hot: 18 },
    ],
  };

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      <PageHeader
        eyebrow={<>Section C · Discovery</>}
        title="Discovery workspace"
        subtitle="Outgoing requests, incoming responses, document productions. Privilege log auto-built. Hot docs flagged for review."
        right={<>
          <Btn icon={Icons.upload}>Production drop</Btn>
          <Btn kind="primary" icon={Icons.plus}>New request</Btn>
        </>}
      >
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 14 }}>
          <Segmented dense value={matterId} onChange={setMatterId}
            options={OPERATING_CASELOAD.slice(0,5).map(id => ({ value: id, label: MATTERS[id].short || MATTERS[id].title.split(' ')[0] }))}/>
        </div>
      </PageHeader>

      {_opTabs(tab, setTab, [
        { value: 'outgoing', label: 'Outgoing', count: requests.outgoing.length },
        { value: 'incoming', label: 'Incoming', count: requests.incoming.length },
        { value: 'productions', label: 'Productions', count: requests.productions.length },
        { value: 'privilege', label: 'Privilege log', count: 96 },
      ])}

      <div style={{ flex: 1, overflowY: 'auto', padding: '20px 32px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 12, marginBottom: 18 }}>
          <Stat label="Open requests" value="5" sub="3 outgoing · 2 incoming" tone={THEME.blue}/>
          <Stat label="Days to next deadline" value="9" sub="Apr 22 · ROG response" tone={THEME.warn}/>
          <Stat label="Pages produced" value="2,087" sub="247 hot · 96 priv" tone={THEME.text}/>
          <Stat label="Privilege rate" value="4.6%" sub="industry: 6-8%" tone={THEME.success}/>
        </div>

        {tab === 'outgoing' && (
          <Card padding="0">
            <div style={{ display: 'grid', gridTemplateColumns: '60px 1.5fr 80px 80px 100px 90px', padding: '12px 18px', borderBottom: `1px solid ${THEME.line}`, fontSize: 10.5, color: THEME.textMute, letterSpacing: 0.6, fontWeight: 600, textTransform: 'uppercase' }}>
              <span>Type</span><span>Request</span><span>Sent</span><span>Due</span><span>Status</span><span>Items</span>
            </div>
            {requests.outgoing.map((r, i) => (
              <div key={r.id} style={{ display: 'grid', gridTemplateColumns: '60px 1.5fr 80px 80px 100px 90px', padding: '14px 18px', borderTop: i ? `1px solid ${THEME.lineSoft}` : 'none', alignItems: 'center', cursor: 'pointer' }}>
                <Pill tone={THEME.accent} soft dense>{r.kind}</Pill>
                <div>
                  <div style={{ fontSize: 13, color: THEME.text, fontWeight: 600 }}>{r.title}</div>
                  <div style={{ fontSize: 11, color: THEME.textMute, marginTop: 2 }}>To: Cypress Realty · Set 1</div>
                </div>
                <span style={{ fontSize: 12, color: THEME.textDim }}>{r.sent}</span>
                <span style={{ fontSize: 12, color: THEME.warn, fontWeight: 600 }}>{r.due}</span>
                <Pill tone={r.status === 'awaiting' ? THEME.warn : THEME.success} soft dense>{r.status === 'awaiting' ? 'Awaiting' : 'Served'}</Pill>
                <span style={{ fontSize: 12, color: THEME.textDim, fontVariantNumeric: 'tabular-nums' }}>{r.items} items</span>
              </div>
            ))}
          </Card>
        )}

        {tab === 'incoming' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {requests.incoming.map(r => (
              <Card key={r.id} accent={THEME.warn} padding="14px 18px">
                <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14 }}>
                  <Pill tone={THEME.accent} soft>{r.kind}</Pill>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 14, color: THEME.text, fontWeight: 600, marginBottom: 4 }}>{r.title}</div>
                    <div style={{ fontSize: 11.5, color: THEME.textMute, marginBottom: 10 }}>Received {r.received} · Response due <span style={{ color: THEME.warn, fontWeight: 600 }}>{r.due}</span></div>
                    <Progress pct={Math.round((r.complete/r.items)*100)} label={`${r.complete}/${r.items} responses drafted`}/>
                  </div>
                  <Btn kind="primary" style={{ padding: '6px 14px', fontSize: 11 }}>Continue drafting</Btn>
                </div>
              </Card>
            ))}
          </div>
        )}

        {tab === 'productions' && (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            {requests.productions.map(p => (
              <Card key={p.id} padding="16px 18px">
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                  <Icon d={Icons.folder} size={15} stroke={THEME.blue}/>
                  <div style={{ fontSize: 13.5, color: THEME.text, fontWeight: 600, flex: 1 }}>{p.name}</div>
                </div>
                <div style={{ fontSize: 11.5, color: THEME.textMute, marginBottom: 10 }}>From {p.from} · {p.received} · {p.size}</div>
                <div style={{ display: 'flex', gap: 8 }}>
                  <Pill tone={THEME.danger} soft dense>{p.hot} hot</Pill>
                  <Pill tone={THEME.warn} soft dense>{p.priv} privileged</Pill>
                  <div style={{ flex: 1 }}/>
                  <Btn kind="ghost" style={{ padding: '4px 10px', fontSize: 11 }}>Open viewer</Btn>
                </div>
              </Card>
            ))}
          </div>
        )}

        {tab === 'privilege' && (
          <Card padding="14px 18px">
            <SectionLabel>Privilege log · auto-generated</SectionLabel>
            <div style={{ fontSize: 12, color: THEME.textDim, marginBottom: 12, lineHeight: 1.5 }}>
              96 documents withheld. Each entry shows date, author, recipient, and basis. Export to opposing counsel as PDF.
            </div>
            {[
              { date: '2024-03-12', author: 'C. Alvarez', to: 'M. Riggs (counsel)', basis: 'Attorney-client', topic: 'Lease negotiation strategy' },
              { date: '2024-04-02', author: 'M. Riggs', to: 'C. Alvarez', basis: 'Work product', topic: 'Risk analysis re option to renew' },
              { date: '2024-05-19', author: 'C. Alvarez', to: 'M. Riggs', basis: 'Attorney-client', topic: 'Notice of breach drafting' },
            ].map((p, i) => (
              <div key={i} style={{ display: 'grid', gridTemplateColumns: '90px 1fr 1fr 130px 1fr', gap: 10, padding: '10px 0', borderTop: i ? `1px solid ${THEME.lineSoft}` : 'none', fontSize: 12, alignItems: 'center' }}>
                <span style={{ color: THEME.textDim, fontVariantNumeric: 'tabular-nums' }}>{p.date}</span>
                <span style={{ color: THEME.text }}>{p.author}</span>
                <span style={{ color: THEME.text }}>→ {p.to}</span>
                <Pill tone={THEME.accent} soft dense>{p.basis}</Pill>
                <span style={{ color: THEME.textDim }}>{p.topic}</span>
              </div>
            ))}
          </Card>
        )}
      </div>
    </div>
  );
};

window.OperatingTheoryScreen = OperatingTheoryScreen;
window.OperatingStrengthScreen = OperatingStrengthScreen;
window.OperatingPleadingsScreen = OperatingPleadingsScreen;
window.OperatingDiscoveryScreen = OperatingDiscoveryScreen;
