// MOTIONS PLATFORM — Drafting + Brief Bank
const { useState: useMnDrState, useMemo: useMnDrMemo } = React;
const Tmndr = window.ArbiterTokens;

function MotionsDrafting({ data }) {
  const mn = window.__mn;

  const sectionStatusColor = (s) => ({
    complete:       { bg: 'rgba(5,150,105,0.08)',  color: '#059669' },
    drafting:       { bg: 'rgba(180,83,9,0.08)',   color: '#B45309' },
    outlined:       { bg: 'rgba(29,78,216,0.08)',  color: '#1D4ED8' },
    'not-started':  { bg: Tmndr.color.bg.secondary, color: Tmndr.color.text.tertiary },
  }[s] || { bg: Tmndr.color.bg.secondary, color: Tmndr.color.text.secondary });

  return (
    <div>
      <div style={mn.stripAuto(200)}>
        <div style={mn.stat}><span style={mn.statLabel}>Active drafts</span><span style={mn.statValue}>{data.drafts.length}</span></div>
        <div style={mn.stat}><span style={mn.statLabel}>Total sections</span><span style={mn.statValue}>{data.drafts.reduce((s, d) => s + d.sections.length, 0)}</span></div>
        <div style={mn.stat}><span style={mn.statLabel}>Sections complete</span><span style={{ ...mn.statValue, color: mn.emerald }}>{data.drafts.reduce((s, d) => s + d.sections.filter(x => x.status === 'complete').length, 0)}</span></div>
        <div style={mn.stat}><span style={mn.statLabel}>Avg draft progress</span><span style={mn.statValue}>{Math.round(data.drafts.reduce((s, d) => s + d.sections.reduce((a, b) => a + (b.words / b.target), 0) / d.sections.length * 100, 0) / data.drafts.length)}%</span></div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: '14px' }}>
        {data.drafts.map(d => {
          const motion = data.motions.find(m => m.id === d.motionId);
          const ts = motion ? mn.typeStyle(motion.type) : { bg: mn.plumBg, color: mn.plum, icon: '◆' };
          const totalWords = d.sections.reduce((s, sec) => s + sec.words, 0);
          const totalTarget = d.sections.reduce((s, sec) => s + sec.target, 0);
          const progressPct = (totalWords / totalTarget) * 100;
          const completePct = d.sections.filter(s => s.status === 'complete').length / d.sections.length * 100;

          return (
            <div key={d.motionId} style={mn.card}>
              {/* Header */}
              <div style={{ padding: '14px 16px', borderBottom: `1px solid ${Tmndr.color.border.light}` }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '6px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                    <span style={{ ...mn.tag, background: ts.bg, color: ts.color, fontSize: '11px', padding: '3px 10px' }}>{ts.icon} {motion?.kind || 'Motion'}</span>
                    <span style={{ fontSize: '14px', fontWeight: 700, color: Tmndr.color.text.primary }}>{d.caption}</span>
                  </div>
                  <div style={{ display: 'flex', gap: '10px' }}>
                    <span style={{ ...mn.tag, background: mn.plumBg, color: mn.plum }}>{d.motionId}</span>
                    <span style={{ fontSize: '11px', color: Tmndr.color.text.tertiary }}>by {d.author} · updated {d.lastEdit}</span>
                  </div>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: '14px', flexWrap: 'wrap', rowGap: '10px' }}>
                  <div style={{ flex: '1 1 240px', minWidth: 0 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '10px', color: Tmndr.color.text.tertiary, marginBottom: '4px' }}>
                      <span>Word count</span>
                      <span style={{ fontFamily: Tmndr.font.mono }}>{totalWords.toLocaleString()} / {totalTarget.toLocaleString()} · {progressPct.toFixed(0)}%</span>
                    </div>
                    <div style={{ height: '6px', background: Tmndr.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                      <div style={{ width: `${Math.min(100, progressPct)}%`, height: '100%', background: progressPct >= 90 ? mn.emerald : progressPct >= 60 ? mn.plum : mn.amber }} />
                    </div>
                  </div>
                  <div style={{ flex: '1 1 240px', minWidth: 0 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '10px', color: Tmndr.color.text.tertiary, marginBottom: '4px' }}>
                      <span>Sections complete</span>
                      <span style={{ fontFamily: Tmndr.font.mono }}>{d.sections.filter(s => s.status === 'complete').length} / {d.sections.length} · {completePct.toFixed(0)}%</span>
                    </div>
                    <div style={{ height: '6px', background: Tmndr.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                      <div style={{ width: `${completePct}%`, height: '100%', background: mn.plum }} />
                    </div>
                  </div>
                </div>
              </div>

              {/* Section list */}
              <div>
                {d.sections.map((s, i) => {
                  const ssc = sectionStatusColor(s.status);
                  const pct = Math.round((s.words / s.target) * 100);
                  return (
                    <div key={s.id} style={{ padding: '10px 16px', borderBottom: i < d.sections.length - 1 ? `1px solid ${Tmndr.color.border.light}` : 'none' }}>
                      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '4px' }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flex: 1, minWidth: 0 }}>
                          <span style={{ fontFamily: Tmndr.font.mono, fontSize: '10px', color: Tmndr.color.text.tertiary, minWidth: '22px' }}>{s.id}</span>
                          <span style={{ fontSize: '12px', fontWeight: 600, color: Tmndr.color.text.primary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.title}</span>
                        </div>
                        <div style={{ display: 'flex', gap: '6px', alignItems: 'center' }}>
                          <span style={{ ...mn.tag, background: ssc.bg, color: ssc.color }}>{s.status}</span>
                          <span style={{ ...mn.tag, background: mn.plumBg, color: mn.plum }}>{s.cites} cites</span>
                        </div>
                      </div>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                        <div style={{ flex: 1, height: '4px', background: Tmndr.color.border.light, borderRadius: '2px', overflow: 'hidden' }}>
                          <div style={{ width: `${Math.min(100, pct)}%`, height: '100%', background: pct >= 95 ? mn.emerald : pct >= 50 ? mn.plum : mn.amber }} />
                        </div>
                        <span style={{ fontFamily: Tmndr.font.mono, fontSize: '10px', color: Tmndr.color.text.tertiary, minWidth: '100px', textAlign: 'right' }}>{s.words.toLocaleString()} / {s.target.toLocaleString()}</span>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function MotionsBriefBank({ data }) {
  const mn = window.__mn;
  const [catFilter, setCatFilter] = useMnDrState('All');
  const [search, setSearch] = useMnDrState('');

  const categories = useMnDrMemo(() => ['All', ...new Set(data.briefBank.map(b => b.category))], [data]);
  const filtered = data.briefBank.filter(b =>
    (catFilter === 'All' || b.category === catFilter) &&
    (!search || b.title.toLowerCase().includes(search.toLowerCase()) || b.tags.some(t => t.toLowerCase().includes(search.toLowerCase())))
  );

  return (
    <div>
      <div style={mn.stripAuto(200)}>
        <div style={mn.stat}><span style={mn.statLabel}>Brief bank</span><span style={mn.statValue}>{data.briefBank.length}</span><span style={{ ...mn.statDelta, color: Tmndr.color.text.tertiary }}>prior-winning briefs</span></div>
        <div style={mn.stat}><span style={mn.statLabel}>Total cites cataloged</span><span style={{ ...mn.statValue, color: mn.plum }}>{data.briefBank.reduce((s, b) => s + b.cites, 0)}</span></div>
        <div style={mn.stat}><span style={mn.statLabel}>Categories</span><span style={mn.statValue}>{categories.length - 1}</span></div>
        <div style={mn.stat}><span style={mn.statLabel}>Avg cites / brief</span><span style={mn.statValue}>{Math.round(data.briefBank.reduce((s, b) => s + b.cites, 0) / data.briefBank.length)}</span></div>
      </div>

      <div style={{ display: 'flex', gap: '8px', marginBottom: '14px', alignItems: 'center', flexWrap: 'wrap', rowGap: '8px' }}>
        <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search by title or tag…"
          style={{ padding: '4px 10px', fontSize: '11px', border: `1px solid ${Tmndr.color.border.light}`, borderRadius: '5px', background: Tmndr.color.bg.card, color: Tmndr.color.text.primary, flex: '1 1 220px', minWidth: '180px', maxWidth: '320px', height: '32px', fontFamily: Tmndr.font.family }} />
        <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
          {categories.map(c => (
            <button key={c} onClick={() => setCatFilter(c)}
              style={{ padding: '4px 10px', borderRadius: '12px', border: `1px solid ${catFilter === c ? mn.plum : Tmndr.color.border.light}`, background: catFilter === c ? mn.plumBg : Tmndr.color.bg.card, color: catFilter === c ? mn.plum : Tmndr.color.text.secondary, fontSize: '11px', fontWeight: 500, cursor: 'pointer', fontFamily: Tmndr.font.family }}>{c}</button>
          ))}
        </div>
        <div style={{ flex: 1 }} />
        <span style={{ fontSize: '11px', color: Tmndr.color.text.tertiary }}>{filtered.length} of {data.briefBank.length}</span>
      </div>

      <div style={mn.cardGrid(400)}>
        {filtered.map(b => (
          <div key={b.id} style={{ ...mn.card, marginBottom: 0 }}>
            <div style={{ padding: '12px 14px', borderBottom: `1px solid ${Tmndr.color.border.light}`, background: `linear-gradient(135deg, ${mn.plumBg} 0%, transparent 100%)` }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '6px' }}>
                <span style={{ ...mn.tag, background: mn.plumBg, color: mn.plum, fontSize: '10px', padding: '3px 10px' }}>{b.category}</span>
                <span style={{ fontSize: '10px', fontFamily: Tmndr.font.mono, color: Tmndr.color.text.tertiary }}>{b.id}</span>
              </div>
              <div style={{ fontSize: '13px', fontWeight: 700, color: Tmndr.color.text.primary }}>{b.title}</div>
              <div style={{ fontSize: '10px', color: Tmndr.color.text.tertiary, marginTop: '2px' }}>{b.type} · from {b.matterOrigin}</div>
            </div>
            <div style={{ padding: '12px 14px' }}>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(min(90px, 100%), 1fr))', gap: '8px', marginBottom: '10px' }}>
                <div>
                  <div style={{ fontSize: '9px', color: Tmndr.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Prior wins</div>
                  <div style={{ fontSize: '13px', fontWeight: 700, color: mn.emerald, fontFamily: Tmndr.font.mono }}>{b.winRate}</div>
                </div>
                <div>
                  <div style={{ fontSize: '9px', color: Tmndr.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Pages</div>
                  <div style={{ fontSize: '13px', fontWeight: 700, color: Tmndr.color.text.primary, fontFamily: Tmndr.font.mono }}>{b.pages}</div>
                </div>
                <div>
                  <div style={{ fontSize: '9px', color: Tmndr.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Cites</div>
                  <div style={{ fontSize: '13px', fontWeight: 700, color: mn.plum, fontFamily: Tmndr.font.mono }}>{b.cites}</div>
                </div>
              </div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px', marginBottom: '10px' }}>
                {b.tags.map(t => <span key={t} style={{ ...mn.tag, background: Tmndr.color.bg.secondary, color: Tmndr.color.text.secondary }}>#{t}</span>)}
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: '10px', borderTop: `1px solid ${Tmndr.color.border.light}` }}>
                <span style={{ fontSize: '10px', color: Tmndr.color.text.tertiary }}>{b.author} · updated {b.lastUpdated}</span>
                <button style={mn.btnGhost}>Import →</button>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

window.MotionsDrafting = MotionsDrafting;
window.MotionsBriefBank = MotionsBriefBank;
