// JURISDICTIONS PLATFORM — primary hub views (Dashboard, Courts, Judges, Rules)
(function(){
const { useState, useMemo } = React;
const T = window.ArbiterTokens;

// ── DASHBOARD HUB ──────────────────────────────────────────────────────────
function JxDashboardHub({ data, onOpenCourt, onOpenJudge, onOpenAdmission, onOpenPhv }) {
  const jx = window.__jx;
  const alerts = data.alerts || [];
  const recentAudits = (data.auditLog || []).slice(0, 8);

  const upcomingCle = data.admissions
    .filter(a => a.cleDue)
    .map(a => ({ ...a, days: jx.daysUntil(a.cleDue) }))
    .filter(a => a.days != null && a.days <= 120 && a.days >= -30)
    .sort((a, b) => a.days - b.days)
    .slice(0, 6);

  const pendingPhv = data.proHacVice.filter(p => p.status === 'Pending');

  return (
    <div>
      {/* Alert strip */}
      {alerts.length > 0 && (
        <div style={{ ...jx.card, background: jx.forestBg, border: `1px solid ${jx.forestBorder}` }}>
          <div style={jx.cardH}>
            <span style={{ display:'flex', alignItems:'center', gap:'8px' }}>
              <span style={{ fontSize:'11px', fontWeight:700, color:jx.forestDeep, textTransform:'uppercase', letterSpacing:'0.08em' }}>Jurisdictional Alerts</span>
              <span style={{ ...jx.pill, background:jx.forestBg, color:jx.forestDeep }}>{alerts.length}</span>
            </span>
          </div>
          <div style={{ padding:'0 16px 8px' }}>
            {alerts.slice(0, 5).map(a => {
              const sev = jx.severityColor(a.severity);
              return (
                <div key={a.id} style={{ display:'flex', alignItems:'center', gap:'10px', padding:'8px 0', borderTop: `1px solid ${T.color.border.light}` }}>
                  <span style={{ ...jx.tag, background: sev.bg, color: sev.color, minWidth:'64px', justifyContent:'center' }}>{a.severity}</span>
                  <span style={{ fontSize:'12px', color: T.color.text.primary, flex: 1 }}>{a.message}</span>
                  <span style={{ fontSize:'10px', color: T.color.text.tertiary }}>{jx.fmtDate(a.createdAt)}</span>
                  <button style={jx.btnGhost} onClick={() => window.JurisdictionsStore.dismissAlert(a.id)}>Dismiss</button>
                </div>
              );
            })}
          </div>
        </div>
      )}

      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'16px' }}>
        {/* CLE due */}
        <div style={jx.card}>
          <div style={jx.cardH}>CLE Deadlines (next 120 days)</div>
          <table style={{ width:'100%', borderCollapse:'collapse' }}>
            <thead><tr>
              <th style={jx.th}>Attorney</th><th style={jx.th}>Court</th>
              <th style={jx.th}>Due</th><th style={jx.th}>Hours</th>
            </tr></thead>
            <tbody>
              {upcomingCle.map(a => (
                <tr key={a.id} style={{ cursor:'pointer' }} onClick={() => onOpenAdmission && onOpenAdmission(a)}>
                  <td style={jx.td}>{a.attorneyName}</td>
                  <td style={jx.td}>{(data.courts.find(c => c.id === a.courtId) || {}).short || a.courtId}</td>
                  <td style={jx.td}>
                    <span style={{ ...jx.tag, background: a.days < 30 ? jx.crimsonBg : jx.amberBg, color: a.days < 30 ? jx.crimson : jx.amber }}>
                      {a.days < 0 ? `${Math.abs(a.days)}d overdue` : `${a.days}d`}
                    </span>
                  </td>
                  <td style={jx.td}>
                    <span style={{ fontFamily: T.font.mono, fontSize:'11px' }}>{a.cleHoursCompleted}/{a.cleHoursRequired}</span>
                  </td>
                </tr>
              ))}
              {upcomingCle.length === 0 && (
                <tr><td colSpan="4" style={{ ...jx.td, textAlign:'center', color: T.color.text.tertiary }}>No CLE deadlines in next 120 days.</td></tr>
              )}
            </tbody>
          </table>
        </div>

        {/* Pending PHV */}
        <div style={jx.card}>
          <div style={jx.cardH}>Pending Pro Hac Vice</div>
          <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}>Filed</th>
            </tr></thead>
            <tbody>
              {pendingPhv.map(p => (
                <tr key={p.id} style={{ cursor:'pointer' }} onClick={() => onOpenPhv && onOpenPhv(p)}>
                  <td style={jx.td}>{p.attorneyName}</td>
                  <td style={jx.td}>{(data.courts.find(c => c.id === p.courtId) || {}).short || p.courtId}</td>
                  <td style={jx.td}>{p.matterName}</td>
                  <td style={jx.td}>{jx.fmtDate(p.filedDate)}</td>
                </tr>
              ))}
              {pendingPhv.length === 0 && (
                <tr><td colSpan="4" style={{ ...jx.td, textAlign:'center', color: T.color.text.tertiary }}>No pending applications.</td></tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Court map and recent activity */}
      <div style={{ display:'grid', gridTemplateColumns:'2fr 1fr', gap:'16px' }}>
        <div style={jx.card}>
          <div style={jx.cardH}>Jurisdictional Footprint</div>
          <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(200px, 1fr))', gap:'10px', padding:'12px' }}>
            {data.courts.map(c => {
              const t = jx.courtTypeColor(c.type);
              const practicing = data.admissions.filter(a => a.courtId === c.id && a.status === 'Active').length;
              return (
                <div key={c.id} onClick={() => onOpenCourt && onOpenCourt(c)} style={{ padding:'10px 12px', border:`1px solid ${T.color.border.light}`, borderRadius:'8px', cursor:'pointer', background: T.color.bg.card, transition:'all 0.15s' }}>
                  <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:'4px' }}>
                    <span style={{ ...jx.tag, background: t.bg, color: t.color }}>{c.type}</span>
                    <span style={{ fontSize:'10px', color: T.color.text.tertiary }}>{c.state}</span>
                  </div>
                  <div style={{ fontSize:'12px', fontWeight:600, color: T.color.text.primary, marginBottom:'2px' }}>{c.short}</div>
                  <div style={{ fontSize:'10px', color: T.color.text.tertiary, lineHeight:1.3 }}>{c.name.replace(/^U\.S\. /,'')}</div>
                  <div style={{ marginTop:'6px', fontSize:'10px', color: T.color.text.secondary, fontFamily: T.font.mono }}>{practicing} admitted</div>
                </div>
              );
            })}
          </div>
        </div>

        <div style={jx.card}>
          <div style={jx.cardH}>Recent Activity</div>
          <div style={{ padding:'8px 12px', maxHeight:'380px', overflow:'auto' }}>
            {recentAudits.map(a => (
              <div key={a.id} style={{ padding:'6px 0', borderBottom: `1px solid ${T.color.border.light}` }}>
                <div style={{ fontSize:'11px', color: T.color.text.primary }}>
                  <b style={{ color: jx.forestDeep, textTransform:'capitalize' }}>{a.action}</b> {a.entity} · {a.id}
                </div>
                <div style={{ fontSize:'10px', color: T.color.text.tertiary, marginTop:'2px' }}>
                  {new Date(a.at).toLocaleString()}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ── COURTS HUB ─────────────────────────────────────────────────────────────
function JxCourtsHub({ data, onOpenCourt }) {
  const jx = window.__jx;
  const [query, setQuery] = useState('');
  const [typeFilter, setTypeFilter] = useState('all');

  const filtered = useMemo(() => {
    return data.courts.filter(c => {
      if (typeFilter !== 'all' && c.type !== typeFilter) return false;
      if (query && !(c.name + ' ' + c.short + ' ' + c.state).toLowerCase().includes(query.toLowerCase())) return false;
      return true;
    });
  }, [data.courts, query, typeFilter]);

  const types = ['all', ...new Set(data.courts.map(c => c.type))];

  return (
    <div>
      <div style={{ ...jx.card, marginBottom:'12px' }}>
        <div style={{ padding:'10px 16px', display:'flex', alignItems:'center', gap:'10px', flexWrap:'wrap' }}>
          <input
            type="text" placeholder="Search courts…"
            value={query} onChange={e => setQuery(e.target.value)}
            style={{ flex:1, minWidth:'240px', padding:'6px 10px', border:`1px solid ${T.color.border.light}`, borderRadius:'6px', fontSize:'12px', fontFamily: T.font.family }}
          />
          <div style={{ display:'flex', gap:'4px' }}>
            {types.map(t => (
              <button key={t} onClick={() => setTypeFilter(t)}
                style={{ ...jx.filterBtn, ...(typeFilter === t ? jx.filterBtnActive : {}) }}>
                {t === 'all' ? 'All' : t}
              </button>
            ))}
          </div>
        </div>
      </div>

      <div style={jx.card}>
        <table style={{ width:'100%', borderCollapse:'collapse' }}>
          <thead><tr>
            <th style={jx.th}>Court</th><th style={jx.th}>Type</th><th style={jx.th}>Circuit</th>
            <th style={jx.th}>State</th><th style={jx.th}>E-file</th>
            <th style={jx.th}>Judges</th><th style={jx.th}>Rules</th><th style={jx.th}>Filing Fee</th>
          </tr></thead>
          <tbody>
            {filtered.map(c => {
              const t = jx.courtTypeColor(c.type);
              const numJudges = data.judges.filter(j => j.courtId === c.id).length;
              const numRules = data.rules.filter(r => r.courtId === c.id || (r.appliesTo || []).includes(c.id)).length;
              return (
                <tr key={c.id} style={{ cursor:'pointer' }} onClick={() => onOpenCourt && onOpenCourt(c)}>
                  <td style={jx.td}>
                    <div style={{ fontWeight:600, color: T.color.text.primary }}>{c.short}</div>
                    <div style={{ fontSize:'10px', color: T.color.text.tertiary }}>{c.name}</div>
                  </td>
                  <td style={jx.td}><span style={{ ...jx.tag, background: t.bg, color: t.color }}>{c.type}</span></td>
                  <td style={jx.td}>{c.circuit}</td>
                  <td style={jx.td}>{c.state}</td>
                  <td style={jx.td}>{c.filingSystem}</td>
                  <td style={jx.td}><span style={{ fontFamily: T.font.mono }}>{numJudges}</span></td>
                  <td style={jx.td}><span style={{ fontFamily: T.font.mono }}>{numRules}</span></td>
                  <td style={jx.td}><span style={{ fontFamily: T.font.mono }}>${jx.num(c.filingFeeCivil)}</span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ── JUDGES HUB ─────────────────────────────────────────────────────────────
function JxJudgesHub({ data, onOpenJudge }) {
  const jx = window.__jx;
  const [query, setQuery] = useState('');
  const [courtFilter, setCourtFilter] = useState('all');
  const [sortBy, setSortBy] = useState('caseload');

  const filtered = useMemo(() => {
    let list = data.judges.filter(j => {
      if (courtFilter !== 'all' && j.courtId !== courtFilter) return false;
      if (query && !(j.name + ' ' + (j.knownFor || '')).toLowerCase().includes(query.toLowerCase())) return false;
      return true;
    });
    const get = { caseload: j => j.caseload || 0, msj: j => j.summaryJudgmentGrantRate || 0, rating: j => j.rating || 0, disposition: j => j.avgDispositionDays || 0 };
    list.sort((a, b) => (get[sortBy] || get.caseload)(b) - (get[sortBy] || get.caseload)(a));
    return list;
  }, [data.judges, query, courtFilter, sortBy]);

  return (
    <div>
      <div style={{ ...jx.card, marginBottom:'12px' }}>
        <div style={{ padding:'10px 16px', display:'flex', alignItems:'center', gap:'10px', flexWrap:'wrap' }}>
          <input type="text" placeholder="Search judges, keywords…" value={query} onChange={e => setQuery(e.target.value)}
            style={{ flex:1, minWidth:'220px', 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', fontFamily: T.font.family, 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>
          <select value={sortBy} onChange={e => setSortBy(e.target.value)}
            style={{ padding:'6px 10px', border:`1px solid ${T.color.border.light}`, borderRadius:'6px', fontSize:'12px', fontFamily: T.font.family, background: T.color.bg.card }}>
            <option value="caseload">Sort: Caseload</option>
            <option value="msj">Sort: MSJ grant rate</option>
            <option value="rating">Sort: Rating</option>
            <option value="disposition">Sort: Avg disposition</option>
          </select>
        </div>
      </div>

      <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(360px, 1fr))', gap:'12px' }}>
        {filtered.map(j => {
          const court = data.courts.find(c => c.id === j.courtId);
          return (
            <div key={j.id} onClick={() => onOpenJudge && onOpenJudge(j)}
              style={{ ...jx.card, marginBottom:0, cursor:'pointer', padding:0 }}>
              <div style={{ padding:'12px 16px', borderBottom: `1px solid ${T.color.border.light}` }}>
                <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:'6px' }}>
                  <div style={{ fontSize:'13px', fontWeight:700, color: T.color.text.primary }}>{j.name}</div>
                  <span style={{ ...jx.pill, background: jx.forestBg, color: jx.forestDeep }}>* {j.rating || '—'}</span>
                </div>
                <div style={{ fontSize:'11px', color: T.color.text.tertiary }}>{j.role} · {court ? court.short : j.courtId}</div>
                <div style={{ fontSize:'10px', color: T.color.text.tertiary, marginTop:'2px' }}>Appointed {j.appointed} by {j.appointedBy}</div>
              </div>
              <div style={{ padding:'8px 16px', display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:'8px' }}>
                <div>
                  <div style={{ fontSize:'9px', color: T.color.text.tertiary, textTransform:'uppercase', letterSpacing:'0.06em' }}>Caseload</div>
                  <div style={{ fontSize:'14px', fontWeight:700, color: T.color.text.primary, fontFamily: T.font.mono }}>{j.caseload || '—'}</div>
                </div>
                <div>
                  <div style={{ fontSize:'9px', color: T.color.text.tertiary, textTransform:'uppercase', letterSpacing:'0.06em' }}>MSJ grant</div>
                  <div style={{ fontSize:'14px', fontWeight:700, color: T.color.text.primary, fontFamily: T.font.mono }}>{j.summaryJudgmentGrantRate != null ? (j.summaryJudgmentGrantRate * 100).toFixed(0) + '%' : '—'}</div>
                </div>
                <div>
                  <div style={{ fontSize:'9px', color: T.color.text.tertiary, textTransform:'uppercase', letterSpacing:'0.06em' }}>Avg dispo</div>
                  <div style={{ fontSize:'14px', fontWeight:700, color: T.color.text.primary, fontFamily: T.font.mono }}>{j.avgDispositionDays ? j.avgDispositionDays + 'd' : '—'}</div>
                </div>
              </div>
              {j.knownFor && (
                <div style={{ padding:'8px 16px 12px', borderTop: `1px solid ${T.color.border.light}`, fontSize:'11px', color: T.color.text.secondary, lineHeight:1.4 }}>
                  <b style={{ color: jx.forestDeep }}>Known for:</b> {j.knownFor}
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ── RULES HUB ──────────────────────────────────────────────────────────────
function JxRulesHub({ data }) {
  const jx = window.__jx;
  const [query, setQuery] = useState('');
  const [cat, setCat] = useState('all');
  const [courtFilter, setCourtFilter] = useState('all');
  const [expanded, setExpanded] = useState(null);

  const cats = ['all', ...new Set(data.rules.map(r => r.category))];

  const filtered = useMemo(() => {
    return data.rules.filter(r => {
      if (cat !== 'all' && r.category !== cat) return false;
      if (courtFilter !== 'all' && r.courtId !== courtFilter && !(r.appliesTo || []).includes(courtFilter)) return false;
      if (query) {
        const q = query.toLowerCase();
        if (!(r.name + ' ' + r.summary + ' ' + r.citation + ' ' + (r.tags || []).join(' ')).toLowerCase().includes(q)) return false;
      }
      return true;
    });
  }, [data.rules, query, cat, courtFilter]);

  return (
    <div>
      <div style={{ ...jx.card, marginBottom:'12px' }}>
        <div style={{ padding:'10px 16px', display:'flex', gap:'10px', flexWrap:'wrap', alignItems:'center' }}>
          <input type="text" placeholder="Search rules, citations, tags…" value={query} onChange={e => setQuery(e.target.value)}
            style={{ flex:1, minWidth:'240px', 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={() => setCat(c)} style={{ ...jx.filterBtn, ...(cat === c ? jx.filterBtnActive : {}) }}>
                {c === 'all' ? 'All' : c}
              </button>
            ))}
          </div>
        </div>
      </div>

      <div>
        {filtered.map(r => {
          const court = data.courts.find(c => c.id === r.courtId);
          const isOpen = expanded === r.id;
          return (
            <div key={r.id} style={jx.card}>
              <div style={{ ...jx.cardH, cursor:'pointer' }} onClick={() => setExpanded(isOpen ? null : r.id)}>
                <div style={{ display:'flex', alignItems:'center', gap:'10px' }}>
                  <span style={{ ...jx.tag, background: jx.indigoBg, color: jx.indigo }}>{r.category}</span>
                  <span style={{ fontWeight:700 }}>{r.citation}</span>
                  <span style={{ color: T.color.text.secondary, fontWeight:500 }}>{r.name}</span>
                </div>
                <span style={{ fontSize:'10px', color: T.color.text.tertiary }}>{court ? court.short : (r.appliesTo || []).join(', ')}</span>
              </div>
              {isOpen && (
                <div style={{ padding:'12px 16px', fontSize:'12px', color: T.color.text.secondary, lineHeight:1.5 }}>
                  <div style={{ marginBottom:'8px' }}>{r.summary}</div>
                  <div style={{ display:'flex', gap:'16px', fontSize:'11px', color: T.color.text.tertiary }}>
                    <span><b>Effective:</b> {jx.fmtDate(r.effectiveDate)}</span>
                    {r.tags && <span><b>Tags:</b> {r.tags.join(', ')}</span>}
                  </div>
                </div>
              )}
            </div>
          );
        })}
        {filtered.length === 0 && (
          <div style={{ ...jx.card, padding:'24px', textAlign:'center', color: T.color.text.tertiary }}>No matching rules.</div>
        )}
      </div>
    </div>
  );
}

window.JxDashboardHub = JxDashboardHub;
window.JxCourtsHub = JxCourtsHub;
window.JxJudgesHub = JxJudgesHub;
window.JxRulesHub = JxRulesHub;

})();
