// CRIMINAL HEARINGS PLATFORM — Views + Entry
const { useState: useCHState } = React;
const Tch = window.ArbiterTokens;

const urgencyColor = (u, cj) => ({
  critical: { bg: cj.burgundyBg, color: cj.burgundy, border: cj.burgundy },
  high:     { bg: cj.orangeBg,   color: cj.orange,   border: cj.orange },
  medium:   { bg: cj.amberBg,    color: cj.amber,     border: cj.amber },
  low:      { bg: Tch.color.bg.secondary, color: Tch.color.text.tertiary, border: Tch.color.border.light },
}[u] || { bg: Tch.color.bg.secondary, color: Tch.color.text.secondary, border: Tch.color.border.light });

const typeIcon = (type) => type.includes('Trial') ? '' : type.includes('Sentencing') ? '' : type.includes('Grand jury') ? '' : type.includes('Appeal') ? '⬆' : type.includes('Franks') ? '' : type.includes('Suppress') ? '' : type.includes('§ 2255') ? '' : '';

function HearingsOverview({ data }) {
  const cj = window.__cj;
  const hearings = [...data.hearings].sort((a, b) => a.date.localeCompare(b.date));
  const byUrgency = hearings.reduce((a, h) => { a[h.urgency] = (a[h.urgency]||0)+1; return a; }, {});
  const today = new Date('2026-04-21');
  const next7 = hearings.filter(h => (new Date(h.date) - today) / 86400000 <= 7);
  const trials = hearings.filter(h => h.type.includes('Trial'));
  const sentencings = hearings.filter(h => h.type.toLowerCase().includes('sentencing'));

  return (
    <div>
      <div style={{ ...cj.card, borderLeft: `3px solid ${cj.burgundy}`, background: cj.burgundyBg, marginBottom: '14px' }}>
        <div style={{ padding: '14px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <div style={{ fontSize: '13px', fontWeight: 700, color: cj.burgundy, textTransform: 'uppercase', letterSpacing: '0.08em' }}> Hearing Calendar — {hearings.length} proceedings next 60 days</div>
            <div style={{ fontSize: '12px', color: Tch.color.text.secondary, marginTop: '6px', lineHeight: 1.55 }}>
              <b style={{ color: cj.burgundy }}>{byUrgency.critical || 0} critical proceedings</b> including {trials.length} trial{trials.length!==1?'s':''} and {sentencings.length} sentencing{sentencings.length!==1?'s':''}.{' '}
              {next7.length > 0 && <b style={{ color: cj.orange }}>{next7.length} hearing{next7.length!==1?'s':''} within 7 days.</b>}
            </div>
          </div>
          <button style={cj.btnPrimary}>+ Add hearing</button>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: '10px', marginBottom: '14px' }}>
        {[
          { l: 'Total hearings', v: hearings.length, c: null },
          { l: 'Critical', v: byUrgency.critical||0, c: cj.burgundy },
          { l: 'High priority', v: byUrgency.high||0, c: cj.orange },
          { l: 'Trials', v: trials.length, c: cj.burgundy },
          { l: 'Sentencings', v: sentencings.length, c: cj.orange },
          { l: 'Next 7 days', v: next7.length, c: next7.length > 0 ? cj.orange : null },
        ].map(s => (
          <div key={s.l} style={cj.stat}>
            <span style={cj.statLabel}>{s.l}</span>
            <span style={{ ...cj.statValue, color: s.c || Tch.color.text.primary }}>{s.v}</span>
          </div>
        ))}
      </div>

      {/* Next 7 days urgent alert */}
      {next7.length > 0 && (
        <div style={{ ...cj.card, borderLeft: `3px solid ${cj.orange}`, background: cj.orangeBg, marginBottom: '14px' }}>
          <div style={{ padding: '10px 16px' }}>
            <div style={{ fontSize: '12px', fontWeight: 700, color: cj.orange, marginBottom: '6px' }}>! Next 7 days — {next7.length} proceeding{next7.length!==1?'s':''} require preparation</div>
            {next7.map(h => {
              const uc = urgencyColor(h.urgency, cj);
              const daysLeft = Math.round((new Date(h.date) - today) / 86400000);
              return (
                <div key={h.id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '6px 0', borderTop: `1px solid ${cj.orange}22`, fontSize: '11px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                    <span style={{ fontSize: '14px' }}>{typeIcon(h.type)}</span>
                    <div>
                      <div style={{ fontWeight: 600, color: Tch.color.text.primary }}>{h.defendant} — {h.type}</div>
                      <div style={{ color: Tch.color.text.tertiary }}>{h.court} · {h.judge}</div>
                    </div>
                  </div>
                  <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                    <span style={{ ...cj.tag, background: uc.bg, color: uc.color }}>{h.urgency}</span>
                    <span style={{ fontFamily: Tch.font.mono, fontWeight: 700, color: daysLeft === 0 ? cj.burgundy : daysLeft <= 3 ? cj.orange : cj.amber, fontSize: '13px' }}>{daysLeft === 0 ? 'TODAY' : `${daysLeft}d`}</span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* By defendant timeline */}
      <div style={cj.card}>
        <div style={cj.cardH}>Proceedings by defendant — chronological</div>
        <div style={{ padding: '12px 16px' }}>
          {Object.entries(
            hearings.reduce((a, h) => { (a[h.defendant] = a[h.defendant]||[]).push(h); return a; }, {})
          ).map(([def, hs]) => (
            <div key={def} style={{ marginBottom: '14px' }}>
              <div style={{ fontSize: '12px', fontWeight: 700, color: Tch.color.text.primary, marginBottom: '6px' }}>{def}</div>
              <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
                {hs.sort((a,b) => a.date.localeCompare(b.date)).map(h => {
                  const uc = urgencyColor(h.urgency, cj);
                  return (
                    <div key={h.id} title={`${h.date} ${h.time} — ${h.type}\n${h.purpose}`} style={{ padding: '6px 10px', borderRadius: '5px', background: uc.bg, border: `1px solid ${uc.border}22`, fontSize: '11px', cursor: 'default' }}>
                      <div style={{ fontFamily: Tch.font.mono, fontSize: '10px', color: uc.color, marginBottom: '2px' }}>{h.date}</div>
                      <div style={{ color: Tch.color.text.primary, fontWeight: 500 }}>{typeIcon(h.type)} {h.type}</div>
                    </div>
                  );
                })}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function HearingsCalendar({ data }) {
  const cj = window.__cj;
  const [urgFilter, setUrgFilter] = useCHState('All');
  const hearings = [...data.hearings].sort((a, b) => a.date.localeCompare(b.date));
  const filtered = urgFilter === 'All' ? hearings : hearings.filter(h => h.urgency === urgFilter);
  const grouped = filtered.reduce((a, h) => { (a[h.date] = a[h.date]||[]).push(h); return a; }, {});

  return (
    <div>
      <div style={cj.card}>
        <div style={cj.cardH}>
          <span>Hearing calendar — {filtered.length} proceedings</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            {['All','critical','high','medium'].map(u => (
              <button key={u} onClick={() => setUrgFilter(u)} style={{ padding: '3px 10px', fontSize: '11px', borderRadius: '5px', border: `1px solid ${Tch.color.border.light}`, cursor: 'pointer', fontFamily: Tch.font.family, background: urgFilter===u ? (u==='critical'?cj.burgundy:u==='high'?cj.orange:u==='medium'?cj.amber:Tch.color.text.primary) : Tch.color.bg.secondary, color: urgFilter===u ? '#fff' : Tch.color.text.secondary }}>
                {u === 'All' ? 'All' : u.charAt(0).toUpperCase()+u.slice(1)}
              </button>
            ))}
            <button style={cj.btnPrimary}>+ Add hearing</button>
          </div>
        </div>

        {Object.entries(grouped).map(([date, hs]) => (
          <div key={date}>
            <div style={{ padding: '8px 16px', background: Tch.color.bg.secondary, fontSize: '11px', fontWeight: 700, color: Tch.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', display: 'flex', justifyContent: 'space-between' }}>
              <span style={{ fontFamily: Tch.font.mono, color: cj.burgundy }}>{date}</span>
              <span>{hs.length} hearing{hs.length > 1 ? 's' : ''}</span>
            </div>
            {hs.map(h => {
              const uc = urgencyColor(h.urgency, cj);
              return (
                <div key={h.id} style={{ padding: '12px 16px', borderBottom: `1px solid ${Tch.color.border.light}`, borderLeft: `4px solid ${uc.border}`, display: 'grid', gridTemplateColumns: '70px 180px 1fr 220px 100px', gap: '14px', alignItems: 'center' }}>
                  <span style={{ fontFamily: Tch.font.mono, fontSize: '12px', color: uc.color, fontWeight: 700 }}>{h.time}</span>
                  <div>
                    <div style={{ fontSize: '12px', fontWeight: 700, color: Tch.color.text.primary }}>{h.defendant}</div>
                    <div style={{ fontSize: '10px', color: Tch.color.text.tertiary, fontFamily: Tch.font.mono }}>{h.id}</div>
                  </div>
                  <div>
                    <div style={{ fontSize: '12px', fontWeight: 700, color: Tch.color.text.primary }}>{typeIcon(h.type)} {h.type}</div>
                    <div style={{ fontSize: '11px', color: Tch.color.text.secondary, marginTop: '2px' }}>{h.purpose}</div>
                  </div>
                  <div style={{ fontSize: '11px' }}>
                    <div style={{ fontWeight: 600, color: Tch.color.text.primary }}>{h.court}</div>
                    <div style={{ color: Tch.color.text.tertiary }}>{h.judge}</div>
                    <div style={{ color: Tch.color.text.tertiary, fontFamily: Tch.font.mono, fontSize: '10px' }}>{h.location}</div>
                  </div>
                  <span style={{ ...cj.tag, background: uc.bg, color: uc.color, justifySelf: 'end', padding: '4px 10px' }}>{h.urgency}</span>
                </div>
              );
            })}
          </div>
        ))}
      </div>
    </div>
  );
}

function HearingsTrialPrep({ data }) {
  const cj = window.__cj;
  const trials = data.hearings.filter(h => h.type.includes('Trial'));
  const today = new Date('2026-04-21');

  if (!trials.length) return (
    <div style={{ ...cj.card, padding: '32px 16px', textAlign: 'center' }}>
      <div style={{ fontSize: '14px', color: Tch.color.text.tertiary }}>No trials currently scheduled.</div>
    </div>
  );

  return (
    <div>
      <div style={{ ...cj.card, borderLeft: `3px solid ${cj.burgundy}`, background: cj.burgundyBg, marginBottom: '14px' }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: cj.burgundy, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Trial Preparation Dashboard — {trials.length} trial{trials.length!==1?'s':''} scheduled</div>
          <div style={{ fontSize: '11px', color: Tch.color.text.secondary, marginTop: '4px' }}>Countdown to each trial commencement with pre-trial deadline milestones.</div>
        </div>
      </div>

      {trials.map(t => {
        const daysLeft = Math.round((new Date(t.date) - today) / 86400000);
        const def = data.defendants.find(d => d.name === t.defendant);
        const motions = data.motions.filter(m => m.defendant === t.defendant);
        const witnesses = data.witnesses.filter(w => w.matter === (def?.matter?.split(' v. ').pop() || ''));
        const milestones = [
          { label: 'Jencks material due', days: daysLeft - 30, done: false },
          { label: 'Motions in limine deadline', days: daysLeft - 21, done: false },
          { label: 'Exhibit list exchange', days: daysLeft - 14, done: false },
          { label: 'Witness list final', days: daysLeft - 14, done: false },
          { label: 'Jury charge submissions', days: daysLeft - 7, done: false },
          { label: 'Trial begins', days: daysLeft, done: false },
        ];
        const urgC = daysLeft <= 14 ? cj.burgundy : daysLeft <= 30 ? cj.orange : cj.amber;
        return (
          <div key={t.id} style={{ ...cj.card, marginBottom: '14px', borderTop: `3px solid ${urgC}` }}>
            <div style={{ padding: '14px 16px', borderBottom: `1px solid ${Tch.color.border.light}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: `linear-gradient(135deg, ${cj.burgundyBg} 0%, transparent 100%)` }}>
              <div>
                <div style={{ fontSize: '14px', fontWeight: 700, color: Tch.color.text.primary, marginBottom: '2px' }}>{t.defendant}</div>
                <div style={{ fontSize: '11px', color: Tch.color.text.tertiary }}>{t.court} · {t.judge} · {t.location}</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontFamily: Tch.font.mono, fontSize: '32px', fontWeight: 700, color: urgC, lineHeight: 1 }}>{daysLeft}</div>
                <div style={{ fontSize: '11px', color: Tch.color.text.tertiary }}>days to trial · {t.date}</div>
              </div>
            </div>
            <div style={{ padding: '14px 16px' }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '14px', marginBottom: '14px' }}>
                <div><div style={{ fontSize: '10px', fontWeight: 700, color: Tch.color.text.tertiary, textTransform: 'uppercase', marginBottom: '4px' }}>Purpose</div><div style={{ fontSize: '12px', color: Tch.color.text.primary, lineHeight: 1.5 }}>{t.purpose}</div></div>
                <div><div style={{ fontSize: '10px', fontWeight: 700, color: Tch.color.text.tertiary, textTransform: 'uppercase', marginBottom: '4px' }}>Pending motions</div><div style={{ fontSize: '22px', fontWeight: 700, fontFamily: Tch.font.mono, color: motions.filter(m=>m.status!=='Denied'&&m.status!=='Granted').length > 0 ? cj.amber : cj.emerald }}>{motions.filter(m=>m.status!=='Denied').length}</div></div>
                <div><div style={{ fontSize: '10px', fontWeight: 700, color: Tch.color.text.tertiary, textTransform: 'uppercase', marginBottom: '4px' }}>Defense witnesses</div><div style={{ fontSize: '22px', fontWeight: 700, fontFamily: Tch.font.mono, color: cj.cobalt }}>{witnesses.length || '—'}</div></div>
              </div>

              {/* Milestone countdown */}
              <div style={{ fontSize: '10px', fontWeight: 700, color: Tch.color.text.tertiary, textTransform: 'uppercase', marginBottom: '8px' }}>Pre-trial milestones</div>
              <div style={{ display: 'flex', gap: '0', position: 'relative' }}>
                <div style={{ position: 'absolute', top: '12px', left: 0, right: 0, height: '2px', background: Tch.color.border.light }} />
                {milestones.map((m, i) => {
                  const isPast = m.days <= 0;
                  const mc = isPast ? cj.emerald : m.days <= 7 ? cj.burgundy : m.days <= 14 ? cj.orange : cj.cobalt;
                  return (
                    <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', position: 'relative' }}>
                      <div style={{ width: '24px', height: '24px', borderRadius: '50%', background: mc, display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative', zIndex: 1, fontSize: '10px', color: '#fff', fontWeight: 700 }}>{isPast ? 'ok' : m.days}</div>
                      <div style={{ fontSize: '9px', color: Tch.color.text.tertiary, textAlign: 'center', marginTop: '4px', lineHeight: 1.3, maxWidth: '80px' }}>{m.label}</div>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

function CriminalHearingsPlatform({ data }) {
  const cj = window.__cj;
  const [activeView, setActiveView] = useCHState('overview');
  const views = [
    { id: 'overview',  label: 'Overview' },
    { id: 'calendar',  label: 'Calendar' },
    { id: 'trialprep', label: 'Trial Prep' },
  ];
  const render = () => {
    switch (activeView) {
      case 'overview':  return <HearingsOverview data={data} />;
      case 'calendar':  return <HearingsCalendar data={data} />;
      case 'trialprep': return <HearingsTrialPrep data={data} />;
      default:          return <HearingsOverview data={data} />;
    }
  };
  return (
    <div>
      <div style={{ display: 'flex', gap: '4px', padding: '5px', background: Tch.color.bg.secondary, border: `1px solid ${Tch.color.border.light}`, borderRadius: '8px', marginBottom: '16px' }}>
        {views.map(v => (
          <button key={v.id} onClick={() => setActiveView(v.id)} style={{
            padding: '6px 14px', fontSize: '11px', fontWeight: activeView===v.id ? 700 : 500,
            borderRadius: '6px', border: 'none', cursor: 'pointer',
            background: activeView===v.id ? cj.burgundy : 'transparent',
            color: activeView===v.id ? '#fff' : Tch.color.text.secondary,
            fontFamily: Tch.font.family, transition: 'all .15s',
          }}>{v.label}</button>
        ))}
      </div>
      {render()}
    </div>
  );
}

window.CriminalHearingsPlatform = CriminalHearingsPlatform;
