// MOTIONS PLATFORM — Dashboard + Motion Queue
const { useState: useMnDashState, useMemo: useMnDashMemo } = React;
const Tmnd = window.ArbiterTokens;

function MotionsDashboard({ data }) {
  const mn = window.__mn;
  const k = data.kpis;
  const trend = data.analytics.monthlyTrend;
  const maxT = Math.max(...trend.map(t => t.filed));

  // Stage pipeline
  const stages = [
    { name: 'Drafting',        count: k.drafting,         color: mn.slate },
    { name: 'Partner Review',  count: k.partnerReview,    color: mn.violet },
    { name: 'Filed',           count: k.filed,            color: mn.cobalt },
    { name: 'Under Submission',count: k.underSubmission,  color: mn.plum },
  ];

  // Top 5 upcoming deadlines
  const upcoming = [...data.calendar].sort((a, b) => a.date.localeCompare(b.date)).slice(0, 5);

  const urgencyColor = (u) => u === 'critical' ? mn.crimson : u === 'high' ? mn.orange : u === 'medium' ? mn.amber : Tmnd.color.text.tertiary;

  return (
    <div>
      {/* KPI strip */}
      <div style={mn.stripKpi}>
        <div style={mn.stat}><span style={mn.statLabel}>Active motions</span><span style={mn.statValue}>{k.activeMotions}</span><span style={{ ...mn.statDelta, color: Tmnd.color.text.tertiary }}>across all matters</span></div>
        <div style={mn.stat}><span style={mn.statLabel}>Win rate (YTD)</span><span style={{ ...mn.statValue, color: mn.winColor(k.avgWinRate) }}>{k.avgWinRate}%</span><span style={{ ...mn.statDelta, color: Tmnd.color.text.tertiary }}>{k.grantedYtd} granted · {k.grantedInPartYtd} partial</span></div>
        <div style={mn.stat}><span style={mn.statLabel}>Due this week</span><span style={{ ...mn.statValue, color: mn.crimson }}>{k.dueThisWeek}</span><span style={{ ...mn.statDelta, color: Tmnd.color.text.tertiary }}>{k.dueNext30} in next 30 days</span></div>
        <div style={mn.stat}><span style={mn.statLabel}>Oral args ≤ 14 days</span><span style={{ ...mn.statValue, color: mn.plum }}>{k.oralArgsNext14}</span></div>
        <div style={mn.stat}><span style={mn.statLabel}>Brief bank</span><span style={{ ...mn.statValue, color: mn.violet }}>{k.briefBankEntries}</span><span style={{ ...mn.statDelta, color: Tmnd.color.text.tertiary }}>{k.templatesActive} templates</span></div>
        <div style={mn.stat}><span style={mn.statLabel}>Avg days to ruling</span><span style={mn.statValue}>{k.avgDaysToRuling}</span><span style={{ ...mn.statDelta, color: Tmnd.color.text.tertiary }}>{k.rulingsReceivedYtd} rulings YTD</span></div>
      </div>

      {/* Stage pipeline */}
      <div style={mn.card}>
        <div style={mn.cardH}>Motion pipeline — current state</div>
        <div style={{ padding: '14px 16px', display: 'flex', gap: '8px' }}>
          {stages.map((s, i) => (
            <div key={s.name} style={{ flex: 1, position: 'relative' }}>
              <div style={{ padding: '10px 12px', background: `${s.color}12`, border: `1px solid ${s.color}22`, borderRadius: '6px', textAlign: 'center' }}>
                <div style={{ fontSize: '9px', fontWeight: 700, color: s.color, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '3px' }}>{s.name}</div>
                <div style={{ fontSize: '22px', fontWeight: 700, color: s.color, fontFamily: Tmnd.font.mono }}>{s.count}</div>
              </div>
              {i < stages.length - 1 && (
                <div style={{ position: 'absolute', right: '-4px', top: '50%', transform: 'translateY(-50%)', color: Tmnd.color.text.tertiary, fontSize: '10px' }}>›</div>
              )}
            </div>
          ))}
        </div>
      </div>

      <div style={{ ...mn.split(360), marginBottom: 'clamp(12px, 1vw + 6px, 18px)' }}>
        {/* 12-month trend */}
        <div style={mn.card}>
          <div style={mn.cardH}>
            <span>12-month motion filings &amp; rulings</span>
            <div style={{ display: 'flex', gap: '12px', fontSize: '10px' }}>
              <span style={{ color: mn.slate }}>■ Filed</span>
              <span style={{ color: mn.plum }}>■ Granted</span>
            </div>
          </div>
          <div style={{ padding: '18px 16px 14px', display: 'flex', gap: '8px', alignItems: 'flex-end', height: '160px' }}>
            {trend.map((t, i) => (
              <div key={t.m} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '3px' }}>
                <div style={{ display: 'flex', gap: '2px', alignItems: 'flex-end', height: '120px', width: '100%', justifyContent: 'center' }}>
                  <div style={{ width: '40%', height: `${(t.filed / maxT) * 100}%`, background: mn.slate, opacity: 0.6, borderRadius: '2px 2px 0 0' }} />
                  <div style={{ width: '40%', height: `${(t.granted / maxT) * 100}%`, background: mn.plum, borderRadius: '2px 2px 0 0' }} />
                </div>
                <span style={{ fontSize: '9px', color: Tmnd.color.text.tertiary, fontFamily: Tmnd.font.mono }}>{t.m}</span>
              </div>
            ))}
          </div>
        </div>

        {/* Upcoming deadlines */}
        <div style={mn.card}>
          <div style={{ ...mn.cardH, color: mn.crimson }}>! Upcoming deadlines</div>
          <div>
            {upcoming.map(c => {
              const uc = urgencyColor(c.urgency);
              return (
                <div key={c.motionId + c.date} style={{ padding: '10px 16px', borderBottom: `1px solid ${Tmnd.color.border.light}`, borderLeft: `3px solid ${uc}` }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '3px' }}>
                    <span style={{ fontSize: '11px', fontFamily: Tmnd.font.mono, color: uc, fontWeight: 700 }}>{c.date}</span>
                    <span style={{ ...mn.tag, background: `${uc}18`, color: uc }}>{c.type}</span>
                  </div>
                  <div style={{ fontSize: '12px', fontWeight: 600, color: Tmnd.color.text.primary }}>{c.caption}</div>
                  <div style={{ fontSize: '10px', color: Tmnd.color.text.tertiary, marginTop: '2px' }}>{c.matter} · {c.motionId}</div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* Win rate by type */}
      <div style={mn.card}>
        <div style={mn.cardH}>Win rate by motion type — YTD</div>
        <div style={mn.tableWrap}>
        <table style={mn.tableFixed}>
          <thead>
            <tr>
              <th style={mn.th}>Type</th>
              <th style={{ ...mn.th, textAlign: 'right' }}>Filed</th>
              <th style={{ ...mn.th, textAlign: 'right' }}>Granted</th>
              <th style={{ ...mn.th, textAlign: 'right' }}>Partial</th>
              <th style={{ ...mn.th, textAlign: 'right' }}>Denied</th>
              <th style={mn.th}>Win rate</th>
            </tr>
          </thead>
          <tbody>
            {data.analytics.winRateByType.slice(0, 8).map(r => {
              const ts = mn.typeStyle(r.type);
              return (
                <tr key={r.type}>
                  <td style={mn.td}><span style={{ ...mn.tag, background: ts.bg, color: ts.color }}>{ts.icon} {r.type}</span></td>
                  <td style={{ ...mn.td, textAlign: 'right', fontFamily: Tmnd.font.mono, fontWeight: 600 }}>{r.filed}</td>
                  <td style={{ ...mn.td, textAlign: 'right', fontFamily: Tmnd.font.mono, color: mn.emerald, fontWeight: 700 }}>{r.granted}</td>
                  <td style={{ ...mn.td, textAlign: 'right', fontFamily: Tmnd.font.mono, color: mn.teal }}>{r.partial}</td>
                  <td style={{ ...mn.td, textAlign: 'right', fontFamily: Tmnd.font.mono, color: mn.crimson }}>{r.denied}</td>
                  <td style={mn.td}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                      <div style={{ width: '120px', height: '6px', background: Tmnd.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                        <div style={{ width: `${r.winRate}%`, height: '100%', background: mn.winColor(r.winRate) }} />
                      </div>
                      <span style={{ fontFamily: Tmnd.font.mono, color: mn.winColor(r.winRate), fontWeight: 700 }}>{r.winRate}%</span>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        </div>
      </div>
    </div>
  );
}

function MotionsQueue({ data }) {
  const mn = window.__mn;
  const [statusFilter, setStatusFilter] = useMnDashState('All');
  const [matterFilter, setMatterFilter] = useMnDashState('All');
  const [search, setSearch] = useMnDashState('');

  const statuses = useMnDashMemo(() => ['All', ...new Set(data.motions.map(m => m.status))], [data]);
  const matters = useMnDashMemo(() => ['All', ...new Set(data.motions.map(m => m.matter))], [data]);

  const filtered = data.motions.filter(m =>
    (statusFilter === 'All' || m.status === statusFilter) &&
    (matterFilter === 'All' || m.matter === matterFilter) &&
    (!search || m.captionShort.toLowerCase().includes(search.toLowerCase()) || m.type.toLowerCase().includes(search.toLowerCase()))
  );

  return (
    <div>
      <div style={mn.stripKpi}>
        <div style={mn.stat}><span style={mn.statLabel}>Motions shown</span><span style={mn.statValue}>{filtered.length}</span><span style={{ ...mn.statDelta, color: Tmnd.color.text.tertiary }}>of {data.motions.length} active</span></div>
        <div style={mn.stat}><span style={mn.statLabel}>Under submission</span><span style={{ ...mn.statValue, color: mn.plum }}>{data.motions.filter(m => m.status === 'Under Submission' || m.status === 'Awaiting Argument').length}</span></div>
        <div style={mn.stat}><span style={mn.statLabel}>Fully briefed</span><span style={{ ...mn.statValue, color: mn.plum }}>{data.motions.filter(m => m.status === 'Fully Briefed').length}</span></div>
        <div style={mn.stat}><span style={mn.statLabel}>Opposition pending</span><span style={{ ...mn.statValue, color: mn.orange }}>{data.motions.filter(m => m.status === 'Opposition Pending').length}</span></div>
        <div style={mn.stat}><span style={mn.statLabel}>Drafting</span><span style={{ ...mn.statValue, color: mn.slate }}>{data.motions.filter(m => m.status === 'Drafting').length}</span></div>
      </div>

      <div style={mn.card}>
        <div style={mn.cardH}>
          <span>Motion queue — {filtered.length}</span>
          <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap', rowGap: '6px' }}>
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search caption / type…"
              style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tmnd.color.border.light}`, borderRadius: '5px', background: Tmnd.color.bg.card, color: Tmnd.color.text.primary, flex: '1 1 180px', minWidth: '160px', maxWidth: '260px', fontFamily: Tmnd.font.family }} />
            <select value={statusFilter} onChange={e => setStatusFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tmnd.color.border.light}`, borderRadius: '5px', background: Tmnd.color.bg.card, color: Tmnd.color.text.secondary }}>
              {statuses.map(s => <option key={s} value={s}>Status: {s}</option>)}
            </select>
            <select value={matterFilter} onChange={e => setMatterFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tmnd.color.border.light}`, borderRadius: '5px', background: Tmnd.color.bg.card, color: Tmnd.color.text.secondary }}>
              {matters.map(m => <option key={m} value={m}>Matter: {m === 'All' ? 'All' : m.length > 22 ? m.slice(0, 20) + '…' : m}</option>)}
            </select>
            <button style={mn.btnPrimary}>+ New motion</button>
          </div>
        </div>
        <div style={mn.tableWrap}>
        <table style={{ ...mn.tableFixed, minWidth: '1280px' }}>
          <thead>
            <tr>
              <th style={mn.th}>ID</th>
              <th style={mn.th}>Type</th>
              <th style={mn.th}>Caption</th>
              <th style={mn.th}>Matter</th>
              <th style={mn.th}>Court / Judge</th>
              <th style={mn.th}>Author</th>
              <th style={mn.th}>Hearing</th>
              <th style={{ ...mn.th, textAlign: 'right' }}>Pages</th>
              <th style={{ ...mn.th, textAlign: 'right' }}>Cites</th>
              <th style={mn.th}>Status</th>
              <th style={mn.th}>Expected outcome</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(m => {
              const ss = mn.statusColor(m.status);
              const ts = mn.typeStyle(m.type);
              return (
                <tr key={m.id}>
                  <td style={{ ...mn.td, fontFamily: Tmnd.font.mono, color: mn.plum, fontWeight: 700 }}>{m.id}</td>
                  <td style={mn.td}><span style={{ ...mn.tag, background: ts.bg, color: ts.color }}>{ts.icon} {m.kind}</span></td>
                  <td style={{ ...mn.td, fontWeight: 600, color: Tmnd.color.text.primary, maxWidth: '220px' }}>
                    {m.captionShort}
                    <div style={{ fontSize: '10px', color: Tmnd.color.text.tertiary, marginTop: '2px' }}>{m.type}</div>
                  </td>
                  <td style={{ ...mn.td, color: Tmnd.color.text.secondary, fontSize: '11px', maxWidth: '180px' }}>{m.matter}</td>
                  <td style={{ ...mn.td, color: Tmnd.color.text.secondary, fontSize: '11px' }}>
                    {m.court}
                    <div style={{ fontSize: '10px', color: Tmnd.color.text.tertiary }}>{m.judge}</div>
                  </td>
                  <td style={{ ...mn.td, color: Tmnd.color.text.secondary, fontSize: '11px' }}>{m.author}</td>
                  <td style={{ ...mn.td, fontFamily: Tmnd.font.mono, fontSize: '11px', color: mn.amber }}>{m.hearingDate || '—'}</td>
                  <td style={{ ...mn.td, textAlign: 'right', fontFamily: Tmnd.font.mono, color: Tmnd.color.text.primary }}>{m.pages || '—'}</td>
                  <td style={{ ...mn.td, textAlign: 'right', fontFamily: Tmnd.font.mono, color: mn.plum, fontWeight: 700 }}>{m.cites}</td>
                  <td style={mn.td}><span style={{ ...mn.tag, background: ss.bg, color: ss.color }}>{m.status}</span></td>
                  <td style={{ ...mn.td, fontSize: '10px', color: Tmnd.color.text.secondary, fontStyle: 'italic' }}>{m.expectedOutcome}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
        </div>
      </div>
    </div>
  );
}

window.MotionsDashboard = MotionsDashboard;
window.MotionsQueue = MotionsQueue;
