// MOTIONS PLATFORM — Citations + Calendar
const Tmnc = window.ArbiterTokens;

function MotionsCitations({ data }) {
  const mn = window.__mn;
  const flagged = data.citations.filter(c => c.treatment === 'caution' || c.treatment === 'negative');
  const positive = data.citations.filter(c => c.treatment === 'positive');
  const maxUsage = Math.max(...data.citations.map(c => c.firmUsage));

  const treatmentColor = (t) => ({
    positive:  { bg: 'rgba(5,150,105,0.08)', color: '#059669', label: 'positive' },
    caution:   { bg: 'rgba(180,83,9,0.08)',  color: '#B45309', label: 'caution' },
    negative:  { bg: 'rgba(185,28,28,0.08)', color: '#B91C1C', label: 'negative' },
    neutral:   { bg: Tmnc.color.bg.secondary, color: Tmnc.color.text.secondary, label: 'neutral' },
  }[t] || { bg: Tmnc.color.bg.secondary, color: Tmnc.color.text.secondary, label: t });

  return (
    <div>
      <div style={{ ...mn.card, borderLeft: `3px solid ${mn.plum}`, background: mn.plumBg }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: mn.plum, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Firm-wide citation intelligence</div>
          <div style={{ fontSize: '11px', color: Tmnc.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            {data.kpis.totalCitations.toLocaleString()} active citations across {data.motions.length} motions, ranked by treatment and firm-wide usage.
            <b style={{ color: mn.amber, fontFamily: Tmnc.font.mono }}> {flagged.length}</b> flagged for re-verification;
            <b style={{ color: mn.emerald, fontFamily: Tmnc.font.mono }}> {positive.length}</b> verified positive.
          </div>
        </div>
      </div>

      <div style={mn.stripKpi}>
        <div style={mn.stat}><span style={mn.statLabel}>Total citations</span><span style={mn.statValue}>{data.kpis.totalCitations.toLocaleString()}</span></div>
        <div style={mn.stat}><span style={mn.statLabel}>Tracked here</span><span style={mn.statValue}>{data.citations.length}</span><span style={{ ...mn.statDelta, color: Tmnc.color.text.tertiary }}>canonical records</span></div>
        <div style={mn.stat}><span style={mn.statLabel}>Positive</span><span style={{ ...mn.statValue, color: mn.emerald }}>{positive.length}</span></div>
        <div style={mn.stat}><span style={mn.statLabel}>Flagged</span><span style={{ ...mn.statValue, color: mn.amber }}>{flagged.length}</span><span style={{ ...mn.statDelta, color: Tmnc.color.text.tertiary }}>review before filing</span></div>
        <div style={mn.stat}><span style={mn.statLabel}>Avg firm usage</span><span style={mn.statValue}>{Math.round(data.citations.reduce((s, c) => s + c.firmUsage, 0) / data.citations.length)}</span><span style={{ ...mn.statDelta, color: Tmnc.color.text.tertiary }}>times cited YTD</span></div>
      </div>

      <div style={mn.card}>
        <div style={mn.cardH}>
          <span>Citation index — {data.citations.length} tracked</span>
          <button style={mn.btnSecondary}>Run Shepard batch ◆</button>
        </div>
        <div style={mn.tableWrap}>
        <table style={{ ...mn.tableFixed, minWidth: '1100px' }}>
          <thead>
            <tr>
              <th style={mn.th}>Short cite</th>
              <th style={mn.th}>Full citation</th>
              <th style={mn.th}>Treatment</th>
              <th style={{ ...mn.th, textAlign: 'right' }}>Uses in motions</th>
              <th style={{ ...mn.th, textAlign: 'right' }}>Firm usage (YTD)</th>
              <th style={mn.th}>Firm usage visual</th>
              <th style={mn.th}>Last verified</th>
              <th style={mn.th}>Flag</th>
            </tr>
          </thead>
          <tbody>
            {data.citations.map(c => {
              const tc = treatmentColor(c.treatment);
              return (
                <tr key={c.id} style={c.treatment === 'caution' || c.treatment === 'negative' ? { background: 'rgba(180,83,9,0.03)' } : undefined}>
                  <td style={{ ...mn.td, fontWeight: 700, color: Tmnc.color.text.primary }}>{c.short}</td>
                  <td style={{ ...mn.td, fontFamily: Tmnc.font.mono, fontSize: '11px', color: Tmnc.color.text.secondary }}>{c.cite}</td>
                  <td style={mn.td}><span style={{ ...mn.tag, background: tc.bg, color: tc.color }}>{tc.label}</span></td>
                  <td style={{ ...mn.td, textAlign: 'right', fontFamily: Tmnc.font.mono, color: Tmnc.color.text.primary, fontWeight: 600 }}>{c.motionIds.length}</td>
                  <td style={{ ...mn.td, textAlign: 'right', fontFamily: Tmnc.font.mono, color: mn.plum, fontWeight: 700 }}>{c.firmUsage}</td>
                  <td style={mn.td}>
                    <div style={{ width: '120px', height: '5px', background: Tmnc.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                      <div style={{ width: `${(c.firmUsage / maxUsage) * 100}%`, height: '100%', background: mn.plum }} />
                    </div>
                  </td>
                  <td style={{ ...mn.td, fontFamily: Tmnc.font.mono, fontSize: '11px', color: Tmnc.color.text.tertiary }}>{c.lastVerified}</td>
                  <td style={mn.td}>
                    {c.flagNote ? <span style={{ ...mn.tag, background: mn.amberBg, color: mn.amber }} title={c.flagNote}>! {c.flagNote.slice(0, 30)}…</span> : c.treatment === 'positive' ? <span style={{ ...mn.tag, background: mn.emeraldBg, color: mn.emerald }}><Icons.Check size={11}/></span> : '—'}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        </div>
      </div>
    </div>
  );
}

function MotionsCalendar({ data }) {
  const mn = window.__mn;
  // Group by date
  const grouped = {};
  data.calendar.forEach(c => { (grouped[c.date] = grouped[c.date] || []).push(c); });
  const dates = Object.keys(grouped).sort();

  const urgencyStyle = (u) => ({
    critical: { bg: mn.crimsonBg, color: mn.crimson, border: mn.crimson },
    high:     { bg: mn.orangeBg, color: mn.orange, border: mn.orange },
    medium:   { bg: mn.amberBg, color: mn.amber, border: mn.amber },
    low:      { bg: Tmnc.color.bg.secondary, color: Tmnc.color.text.tertiary, border: Tmnc.color.border.light },
  }[u] || { bg: Tmnc.color.bg.secondary, color: Tmnc.color.text.secondary, border: Tmnc.color.border.light });

  const typeStyle = (t) => ({
    Hearing:     { bg: mn.cobaltBg, color: mn.cobalt },
    Argument:    { bg: mn.plumBg, color: mn.plum },
    'Oral Arg':  { bg: mn.plumBg, color: mn.plum },
    Evidentiary: { bg: mn.crimsonBg, color: mn.crimson },
    Filing:      { bg: mn.tealBg, color: mn.teal },
  }[t] || { bg: Tmnc.color.bg.secondary, color: Tmnc.color.text.secondary });

  const byUrgency = { critical: 0, high: 0, medium: 0 };
  data.calendar.forEach(c => byUrgency[c.urgency] = (byUrgency[c.urgency] || 0) + 1);

  return (
    <div>
      <div style={mn.stripKpi}>
        <div style={mn.stat}><span style={mn.statLabel}>Total events</span><span style={mn.statValue}>{data.calendar.length}</span></div>
        <div style={mn.stat}><span style={mn.statLabel}>Critical</span><span style={{ ...mn.statValue, color: mn.crimson }}>{byUrgency.critical || 0}</span></div>
        <div style={mn.stat}><span style={mn.statLabel}>High priority</span><span style={{ ...mn.statValue, color: mn.orange }}>{byUrgency.high || 0}</span></div>
        <div style={mn.stat}><span style={mn.statLabel}>Oral arguments</span><span style={{ ...mn.statValue, color: mn.plum }}>{data.calendar.filter(c => c.type === 'Argument' || c.type === 'Oral Arg').length}</span></div>
        <div style={mn.stat}><span style={mn.statLabel}>Filing deadlines</span><span style={{ ...mn.statValue, color: mn.teal }}>{data.calendar.filter(c => c.type === 'Filing').length}</span></div>
      </div>

      <div style={mn.card}>
        <div style={mn.cardH}>
          <span>Motion calendar · {data.calendar.length} events</span>
          <div style={{ display: 'flex', gap: '10px', fontSize: '10px' }}>
            <span style={{ color: mn.crimson }}>■ Critical</span>
            <span style={{ color: mn.orange }}>■ High</span>
            <span style={{ color: mn.amber }}>■ Medium</span>
          </div>
        </div>
        <div style={mn.tableWrap}>
        {dates.map(date => (
          <div key={date} style={{ minWidth: '720px' }}>
            <div style={{ padding: '8px 16px', background: Tmnc.color.bg.secondary, fontSize: '11px', fontWeight: 700, color: Tmnc.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', display: 'flex', justifyContent: 'space-between' }}>
              <span style={{ fontFamily: Tmnc.font.mono, color: mn.plum }}>{date}</span>
              <span>{grouped[date].length} event{grouped[date].length > 1 ? 's' : ''}</span>
            </div>
            {grouped[date].map(c => {
              const us = urgencyStyle(c.urgency);
              const ts = typeStyle(c.type);
              return (
                <div key={c.motionId + c.date + c.caption} style={{ padding: '10px 16px', borderBottom: `1px solid ${Tmnc.color.border.light}`, borderLeft: `3px solid ${us.border}`, display: 'grid', gridTemplateColumns: 'minmax(100px, 120px) minmax(180px, 2fr) minmax(140px, 1fr) minmax(90px, 110px) minmax(80px, 90px)', gap: '12px', alignItems: 'center' }}>
                  <span style={{ ...mn.tag, background: ts.bg, color: ts.color }}>{c.type}</span>
                  <div>
                    <div style={{ fontSize: '12px', fontWeight: 600, color: Tmnc.color.text.primary }}>{c.caption}</div>
                    <div style={{ fontSize: '10px', color: Tmnc.color.text.tertiary, marginTop: '2px' }}>{c.matter}</div>
                  </div>
                  <span style={{ fontSize: '11px', color: Tmnc.color.text.secondary }}>{c.matter}</span>
                  <span style={{ fontFamily: Tmnc.font.mono, fontSize: '11px', color: mn.plum, fontWeight: 700 }}>{c.motionId}</span>
                  <span style={{ ...mn.tag, background: us.bg, color: us.color, padding: '3px 10px', justifySelf: 'end' }}>{c.urgency}</span>
                </div>
              );
            })}
          </div>
        ))}
        </div>
      </div>
    </div>
  );
}

window.MotionsCitations = MotionsCitations;
window.MotionsCalendar = MotionsCalendar;
