const { useState } = React;
const T = window.ArbiterTokens;

// ── RESOURCE SCHEDULING ──
function CalResources() {
  const attorneys = window.ATTORNEYS;
  const dl = window.DOCKET_DEADLINES;
  const [hovered, setHovered] = useState(null);

  const now = new Date('2026-04-20');
  const getAttorneyDeadlines = (name) => dl.filter(d => d.assignee === name).sort((a, b) => a.date.localeCompare(b.date));

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={cal.stat}><span style={cal.statLabel}>Attorneys</span><span style={cal.statValue}>{attorneys.length}</span></div>
        <div style={cal.stat}><span style={cal.statLabel}>Conflicts Detected</span><span style={{ ...cal.statValue, color: '#C23030' }}>{attorneys.filter(a => a.conflicts.length > 0).length}</span></div>
        <div style={cal.stat}><span style={cal.statLabel}>Avg Capacity Used</span><span style={{ ...cal.statValue, color: cal.amber }}>{Math.round(attorneys.reduce((s, a) => s + (100 - a.capacity), 0) / attorneys.length)}%</span></div>
      </div>

      {/* Attorney cards */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
        {attorneys.map((att, i) => {
          const deadlines = getAttorneyDeadlines(att.name);
          const capacityUsed = 100 - att.capacity;
          const capColor = capacityUsed >= 70 ? '#C23030' : capacityUsed >= 50 ? cal.amber : T.color.status.active;
          return (
            <div key={att.id} style={{ ...cal.card, borderColor: att.conflicts.length > 0 ? '#C2303030' : T.color.border.light }}>
              <div style={{ padding: '12px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', alignItems: 'center', gap: '10px' }}>
                <div style={{ width: '36px', height: '36px', borderRadius: '50%', background: att.color, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '12px', fontWeight: 700, color: '#fff', flexShrink: 0 }}>{att.initials}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 600, fontSize: '13px', color: T.color.text.primary }}>{att.name}</div>
                  <div style={{ fontSize: '10px', color: T.color.text.tertiary }}>{att.role} · {att.matters} matters</div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontSize: '16px', fontWeight: 700, fontFamily: T.font.mono, color: capColor }}>{capacityUsed}%</div>
                  <div style={{ fontSize: '9px', color: T.color.text.tertiary }}>utilized</div>
                </div>
              </div>
              {/* Capacity bar */}
              <div style={{ padding: '8px 16px', borderBottom: `1px solid ${T.color.border.light}` }}>
                <div style={{ height: '6px', borderRadius: '3px', background: T.color.border.light }}>
                  <div style={{ width: `${capacityUsed}%`, height: '100%', borderRadius: '3px', background: capColor, transition: 'width 0.5s' }} />
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '4px', fontSize: '9px', color: T.color.text.tertiary }}>
                  <span>{att.deadlinesThisWeek} this week · {att.deadlinesNextWeek} next week</span>
                  <span>{att.capacity}% available</span>
                </div>
              </div>
              {/* Conflicts */}
              {att.conflicts.length > 0 && (
                <div style={{ padding: '8px 16px', background: 'rgba(194,48,48,0.03)', borderBottom: `1px solid ${T.color.border.light}` }}>
                  {att.conflicts.map((c, j) => (
                    <div key={j} style={{ display: 'flex', gap: '6px', alignItems: 'baseline', fontSize: '11px', color: '#C23030' }}>
                      <span style={{ fontSize: '10px' }}><Icons.Alert size={11}/></span>{c}
                    </div>
                  ))}
                </div>
              )}
              {/* Upcoming deadlines */}
              {deadlines.slice(0, 4).map((d, j) => {
                const days = Math.ceil((new Date(d.date) - now) / (1000 * 60 * 60 * 24));
                return (
                  <div key={d.id} style={{ padding: '6px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', alignItems: 'center', gap: '8px', fontSize: '11px' }}>
                    <span style={{ fontFamily: T.font.mono, fontSize: '10px', color: days <= 3 ? '#C23030' : T.color.text.tertiary, minWidth: '40px' }}>{new Date(d.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}</span>
                    <span style={{ flex: 1, color: T.color.text.secondary }}>{d.label}</span>
                    <span style={{ fontSize: '9px', color: T.color.text.tertiary }}>{d.matter.split(' ').slice(0, 2).join(' ')}</span>
                  </div>
                );
              })}
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ── COURT RULES ENGINE ──
function CalRules() {
  const rules = window.COURT_RULES;
  const [search, setSearch] = useState('');
  const [typeFilter, setTypeFilter] = useState('All');
  const types = ['All', ...new Set(rules.map(r => r.type))];

  const filtered = rules.filter(r => {
    if (typeFilter !== 'All' && r.type !== typeFilter) return false;
    if (search) {
      const q = search.toLowerCase();
      return r.rule.toLowerCase().includes(q) || r.description.toLowerCase().includes(q) || r.triggerEvent.toLowerCase().includes(q);
    }
    return true;
  });

  return (
    <div>
      <div style={{ ...cal.card, marginBottom: '16px' }}>
        <div style={{ padding: '12px 16px', background: cal.amberBg, fontSize: '12px', color: T.color.text.secondary, lineHeight: 1.5 }}>
          <div style={{ fontSize: '10px', fontWeight: 600, color: cal.amber, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '4px' }}>◆ Court Rules Engine</div>
          Select a trigger event and jurisdiction to auto-calculate downstream deadlines. All rules include the applicable FRCP or Local Rule citation. Use the deadline calculator below to generate chains for new events.
        </div>
      </div>

      {/* Filters */}
      <div style={{ display: 'flex', gap: '8px', marginBottom: '12px', alignItems: 'center' }}>
        <input style={{ height: '32px', border: `1px solid ${T.color.border.light}`, borderRadius: T.radius.md, padding: '0 12px', fontSize: '12px', fontFamily: T.font.family, background: T.color.bg.card, color: T.color.text.primary, outline: 'none', width: '240px' }} placeholder="Search rules..." value={search} onChange={e => setSearch(e.target.value)} />
        {types.map(t => (
          <button key={t} style={{ ...cal.filterBtn, ...(typeFilter === t ? cal.filterBtnActive : {}) }} onClick={() => setTypeFilter(t)}>{t === 'All' ? 'All Types' : t}</button>
        ))}
      </div>

      <div style={cal.card}>
        <div style={{ display: 'grid', gridTemplateColumns: '100px 120px 1fr 140px 60px 80px', padding: '6px 16px', background: T.color.bg.secondary, borderBottom: `1px solid ${T.color.border.light}`, fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', gap: '8px' }}>
          <span>Rule</span><span>Jurisdiction</span><span>Description</span><span>Trigger Event</span><span>Days</span><span>Type</span>
        </div>
        {filtered.map(r => (
          <div key={r.id} style={{ display: 'grid', gridTemplateColumns: '100px 120px 1fr 140px 60px 80px', padding: '8px 16px', borderBottom: `1px solid ${T.color.border.light}`, fontSize: '12px', alignItems: 'center', gap: '8px' }}>
            <span style={{ fontFamily: T.font.mono, fontWeight: 600, color: cal.amber, fontSize: '11px' }}>{r.rule}</span>
            <span style={{ fontSize: '10px', color: T.color.text.secondary }}>{r.jurisdiction}</span>
            <span style={{ color: T.color.text.primary, fontSize: '11px' }}>{r.description}</span>
            <span style={{ fontSize: '10px', color: T.color.text.tertiary }}>{r.triggerEvent}</span>
            <span style={{ fontFamily: T.font.mono, fontWeight: 700, color: r.days < 0 ? '#A855F7' : T.color.text.primary }}>{r.days > 0 ? '+' : ''}{r.days}</span>
            <span style={{ ...cal.tag, background: cal.amberBg, color: cal.amber }}>{r.type}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ── SOL TRACKER + ANALYTICS ──
function CalAnalytics() {
  const sol = window.SOL_TRACKER;
  const dl = window.DOCKET_DEADLINES;
  const attorneys = window.ATTORNEYS;

  // Workload per matter
  const matterLoad = {};
  dl.forEach(d => { matterLoad[d.matter] = (matterLoad[d.matter] || 0) + 1; });

  // Density by week
  const now = new Date('2026-04-20');
  const weekDensity = [];
  for (let w = 0; w < 12; w++) {
    const start = new Date(now); start.setDate(start.getDate() + w * 7);
    const end = new Date(start); end.setDate(end.getDate() + 7);
    const count = dl.filter(d => { const dd = new Date(d.date); return dd >= start && dd < end; }).length;
    weekDensity.push({ week: `W${w + 1}`, start: start.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }), count });
  }
  const maxDensity = Math.max(...weekDensity.map(w => w.count));

  return (
    <div>
      {/* SOL Tracker */}
      <div style={cal.card}>
        <div style={{ ...cal.cardH, background: 'rgba(194,48,48,0.03)' }}><span style={{ color: '#C23030' }}> Statute of Limitations Tracker</span></div>
        {sol.map((s, i) => {
          const stColor = s.status === 'Safe' ? T.color.status.active : s.status === 'Monitor' ? cal.amber : '#C23030';
          return (
            <div key={i} style={{ padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', alignItems: 'center', gap: '12px', fontSize: '12px' }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 600, color: T.color.text.primary }}>{s.claim}</div>
                <div style={{ fontSize: '10px', color: T.color.text.tertiary }}>{s.matter} · {s.sol}</div>
              </div>
              <span style={{ fontFamily: T.font.mono, fontSize: '11px', color: T.color.text.tertiary }}>{s.expires}</span>
              <div style={{ display: 'flex', alignItems: 'center', gap: '4px', minWidth: '80px' }}>
                <span style={{ fontSize: '14px', fontWeight: 700, fontFamily: T.font.mono, color: stColor }}>{s.daysRemaining}</span>
                <span style={{ fontSize: '9px', color: T.color.text.tertiary }}>days</span>
              </div>
              <span style={{ ...cal.tag, background: `${stColor}10`, color: stColor }}>{s.status}</span>
            </div>
          );
        })}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
        {/* Weekly density */}
        <div style={cal.card}>
          <div style={cal.cardH}><span>Deadline Density — Next 12 Weeks</span></div>
          <div style={{ padding: '16px' }}>
            <div style={{ display: 'flex', alignItems: 'flex-end', gap: '4px', height: '100px', marginBottom: '8px' }}>
              {weekDensity.map((w, i) => (
                <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '2px' }}>
                  {w.count > 0 && <span style={{ fontSize: '9px', fontFamily: T.font.mono, color: w.count >= 3 ? '#C23030' : T.color.text.tertiary }}>{w.count}</span>}
                  <div style={{ width: '100%', borderRadius: '2px 2px 0 0', height: `${Math.max((w.count / Math.max(maxDensity, 1)) * 70, w.count > 0 ? 4 : 0)}px`, background: w.count >= 3 ? '#C23030' : w.count >= 2 ? cal.amber : w.count > 0 ? '#3B82F6' : T.color.border.light }} />
                  <span style={{ fontSize: '8px', color: T.color.text.tertiary }}>{w.start.split(' ')[1]}</span>
                </div>
              ))}
            </div>
            <div style={{ display: 'flex', gap: '12px', justifyContent: 'center', fontSize: '9px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '3px' }}><div style={{ width: '8px', height: '8px', borderRadius: '2px', background: '#C23030' }} />High (3+)</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: '3px' }}><div style={{ width: '8px', height: '8px', borderRadius: '2px', background: cal.amber }} />Medium (2)</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: '3px' }}><div style={{ width: '8px', height: '8px', borderRadius: '2px', background: '#3B82F6' }} />Low (1)</div>
            </div>
          </div>
        </div>

        {/* Workload by matter */}
        <div style={cal.card}>
          <div style={cal.cardH}><span>Deadlines by Matter</span></div>
          {Object.entries(matterLoad).sort((a, b) => b[1] - a[1]).map(([matter, count], i) => {
            const maxLoad = Math.max(...Object.values(matterLoad));
            return (
              <div key={i} style={{ padding: '6px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', alignItems: 'center', gap: '10px', fontSize: '11px' }}>
                <span style={{ flex: 1, fontWeight: 500, color: T.color.text.primary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{matter}</span>
                <div style={{ width: '80px', height: '6px', borderRadius: '3px', background: T.color.border.light }}>
                  <div style={{ width: `${(count / maxLoad) * 100}%`, height: '100%', borderRadius: '3px', background: cal.amber }} />
                </div>
                <span style={{ fontFamily: T.font.mono, fontWeight: 700, minWidth: '20px', textAlign: 'right', color: T.color.text.primary }}>{count}</span>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CalResources, CalRules, CalAnalytics });
