// JURISDICTIONS PLATFORM — secondary hubs, panels and modals
(function(){
const { useState, useMemo } = React;
const T = window.ArbiterTokens;

// ── ADMISSIONS HUB ─────────────────────────────────────────────────────────
function JxAdmissionsHub({ data, onOpenAdmission, onOpenPhv, onLogCle, onRenew, onFilePhv }) {
  const jx = window.__jx;
  const [tab, setTab] = useState('admissions');
  const [q, setQ] = useState('');

  const admissions = useMemo(() => {
    return data.admissions.filter(a => !q || (a.attorneyName + ' ' + a.barNumber).toLowerCase().includes(q.toLowerCase()));
  }, [data.admissions, q]);

  const phv = useMemo(() => {
    return data.proHacVice.filter(a => !q || (a.attorneyName + ' ' + a.matterName).toLowerCase().includes(q.toLowerCase()));
  }, [data.proHacVice, q]);

  return (
    <div>
      <div style={{ ...jx.card, marginBottom:'12px' }}>
        <div style={{ padding:'10px 16px', display:'flex', gap:'10px', alignItems:'center' }}>
          <div style={{ display:'flex', gap:'0', borderRadius:'6px', border:`1px solid ${T.color.border.light}`, overflow:'hidden' }}>
            <button onClick={() => setTab('admissions')} style={{
              padding:'6px 12px', border:'none', background: tab === 'admissions' ? jx.forest : T.color.bg.card,
              color: tab === 'admissions' ? '#fff' : T.color.text.secondary, fontSize:'11px', fontWeight:600, cursor:'pointer', fontFamily: T.font.family
            }}>Bar Admissions ({data.admissions.length})</button>
            <button onClick={() => setTab('phv')} style={{
              padding:'6px 12px', border:'none', background: tab === 'phv' ? jx.forest : T.color.bg.card,
              color: tab === 'phv' ? '#fff' : T.color.text.secondary, fontSize:'11px', fontWeight:600, cursor:'pointer', fontFamily: T.font.family
            }}>Pro Hac Vice ({data.proHacVice.length})</button>
          </div>
          <input type="text" placeholder="Search attorney, bar #, matter…" value={q} onChange={e => setQ(e.target.value)}
            style={{ flex:1, padding:'6px 10px', border:`1px solid ${T.color.border.light}`, borderRadius:'6px', fontSize:'12px', fontFamily: T.font.family }} />
          {tab === 'phv' && <button style={jx.btnPrimary} onClick={onFilePhv}>+ File Pro Hac Vice</button>}
        </div>
      </div>

      {tab === 'admissions' && (
        <div style={jx.card}>
          <table style={{ width:'100%', borderCollapse:'collapse' }}>
            <thead><tr>
              <th style={jx.th}>Attorney</th><th style={jx.th}>Court</th><th style={jx.th}>Bar #</th>
              <th style={jx.th}>Status</th><th style={jx.th}>CLE</th><th style={jx.th}>Renewal</th><th style={jx.th}></th>
            </tr></thead>
            <tbody>
              {admissions.map(a => {
                const court = data.courts.find(c => c.id === a.courtId);
                const sc = jx.admissionStatusColor(a.status);
                const clePct = a.cleHoursRequired ? Math.round((a.cleHoursCompleted / a.cleHoursRequired) * 100) : 100;
                const dueDays = jx.daysUntil(a.renewalDate);
                return (
                  <tr key={a.id} style={{ cursor:'pointer' }}>
                    <td style={jx.td} onClick={() => onOpenAdmission && onOpenAdmission(a)}>
                      <div style={{ fontWeight:600 }}>{a.attorneyName}</div>
                      <div style={{ fontSize:'10px', color: T.color.text.tertiary }}>{a.attorneyId}</div>
                    </td>
                    <td style={jx.td}>{court ? court.short : a.courtId}</td>
                    <td style={jx.td}><span style={{ fontFamily: T.font.mono, fontSize:'11px' }}>{a.barNumber}</span></td>
                    <td style={jx.td}>
                      <span style={{ ...jx.tag, background: sc.bg, color: sc.color }}>
                        {a.status}{a.goodStanding === false && ' !'}
                      </span>
                    </td>
                    <td style={jx.td}>
                      {a.cleDue ? (
                        <div>
                          <div style={{ fontSize:'11px', fontFamily: T.font.mono }}>{a.cleHoursCompleted}/{a.cleHoursRequired}</div>
                          <div style={{ width:'70px', height:'4px', background: T.color.bg.secondary, borderRadius:'2px', marginTop:'3px' }}>
                            <div style={{ width: clePct + '%', height:'100%', background: clePct >= 100 ? jx.emerald : clePct >= 75 ? jx.forest : clePct >= 50 ? jx.amber : jx.crimson, borderRadius:'2px' }} />
                          </div>
                        </div>
                      ) : <span style={{ color: T.color.text.tertiary }}>—</span>}
                    </td>
                    <td style={jx.td}>
                      {a.renewalDate ? (
                        <span style={{ ...jx.tag, background: dueDays < 30 ? jx.crimsonBg : dueDays < 90 ? jx.amberBg : jx.emeraldBg, color: dueDays < 30 ? jx.crimson : dueDays < 90 ? jx.amber : jx.emerald }}>
                          {jx.fmtDate(a.renewalDate)}
                        </span>
                      ) : <span style={{ color: T.color.text.tertiary }}>—</span>}
                    </td>
                    <td style={jx.td}>
                      <button style={jx.btnGhost} onClick={() => onLogCle && onLogCle(a)}>+ CLE</button>
                      <button style={jx.btnGhost} onClick={() => onRenew && onRenew(a)}>Renew</button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}

      {tab === 'phv' && (
        <div style={jx.card}>
          <table style={{ width:'100%', borderCollapse:'collapse' }}>
            <thead><tr>
              <th style={jx.th}>Attorney</th><th style={jx.th}>Court</th><th style={jx.th}>Matter</th>
              <th style={jx.th}>Status</th><th style={jx.th}>Filed</th><th style={jx.th}>Local Counsel</th>
              <th style={jx.th}>Fee</th><th style={jx.th}>Expires</th>
            </tr></thead>
            <tbody>
              {phv.map(p => {
                const court = data.courts.find(c => c.id === p.courtId);
                const sc = jx.phvStatusColor(p.status);
                return (
                  <tr key={p.id} style={{ cursor:'pointer' }} onClick={() => onOpenPhv && onOpenPhv(p)}>
                    <td style={jx.td}>{p.attorneyName}</td>
                    <td style={jx.td}>{court ? court.short : p.courtId}</td>
                    <td style={jx.td}>
                      <div style={{ fontWeight:500 }}>{p.matterName}</div>
                      <div style={{ fontSize:'10px', color: T.color.text.tertiary }}>{p.matterId}</div>
                    </td>
                    <td style={jx.td}><span style={{ ...jx.tag, background: sc.bg, color: sc.color }}>{p.status}</span></td>
                    <td style={jx.td}>{jx.fmtDate(p.filedDate)}</td>
                    <td style={jx.td}>{p.localCounsel || '—'}</td>
                    <td style={jx.td}><span style={{ fontFamily: T.font.mono }}>${jx.num(p.fee)}</span></td>
                    <td style={jx.td}>{jx.fmtDate(p.expiresDate)}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

// ── FORMS HUB ──────────────────────────────────────────────────────────────
function JxFormCard({ form, court, jx, isFav, isSelected, onOpen, onToggleFav, onToggleSelect, compact }) {
  const completions = (window.JurisdictionsStore.state.formCompletions || []).filter(fc => fc.formId === form.id);
  const completeCount = completions.filter(fc => fc.status === 'Complete').length;
  return (
    <div style={{
      padding:'12px',
      border: isSelected ? `2px solid ${jx.forest}` : `1px solid ${T.color.border.light}`,
      borderRadius:'8px',
      background: form.deprecated ? T.color.bg.secondary : T.color.bg.card,
      opacity: form.deprecated ? 0.8 : 1,
      position:'relative',
    }}>
      {form.deprecated && (
        <div style={{ ...jx.tag, background: jx.crimsonBg, color: jx.crimson, marginBottom:'6px', display:'inline-block' }}>
          Deprecated{form.supersededBy ? ' → use ' + form.supersededBy : ''}
        </div>
      )}
      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:'6px', gap:'6px' }}>
        <span style={{ ...jx.tag, background: jx.forestBg, color: jx.forestDeep, fontFamily: T.font.mono }}>{form.code}</span>
        <div style={{ display:'flex', gap:'4px', alignItems:'center' }}>
          <button onClick={onToggleFav} title={isFav ? 'Unpin' : 'Pin to favorites'} style={{
            border:'none', background:'none', cursor:'pointer', fontSize:'14px', color: isFav ? jx.amber : T.color.text.tertiary, padding:'0 2px',
          }}>{isFav ? '*' : '*'}</button>
          <span style={{ fontSize:'10px', color: T.color.text.tertiary }}>v{form.version}</span>
        </div>
      </div>
      <div style={{ fontSize:'12px', fontWeight:600, color: T.color.text.primary, marginBottom:'2px' }}>{form.name}</div>
      <div style={{ fontSize:'10px', color: T.color.text.tertiary, marginBottom:'6px' }}>
        {court ? court.short : (form.courtId || '—')} · {form.category}
        {form.pageCount ? ' · ' + form.pageCount + ' pp' : ''}
        {form.estMinutes ? ' · ~' + form.estMinutes + ' min' : ''}
      </div>
      {!compact && (
        <div style={{ fontSize:'10px', color: T.color.text.secondary, marginBottom:'6px' }}>{form.requiredBy}</div>
      )}
      <div style={{ marginTop:'6px', display:'flex', gap:'4px', alignItems:'center', flexWrap:'wrap' }}>
        {form.efileCompatible ? (
          <span style={{ ...jx.tag, background: jx.emeraldBg, color: jx.emerald }}>e-File</span>
        ) : (
          <span style={{ ...jx.tag, background: jx.amberBg, color: jx.amber }}>Paper only</span>
        )}
        {form.fillable && <span style={{ ...jx.tag, background: jx.indigoBg, color: jx.indigo }}>Fillable</span>}
        <span style={{ ...jx.tag, background: T.color.bg.secondary, color: T.color.text.tertiary }}>{form.fileType}</span>
        {completeCount > 0 && <span style={{ ...jx.tag, background: jx.forestBg, color: jx.forestDeep }}>{completeCount} filed</span>}
      </div>
      <div style={{ marginTop:'8px', display:'flex', gap:'6px' }}>
        <button style={jx.btnGhost} onClick={onOpen}>Detail</button>
        <button style={{ ...jx.btnGhost, marginLeft:'auto', background: isSelected ? jx.forestBg : 'transparent', color: isSelected ? jx.forestDeep : T.color.text.secondary }}
          onClick={onToggleSelect}>
          {isSelected ? 'ok Selected' : '+ Assemble'}
        </button>
      </div>
    </div>
  );
}

function JxFormsHub({ data }) {
  const jx = window.__jx;
  const [subTab, setSubTab] = useState('all'); // all | packs | favorites | completions
  const [q, setQ] = useState('');
  const [catFilter, setCatFilter] = useState('all');
  const [courtFilter, setCourtFilter] = useState('all');
  const [showDeprecated, setShowDeprecated] = useState(false);
  const [selected, setSelected] = useState([]); // formIds
  const [detailForm, setDetailForm] = useState(null);
  const [assembleOpen, setAssembleOpen] = useState(false);
  const [prefillPack, setPrefillPack] = useState(null);

  const favIds = data.favoriteFormIds || [];
  const packs = data.formPacks || [];
  const completions = data.formCompletions || [];

  const cats = ['all', ...Array.from(new Set(data.forms.map(f => f.category)))];

  const filtered = useMemo(() => {
    return data.forms.filter(f => {
      if (!showDeprecated && f.deprecated) return false;
      if (catFilter !== 'all' && f.category !== catFilter) return false;
      if (courtFilter !== 'all' && f.courtId !== courtFilter) return false;
      if (q && !(f.name + ' ' + f.code + ' ' + (f.tags||[]).join(' ')).toLowerCase().includes(q.toLowerCase())) return false;
      return true;
    });
  }, [data.forms, q, catFilter, courtFilter, showDeprecated]);

  const favorites = data.forms.filter(f => favIds.includes(f.id));

  const toggleSelect = (id) => {
    setSelected(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
  };
  const toggleFav = (id) => {
    window.JurisdictionsStore.toggleFavorite(id);
  };

  // Group completions by matter
  const completionsByMatter = useMemo(() => {
    const map = {};
    completions.forEach(fc => {
      if (!map[fc.matterId]) map[fc.matterId] = { matterId: fc.matterId, matterName: fc.matterName, items: [] };
      map[fc.matterId].items.push(fc);
    });
    return Object.values(map);
  }, [completions]);

  const subTabs = [
    { id:'all',         label:'All Forms',  badge: data.forms.length },
    { id:'packs',       label:'Packs',      badge: packs.length },
    { id:'favorites',   label:'Favorites',  badge: favorites.length },
    { id:'completions', label:'Completions', badge: completionsByMatter.length },
  ];

  return (
    <div>
      {/* Sub-tabs */}
      <div style={{ display:'flex', gap:'2px', marginBottom:'12px', borderBottom:`1px solid ${T.color.border.light}` }}>
        {subTabs.map(t => (
          <button key={t.id} onClick={() => setSubTab(t.id)} style={{
            padding:'8px 14px', border:'none', background:'none', cursor:'pointer',
            fontSize:'12px', fontWeight:600,
            color: subTab === t.id ? jx.forestDeep : T.color.text.secondary,
            borderBottom: subTab === t.id ? `2px solid ${jx.forestDeep}` : '2px solid transparent',
            marginBottom:'-1px',
          }}>
            {t.label}
            {t.badge != null && <span style={{
              marginLeft:'6px', padding:'1px 6px', borderRadius:'8px',
              background: subTab === t.id ? jx.forestBg : T.color.bg.secondary,
              color: subTab === t.id ? jx.forestDeep : T.color.text.tertiary,
              fontSize:'9px', fontWeight:800, fontFamily: T.font.mono,
            }}>{t.badge}</span>}
          </button>
        ))}
        <div style={{ flex:1 }} />
        {selected.length > 0 && (
          <button style={{ ...jx.btnPrimary, margin:'4px 0' }} onClick={() => setAssembleOpen(true)}>
            Assemble package ({selected.length})
          </button>
        )}
      </div>

      {/* ALL FORMS */}
      {subTab === 'all' && (
        <div>
          <div style={{ ...jx.card, marginBottom:'12px' }}>
            <div style={{ padding:'10px 16px', display:'flex', gap:'10px', alignItems:'center', flexWrap:'wrap' }}>
              <input type="text" placeholder="Search forms, codes, tags…" value={q} onChange={e => setQ(e.target.value)}
                style={{ flex:1, minWidth:'200px', padding:'6px 10px', border:`1px solid ${T.color.border.light}`, borderRadius:'6px', fontSize:'12px', fontFamily: T.font.family }} />
              <select value={courtFilter} onChange={e => setCourtFilter(e.target.value)}
                style={{ padding:'6px 10px', border:`1px solid ${T.color.border.light}`, borderRadius:'6px', fontSize:'12px', background: T.color.bg.card }}>
                <option value="all">All courts</option>
                {data.courts.map(c => <option key={c.id} value={c.id}>{c.short}</option>)}
              </select>
              <div style={{ display:'flex', gap:'4px', flexWrap:'wrap' }}>
                {cats.map(c => (
                  <button key={c} onClick={() => setCatFilter(c)} style={{ ...jx.filterBtn, ...(catFilter === c ? jx.filterBtnActive : {}) }}>
                    {c === 'all' ? 'All' : c}
                  </button>
                ))}
              </div>
              <label style={{ fontSize:'11px', color: T.color.text.secondary, display:'flex', alignItems:'center', gap:'4px' }}>
                <input type="checkbox" checked={showDeprecated} onChange={e => setShowDeprecated(e.target.checked)} />
                Show deprecated
              </label>
            </div>
          </div>

          <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(320px, 1fr))', gap:'10px' }}>
            {filtered.map(f => {
              const court = data.courts.find(c => c.id === f.courtId);
              return (
                <JxFormCard key={f.id} form={f} court={court} jx={jx}
                  isFav={favIds.includes(f.id)}
                  isSelected={selected.includes(f.id)}
                  onOpen={() => setDetailForm(f)}
                  onToggleFav={() => toggleFav(f.id)}
                  onToggleSelect={() => toggleSelect(f.id)}
                />
              );
            })}
            {filtered.length === 0 && (
              <div style={{ ...jx.card, padding:'24px', textAlign:'center', color: T.color.text.tertiary, fontSize:'12px', gridColumn:'1 / -1' }}>
                No forms match current filters.
              </div>
            )}
          </div>
        </div>
      )}

      {/* PACKS */}
      {subTab === 'packs' && (
        <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(340px, 1fr))', gap:'10px' }}>
          {packs.map(p => {
            const court = data.courts.find(c => c.id === p.courtId);
            const packForms = p.formIds.map(id => data.forms.find(f => f.id === id)).filter(Boolean);
            const efileOk = packForms.every(f => f.efileCompatible);
            return (
              <div key={p.id} style={{ padding:'14px', border:`1px solid ${T.color.border.light}`, borderRadius:'8px', background: T.color.bg.card }}>
                <div style={{ display:'flex', alignItems:'center', gap:'8px', marginBottom:'6px' }}>
                  <span style={{ ...jx.tag, background: jx.indigoBg, color: jx.indigo }}>{p.category}</span>
                  {court && <span style={{ ...jx.tag, background: jx.forestBg, color: jx.forestDeep }}>{court.short}</span>}
                  {!court && <span style={{ ...jx.tag, background: T.color.bg.secondary, color: T.color.text.tertiary }}>Multi-court</span>}
                  {efileOk
                    ? <span style={{ ...jx.tag, background: jx.emeraldBg, color: jx.emerald }}>e-File ready</span>
                    : <span style={{ ...jx.tag, background: jx.amberBg, color: jx.amber }}>Mixed filing</span>}
                </div>
                <div style={{ fontSize:'13px', fontWeight:700, color: T.color.text.primary, marginBottom:'2px' }}>{p.name}</div>
                <div style={{ fontSize:'11px', color: T.color.text.secondary, marginBottom:'8px' }}>{p.description}</div>
                <div style={{ fontSize:'10px', color: T.color.text.tertiary, marginBottom:'8px' }}>
                  {packForms.length} forms · ~{p.estMinutes} min total
                </div>
                <ul style={{ margin:'0 0 10px 0', padding:'0 0 0 16px', fontSize:'11px', color: T.color.text.secondary }}>
                  {packForms.map(f => (
                    <li key={f.id}>
                      <span style={{ fontFamily: T.font.mono, color: jx.forestDeep, fontWeight:700 }}>{f.code}</span>
                      {' '}— {f.name}
                    </li>
                  ))}
                </ul>
                <div style={{ display:'flex', gap:'6px' }}>
                  <button style={jx.btnPrimary} onClick={() => { setSelected(p.formIds); setPrefillPack(p); setAssembleOpen(true); }}>
                    Assemble pack
                  </button>
                  <button style={jx.btnSecondary} onClick={() => { setSubTab('all'); setSelected(p.formIds); }}>
                    Open in selection
                  </button>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* FAVORITES */}
      {subTab === 'favorites' && (
        <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(320px, 1fr))', gap:'10px' }}>
          {favorites.length === 0 && (
            <div style={{ ...jx.card, padding:'24px', textAlign:'center', color: T.color.text.tertiary, fontSize:'12px', gridColumn:'1 / -1' }}>
              No favorites yet. Pin forms from the All Forms tab with the * icon.
            </div>
          )}
          {favorites.map(f => {
            const court = data.courts.find(c => c.id === f.courtId);
            return (
              <JxFormCard key={f.id} form={f} court={court} jx={jx}
                isFav={true}
                isSelected={selected.includes(f.id)}
                onOpen={() => setDetailForm(f)}
                onToggleFav={() => toggleFav(f.id)}
                onToggleSelect={() => toggleSelect(f.id)}
              />
            );
          })}
        </div>
      )}

      {/* COMPLETIONS */}
      {subTab === 'completions' && (
        <div style={{ display:'grid', gap:'12px' }}>
          {completionsByMatter.length === 0 && (
            <div style={{ ...jx.card, padding:'24px', textAlign:'center', color: T.color.text.tertiary, fontSize:'12px' }}>
              No form completion activity yet.
            </div>
          )}
          {completionsByMatter.map(m => {
            const done = m.items.filter(i => i.status === 'Complete').length;
            const pct = Math.round(100 * done / m.items.length);
            return (
              <div key={m.matterId} style={{ padding:'14px', border:`1px solid ${T.color.border.light}`, borderRadius:'8px', background: T.color.bg.card }}>
                <div style={{ display:'flex', alignItems:'center', gap:'10px', marginBottom:'8px' }}>
                  <span style={{ ...jx.tag, background: jx.indigoBg, color: jx.indigo, fontFamily: T.font.mono }}>{m.matterId}</span>
                  <div style={{ fontSize:'13px', fontWeight:700, color: T.color.text.primary, flex:1 }}>{m.matterName}</div>
                  <div style={{ fontSize:'11px', color: T.color.text.tertiary, fontFamily: T.font.mono }}>{done}/{m.items.length} complete</div>
                </div>
                <div style={{ height:'6px', background: T.color.bg.secondary, borderRadius:'3px', overflow:'hidden', marginBottom:'10px' }}>
                  <div style={{ width: pct + '%', height:'100%', background: pct === 100 ? jx.emerald : jx.forest }} />
                </div>
                <table style={{ width:'100%', borderCollapse:'collapse' }}>
                  <thead>
                    <tr>
                      <th style={jx.th}>Form</th>
                      <th style={jx.th}>Status</th>
                      <th style={jx.th}>Completed</th>
                      <th style={jx.th}>By</th>
                      <th style={jx.th}></th>
                    </tr>
                  </thead>
                  <tbody>
                    {m.items.map(fc => {
                      const form = data.forms.find(f => f.id === fc.formId);
                      const statusColor = fc.status === 'Complete' ? { bg: jx.emeraldBg, c: jx.emerald }
                        : fc.status === 'In Progress' ? { bg: jx.amberBg, c: jx.amber }
                        : { bg: T.color.bg.secondary, c: T.color.text.tertiary };
                      return (
                        <tr key={fc.id}>
                          <td style={jx.td}>
                            <span style={{ fontFamily: T.font.mono, color: jx.forestDeep, fontWeight:700, marginRight:'6px' }}>{form ? form.code : fc.formId}</span>
                            {form ? form.name : ''}
                          </td>
                          <td style={jx.td}>
                            <span style={{ ...jx.tag, background: statusColor.bg, color: statusColor.c }}>{fc.status}</span>
                          </td>
                          <td style={jx.td}>{fc.completedAt || '—'}</td>
                          <td style={jx.td}>{fc.completedBy || '—'}</td>
                          <td style={jx.td}>
                            {fc.status !== 'Complete' && (
                              <button style={jx.btnGhost} onClick={() => window.JurisdictionsStore.markFormCompleted(m.matterId, m.matterName, fc.formId)}>
                                Mark complete
                              </button>
                            )}
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            );
          })}
        </div>
      )}

      {/* Modals */}
      {detailForm && (
        <JxFormDetailModal form={detailForm} data={data} onClose={() => setDetailForm(null)}
          isFav={favIds.includes(detailForm.id)}
          onToggleFav={() => toggleFav(detailForm.id)}
          onAddToAssemble={() => { toggleSelect(detailForm.id); setDetailForm(null); }}
        />
      )}
      <JxAssemblePackModal open={assembleOpen} onClose={() => { setAssembleOpen(false); setPrefillPack(null); }}
        data={data} formIds={selected} pack={prefillPack}
        onAssembled={() => { setAssembleOpen(false); setSelected([]); setPrefillPack(null); }}
      />
    </div>
  );
}

// ── FORM DETAIL MODAL ──────────────────────────────────────────────────────
function JxFormDetailModal({ form, data, onClose, isFav, onToggleFav, onAddToAssemble }) {
  const jx = window.__jx;
  const court = data.courts.find(c => c.id === form.courtId);
  const supersededBy = form.supersededBy ? data.forms.find(f => f.id === form.supersededBy) : null;
  return (
    <JxModal open={true} onClose={onClose} title={form.code + ' · ' + form.name} width="720px">
      <div style={{ display:'grid', gap:'12px' }}>
        {form.deprecated && (
          <div style={{ padding:'10px 12px', background: jx.crimsonBg, color: jx.crimson, borderRadius:'6px', fontSize:'11px', fontWeight:600 }}>
            This form is deprecated.{supersededBy ? ' Use ' + supersededBy.code + ' — ' + supersededBy.name + ' instead.' : ''}
          </div>
        )}
        <div style={{ display:'flex', gap:'6px', flexWrap:'wrap' }}>
          <span style={{ ...jx.tag, background: jx.forestBg, color: jx.forestDeep, fontFamily: T.font.mono }}>{form.code}</span>
          <span style={{ ...jx.tag, background: jx.indigoBg, color: jx.indigo }}>{form.category}</span>
          {court && <span style={{ ...jx.tag, background: T.color.bg.secondary, color: T.color.text.secondary }}>{court.short}</span>}
          <span style={{ ...jx.tag, background: T.color.bg.secondary, color: T.color.text.tertiary, fontFamily: T.font.mono }}>v{form.version}</span>
          {form.efileCompatible
            ? <span style={{ ...jx.tag, background: jx.emeraldBg, color: jx.emerald }}>e-File ready</span>
            : <span style={{ ...jx.tag, background: jx.amberBg, color: jx.amber }}>Paper only</span>}
          {form.pageCount && <span style={{ ...jx.tag, background: T.color.bg.secondary, color: T.color.text.tertiary }}>{form.pageCount} pp</span>}
          {form.estMinutes && <span style={{ ...jx.tag, background: T.color.bg.secondary, color: T.color.text.tertiary }}>~{form.estMinutes} min</span>}
        </div>

        {form.instructions && (
          <div>
            <div style={{ fontSize:'10px', fontWeight:700, color: T.color.text.tertiary, textTransform:'uppercase', letterSpacing:'0.05em', marginBottom:'4px' }}>Clerk Instructions</div>
            <div style={{ fontSize:'12px', color: T.color.text.primary, lineHeight:1.5 }}>{form.instructions}</div>
          </div>
        )}

        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'12px' }}>
          <div>
            <div style={{ fontSize:'10px', fontWeight:700, color: T.color.text.tertiary, textTransform:'uppercase', letterSpacing:'0.05em', marginBottom:'4px' }}>Signatures Required</div>
            {(form.signaturesRequired && form.signaturesRequired.length) ? (
              <ul style={{ margin:0, padding:'0 0 0 16px', fontSize:'11px', color: T.color.text.secondary }}>
                {form.signaturesRequired.map((s, i) => <li key={i}>{s}</li>)}
              </ul>
            ) : <div style={{ fontSize:'11px', color: T.color.text.tertiary }}>None specified</div>}
          </div>
          <div>
            <div style={{ fontSize:'10px', fontWeight:700, color: T.color.text.tertiary, textTransform:'uppercase', letterSpacing:'0.05em', marginBottom:'4px' }}>Required Attachments</div>
            {(form.attachments && form.attachments.length) ? (
              <ul style={{ margin:0, padding:'0 0 0 16px', fontSize:'11px', color: T.color.text.secondary }}>
                {form.attachments.map((a, i) => <li key={i}>{a}</li>)}
              </ul>
            ) : <div style={{ fontSize:'11px', color: T.color.text.tertiary }}>None</div>}
          </div>
        </div>

        {form.fields && form.fields.length > 0 && (
          <div>
            <div style={{ fontSize:'10px', fontWeight:700, color: T.color.text.tertiary, textTransform:'uppercase', letterSpacing:'0.05em', marginBottom:'4px' }}>Field Library · merge fields auto-fill from matter</div>
            <table style={{ width:'100%', borderCollapse:'collapse' }}>
              <thead>
                <tr>
                  <th style={jx.th}>Field</th>
                  <th style={jx.th}>Type</th>
                  <th style={jx.th}>Merge From</th>
                  <th style={jx.th}>Required</th>
                </tr>
              </thead>
              <tbody>
                {form.fields.map(fd => (
                  <tr key={fd.name}>
                    <td style={jx.td}>{fd.label} <span style={{ color: T.color.text.tertiary, fontFamily: T.font.mono, fontSize:'10px' }}>({fd.name})</span></td>
                    <td style={jx.td}>{fd.type}</td>
                    <td style={jx.td}>{fd.mergeFrom
                      ? <span style={{ ...jx.tag, background: jx.forestBg, color: jx.forestDeep, fontFamily: T.font.mono }}>{fd.mergeFrom}</span>
                      : <span style={{ color: T.color.text.tertiary }}>—</span>}</td>
                    <td style={jx.td}>{fd.required ? 'Yes' : 'No'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {form.versions && form.versions.length > 0 && (
          <div>
            <div style={{ fontSize:'10px', fontWeight:700, color: T.color.text.tertiary, textTransform:'uppercase', letterSpacing:'0.05em', marginBottom:'4px' }}>Version History</div>
            <table style={{ width:'100%', borderCollapse:'collapse' }}>
              <thead>
                <tr>
                  <th style={jx.th}>Version</th>
                  <th style={jx.th}>Date</th>
                  <th style={jx.th}>Note</th>
                  <th style={jx.th}></th>
                </tr>
              </thead>
              <tbody>
                {form.versions.map((v, i) => (
                  <tr key={i}>
                    <td style={{ ...jx.td, fontFamily: T.font.mono }}>v{v.version}</td>
                    <td style={jx.td}>{v.date}</td>
                    <td style={jx.td}>{v.note}</td>
                    <td style={jx.td}>{v.current && <span style={{ ...jx.tag, background: jx.emeraldBg, color: jx.emerald }}>Current</span>}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {form.tags && form.tags.length > 0 && (
          <div style={{ display:'flex', gap:'4px', flexWrap:'wrap' }}>
            {form.tags.map(t => <span key={t} style={{ ...jx.tag, background: T.color.bg.secondary, color: T.color.text.tertiary }}>#{t}</span>)}
          </div>
        )}

        <div style={{ display:'flex', gap:'8px', justifyContent:'flex-end', borderTop:`1px solid ${T.color.border.light}`, paddingTop:'10px' }}>
          <button style={jx.btnSecondary} onClick={onToggleFav}>{isFav ? '* Unpin' : '* Pin to favorites'}</button>
          <button style={jx.btnGhost} onClick={onClose}>Close</button>
          <button style={jx.btnPrimary} onClick={onAddToAssemble} disabled={form.deprecated}>
            + Add to assemble
          </button>
        </div>
      </div>
    </JxModal>
  );
}

// ── ASSEMBLE PACK MODAL ────────────────────────────────────────────────────
function JxAssemblePackModal({ open, onClose, data, formIds, pack, onAssembled }) {
  const jx = window.__jx;
  const [matterPick, setMatterPick] = useState('');
  const [assembled, setAssembled] = useState(null);

  // Derive matter list from completions + a couple of defaults
  const matters = useMemo(() => {
    const m = {};
    (data.formCompletions || []).forEach(fc => {
      if (!m[fc.matterId]) m[fc.matterId] = { id: fc.matterId, name: fc.matterName, caseNumber:'', plaintiff:'', defendant:'', leadAttorney:'M. Kirkland' };
    });
    // Enrich common mock fields
    const mk = (id, caseNumber, plaintiff, defendant) => {
      if (m[id]) { m[id].caseNumber = caseNumber; m[id].plaintiff = plaintiff; m[id].defendant = defendant; }
    };
    mk('M-2025-003', '25-cv-1442 (SDNY)', 'Priya Singh',   'Apex Capital Partners LLC');
    mk('M-2025-007', '25-cv-2988 (SDNY)', 'Beacon Fund LP', 'Oversight Corp.');
    mk('M-2024-028', 'BC-2024-071245',    'Westview Holdings','Marriott Actuarial');
    return Object.values(m);
  }, [data.formCompletions]);

  const selectedForms = (formIds || []).map(id => data.forms.find(f => f.id === id)).filter(Boolean);
  const matter = matters.find(m => m.id === matterPick);

  const handleAssemble = () => {
    const pkg = window.JurisdictionsStore.assembleFormPackage(formIds, matter || {});
    setAssembled(pkg);
    if (matter) {
      formIds.forEach(fid => window.JurisdictionsStore.setFormStatus(matter.id, matter.name, fid, 'In Progress'));
    }
  };
  const handleDone = () => {
    setAssembled(null);
    setMatterPick('');
    if (onAssembled) onAssembled();
  };

  if (!open) return null;

  const totalMinutes = selectedForms.reduce((s, f) => s + (f.estMinutes || 0), 0);
  const totalPages = selectedForms.reduce((s, f) => s + (f.pageCount || 0), 0);
  const sigs = Array.from(new Set(selectedForms.flatMap(f => f.signaturesRequired || [])));
  const atts = Array.from(new Set(selectedForms.flatMap(f => f.attachments || [])));
  const efileOk = selectedForms.every(f => f.efileCompatible);

  return (
    <JxModal open={open} onClose={onClose} title={pack ? 'Assemble — ' + pack.name : 'Assemble form package'} width="720px">
      {!assembled ? (
        <div style={{ display:'grid', gap:'12px' }}>
          <div>
            <div style={{ fontSize:'10px', fontWeight:700, color: T.color.text.tertiary, textTransform:'uppercase', letterSpacing:'0.05em', marginBottom:'4px' }}>
              {selectedForms.length} form{selectedForms.length === 1 ? '' : 's'} selected
            </div>
            <ul style={{ margin:0, padding:'0 0 0 16px', fontSize:'11px', color: T.color.text.secondary, maxHeight:'140px', overflow:'auto' }}>
              {selectedForms.map(f => (
                <li key={f.id}>
                  <span style={{ fontFamily: T.font.mono, color: jx.forestDeep, fontWeight:700 }}>{f.code}</span>
                  {' '}— {f.name}
                  {!f.efileCompatible && <span style={{ ...jx.tag, background: jx.amberBg, color: jx.amber, marginLeft:'6px' }}>paper</span>}
                </li>
              ))}
            </ul>
          </div>

          <div style={{ display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap:'8px' }}>
            <div style={{ padding:'8px', background: T.color.bg.secondary, borderRadius:'6px', textAlign:'center' }}>
              <div style={{ fontSize:'16px', fontWeight:800, color: T.color.text.primary, fontFamily: T.font.mono }}>{selectedForms.length}</div>
              <div style={{ fontSize:'9px', color: T.color.text.tertiary, textTransform:'uppercase' }}>Forms</div>
            </div>
            <div style={{ padding:'8px', background: T.color.bg.secondary, borderRadius:'6px', textAlign:'center' }}>
              <div style={{ fontSize:'16px', fontWeight:800, color: T.color.text.primary, fontFamily: T.font.mono }}>{totalPages}</div>
              <div style={{ fontSize:'9px', color: T.color.text.tertiary, textTransform:'uppercase' }}>Pages</div>
            </div>
            <div style={{ padding:'8px', background: T.color.bg.secondary, borderRadius:'6px', textAlign:'center' }}>
              <div style={{ fontSize:'16px', fontWeight:800, color: T.color.text.primary, fontFamily: T.font.mono }}>{totalMinutes}m</div>
              <div style={{ fontSize:'9px', color: T.color.text.tertiary, textTransform:'uppercase' }}>Est. Time</div>
            </div>
            <div style={{ padding:'8px', background: efileOk ? jx.emeraldBg : jx.amberBg, borderRadius:'6px', textAlign:'center' }}>
              <div style={{ fontSize:'12px', fontWeight:800, color: efileOk ? jx.emerald : jx.amber }}>{efileOk ? 'e-File' : 'Mixed'}</div>
              <div style={{ fontSize:'9px', color: efileOk ? jx.emerald : jx.amber, textTransform:'uppercase' }}>Filing</div>
            </div>
          </div>

          <label style={{ fontSize:'11px', fontWeight:600, color: T.color.text.secondary }}>Matter (for merge fields & completion tracking)
            <select value={matterPick} onChange={e => setMatterPick(e.target.value)}
              style={{ width:'100%', padding:'6px 10px', border:`1px solid ${T.color.border.light}`, borderRadius:'6px', fontSize:'12px', background: T.color.bg.card, marginTop:'4px' }}>
              <option value="">— Optional — leave blank for blank package —</option>
              {matters.map(m => <option key={m.id} value={m.id}>{m.id} — {m.name}</option>)}
            </select>
          </label>

          {sigs.length > 0 && (
            <div>
              <div style={{ fontSize:'10px', fontWeight:700, color: T.color.text.tertiary, textTransform:'uppercase', letterSpacing:'0.05em', marginBottom:'4px' }}>Signatures needed ({sigs.length})</div>
              <div style={{ display:'flex', gap:'4px', flexWrap:'wrap' }}>
                {sigs.map((s, i) => <span key={i} style={{ ...jx.tag, background: jx.indigoBg, color: jx.indigo }}>{s}</span>)}
              </div>
            </div>
          )}
          {atts.length > 0 && (
            <div>
              <div style={{ fontSize:'10px', fontWeight:700, color: T.color.text.tertiary, textTransform:'uppercase', letterSpacing:'0.05em', marginBottom:'4px' }}>Attachments required ({atts.length})</div>
              <ul style={{ margin:0, padding:'0 0 0 16px', fontSize:'11px', color: T.color.text.secondary }}>
                {atts.map((a, i) => <li key={i}>{a}</li>)}
              </ul>
            </div>
          )}

          <div style={{ display:'flex', gap:'8px', justifyContent:'flex-end' }}>
            <button style={jx.btnSecondary} onClick={onClose}>Cancel</button>
            <button style={jx.btnPrimary} onClick={handleAssemble} disabled={selectedForms.length === 0}>
              Assemble Package
            </button>
          </div>
        </div>
      ) : (
        <div style={{ display:'grid', gap:'12px' }}>
          <div style={{ padding:'12px', background: jx.emeraldBg, color: jx.emerald, borderRadius:'6px', fontSize:'12px', fontWeight:600 }}>
            ok Package assembled — {assembled.forms.length} forms, {assembled.totalPages} pages, ~{assembled.totalMinutes} min
          </div>
          <div>
            <div style={{ fontSize:'10px', fontWeight:700, color: T.color.text.tertiary, textTransform:'uppercase', letterSpacing:'0.05em', marginBottom:'6px' }}>Merge Field Preview</div>
            <table style={{ width:'100%', borderCollapse:'collapse' }}>
              <thead>
                <tr>
                  <th style={jx.th}>Form</th>
                  <th style={jx.th}>Field</th>
                  <th style={jx.th}>Merged Value</th>
                </tr>
              </thead>
              <tbody>
                {assembled.fieldPreview.flatMap(fp => fp.values.map((v, i) => (
                  <tr key={fp.formId + '-' + v.name}>
                    {i === 0 && <td style={{ ...jx.td, fontFamily: T.font.mono, fontWeight:700, color: jx.forestDeep }} rowSpan={fp.values.length}>{fp.code}</td>}
                    <td style={jx.td}>{v.label}{v.required && <span style={{ color: jx.crimson }}><Icons.Star size={11}/></span>}</td>
                    <td style={jx.td}>
                      {v.mergedValue
                        ? <span style={{ ...jx.tag, background: jx.forestBg, color: jx.forestDeep }}>{v.mergedValue}</span>
                        : <span style={{ color: T.color.text.tertiary, fontStyle:'italic' }}>manual entry</span>}
                    </td>
                  </tr>
                )))}
                {assembled.fieldPreview.every(fp => fp.values.length === 0) && (
                  <tr><td colSpan={3} style={{ ...jx.td, color: T.color.text.tertiary, textAlign:'center' }}>Selected forms have no merge fields defined.</td></tr>
                )}
              </tbody>
            </table>
          </div>
          <div style={{ display:'flex', gap:'8px', justifyContent:'flex-end' }}>
            <button style={jx.btnSecondary} onClick={handleDone}>Done</button>
            <button style={jx.btnPrimary} onClick={handleDone}>Download ZIP</button>
          </div>
        </div>
      )}
    </JxModal>
  );
}

// ── ANALYTICS HUB ──────────────────────────────────────────────────────────
function JxAnalyticsHub({ data }) {
  const jx = window.__jx;
  const [side, setSide] = useState('plaintiff');

  const ranked = useMemo(() => {
    return window.JurisdictionsStore.recommendVenue({ side });
  }, [side, data.venueAnalytics]);

  const topJudges = useMemo(() => window.JurisdictionsStore.rankJudgesBy('caseload').slice(0, 8), [data.judges]);

  return (
    <div>
      <div style={{ display:'grid', gridTemplateColumns:'2fr 1fr', gap:'16px' }}>
        <div style={jx.card}>
          <div style={jx.cardH}>
            <span>Venue Analysis</span>
            <div style={{ display:'flex', gap:'4px' }}>
              <button onClick={() => setSide('plaintiff')} style={{ ...jx.filterBtn, ...(side === 'plaintiff' ? jx.filterBtnActive : {}) }}>Plaintiff</button>
              <button onClick={() => setSide('defendant')} style={{ ...jx.filterBtn, ...(side === 'defendant' ? jx.filterBtnActive : {}) }}>Defendant</button>
            </div>
          </div>
          <table style={{ width:'100%', borderCollapse:'collapse' }}>
            <thead><tr>
              <th style={jx.th}>Court</th><th style={jx.th}>Avg Dispo</th><th style={jx.th}>MSJ Grant</th>
              <th style={jx.th}>Settlement</th><th style={jx.th}>Trial</th><th style={jx.th}>Plaintiff Win</th><th style={jx.th}>Avg Award</th>
            </tr></thead>
            <tbody>
              {ranked.map((v, i) => (
                <tr key={v.courtId}>
                  <td style={jx.td}>
                    <div style={{ display:'flex', alignItems:'center', gap:'8px' }}>
                      <span style={{ width:'22px', height:'22px', borderRadius:'50%', background: i < 3 ? jx.forestBg : T.color.bg.secondary, color: i < 3 ? jx.forestDeep : T.color.text.tertiary, display:'flex', alignItems:'center', justifyContent:'center', fontSize:'10px', fontWeight:700, fontFamily: T.font.mono }}>{i + 1}</span>
                      <span style={{ fontWeight:600 }}>{(v.court || {}).short || v.courtId}</span>
                    </div>
                  </td>
                  <td style={jx.td}><span style={{ fontFamily: T.font.mono }}>{v.avgDispositionDays}d</span></td>
                  <td style={jx.td}><span style={{ fontFamily: T.font.mono }}>{(v.msjGrantRate * 100).toFixed(0)}%</span></td>
                  <td style={jx.td}><span style={{ fontFamily: T.font.mono }}>{(v.settlementRate * 100).toFixed(0)}%</span></td>
                  <td style={jx.td}><span style={{ fontFamily: T.font.mono }}>{(v.trialRate * 100).toFixed(0)}%</span></td>
                  <td style={jx.td}><span style={{ fontFamily: T.font.mono, color: jx.forestDeep, fontWeight:600 }}>{(v.plaintiffVerdictRate * 100).toFixed(0)}%</span></td>
                  <td style={jx.td}><span style={{ fontFamily: T.font.mono }}>${jx.num(v.avgAwardK)}K</span></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div style={jx.card}>
          <div style={jx.cardH}>Top Judges by Caseload</div>
          <div style={{ padding:'8px 12px' }}>
            {topJudges.map((j, i) => {
              const court = data.courts.find(c => c.id === j.courtId);
              const max = topJudges[0].caseload || 1;
              const pct = (j.caseload || 0) / max * 100;
              return (
                <div key={j.id} style={{ padding:'6px 0', borderBottom: i < topJudges.length - 1 ? `1px solid ${T.color.border.light}` : 'none' }}>
                  <div style={{ display:'flex', justifyContent:'space-between', fontSize:'11px', marginBottom:'3px' }}>
                    <span style={{ fontWeight:600 }}>{j.name}</span>
                    <span style={{ fontFamily: T.font.mono, color: T.color.text.secondary }}>{j.caseload}</span>
                  </div>
                  <div style={{ display:'flex', alignItems:'center', gap:'6px' }}>
                    <div style={{ flex:1, height:'4px', background: T.color.bg.secondary, borderRadius:'2px' }}>
                      <div style={{ width: pct + '%', height:'100%', background: jx.forest, borderRadius:'2px' }} />
                    </div>
                    <span style={{ fontSize:'9px', color: T.color.text.tertiary }}>{court ? court.short : ''}</span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      <div style={jx.card}>
        <div style={jx.cardH}>MSJ Grant Rate by Court</div>
        <div style={{ padding:'12px 16px' }}>
          {ranked.map(v => {
            const pct = v.msjGrantRate * 100;
            return (
              <div key={v.courtId} style={{ display:'flex', alignItems:'center', gap:'12px', padding:'6px 0' }}>
                <span style={{ width:'110px', fontSize:'11px', fontWeight:600, color: T.color.text.primary }}>{(v.court || {}).short || v.courtId}</span>
                <div style={{ flex:1, height:'18px', background: T.color.bg.secondary, borderRadius:'3px', position:'relative' }}>
                  <div style={{ width: pct * 2 + '%', height:'100%', background: pct > 35 ? jx.crimson : pct > 30 ? jx.amber : jx.forest, borderRadius:'3px', transition:'width 0.3s' }} />
                  <span style={{ position:'absolute', right:'8px', top:'50%', transform:'translateY(-50%)', fontSize:'10px', fontFamily: T.font.mono, color: T.color.text.primary, fontWeight:600 }}>{pct.toFixed(0)}%</span>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ── COURT DETAIL PANEL ─────────────────────────────────────────────────────
function JxCourtDetailPanel({ court, data, onClose, onOpenJudge }) {
  const jx = window.__jx;
  if (!court) return null;
  const judges = data.judges.filter(j => j.courtId === court.id);
  const rules = data.rules.filter(r => r.courtId === court.id || (r.appliesTo || []).includes(court.id));
  const analytics = data.venueAnalytics.find(v => v.courtId === court.id);
  const deadlineRules = window.JurisdictionsStore.deadlinesForCourt(court.id);
  const forms = data.forms.filter(f => f.courtId === court.id);
  const admissions = data.admissions.filter(a => a.courtId === court.id);

  const t = jx.courtTypeColor(court.type);

  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(15,23,42,0.55)', zIndex:500, display:'flex', justifyContent:'flex-end' }}>
      <div onClick={e => e.stopPropagation()} style={{ width:'720px', maxWidth:'95vw', height:'100%', background: T.color.bg.card, overflow:'auto', borderLeft:`1px solid ${T.color.border.light}` }}>
        <div style={{ padding:'18px 24px', borderBottom: `1px solid ${T.color.border.light}`, background: T.color.bg.secondary }}>
          <div style={{ display:'flex', alignItems:'flex-start', justifyContent:'space-between', gap:'12px' }}>
            <div>
              <div style={{ display:'flex', alignItems:'center', gap:'8px', marginBottom:'6px' }}>
                <span style={{ ...jx.tag, background: t.bg, color: t.color }}>{court.type}</span>
                <span style={{ ...jx.tag, background: jx.indigoBg, color: jx.indigo }}>{court.circuit}</span>
              </div>
              <div style={{ fontSize:'18px', fontWeight:700, color: T.color.text.primary, letterSpacing:'-0.01em' }}>{court.name}</div>
              <div style={{ fontSize:'12px', color: T.color.text.secondary, marginTop:'2px' }}>{court.address}</div>
            </div>
            <button style={jx.btnSecondary} onClick={onClose}>Close</button>
          </div>
        </div>

        <div style={{ padding:'16px 24px' }}>
          {/* Filing info */}
          <div style={{ ...jx.card, padding:0 }}>
            <div style={jx.cardH}>Filing & Practice</div>
            <div style={{ padding:'12px 16px', display:'grid', gridTemplateColumns:'repeat(2,1fr)', gap:'10px' }}>
              <div><div style={jx.statLabel}>Filing system</div><div style={{ fontSize:'12px', fontWeight:600 }}>{court.filingSystem}</div></div>
              <div><div style={jx.statLabel}>E-filing</div><div style={{ fontSize:'12px', fontWeight:600 }}>{court.efileMandatory ? 'Mandatory' : 'Permitted'}</div></div>
              <div><div style={jx.statLabel}>Civil filing fee</div><div style={{ fontSize:'12px', fontWeight:600, fontFamily: T.font.mono }}>${jx.num(court.filingFeeCivil)}</div></div>
              <div><div style={jx.statLabel}>Jury demand</div><div style={{ fontSize:'12px', fontWeight:600 }}>{court.juryDemand}</div></div>
              <div style={{ gridColumn:'span 2' }}><div style={jx.statLabel}>Motion practice</div><div style={{ fontSize:'12px' }}>{court.motionPractice}</div></div>
              <div><div style={jx.statLabel}>Clerk</div><div style={{ fontSize:'12px', fontFamily: T.font.mono }}>{court.clerkPhone}</div></div>
              <div><div style={jx.statLabel}>Rules</div><div style={{ fontSize:'12px', color: jx.forest }}>{court.rulesUrl}</div></div>
            </div>
          </div>

          {/* Analytics */}
          {analytics && (
            <div style={{ ...jx.card, padding:0 }}>
              <div style={jx.cardH}>Venue Analytics</div>
              <div style={{ padding:'12px 16px', display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:'10px' }}>
                <div style={jx.stat}><div style={jx.statLabel}>Avg disposition</div><div style={jx.statValue}>{analytics.avgDispositionDays}d</div></div>
                <div style={jx.stat}><div style={jx.statLabel}>MSJ grant</div><div style={jx.statValue}>{(analytics.msjGrantRate * 100).toFixed(0)}%</div></div>
                <div style={jx.stat}><div style={jx.statLabel}>Settlement</div><div style={jx.statValue}>{(analytics.settlementRate * 100).toFixed(0)}%</div></div>
                <div style={jx.stat}><div style={jx.statLabel}>Plaintiff verdicts</div><div style={jx.statValue}>{(analytics.plaintiffVerdictRate * 100).toFixed(0)}%</div></div>
              </div>
            </div>
          )}

          {/* Judges */}
          <div style={{ ...jx.card, padding:0 }}>
            <div style={jx.cardH}>Judges ({judges.length})</div>
            <div style={{ padding:'6px' }}>
              {judges.map(j => (
                <div key={j.id} onClick={() => onOpenJudge && onOpenJudge(j)} style={{ padding:'8px 10px', borderRadius:'6px', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
                  <div>
                    <div style={{ fontSize:'12px', fontWeight:600 }}>{j.name}</div>
                    <div style={{ fontSize:'10px', color: T.color.text.tertiary }}>{j.role} · {j.caseload || 0} cases</div>
                  </div>
                  <span style={{ ...jx.pill, background: jx.forestBg, color: jx.forestDeep }}>* {j.rating || '—'}</span>
                </div>
              ))}
            </div>
          </div>

          {/* Deadline rules */}
          <div style={{ ...jx.card, padding:0 }}>
            <div style={jx.cardH}>Deadline Rules ({deadlineRules.length})</div>
            <div style={{ padding:'8px 16px', fontSize:'11px' }}>
              {deadlineRules.map(dr => (
                <div key={dr.id} style={{ padding:'6px 0', borderBottom: `1px solid ${T.color.border.light}` }}>
                  <div style={{ display:'flex', justifyContent:'space-between' }}>
                    <span style={{ fontWeight:600 }}>{dr.name}</span>
                    <span style={{ fontFamily: T.font.mono, color: jx.forest }}>{dr.offsetDays > 0 ? '+' : ''}{dr.offsetDays}d</span>
                  </div>
                  <div style={{ color: T.color.text.tertiary, marginTop:'2px' }}>Trigger: {dr.trigger} · {dr.source}</div>
                </div>
              ))}
            </div>
          </div>

          {/* Rules */}
          <div style={{ ...jx.card, padding:0 }}>
            <div style={jx.cardH}>Applicable Rules ({rules.length})</div>
            <div style={{ padding:'8px 16px', fontSize:'11px' }}>
              {rules.map(r => (
                <div key={r.id} style={{ padding:'6px 0', borderBottom: `1px solid ${T.color.border.light}` }}>
                  <div style={{ fontWeight:600 }}>{r.citation} — {r.name}</div>
                  <div style={{ color: T.color.text.tertiary, marginTop:'2px', lineHeight:1.4 }}>{r.summary}</div>
                </div>
              ))}
            </div>
          </div>

          {/* Forms */}
          {forms.length > 0 && (
            <div style={{ ...jx.card, padding:0 }}>
              <div style={jx.cardH}>Forms ({forms.length})</div>
              <div style={{ padding:'8px 16px', fontSize:'11px' }}>
                {forms.map(f => (
                  <div key={f.id} style={{ display:'flex', justifyContent:'space-between', padding:'4px 0' }}>
                    <span><b>{f.code}</b> {f.name}</span>
                    <span style={{ color: T.color.text.tertiary }}>{f.category}</span>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ── JUDGE DETAIL PANEL ─────────────────────────────────────────────────────
function JxJudgeDetailPanel({ judge, data, onClose }) {
  const jx = window.__jx;
  if (!judge) return null;
  const court = data.courts.find(c => c.id === judge.courtId);
  const orders = data.standingOrders.filter(so => so.judgeId === judge.id);

  const totalMotions = (judge.motionStats && (judge.motionStats.granted + judge.motionStats.denied + judge.motionStats.partial)) || 0;

  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(15,23,42,0.55)', zIndex:500, display:'flex', justifyContent:'flex-end' }}>
      <div onClick={e => e.stopPropagation()} style={{ width:'640px', maxWidth:'95vw', height:'100%', background: T.color.bg.card, overflow:'auto', borderLeft:`1px solid ${T.color.border.light}` }}>
        <div style={{ padding:'18px 24px', borderBottom:`1px solid ${T.color.border.light}`, background: T.color.bg.secondary }}>
          <div style={{ display:'flex', alignItems:'flex-start', justifyContent:'space-between', gap:'12px' }}>
            <div>
              <div style={{ fontSize:'18px', fontWeight:700 }}>{judge.name}</div>
              <div style={{ fontSize:'12px', color: T.color.text.secondary }}>{judge.role} · {court ? court.short : judge.courtId}</div>
              <div style={{ fontSize:'11px', color: T.color.text.tertiary, marginTop:'2px' }}>Appointed {judge.appointed} by {judge.appointedBy} · {judge.lawSchool}</div>
            </div>
            <button style={jx.btnSecondary} onClick={onClose}>Close</button>
          </div>
        </div>

        <div style={{ padding:'16px 24px' }}>
          <div style={{ ...jx.card, padding:0 }}>
            <div style={jx.cardH}>Judicial Metrics</div>
            <div style={{ padding:'12px 16px', display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:'10px' }}>
              <div style={jx.stat}><div style={jx.statLabel}>Caseload</div><div style={jx.statValue}>{judge.caseload || '—'}</div></div>
              <div style={jx.stat}><div style={jx.statLabel}>MSJ grant rate</div><div style={jx.statValue}>{judge.summaryJudgmentGrantRate != null ? (judge.summaryJudgmentGrantRate * 100).toFixed(0) + '%' : '—'}</div></div>
              <div style={jx.stat}><div style={jx.statLabel}>Avg disposition</div><div style={jx.statValue}>{judge.avgDispositionDays ? judge.avgDispositionDays + 'd' : '—'}</div></div>
              <div style={jx.stat}><div style={jx.statLabel}>Rating</div><div style={jx.statValue}>* {judge.rating || '—'}</div></div>
              <div style={jx.stat}><div style={jx.statLabel}>Clerks</div><div style={jx.statValue}>{judge.lawClerks || '—'}</div></div>
              <div style={jx.stat}><div style={jx.statLabel}>Motions ruled</div><div style={jx.statValue}>{totalMotions || '—'}</div></div>
            </div>
            {totalMotions > 0 && (
              <div style={{ padding:'0 16px 12px' }}>
                <div style={{ fontSize:'10px', color: T.color.text.tertiary, textTransform:'uppercase', letterSpacing:'0.06em', marginBottom:'4px' }}>Motion Outcomes</div>
                <div style={{ display:'flex', height:'14px', borderRadius:'3px', overflow:'hidden' }}>
                  <div style={{ width: (judge.motionStats.granted / totalMotions * 100) + '%', background: jx.emerald }} title={`Granted ${judge.motionStats.granted}`} />
                  <div style={{ width: (judge.motionStats.partial / totalMotions * 100) + '%', background: jx.amber }} title={`Partial ${judge.motionStats.partial}`} />
                  <div style={{ width: (judge.motionStats.denied / totalMotions * 100) + '%', background: jx.crimson }} title={`Denied ${judge.motionStats.denied}`} />
                </div>
                <div style={{ display:'flex', justifyContent:'space-between', marginTop:'4px', fontSize:'10px', color: T.color.text.tertiary, fontFamily: T.font.mono }}>
                  <span style={{ color: jx.emerald }}>Granted {judge.motionStats.granted}</span>
                  <span style={{ color: jx.amber }}>Partial {judge.motionStats.partial}</span>
                  <span style={{ color: jx.crimson }}>Denied {judge.motionStats.denied}</span>
                </div>
              </div>
            )}
          </div>

          <div style={{ ...jx.card, padding:0 }}>
            <div style={jx.cardH}>Preferences</div>
            <div style={{ padding:'12px 16px', fontSize:'12px', color: T.color.text.secondary, lineHeight:1.5 }}>{judge.preferences || 'No notes.'}</div>
          </div>

          {judge.rulingTendencies && (
            <div style={{ ...jx.card, padding:0 }}>
              <div style={jx.cardH}>Ruling Tendencies</div>
              <div style={{ padding:'12px 16px', fontSize:'12px', color: T.color.text.secondary, lineHeight:1.5 }}>{judge.rulingTendencies}</div>
            </div>
          )}

          {orders.length > 0 && (
            <div style={{ ...jx.card, padding:0 }}>
              <div style={jx.cardH}>Standing Orders ({orders.length})</div>
              <div style={{ padding:'8px 16px', fontSize:'11px' }}>
                {orders.map(so => (
                  <div key={so.id} style={{ padding:'6px 0', borderBottom: `1px solid ${T.color.border.light}` }}>
                    <div style={{ display:'flex', justifyContent:'space-between' }}>
                      <span style={{ fontWeight:600 }}>{so.title}</span>
                      <span style={{ fontSize:'10px', color: T.color.text.tertiary }}>{jx.fmtDate(so.date)}</span>
                    </div>
                    <div style={{ color: T.color.text.secondary, marginTop:'2px', lineHeight:1.4 }}>{so.summary}</div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {judge.recusalTopics && judge.recusalTopics.length > 0 && (
            <div style={{ ...jx.card, padding:0 }}>
              <div style={jx.cardH}>Recusal Topics</div>
              <div style={{ padding:'10px 16px', display:'flex', gap:'6px', flexWrap:'wrap' }}>
                {judge.recusalTopics.map((r, i) => (
                  <span key={i} style={{ ...jx.tag, background: jx.crimsonBg, color: jx.crimson }}>{r}</span>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ── MODAL SHELL ────────────────────────────────────────────────────────────
function JxModal({ open, onClose, title, children, width }) {
  const jx = window.__jx;
  if (!open) return null;
  return (
    <div onClick={onClose} style={{ position:'fixed', inset:0, background:'rgba(15,23,42,0.55)', zIndex:600, display:'flex', alignItems:'center', justifyContent:'center' }}>
      <div onClick={e => e.stopPropagation()} style={{ width: width || '480px', maxWidth:'95vw', background: T.color.bg.card, borderRadius: T.radius.lg, overflow:'hidden', boxShadow:'0 10px 40px rgba(0,0,0,0.25)' }}>
        <div style={{ padding:'14px 18px', borderBottom: `1px solid ${T.color.border.light}`, display:'flex', alignItems:'center', justifyContent:'space-between' }}>
          <div style={{ fontSize:'14px', fontWeight:700 }}>{title}</div>
          <button style={jx.btnSecondary} onClick={onClose}>Close</button>
        </div>
        <div style={{ padding:'16px 18px' }}>{children}</div>
      </div>
    </div>
  );
}

// ── NEW PHV MODAL ──────────────────────────────────────────────────────────
function JxNewPhvModal({ open, onClose, data, onCreated }) {
  const jx = window.__jx;
  const [form, setForm] = useState({ attorneyName:'', courtId:'', matterName:'', matterId:'', localCounsel:'', fee:300 });
  const submit = () => {
    if (!form.attorneyName || !form.courtId) return;
    const phv = window.JurisdictionsStore.fileProHacVice(form);
    if (onCreated) onCreated(phv);
    onClose();
  };
  const fieldStyle = { width:'100%', padding:'6px 10px', border:`1px solid ${T.color.border.light}`, borderRadius:'6px', fontSize:'12px', fontFamily: T.font.family, background: T.color.bg.card };
  return (
    <JxModal open={open} onClose={onClose} title="File Pro Hac Vice">
      <div style={{ display:'grid', gap:'10px' }}>
        <label style={{ fontSize:'11px', fontWeight:600, color: T.color.text.secondary }}>Attorney
          <input type="text" value={form.attorneyName} onChange={e => setForm({...form, attorneyName: e.target.value})} style={fieldStyle} />
        </label>
        <label style={{ fontSize:'11px', fontWeight:600, color: T.color.text.secondary }}>Court
          <select value={form.courtId} onChange={e => setForm({...form, courtId: e.target.value})} style={fieldStyle}>
            <option value="">Select a court…</option>
            {data.courts.map(c => <option key={c.id} value={c.id}>{c.short} — {c.name}</option>)}
          </select>
        </label>
        <label style={{ fontSize:'11px', fontWeight:600, color: T.color.text.secondary }}>Matter name
          <input type="text" value={form.matterName} onChange={e => setForm({...form, matterName: e.target.value})} style={fieldStyle} />
        </label>
        <label style={{ fontSize:'11px', fontWeight:600, color: T.color.text.secondary }}>Matter ID
          <input type="text" value={form.matterId} onChange={e => setForm({...form, matterId: e.target.value})} style={fieldStyle} />
        </label>
        <label style={{ fontSize:'11px', fontWeight:600, color: T.color.text.secondary }}>Local counsel
          <input type="text" value={form.localCounsel} onChange={e => setForm({...form, localCounsel: e.target.value})} style={fieldStyle} />
        </label>
        <label style={{ fontSize:'11px', fontWeight:600, color: T.color.text.secondary }}>Fee ($)
          <input type="number" value={form.fee} onChange={e => setForm({...form, fee: Number(e.target.value)})} style={fieldStyle} />
        </label>
        <div style={{ display:'flex', gap:'8px', justifyContent:'flex-end', marginTop:'6px' }}>
          <button style={jx.btnSecondary} onClick={onClose}>Cancel</button>
          <button style={jx.btnPrimary} onClick={submit}>File Application</button>
        </div>
      </div>
    </JxModal>
  );
}

// ── LOG CLE MODAL ──────────────────────────────────────────────────────────
function JxLogCleModal({ open, onClose, admission, onLogged }) {
  const jx = window.__jx;
  const [hours, setHours] = useState(1);
  const [topic, setTopic] = useState('');
  const submit = () => {
    if (!admission) return;
    window.JurisdictionsStore.logCle(admission.id, Number(hours), topic);
    if (onLogged) onLogged();
    onClose();
  };
  const fieldStyle = { width:'100%', padding:'6px 10px', border:`1px solid ${T.color.border.light}`, borderRadius:'6px', fontSize:'12px', fontFamily: T.font.family, background: T.color.bg.card };
  return (
    <JxModal open={open} onClose={onClose} title={`Log CLE Hours${admission ? ' — ' + admission.attorneyName : ''}`}>
      <div style={{ display:'grid', gap:'10px' }}>
        <label style={{ fontSize:'11px', fontWeight:600, color: T.color.text.secondary }}>Hours
          <input type="number" step="0.5" value={hours} onChange={e => setHours(e.target.value)} style={fieldStyle} />
        </label>
        <label style={{ fontSize:'11px', fontWeight:600, color: T.color.text.secondary }}>Topic / Course
          <input type="text" value={topic} onChange={e => setTopic(e.target.value)} placeholder="e.g. Ethics: Conflicts of Interest" style={fieldStyle} />
        </label>
        <div style={{ display:'flex', gap:'8px', justifyContent:'flex-end', marginTop:'6px' }}>
          <button style={jx.btnSecondary} onClick={onClose}>Cancel</button>
          <button style={jx.btnPrimary} onClick={submit}>Log</button>
        </div>
      </div>
    </JxModal>
  );
}

// ── DEADLINE CALCULATOR PANEL ──────────────────────────────────────────────
function JxDeadlineCalculator({ data }) {
  const jx = window.__jx;
  const [courtId, setCourtId] = useState('C-USDC-SDNY');
  const [ruleId, setRuleId] = useState('');
  const [triggerDate, setTriggerDate] = useState(new Date().toISOString().slice(0,10));
  const [result, setResult] = useState(null);

  const rulesForCourt = window.JurisdictionsStore.deadlinesForCourt(courtId);

  const calc = () => {
    if (!ruleId) return;
    const r = window.JurisdictionsStore.calcDeadline(ruleId, triggerDate);
    setResult(r);
  };

  const fieldStyle = { width:'100%', padding:'6px 10px', border:`1px solid ${T.color.border.light}`, borderRadius:'6px', fontSize:'12px', fontFamily: T.font.family, background: T.color.bg.card };

  return (
    <div style={jx.card}>
      <div style={jx.cardH}>Deadline Calculator</div>
      <div style={{ padding:'14px 16px', display:'grid', gridTemplateColumns:'1fr 1fr 1fr auto', gap:'10px', alignItems:'end' }}>
        <label style={{ fontSize:'11px', fontWeight:600, color: T.color.text.secondary }}>Court
          <select value={courtId} onChange={e => { setCourtId(e.target.value); setRuleId(''); setResult(null); }} style={fieldStyle}>
            {data.courts.map(c => <option key={c.id} value={c.id}>{c.short}</option>)}
          </select>
        </label>
        <label style={{ fontSize:'11px', fontWeight:600, color: T.color.text.secondary }}>Deadline rule
          <select value={ruleId} onChange={e => { setRuleId(e.target.value); setResult(null); }} style={fieldStyle}>
            <option value="">Select…</option>
            {rulesForCourt.map(r => <option key={r.id} value={r.id}>{r.name}</option>)}
          </select>
        </label>
        <label style={{ fontSize:'11px', fontWeight:600, color: T.color.text.secondary }}>Trigger date
          <input type="date" value={triggerDate} onChange={e => setTriggerDate(e.target.value)} style={fieldStyle} />
        </label>
        <button style={jx.btnPrimary} onClick={calc}>Calculate</button>
      </div>
      {result && (
        <div style={{ padding:'0 16px 14px' }}>
          <div style={{ background: jx.forestBg, border:`1px solid ${jx.forestBorder}`, padding:'12px 14px', borderRadius:'8px' }}>
            <div style={{ fontSize:'10px', fontWeight:700, color: jx.forestDeep, textTransform:'uppercase', letterSpacing:'0.08em' }}>Deadline</div>
            <div style={{ fontSize:'20px', fontWeight:700, color: T.color.text.primary, fontFamily: T.font.mono, marginTop:'4px' }}>{jx.fmtDate(result.deadline)}</div>
            <div style={{ fontSize:'11px', color: T.color.text.secondary, marginTop:'4px' }}>
              {result.daysUntil >= 0 ? `${result.daysUntil} days from today` : `${Math.abs(result.daysUntil)} days ago`} · {result.rule.source}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

window.JxAdmissionsHub = JxAdmissionsHub;
window.JxFormsHub = JxFormsHub;
window.JxFormCard = JxFormCard;
window.JxFormDetailModal = JxFormDetailModal;
window.JxAssemblePackModal = JxAssemblePackModal;
window.JxAnalyticsHub = JxAnalyticsHub;
window.JxCourtDetailPanel = JxCourtDetailPanel;
window.JxJudgeDetailPanel = JxJudgeDetailPanel;
window.JxModal = JxModal;
window.JxNewPhvModal = JxNewPhvModal;
window.JxLogCleModal = JxLogCleModal;
window.JxDeadlineCalculator = JxDeadlineCalculator;

})();
