// CALENDAR OPPORTUNITIES — 20 new components (modals + list views + hubs)
(function () {
  const { useState } = React;
  const T = window.ArbiterTokens;
  const tone = (bg, fg) => ({ background: bg, color: fg });

  // ── Modal shell ──────────────────────────────────────────────────────
  function CalModal({ title, onClose, children, footer, width }) {
    return (
      <div style={{ position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.45)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 9000 }} onClick={onClose}>
        <div onClick={e => e.stopPropagation()} style={{ width: width || '720px', maxWidth: '92vw', maxHeight: '88vh', background: T.color.bg.card, borderRadius: T.radius.lg, boxShadow: '0 20px 60px rgba(15,23,42,0.35)', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
          <div style={{ padding: '12px 18px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div style={{ fontSize: '13px', fontWeight: 700, color: T.color.text.primary }}>{title}</div>
            <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: '18px', color: T.color.text.tertiary }}>×</button>
          </div>
          <div style={{ padding: '16px 18px', overflow: 'auto', flex: 1 }}>{children}</div>
          {footer && <div style={{ padding: '10px 18px', borderTop: `1px solid ${T.color.border.light}`, display: 'flex', gap: '8px', justifyContent: 'flex-end' }}>{footer}</div>}
        </div>
      </div>
    );
  }

  // ── Sub-tabs helper ──────────────────────────────────────────────────
  function CalSubTabs({ tabs, active, onChange }) {
    return (
      <div style={{ display: 'flex', border: `1px solid ${T.color.border.light}`, borderRadius: '6px', overflow: 'hidden', marginBottom: '12px', width: 'fit-content' }}>
        {tabs.map(t => (
          <button key={t.id} onClick={() => onChange(t.id)} style={{
            padding: '6px 14px', border: 'none', cursor: 'pointer', fontFamily: T.font.family,
            background: active === t.id ? cal.amber : T.color.bg.card,
            color: active === t.id ? '#fff' : T.color.text.secondary,
            fontSize: '11px', fontWeight: 600,
            borderRight: `1px solid ${T.color.border.light}`,
          }}>{t.label}{t.count != null ? ` (${t.count})` : ''}</button>
        ))}
      </div>
    );
  }

  // ── 1. Cascade Engine Modal ──────────────────────────────────────────
  function CalCascadeModal({ onClose }) {
    const [trigger, setTrigger] = useState('Discovery Cutoff');
    const [date, setDate] = useState('2026-05-14');
    const [matter, setMatter] = useState('Redstone v. Meridian');
    const [jurisdiction, setJurisdiction] = useState('S.D.N.Y.');
    const [preview, setPreview] = useState(null);

    const run = () => {
      const r = window.CalendarStore.runCascade({ matter, matterId: 'M-2024-0312', trigger, triggerDate: date, jurisdiction, ranBy: 'M. Kirkland' });
      setPreview(r);
    };

    return (
      <CalModal title="Rule-Based Cascade Engine" onClose={onClose} width="760px"
        footer={<>
          <button onClick={onClose} style={cal.filterBtn}>Close</button>
          <button onClick={run} style={{ ...cal.filterBtn, ...cal.filterBtnActive }}>Run cascade</button>
        </>}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px', marginBottom: '14px' }}>
          <label style={{ fontSize: '11px', color: T.color.text.secondary }}>Matter
            <input value={matter} onChange={e => setMatter(e.target.value)} style={{ width: '100%', padding: '6px', fontSize: '12px', border: `1px solid ${T.color.border.light}`, borderRadius: '4px', marginTop: '4px' }} />
          </label>
          <label style={{ fontSize: '11px', color: T.color.text.secondary }}>Jurisdiction
            <select value={jurisdiction} onChange={e => setJurisdiction(e.target.value)} style={{ width: '100%', padding: '6px', fontSize: '12px', border: `1px solid ${T.color.border.light}`, borderRadius: '4px', marginTop: '4px' }}>
              {(window.JURISDICTION_RULE_PACKS || []).map(p => <option key={p.id} value={p.name}>{p.name}</option>)}
            </select>
          </label>
          <label style={{ fontSize: '11px', color: T.color.text.secondary }}>Trigger event
            <select value={trigger} onChange={e => setTrigger(e.target.value)} style={{ width: '100%', padding: '6px', fontSize: '12px', border: `1px solid ${T.color.border.light}`, borderRadius: '4px', marginTop: '4px' }}>
              <option>Discovery Cutoff</option>
              <option>Trial Date</option>
              <option>Complaint Filed</option>
            </select>
          </label>
          <label style={{ fontSize: '11px', color: T.color.text.secondary }}>Trigger date
            <input type="date" value={date} onChange={e => setDate(e.target.value)} style={{ width: '100%', padding: '6px', fontSize: '12px', border: `1px solid ${T.color.border.light}`, borderRadius: '4px', marginTop: '4px' }} />
          </label>
        </div>
        {preview && (
          <div style={{ ...cal.card, margin: 0 }}>
            <div style={cal.cardH}><span>Generated {preview.generated.length} deadlines</span><span style={{ fontSize: '10px', color: T.color.text.tertiary }}>Run {preview.run.id}</span></div>
            {preview.generated.map(d => (
              <div key={d.id} style={{ padding: '8px 16px', borderBottom: `1px solid ${T.color.border.light}`, fontSize: '12px', display: 'flex', gap: '8px', alignItems: 'center' }}>
                <span style={{ ...cal.tag, ...tone(cal.amberBg, cal.amber) }}>{d.date}</span>
                <span style={{ flex: 1, fontWeight: 500 }}>{d.label}</span>
                <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.tertiary }}>{d.rule}</span>
              </div>
            ))}
          </div>
        )}
      </CalModal>
    );
  }

  // ── 2. Jurisdiction Rule Pack Library ───────────────────────────────
  function CalRulePackLibrary() {
    const data = window.useCalStore ? window.useCalStore(['rulepack.external.updated']) : { rulePacks: window.JURISDICTION_RULE_PACKS };
    return (
      <div style={cal.card}>
        <div style={cal.cardH}><span>Jurisdiction Rule Packs</span><span style={{ fontSize: '10px', color: T.color.text.tertiary }}>{data.rulePacks.length} packs</span></div>
        {data.rulePacks.map(p => (
          <div key={p.id} style={{ padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', gap: '10px', alignItems: 'center', fontSize: '12px' }}>
            <span style={{ ...cal.tag, ...tone(cal.amberBg, cal.amber), minWidth: '100px', justifyContent: 'center' }}>{p.name}</span>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 600, color: T.color.text.primary }}>{p.type}</div>
              <div style={{ fontSize: '10px', color: T.color.text.tertiary }}>{p.notes || '—'}</div>
            </div>
            <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.secondary }}>{p.rules} rules</span>
            <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.tertiary }}>{p.matters} matters</span>
            <span style={{ ...cal.tag, ...(p.status === 'active' ? tone('rgba(34,197,94,0.08)', T.color.status.active) : tone(T.color.bg.secondary, T.color.text.tertiary)) }}>{p.status}</span>
          </div>
        ))}
      </div>
    );
  }

  // ── 3. Court Holidays ────────────────────────────────────────────────
  function CalHolidaysTab() {
    const H = window.COURT_HOLIDAYS || [];
    return (
      <div style={cal.card}>
        <div style={cal.cardH}><span>Court Holidays & Closures — 2026</span></div>
        {H.map((h, i) => (
          <div key={i} style={{ padding: '8px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', gap: '10px', fontSize: '12px', alignItems: 'center' }}>
            <span style={{ ...cal.tag, ...tone(cal.amberBg, cal.amber), fontFamily: T.font.mono, minWidth: '96px', justifyContent: 'center' }}>{h.date}</span>
            <span style={{ flex: 1, fontWeight: 500, color: T.color.text.primary }}>{h.name}</span>
            <span style={{ fontSize: '10px', color: T.color.text.tertiary }}>{h.jurisdictions.join(' · ')}</span>
            {h.skipForCalc && <span style={{ ...cal.tag, ...tone('rgba(59,130,246,0.08)', '#3B82F6') }}>Skipped</span>}
          </div>
        ))}
      </div>
    );
  }

  // ── 4. Judge Standing Orders ─────────────────────────────────────────
  function CalStandingOrdersTab() {
    const J = window.JUDGE_STANDING_ORDERS || [];
    return (
      <div style={cal.card}>
        <div style={cal.cardH}><span>Judge Standing Orders</span></div>
        {J.map(j => (
          <div key={j.id} style={{ padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}`, fontSize: '12px' }}>
            <div style={{ display: 'flex', gap: '10px', alignItems: 'center', marginBottom: '4px' }}>
              <span style={{ fontWeight: 700, color: T.color.text.primary }}>{j.judge}</span>
              <span style={{ fontSize: '10px', color: T.color.text.tertiary }}>{j.court} · {j.chambers}</span>
              <span style={{ marginLeft: 'auto', ...cal.tag, ...tone(cal.amberBg, cal.amber) }}>Continuance: {j.continuanceLikelihood}</span>
            </div>
            <div style={{ fontSize: '10px', color: T.color.text.secondary }}>MSJ/Opp/Reply page limits: <b>{j.pageLimits.msj}/{j.pageLimits.opp}/{j.pageLimits.reply}</b> · {j.chambersCopy ? 'Chambers copy' : 'E-only'} · {j.premotion ? 'Pre-motion conf req.' : 'No premotion'}</div>
            {j.notes && <div style={{ fontSize: '10px', color: T.color.text.tertiary, marginTop: '4px' }}>{j.notes}</div>}
          </div>
        ))}
      </div>
    );
  }

  // ── 5. SOL Dashboard ─────────────────────────────────────────────────
  function CalSOLDashboard() {
    const sol = (window.SOL_TRACKER || []).slice().sort((a, b) => a.daysRemaining - b.daysRemaining);
    const counts = sol.reduce((a, s) => (a[s.status] = (a[s.status] || 0) + 1, a), {});
    const tag = s => s === 'Urgent' ? tone('rgba(194,48,48,0.08)', '#C23030') : s === 'Monitor' ? tone(cal.amberBg, cal.amber) : tone('rgba(34,197,94,0.08)', T.color.status.active);
    return (
      <div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: '12px', marginBottom: '12px' }}>
          <div style={cal.stat}><span style={cal.statLabel}>Urgent</span><span style={{ ...cal.statValue, color: '#C23030' }}>{counts.Urgent || 0}</span></div>
          <div style={cal.stat}><span style={cal.statLabel}>Monitor</span><span style={{ ...cal.statValue, color: cal.amber }}>{counts.Monitor || 0}</span></div>
          <div style={cal.stat}><span style={cal.statLabel}>Safe</span><span style={{ ...cal.statValue, color: T.color.status.active }}>{counts.Safe || 0}</span></div>
        </div>
        <div style={cal.card}>
          <div style={cal.cardH}><span>Statute of Limitations Tracker</span></div>
          {sol.map((s, i) => (
            <div key={i} style={{ padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', gap: '10px', alignItems: 'center', fontSize: '12px' }}>
              <span style={{ ...cal.tag, ...tag(s.status), minWidth: '72px', justifyContent: 'center' }}>{s.status}</span>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 600, color: T.color.text.primary }}>{s.matter} — {s.claim}</div>
                <div style={{ fontSize: '10px', color: T.color.text.tertiary }}>{s.sol}</div>
              </div>
              <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.secondary }}>Expires {s.expires}</span>
              <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: s.daysRemaining < 365 ? '#C23030' : T.color.text.tertiary }}>{s.daysRemaining}d</span>
            </div>
          ))}
        </div>
      </div>
    );
  }

  // ── 6. Critical Path Analyzer ───────────────────────────────────────
  function CalCriticalPath() {
    const path = window.CalendarStore ? window.CalendarStore.criticalPath('M-2024-0312') : [];
    return (
      <div style={cal.card}>
        <div style={cal.cardH}><span>Critical Path — Redstone v. Meridian</span><span style={{ fontSize: '10px', color: T.color.text.tertiary }}>{path.length} nodes</span></div>
        {path.map((d, i) => (
          <div key={d.id} style={{ padding: '8px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', gap: '8px', alignItems: 'center', fontSize: '12px' }}>
            <span style={{ width: '24px', fontFamily: T.font.mono, fontSize: '10px', color: T.color.text.tertiary }}>{i + 1}.</span>
            <span style={{ ...cal.tag, ...tone(cal.amberBg, cal.amber), fontFamily: T.font.mono }}>{d.date}</span>
            <span style={{ flex: 1, fontWeight: 500 }}>{d.label}</span>
            {d.priority === 'critical' && <span style={{ ...cal.tag, ...tone('rgba(194,48,48,0.08)', '#C23030') }}>critical</span>}
            {d.parent && <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.tertiary }}>← {d.parent}</span>}
          </div>
        ))}
      </div>
    );
  }

  // ── 7. T-Minus Escalation Ladder ─────────────────────────────────────
  function CalEscalationTab() {
    const data = window.useCalStore ? window.useCalStore(['escalation.toggled']) : { escalationRules: window.ESCALATION_RULES };
    return (
      <div style={cal.card}>
        <div style={cal.cardH}><span>Escalation Ladder — T-Minus Notifications</span></div>
        {data.escalationRules.map(r => (
          <div key={r.id} style={{ padding: '8px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', gap: '10px', alignItems: 'center', fontSize: '12px' }}>
            <span style={{ ...cal.tag, ...tone(cal.amberBg, cal.amber), fontFamily: T.font.mono, minWidth: '48px', justifyContent: 'center' }}>{r.trigger}</span>
            <span style={{ ...cal.tag, ...(r.priority === 'critical' ? tone('rgba(194,48,48,0.08)', '#C23030') : tone(T.color.bg.secondary, T.color.text.secondary)) }}>{r.priority}</span>
            <span style={{ flex: 1, fontSize: '11px', color: T.color.text.secondary }}>{r.recipients.join(' → ')}</span>
            <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.tertiary }}>{r.channel}</span>
            <button onClick={() => window.CalendarStore.toggleEscalation(r.id)} style={{ ...cal.filterBtn, ...(r.enabled ? cal.filterBtnActive : {}), fontSize: '10px' }}>{r.enabled ? 'Enabled' : 'Disabled'}</button>
          </div>
        ))}
      </div>
    );
  }

  // ── 8. Client Status Report Generator ────────────────────────────────
  function CalClientReportsTab() {
    const data = window.useCalStore ? window.useCalStore(['report.sent']) : { clientReports: window.CLIENT_REPORTS };
    return (
      <div style={cal.card}>
        <div style={cal.cardH}><span>Client Status Reports</span></div>
        {data.clientReports.map(r => (
          <div key={r.id} style={{ padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', gap: '10px', alignItems: 'center', fontSize: '12px' }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 600, color: T.color.text.primary }}>{r.matter}</div>
              <div style={{ fontSize: '10px', color: T.color.text.tertiary }}>{r.cadence} · to {r.recipients.join(', ')}</div>
            </div>
            <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.tertiary }}>Last: {r.lastSent}</span>
            <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.secondary }}>Next: {r.nextDue}</span>
            <span style={{ ...cal.tag, ...(r.status === 'sent' ? tone('rgba(34,197,94,0.08)', T.color.status.active) : tone(cal.amberBg, cal.amber)) }}>{r.status}</span>
            {r.status !== 'sent' && <button onClick={() => window.CalendarStore.sendClientReport(r.id)} style={{ ...cal.filterBtn, ...cal.filterBtnActive, fontSize: '10px' }}>Send now</button>}
          </div>
        ))}
      </div>
    );
  }

  // ── 9. PACER Docket Sync ─────────────────────────────────────────────
  function CalPacerTab() {
    const data = window.useCalStore ? window.useCalStore(['pacer.ingested', 'pacer.promoted']) : { pacerEntries: window.PACER_ENTRIES };
    return (
      <div style={cal.card}>
        <div style={cal.cardH}><span>Docket Sync (PACER / State Courts)</span><span style={{ fontSize: '10px', color: T.color.text.tertiary }}>{data.pacerEntries.length} entries</span></div>
        {data.pacerEntries.map(e => (
          <div key={e.id} style={{ padding: '8px 16px', borderBottom: `1px solid ${T.color.border.light}`, fontSize: '12px' }}>
            <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
              <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.tertiary, minWidth: '92px' }}>{e.docketNo}</span>
              <span style={{ flex: 1, color: T.color.text.primary }}>{e.entry}</span>
              <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.tertiary }}>{e.date}</span>
              {e.promotedToDeadline ? (
                <span style={{ ...cal.tag, ...tone('rgba(34,197,94,0.08)', T.color.status.active) }}>→ {e.deadlineId}</span>
              ) : e.ingested ? (
                <span style={{ ...cal.tag, ...tone(cal.amberBg, cal.amber) }}>Ready</span>
              ) : (
                <button onClick={() => window.CalendarStore.ingestPacer(e.id)} style={{ ...cal.filterBtn, fontSize: '10px' }}>Ingest</button>
              )}
            </div>
          </div>
        ))}
      </div>
    );
  }

  // ── 10. Service of Process Tracker ──────────────────────────────────
  function CalServiceTab() {
    const data = window.useCalStore ? window.useCalStore(['service.logged']) : { serviceOfProcess: window.SERVICE_OF_PROCESS };
    const tag = s => s === 'on-time' ? tone('rgba(34,197,94,0.08)', T.color.status.active) : s === 'late' ? tone('rgba(194,48,48,0.08)', '#C23030') : s === 'at-risk' ? tone(cal.amberBg, cal.amber) : tone(T.color.bg.secondary, T.color.text.tertiary);
    return (
      <div style={cal.card}>
        <div style={cal.cardH}><span>Service of Process</span></div>
        {data.serviceOfProcess.map(s => (
          <div key={s.id} style={{ padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', gap: '10px', alignItems: 'center', fontSize: '12px' }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 600, color: T.color.text.primary }}>{s.matter}</div>
              <div style={{ fontSize: '10px', color: T.color.text.tertiary }}>{s.party} · {s.method} · {s.server}</div>
            </div>
            <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.secondary }}>Served {s.served}</span>
            <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.secondary }}>Answer {s.answerDue}</span>
            <span style={{ ...cal.tag, ...tag(s.status) }}>{s.status}{s.daysLate > 0 ? ` +${s.daysLate}d` : ''}</span>
          </div>
        ))}
      </div>
    );
  }

  // ── 11. Motion Tracker ───────────────────────────────────────────────
  function CalMotionsTab() {
    const data = window.useCalStore ? window.useCalStore(['motion.filed', 'motion.updated']) : { motions: window.MOTIONS };
    const tag = s => s === 'ruled' ? tone('rgba(34,197,94,0.08)', T.color.status.active) : s.includes('drafting') ? tone(cal.amberBg, cal.amber) : tone('rgba(59,130,246,0.08)', '#3B82F6');
    return (
      <div style={cal.card}>
        <div style={cal.cardH}><span>Motion Tracker</span></div>
        {data.motions.map(m => (
          <div key={m.id} style={{ padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}`, fontSize: '12px' }}>
            <div style={{ display: 'flex', gap: '10px', alignItems: 'center', marginBottom: '4px' }}>
              <span style={{ fontWeight: 600, color: T.color.text.primary, flex: 1 }}>{m.type} — {m.matter}</span>
              <span style={{ ...cal.tag, ...tag(m.status) }}>{m.status}</span>
              {m.ruling && <span style={{ ...cal.tag, ...tone('rgba(34,197,94,0.08)', T.color.status.active) }}>{m.ruling}</span>}
            </div>
            <div style={{ fontSize: '10px', color: T.color.text.tertiary }}>
              {m.movant} · {m.judge} · Filed {m.filed || '—'} · Opp {m.oppDue || '—'} · Reply {m.replyDue || '—'} · Argument {m.argument || '—'}
            </div>
          </div>
        ))}
      </div>
    );
  }

  // ── 12. Continuance Tracker ──────────────────────────────────────────
  function CalContinuancesTab() {
    const data = window.useCalStore ? window.useCalStore(['continuance.requested', 'continuance.ruled']) : { continuances: window.CONTINUANCES };
    const tag = s => s === 'granted' ? tone('rgba(34,197,94,0.08)', T.color.status.active) : s === 'denied' ? tone('rgba(194,48,48,0.08)', '#C23030') : tone(cal.amberBg, cal.amber);
    return (
      <div style={cal.card}>
        <div style={cal.cardH}><span>Continuance / Extension Tracker</span></div>
        {data.continuances.map(c => (
          <div key={c.id} style={{ padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}`, fontSize: '12px' }}>
            <div style={{ display: 'flex', gap: '10px', alignItems: 'center', marginBottom: '4px' }}>
              <span style={{ fontWeight: 600, color: T.color.text.primary, flex: 1 }}>{c.request} — {c.matter}</span>
              <span style={{ ...cal.tag, ...tag(c.status) }}>{c.status}</span>
            </div>
            <div style={{ fontSize: '10px', color: T.color.text.tertiary }}>{c.requestedBy} · {c.basis}{c.originalDate ? ` · ${c.originalDate} → ${c.newDate || 'pending'}` : ''} · {c.impact}</div>
          </div>
        ))}
      </div>
    );
  }

  // ── 13. Trial Countdown Dashboard ───────────────────────────────────
  function CalTrialCountdown() {
    const dl = window.DOCKET_DEADLINES || [];
    const now = new Date('2026-04-20');
    const trials = dl.filter(d => d.type === 'trial').sort((a, b) => a.date.localeCompare(b.date));
    return (
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(320px, 1fr))', gap: '12px' }}>
        {trials.map(t => {
          const days = Math.ceil((new Date(t.date) - now) / 86400000);
          const color = days <= 14 ? '#C23030' : days <= 45 ? cal.amber : T.color.status.active;
          return (
            <div key={t.id} style={{ ...cal.card, margin: 0 }}>
              <div style={cal.cardH}>
                <span>{t.matter}</span>
                <span style={{ ...cal.tag, ...tone(`${color}15`, color), fontFamily: T.font.mono }}>T-{days}d</span>
              </div>
              <div style={{ padding: '10px 16px', fontSize: '12px' }}>
                <div style={{ fontSize: '22px', fontWeight: 700, color, fontFamily: T.font.mono }}>{t.date}</div>
                <div style={{ fontSize: '10px', color: T.color.text.tertiary, marginBottom: '8px' }}>{t.notes || t.rule}</div>
                <div style={{ fontSize: '10px', color: T.color.text.secondary }}>Lead: {t.assignee}</div>
              </div>
            </div>
          );
        })}
      </div>
    );
  }

  // ── 14. Scheduling Conflict Check ────────────────────────────────────
  function CalConflictCheckTab() {
    const data = window.useCalStore ? window.useCalStore(['conflict.checked']) : { conflictChecks: window.CONFLICT_CHECKS };
    const tag = s => s === 'block' ? tone('rgba(194,48,48,0.08)', '#C23030') : s === 'warn' ? tone(cal.amberBg, cal.amber) : tone('rgba(59,130,246,0.08)', '#3B82F6');
    return (
      <div style={cal.card}>
        <div style={cal.cardH}><span>Scheduling Conflict Checks</span></div>
        {data.conflictChecks.map(c => (
          <div key={c.id} style={{ padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}`, fontSize: '12px' }}>
            <div style={{ display: 'flex', gap: '10px', alignItems: 'center' }}>
              <span style={{ ...cal.tag, ...tag(c.severity) }}>{c.severity}</span>
              <span style={{ flex: 1, fontWeight: 600 }}>{c.attempt} — {c.attorney}</span>
              <span style={{ fontSize: '10px', fontFamily: T.font.mono }}>{c.proposed}</span>
            </div>
            <div style={{ fontSize: '10px', color: T.color.text.tertiary, marginTop: '4px' }}>{c.conflict} · <b>Suggest:</b> {c.suggestion || '—'}</div>
          </div>
        ))}
      </div>
    );
  }

  // ── 15. Workload Heatmap ────────────────────────────────────────────
  function CalWorkloadHeatmap() {
    const W = window.WORKLOAD_FORECAST || [];
    const attorneys = Array.from(new Set(W.map(w => w.attorney)));
    const weeks = Array.from(new Set(W.map(w => w.weekOf))).sort();
    const color = (f) => f >= 55 ? '#C23030' : f >= 45 ? cal.amber : T.color.status.active;
    return (
      <div style={cal.card}>
        <div style={cal.cardH}><span>Attorney Workload Forecast</span></div>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ display: 'grid', gridTemplateColumns: `160px repeat(${weeks.length}, 1fr)`, gap: '4px' }}>
            <span></span>
            {weeks.map(w => <div key={w} style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.tertiary, textAlign: 'center' }}>Wk {w.slice(5)}</div>)}
            {attorneys.map(a => (
              <React.Fragment key={a}>
                <div style={{ fontSize: '11px', fontWeight: 500, color: T.color.text.primary }}>{a}</div>
                {weeks.map(w => {
                  const rec = W.find(x => x.attorney === a && x.weekOf === w);
                  if (!rec) return <div key={w}></div>;
                  const c = color(rec.forecast);
                  return (
                    <div key={w} style={{ padding: '6px', borderRadius: '4px', background: `${c}15`, color: c, textAlign: 'center', fontSize: '11px', fontWeight: 600, fontFamily: T.font.mono }}>
                      {rec.forecast}h
                    </div>
                  );
                })}
              </React.Fragment>
            ))}
          </div>
        </div>
      </div>
    );
  }

  // ── 16. Hearing Prep Rooms ──────────────────────────────────────────
  function CalHearingPrepTab() {
    const data = window.useCalStore ? window.useCalStore(['prep.updated']) : { hearingPrep: window.HEARING_PREP };
    return (
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(340px, 1fr))', gap: '12px' }}>
        {data.hearingPrep.map(h => {
          const pct = Math.round((h.prepDone / h.prepItems) * 100);
          return (
            <div key={h.id} style={{ ...cal.card, margin: 0 }}>
              <div style={cal.cardH}><span>{h.hearing}</span><span style={{ ...cal.tag, ...tone(cal.amberBg, cal.amber) }}>{h.date}</span></div>
              <div style={{ padding: '10px 16px', fontSize: '12px' }}>
                <div style={{ fontWeight: 600, color: T.color.text.primary, marginBottom: '4px' }}>{h.matter}</div>
                <div style={{ fontSize: '10px', color: T.color.text.tertiary, marginBottom: '8px' }}>{h.judge} · {h.venue} · Lead {h.leadCounsel}</div>
                <div style={{ display: 'flex', gap: '8px', marginBottom: '6px' }}>
                  <span style={{ fontSize: '10px', color: T.color.text.secondary }}>Witnesses: <b>{h.witnessesCount}</b></span>
                  <span style={{ fontSize: '10px', color: T.color.text.secondary }}>Exhibits: <b>{h.exhibitsCount}</b></span>
                </div>
                <div style={{ height: '4px', borderRadius: '2px', background: T.color.border.light, marginBottom: '4px' }}>
                  <div style={{ width: `${pct}%`, height: '100%', borderRadius: '2px', background: pct === 100 ? T.color.status.active : cal.amber }} />
                </div>
                <div style={{ fontSize: '10px', color: T.color.text.tertiary }}>Prep: {h.prepDone}/{h.prepItems} · {h.logistics}</div>
              </div>
            </div>
          );
        })}
      </div>
    );
  }

  // ── 17. Witness Availability Matrix ─────────────────────────────────
  function CalWitnessMatrix() {
    const data = window.useCalStore ? window.useCalStore(['witness.scheduled']) : { witnessAvail: window.WITNESS_AVAILABILITY };
    return (
      <div style={cal.card}>
        <div style={cal.cardH}><span>Witness Availability</span></div>
        {data.witnessAvail.map(w => (
          <div key={w.id} style={{ padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', gap: '10px', alignItems: 'center', fontSize: '12px' }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 600, color: T.color.text.primary }}>{w.name}</div>
              <div style={{ fontSize: '10px', color: T.color.text.tertiary }}>{w.matter} · {w.role}</div>
            </div>
            <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.secondary }}>{w.availableFrom} → {w.availableTo}</span>
            {w.blackout.length > 0 && <span style={{ ...cal.tag, ...tone('rgba(194,48,48,0.08)', '#C23030') }}>Blackout: {w.blackout.length}d</span>}
            <span style={{ ...cal.tag, ...(w.scheduled ? tone('rgba(34,197,94,0.08)', T.color.status.active) : tone(T.color.bg.secondary, T.color.text.tertiary)) }}>{w.scheduled ? `Set ${w.scheduled}` : 'Unscheduled'}</span>
          </div>
        ))}
      </div>
    );
  }

  // ── 18. Expert Disclosure Orchestrator ──────────────────────────────
  function CalExpertDisclosureTab() {
    const E = window.EXPERT_DISCLOSURES || [];
    return (
      <div style={cal.card}>
        <div style={cal.cardH}><span>Expert Disclosure Orchestrator — FRCP 26(a)(2)(D)</span></div>
        {E.map(e => (
          <div key={e.id} style={{ padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}`, fontSize: '12px' }}>
            <div style={{ display: 'flex', gap: '10px', alignItems: 'center', marginBottom: '4px' }}>
              <span style={{ fontWeight: 600, color: T.color.text.primary, flex: 1 }}>{e.matter} — {e.expert}</span>
              <span style={{ ...cal.tag, ...tone(cal.amberBg, cal.amber) }}>Trial {e.trialDate}</span>
            </div>
            <div style={{ display: 'flex', gap: '16px', fontSize: '10px', color: T.color.text.tertiary }}>
              <span>Initial: <b>{e.initialDue}</b></span>
              <span>Rebuttal: <b>{e.rebuttalDue || '—'}</b></span>
              <span>Sur-rebuttal: <b>{e.surrebuttalDue || '—'}</b></span>
              <span style={{ marginLeft: 'auto', ...cal.tag, ...tone('rgba(59,130,246,0.08)', '#3B82F6') }}>{e.status}</span>
            </div>
          </div>
        ))}
      </div>
    );
  }

  // ── 19. Event Bundle Templates ──────────────────────────────────────
  function CalTemplatesTab() {
    const TPL = window.EVENT_TEMPLATES || [];
    return (
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: '12px' }}>
        {TPL.map(t => (
          <div key={t.id} style={{ ...cal.card, margin: 0 }}>
            <div style={cal.cardH}><span>{t.name}</span><span style={{ fontSize: '10px', color: T.color.text.tertiary, fontFamily: T.font.mono }}>used {t.uses}×</span></div>
            <div style={{ padding: '10px 16px', fontSize: '12px' }}>
              <div style={{ fontSize: '10px', color: T.color.text.tertiary }}>Trigger: <b>{t.trigger}</b></div>
              <div style={{ fontSize: '10px', color: T.color.text.tertiary }}>Jurisdictions: {t.jurisdictions.join(', ')}</div>
              <div style={{ fontSize: '22px', fontWeight: 700, color: cal.amber, fontFamily: T.font.mono, marginTop: '4px' }}>{t.deadlines}</div>
              <div style={{ fontSize: '10px', color: T.color.text.tertiary }}>deadlines created</div>
            </div>
          </div>
        ))}
      </div>
    );
  }

  // ── 20. Defensibility Audit Log ─────────────────────────────────────
  function CalDefensibilityAudit() {
    const data = window.useCalStore ? window.useCalStore(['audit.logged']) : { defensibilityAudit: window.DEFENSIBILITY_AUDIT };
    return (
      <div style={cal.card}>
        <div style={cal.cardH}><span>Deadline Defensibility Audit</span><span style={{ fontSize: '10px', color: T.color.text.tertiary }}>{data.defensibilityAudit.length} events</span></div>
        {data.defensibilityAudit.slice().reverse().map(a => (
          <div key={a.id} style={{ padding: '8px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', gap: '10px', alignItems: 'center', fontSize: '12px' }}>
            <span style={{ ...cal.tag, ...tone(cal.amberBg, cal.amber), fontFamily: T.font.mono, minWidth: '72px', justifyContent: 'center' }}>{a.event}</span>
            <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.secondary }}>{a.deadlineId || '—'}</span>
            <span style={{ flex: 1, color: T.color.text.primary, fontSize: '11px' }}>{a.reason || '(no reason)'}</span>
            <span style={{ fontSize: '10px', color: T.color.text.tertiary }}>{a.actor}</span>
            <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.tertiary }}>{(a.at || '').slice(0, 10)}</span>
            {a.evidence && <span style={{ ...cal.tag, ...tone(T.color.bg.secondary, T.color.text.tertiary), fontFamily: T.font.mono }}>{a.evidence}</span>}
          </div>
        ))}
      </div>
    );
  }

  // ── HUBS ─────────────────────────────────────────────────────────────
  function CalRulesHub() {
    const [sub, setSub] = useState('packs');
    const tabs = [
      { id: 'packs',    label: 'Rule Packs',       count: (window.JURISDICTION_RULE_PACKS || []).length },
      { id: 'holidays', label: 'Holidays',         count: (window.COURT_HOLIDAYS || []).length },
      { id: 'judges',   label: 'Judge Orders',     count: (window.JUDGE_STANDING_ORDERS || []).length },
      { id: 'templates',label: 'Event Templates',  count: (window.EVENT_TEMPLATES || []).length },
    ];
    return (
      <div>
        <CalSubTabs tabs={tabs} active={sub} onChange={setSub} />
        {sub === 'packs'     && <CalRulePackLibrary />}
        {sub === 'holidays'  && <CalHolidaysTab />}
        {sub === 'judges'    && <CalStandingOrdersTab />}
        {sub === 'templates' && <CalTemplatesTab />}
      </div>
    );
  }

  function CalScheduleHub() {
    const [sub, setSub] = useState('trials');
    const tabs = [
      { id: 'trials',     label: 'Trial Countdown' },
      { id: 'hearings',   label: 'Hearing Prep',      count: (window.HEARING_PREP || []).length },
      { id: 'witnesses',  label: 'Witnesses',         count: (window.WITNESS_AVAILABILITY || []).length },
      { id: 'conflicts',  label: 'Conflict Checks',   count: (window.CONFLICT_CHECKS || []).length },
      { id: 'experts',    label: 'Expert Disclosures',count: (window.EXPERT_DISCLOSURES || []).length },
    ];
    return (
      <div>
        <CalSubTabs tabs={tabs} active={sub} onChange={setSub} />
        {sub === 'trials'    && <CalTrialCountdown />}
        {sub === 'hearings'  && <CalHearingPrepTab />}
        {sub === 'witnesses' && <CalWitnessMatrix />}
        {sub === 'conflicts' && <CalConflictCheckTab />}
        {sub === 'experts'   && <CalExpertDisclosureTab />}
      </div>
    );
  }

  function CalDocketHub({ onCascade }) {
    const [sub, setSub] = useState('motions');
    const tabs = [
      { id: 'motions',      label: 'Motions',       count: (window.MOTIONS || []).length },
      { id: 'continuances', label: 'Continuances',  count: (window.CONTINUANCES || []).length },
      { id: 'service',      label: 'Service',       count: (window.SERVICE_OF_PROCESS || []).length },
      { id: 'pacer',        label: 'PACER Sync',    count: (window.PACER_ENTRIES || []).length },
      { id: 'cascade',      label: 'Cascade Runs',  count: (window.CASCADE_RUNS || []).length },
    ];
    return (
      <div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}>
          <CalSubTabs tabs={tabs} active={sub} onChange={setSub} />
          {sub === 'cascade' && <button onClick={onCascade} style={{ ...cal.filterBtn, ...cal.filterBtnActive, fontSize: '10px' }}>+ Run cascade</button>}
        </div>
        {sub === 'motions'      && <CalMotionsTab />}
        {sub === 'continuances' && <CalContinuancesTab />}
        {sub === 'service'      && <CalServiceTab />}
        {sub === 'pacer'        && <CalPacerTab />}
        {sub === 'cascade'      && <CalCascadeRunsTab />}
      </div>
    );
  }

  function CalCascadeRunsTab() {
    const data = window.useCalStore ? window.useCalStore(['cascade.ran']) : { cascadeRuns: window.CASCADE_RUNS };
    return (
      <div style={cal.card}>
        <div style={cal.cardH}><span>Cascade Runs — Rule-Based Deadline Generation</span></div>
        {data.cascadeRuns.map(r => (
          <div key={r.id} style={{ padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}`, fontSize: '12px' }}>
            <div style={{ display: 'flex', gap: '10px', alignItems: 'center' }}>
              <span style={{ ...cal.tag, ...tone(cal.amberBg, cal.amber), fontFamily: T.font.mono }}>{r.id}</span>
              <span style={{ flex: 1, fontWeight: 600 }}>{r.matter} — {r.trigger}</span>
              <span style={{ fontSize: '10px', fontFamily: T.font.mono, color: T.color.text.tertiary }}>{r.triggerDate}</span>
              <span style={{ ...cal.tag, ...tone('rgba(34,197,94,0.08)', T.color.status.active) }}>{r.generated} deadlines</span>
            </div>
            <div style={{ fontSize: '10px', color: T.color.text.tertiary, marginTop: '2px' }}>{r.jurisdiction} · {r.ranBy} · {(r.ranAt || '').slice(0, 16).replace('T', ' ')}</div>
          </div>
        ))}
      </div>
    );
  }

  function CalComplianceHub() {
    const [sub, setSub] = useState('sol');
    const tabs = [
      { id: 'sol',           label: 'SOL',              count: (window.SOL_TRACKER || []).length },
      { id: 'escalation',    label: 'Escalation Rules', count: (window.ESCALATION_RULES || []).length },
      { id: 'reports',       label: 'Client Reports',   count: (window.CLIENT_REPORTS || []).length },
      { id: 'audit',         label: 'Defensibility' },
      { id: 'path',          label: 'Critical Path' },
    ];
    return (
      <div>
        <CalSubTabs tabs={tabs} active={sub} onChange={setSub} />
        {sub === 'sol'        && <CalSOLDashboard />}
        {sub === 'escalation' && <CalEscalationTab />}
        {sub === 'reports'    && <CalClientReportsTab />}
        {sub === 'audit'      && <CalDefensibilityAudit />}
        {sub === 'path'       && <CalCriticalPath />}
      </div>
    );
  }

  // ── Expose ───────────────────────────────────────────────────────────
  Object.assign(window, {
    CalModal, CalSubTabs,
    CalCascadeModal, CalRulePackLibrary, CalHolidaysTab, CalStandingOrdersTab,
    CalSOLDashboard, CalCriticalPath, CalEscalationTab, CalClientReportsTab,
    CalPacerTab, CalServiceTab, CalMotionsTab, CalContinuancesTab,
    CalTrialCountdown, CalConflictCheckTab, CalWorkloadHeatmap,
    CalHearingPrepTab, CalWitnessMatrix, CalExpertDisclosureTab,
    CalTemplatesTab, CalDefensibilityAudit, CalCascadeRunsTab,
    CalRulesHub, CalScheduleHub, CalDocketHub, CalComplianceHub,
  });
})();
