// MOTIONS PLATFORM — Rulings + Templates + Activity
const Tmnr = window.ArbiterTokens;

function MotionsRulings({ data }) {
  const mn = window.__mn;
  const granted = data.rulings.filter(r => r.outcome === 'Granted').length;
  const partial = data.rulings.filter(r => r.outcome === 'Granted in Part').length;
  const denied = data.rulings.filter(r => r.outcome === 'Denied').length;
  const winPct = Math.round((granted + 0.5 * partial) / data.rulings.length * 100);

  const outcomeStyle = (o) => ({
    'Granted':          { bg: mn.emeraldBg, color: mn.emerald },
    'Granted in Part':  { bg: mn.tealBg, color: mn.teal },
    'Denied':           { bg: mn.crimsonBg, color: mn.crimson },
    'Moot':             { bg: Tmnr.color.bg.secondary, color: Tmnr.color.text.tertiary },
    'Withdrawn':        { bg: Tmnr.color.bg.secondary, color: Tmnr.color.text.tertiary },
  }[o] || { bg: Tmnr.color.bg.secondary, color: Tmnr.color.text.secondary });

  return (
    <div>
      <div style={mn.stripKpi}>
        <div style={mn.stat}><span style={mn.statLabel}>Recent rulings</span><span style={mn.statValue}>{data.rulings.length}</span></div>
        <div style={mn.stat}><span style={mn.statLabel}>Granted</span><span style={{ ...mn.statValue, color: mn.emerald }}>{granted}</span></div>
        <div style={mn.stat}><span style={mn.statLabel}>Granted in part</span><span style={{ ...mn.statValue, color: mn.teal }}>{partial}</span></div>
        <div style={mn.stat}><span style={mn.statLabel}>Denied</span><span style={{ ...mn.statValue, color: mn.crimson }}>{denied}</span></div>
        <div style={mn.stat}><span style={mn.statLabel}>Win rate</span><span style={{ ...mn.statValue, color: mn.winColor(winPct) }}>{winPct}%</span></div>
      </div>

      <div style={mn.card}>
        <div style={mn.cardH}>Recent rulings · {data.rulings.length}</div>
        <div style={mn.tableWrap}>
        <table style={{ ...mn.tableFixed, minWidth: '1100px' }}>
          <thead>
            <tr>
              <th style={mn.th}>Ruling ID</th>
              <th style={mn.th}>Caption</th>
              <th style={mn.th}>Judge</th>
              <th style={{ ...mn.th, textAlign: 'right' }}>Days to ruling</th>
              <th style={mn.th}>Ruling date</th>
              <th style={mn.th}>Outcome</th>
              <th style={mn.th}>Summary</th>
            </tr>
          </thead>
          <tbody>
            {data.rulings.map(r => {
              const os = outcomeStyle(r.outcome);
              return (
                <tr key={r.id}>
                  <td style={{ ...mn.td, fontFamily: Tmnr.font.mono, fontWeight: 700, color: mn.plum }}>{r.id}</td>
                  <td style={{ ...mn.td, fontWeight: 600, color: Tmnr.color.text.primary, maxWidth: '240px' }}>{r.caption}</td>
                  <td style={{ ...mn.td, color: Tmnr.color.text.secondary, fontSize: '11px' }}>{r.judge}</td>
                  <td style={{ ...mn.td, textAlign: 'right', fontFamily: Tmnr.font.mono, color: r.daysToRuling < 30 ? mn.emerald : r.daysToRuling < 50 ? mn.plum : mn.amber, fontWeight: 700 }}>{r.daysToRuling}</td>
                  <td style={{ ...mn.td, fontFamily: Tmnr.font.mono, fontSize: '11px', color: Tmnr.color.text.tertiary }}>{r.rulingDate}</td>
                  <td style={mn.td}><span style={{ ...mn.tag, background: os.bg, color: os.color }}>{r.outcome}</span></td>
                  <td style={{ ...mn.td, color: Tmnr.color.text.secondary, fontSize: '11px', fontStyle: 'italic', maxWidth: '360px', lineHeight: 1.5 }}>{r.oneLineSummary}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
        </div>
      </div>
    </div>
  );
}

function MotionsTemplates({ data }) {
  const mn = window.__mn;
  const { useState } = React;
  const [cat, setCat] = useState('All');
  const cats = ['All', ...new Set(data.templates.map(t => t.category))];
  const filtered = data.templates.filter(t => cat === 'All' || t.category === cat);

  return (
    <div>
      <div style={mn.stripAuto(200)}>
        <div style={mn.stat}><span style={mn.statLabel}>Templates</span><span style={mn.statValue}>{data.templates.length}</span></div>
        <div style={mn.stat}><span style={mn.statLabel}>Total uses YTD</span><span style={mn.statValue}>{data.templates.reduce((s, t) => s + t.usedBy, 0)}</span></div>
        <div style={mn.stat}><span style={mn.statLabel}>Categories</span><span style={mn.statValue}>{cats.length - 1}</span></div>
        <div style={mn.stat}><span style={mn.statLabel}>Most used</span><span style={{ ...mn.statValue, fontSize: '14px', marginTop: '4px' }}>{data.templates.reduce((max, t) => t.usedBy > (max?.usedBy || 0) ? t : max, null)?.name.split(' — ')[0] || '—'}</span></div>
      </div>

      <div style={{ display: 'flex', gap: '6px', marginBottom: '14px', flexWrap: 'wrap' }}>
        {cats.map(c => (
          <button key={c} onClick={() => setCat(c)}
            style={{ padding: '5px 12px', borderRadius: '14px', border: `1px solid ${cat === c ? mn.plum : Tmnr.color.border.light}`, background: cat === c ? mn.plumBg : Tmnr.color.bg.card, color: cat === c ? mn.plum : Tmnr.color.text.secondary, fontSize: '11px', fontWeight: 500, cursor: 'pointer', fontFamily: Tmnr.font.family }}>{c}</button>
        ))}
        <div style={{ flex: 1 }} />
        <button style={mn.btnPrimary}>+ New template</button>
      </div>

      <div style={mn.cardGrid(360)}>
        {filtered.map(t => (
          <div key={t.id} style={{ ...mn.card, marginBottom: 0 }}>
            <div style={{ padding: '14px 16px', borderBottom: `1px solid ${Tmnr.color.border.light}`, background: `linear-gradient(135deg, ${mn.plumBg} 0%, transparent 100%)` }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '4px' }}>
                <span style={{ ...mn.tag, background: mn.plumBg, color: mn.plum }}>{t.category}</span>
              </div>
              <div style={{ fontSize: '14px', fontWeight: 700, color: Tmnr.color.text.primary }}>{t.name}</div>
            </div>
            <div style={{ padding: '14px 16px' }}>
              <div style={{ fontSize: '12px', color: Tmnr.color.text.secondary, lineHeight: 1.55, marginBottom: '12px', minHeight: '44px' }}>{t.description}</div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(min(90px, 100%), 1fr))', gap: '10px', marginBottom: '10px' }}>
                <div>
                  <div style={{ fontSize: '9px', color: Tmnr.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Words</div>
                  <div style={{ fontSize: '13px', fontWeight: 600, color: Tmnr.color.text.primary, fontFamily: Tmnr.font.mono }}>{t.words.toLocaleString()}</div>
                </div>
                <div>
                  <div style={{ fontSize: '9px', color: Tmnr.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Sections</div>
                  <div style={{ fontSize: '13px', fontWeight: 600, color: Tmnr.color.text.primary, fontFamily: Tmnr.font.mono }}>{t.sections}</div>
                </div>
                <div>
                  <div style={{ fontSize: '9px', color: Tmnr.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Used</div>
                  <div style={{ fontSize: '13px', fontWeight: 700, color: mn.plum, fontFamily: Tmnr.font.mono }}>{t.usedBy}×</div>
                </div>
              </div>
              {t.coreCites.length > 0 && (
                <div style={{ marginBottom: '10px' }}>
                  <div style={{ fontSize: '9px', color: Tmnr.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '4px' }}>Core citations</div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: '3px' }}>
                    {t.coreCites.map(c => <span key={c} style={{ ...mn.tag, background: Tmnr.color.bg.secondary, color: Tmnr.color.text.secondary, fontFamily: Tmnr.font.mono }}>{c}</span>)}
                  </div>
                </div>
              )}
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: '10px', borderTop: `1px solid ${Tmnr.color.border.light}` }}>
                <span style={{ fontSize: '10px', color: Tmnr.color.text.tertiary }}>{t.author} · updated {t.updated}</span>
                <button style={mn.btnPrimary}>Use template →</button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function MotionsActivity({ data }) {
  const mn = window.__mn;
  const sev = (s) => s === 'error' ? { bg: mn.crimsonBg, color: mn.crimson }
    : s === 'warn' ? { bg: mn.amberBg, color: mn.amber }
    : { bg: mn.emeraldBg, color: mn.emerald };

  return (
    <div style={mn.card}>
      <div style={mn.cardH}>
        <span>Activity log · {data.activity.length} events</span>
        <button style={mn.btnSecondary}>Export CSV</button>
      </div>
      <div style={mn.tableWrap}>
      <table style={{ ...mn.tableFixed, minWidth: '900px' }}>
        <thead>
          <tr>
            <th style={mn.th}>Time</th>
            <th style={mn.th}>Actor</th>
            <th style={mn.th}>Action</th>
            <th style={mn.th}>Target</th>
            <th style={mn.th}>Severity</th>
          </tr>
        </thead>
        <tbody>
          {data.activity.map(ev => {
            const ss = sev(ev.severity);
            return (
              <tr key={ev.id}>
                <td style={{ ...mn.td, fontFamily: Tmnr.font.mono, color: Tmnr.color.text.tertiary, fontSize: '11px' }}>{ev.time}</td>
                <td style={{ ...mn.td, color: Tmnr.color.text.primary, fontWeight: 500 }}>
                  <span style={{ display: 'inline-block', width: '6px', height: '6px', borderRadius: '50%', background: ss.color, marginRight: '8px' }} />
                  {ev.actor}
                </td>
                <td style={{ ...mn.td, color: Tmnr.color.text.secondary }}>{ev.action}</td>
                <td style={{ ...mn.td, color: Tmnr.color.text.primary, fontWeight: 500, maxWidth: '440px' }}>{ev.target}</td>
                <td style={mn.td}><span style={{ ...mn.tag, background: ss.bg, color: ss.color }}>{ev.severity}</span></td>
              </tr>
            );
          })}
        </tbody>
      </table>
      </div>
    </div>
  );
}

window.MotionsRulings = MotionsRulings;
window.MotionsTemplates = MotionsTemplates;
window.MotionsActivity = MotionsActivity;
