// STUDIO — Sources tab (improvements 13–14: citation manager, opposing counsel exchange)
const { useState: useStSr } = React;
const TspSr = window.ArbiterTokens;

function StudioSources() {
  const st   = window.__st;
  const data = window.STUDIO_DATA;
  const [subTab,    setSubTab]    = useStSr('sources');
  const [expanded,  setExpanded]  = useStSr([]);
  const [citeFilter,setCiteFilter]= useStSr('all');

  const toggleExpand = (id) => setExpanded(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);

  const citeStatusStyle = (s) => ({
    good:    { bg: 'rgba(5,150,105,0.08)',  color: '#059669', label: 'ok Verified'  },
    warning: { bg: 'rgba(180,83,9,0.08)',   color: '#B45309', label: '! Review'    },
    error:   { bg: 'rgba(185,28,28,0.08)',  color: '#B91C1C', label: 'x Problem'   },
  }[s] || { bg: TspSr.color.bg.secondary, color: TspSr.color.text.secondary, label: s });

  const filtCites = citeFilter === 'all'
    ? data.citations
    : data.citations.filter(c => c.status === citeFilter);

  const errCount  = data.citations.filter(c => c.status === 'error').length;
  const warnCount = data.citations.filter(c => c.status === 'warning').length;

  return (
    <div>
      {/* Sub-tab */}
      <div style={{ display: 'flex', gap: '0', borderBottom: `1px solid ${TspSr.color.border.light}`, marginBottom: '16px' }}>
        {[['sources','◈ Source Links'],['citations','◆ Citation Manager'],['opposing','⟐ Opposing Counsel']].map(([id, label]) => (
          <button key={id} onClick={() => setSubTab(id)}
            style={{ padding: '8px 18px', fontSize: '12px', fontWeight: 500, cursor: 'pointer', border: 'none', background: 'transparent', color: subTab === id ? st.gold : TspSr.color.text.secondary, borderBottom: subTab === id ? `2px solid ${st.gold}` : '2px solid transparent', fontFamily: TspSr.font.family, marginBottom: '-1px', position: 'relative' }}>
            {label}
            {id === 'citations' && errCount > 0 && <span style={{ position: 'absolute', top: '6px', right: '6px', width: '6px', height: '6px', borderRadius: '50%', background: '#B91C1C' }} />}
          </button>
        ))}
      </div>

      {/* ── Source Links ──────────────────────────────────────────── */}
      {subTab === 'sources' && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
          {data.sources.map(s => {
            const isOpen = expanded.includes(s.id);
            return (
              <div key={s.id} style={{ background: TspSr.color.bg.card, border: `1px solid ${TspSr.color.border.light}`, borderRadius: TspSr.radius.lg, overflow: 'hidden' }}>
                <div onClick={() => toggleExpand(s.id)} style={{ padding: '12px 16px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '12px', background: isOpen ? `${s.accentBg}` : 'transparent' }}>
                  <div style={{ width: '32px', height: '32px', borderRadius: '8px', background: s.accentBg, border: `1px solid ${s.accent}30`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '14px', color: s.accent, flexShrink: 0 }}>{s.icon}</div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: '12px', fontWeight: 600, color: TspSr.color.text.primary }}>{s.label}</div>
                    <div style={{ fontSize: '10px', color: TspSr.color.text.tertiary, marginTop: '1px' }}>Synced {s.lastSync}</div>
                  </div>
                  <span style={{ ...st.tag, background: 'rgba(5,150,105,0.08)', color: '#059669', fontSize: '10px' }}>{s.status}</span>
                  <span style={{ fontSize: '10px', color: isOpen ? s.accent : TspSr.color.text.tertiary, transition: 'transform 0.15s', display: 'inline-block', transform: isOpen ? 'rotate(90deg)' : 'none' }}>▶</span>
                </div>
                {isOpen && (
                  <div style={{ padding: '4px 16px 14px 60px', display: 'flex', flexDirection: 'column', gap: '6px' }}>
                    {s.items.map((item, i) => (
                      <div key={i} style={{ display: 'flex', alignItems: 'center', gap: '10px', padding: '7px 10px', background: TspSr.color.bg.secondary, borderRadius: '5px', border: `1px solid ${TspSr.color.border.light}` }}>
                        <span style={{ flex: 1, fontSize: '11px', color: TspSr.color.text.primary, lineHeight: 1.4 }}>{item}</span>
                        <button style={{ ...st.btnSecondary, fontSize: '10px', padding: '2px 8px', flexShrink: 0 }}>Insert →</button>
                      </div>
                    ))}
                    <button style={{ ...st.btnSecondary, fontSize: '10px', marginTop: '2px', alignSelf: 'flex-start' }}>Open {s.label} →</button>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}

      {/* ── Citation Manager ──────────────────────────────────────── */}
      {subTab === 'citations' && (
        <div>
          {/* Summary banner */}
          <div style={{ display: 'flex', gap: '8px', marginBottom: '14px', flexWrap: 'wrap', alignItems: 'center' }}>
            <div style={{ display: 'flex', gap: '6px' }}>
              {[['all','All Citations', data.citations.length, TspSr.color.text.secondary],
                ['good','Verified', data.citations.filter(c=>c.status==='good').length, '#059669'],
                ['warning','Review', warnCount, '#B45309'],
                ['error','Problems', errCount, '#B91C1C']].map(([f, label, count, color]) => (
                <button key={f} onClick={() => setCiteFilter(f)}
                  style={{ ...st.btnSecondary, fontSize: '11px', padding: '4px 10px', background: citeFilter === f ? st.goldBg : TspSr.color.bg.card, borderColor: citeFilter === f ? st.gold : TspSr.color.border.light, color: citeFilter === f ? st.gold : color }}>
                  {label} <span style={{ fontWeight: 700, marginLeft: '3px' }}>{count}</span>
                </button>
              ))}
            </div>
            <button style={{ marginLeft: 'auto', ...st.btnPrimary, fontSize: '11px' }}>Verify All</button>
          </div>

          {errCount > 0 && (
            <div style={{ padding: '10px 14px', background: 'rgba(185,28,28,0.06)', border: `1px solid rgba(185,28,28,0.2)`, borderRadius: TspSr.radius.lg, marginBottom: '12px', display: 'flex', alignItems: 'center', gap: '12px' }}>
              <span style={{ fontSize: '14px', color: '#B91C1C' }}><Icons.Flag size={11}/></span>
              <div style={{ flex: 1, fontSize: '11px', color: '#B91C1C', fontWeight: 600 }}>{errCount} citation{errCount > 1 ? 's' : ''} require attention — overruled or bad law detected</div>
              <button style={{ ...st.btnSecondary, fontSize: '11px', borderColor: 'rgba(185,28,28,0.3)', color: '#B91C1C' }}>Review All Issues</button>
            </div>
          )}

          <div style={st.card}>
            <div style={{ display: 'grid', gridTemplateColumns: '3fr 1.4fr 0.5fr 0.8fr', borderBottom: `1px solid ${TspSr.color.border.light}` }}>
              {['Citation (Bluebook)', 'Status', 'Uses', 'Actions'].map(h => <div key={h} style={st.th}>{h}</div>)}
            </div>
            {filtCites.map((c, i) => {
              const ss = citeStatusStyle(c.status);
              return (
                <div key={c.id} style={{ display: 'grid', gridTemplateColumns: '3fr 1.4fr 0.5fr 0.8fr', background: c.status === 'error' ? 'rgba(185,28,28,0.03)' : i % 2 === 0 ? 'transparent' : TspSr.color.bg.secondary }}>
                  <div style={{ ...st.td, flexDirection: 'column', alignItems: 'flex-start', gap: '2px' }}>
                    <div style={{ fontSize: '11px', fontFamily: '"Georgia", serif', color: TspSr.color.text.primary, lineHeight: 1.4 }}>{c.bluebook}</div>
                    {c.issue && <div style={{ fontSize: '10px', color: c.status === 'error' ? '#B91C1C' : '#B45309', marginTop: '2px', fontWeight: 500 }}>! {c.issue}</div>}
                  </div>
                  <div style={st.td}><span style={{ ...st.tag, background: ss.bg, color: ss.color }}>{ss.label}</span></div>
                  <div style={{ ...st.td, fontSize: '11px', color: TspSr.color.text.secondary }}>{c.uses}×</div>
                  <div style={{ ...st.td, gap: '4px' }}>
                    <button style={{ ...st.btnGhost, fontSize: '10px', padding: '2px 7px' }}>Verify</button>
                    {c.status === 'error' && <button style={{ ...st.btnSecondary, fontSize: '10px', padding: '2px 7px', color: '#B91C1C', borderColor: 'rgba(185,28,28,0.3)' }}>Fix</button>}
                    {c.status !== 'error' && <button style={{ ...st.btnGhost, fontSize: '10px', padding: '2px 7px' }}>Insert</button>}
                  </div>
                </div>
              );
            })}
          </div>

          <div style={{ display: 'flex', gap: '8px', marginTop: '10px' }}>
            <button style={{ ...st.btnSecondary, fontSize: '11px' }}>+ Add Citation</button>
            <button style={{ ...st.btnSecondary, fontSize: '11px' }}>Import from Research</button>
            <button style={{ ...st.btnSecondary, fontSize: '11px', marginLeft: 'auto' }}>Export Citation List</button>
          </div>
        </div>
      )}

      {/* ── Opposing Counsel Exchange ─────────────────────────────── */}
      {subTab === 'opposing' && (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 280px', gap: '16px', alignItems: 'start' }}>
          <div>
            <div style={{ fontSize: '11px', fontWeight: 600, color: TspSr.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.07em', marginBottom: '7px' }}>Received from Opposing Counsel ({data.opposingDocs.length})</div>
            <div style={st.card}>
              <div style={{ display: 'grid', gridTemplateColumns: '2.5fr 1.4fr 0.8fr 0.5fr 0.7fr 1fr', borderBottom: `1px solid ${TspSr.color.border.light}` }}>
                {['Document', 'From', 'Received', 'Pages', 'Status', 'Action'].map(h => <div key={h} style={st.th}>{h}</div>)}
              </div>
              {data.opposingDocs.map((d, i) => (
                <div key={d.id} style={{ display: 'grid', gridTemplateColumns: '2.5fr 1.4fr 0.8fr 0.5fr 0.7fr 1fr', background: i % 2 === 0 ? 'transparent' : TspSr.color.bg.secondary }}>
                  <div style={{ ...st.td, flexDirection: 'column', alignItems: 'flex-start', gap: '1px' }}>
                    <div style={{ fontWeight: 600, fontSize: '12px', color: TspSr.color.text.primary }}>{d.title}</div>
                    {d.redlines > 0 && <div style={{ fontSize: '10px', color: '#B91C1C', fontWeight: 600 }}>◉ {d.redlines} redlines</div>}
                  </div>
                  <div style={{ ...st.td, fontSize: '10px', color: TspSr.color.text.secondary }}>{d.from}</div>
                  <div style={{ ...st.td, fontSize: '11px', color: TspSr.color.text.secondary }}>{d.received}</div>
                  <div style={{ ...st.td, fontSize: '11px' }}>{d.pages}p</div>
                  <div style={st.td}>
                    <span style={{ ...st.tag, ...(d.status === 'Reviewed' ? { background: 'rgba(5,150,105,0.08)', color: '#059669' } : { background: 'rgba(180,83,9,0.08)', color: '#B45309' }) }}>
                      {d.status}
                    </span>
                  </div>
                  <div style={st.td}>
                    {d.redlines > 0
                      ? <button style={{ ...st.btnPrimary, fontSize: '10px', padding: '3px 8px' }}>Compare →</button>
                      : <span style={{ fontSize: '10px', color: TspSr.color.text.tertiary, fontStyle: 'italic' }}>{d.action}</span>
                    }
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Right: send panel */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
            <div style={st.card}>
              <div style={st.cardH}><span>Send to Opposing Counsel</span></div>
              <div style={{ padding: '12px 16px', display: 'flex', flexDirection: 'column', gap: '8px' }}>
                <div style={{ fontSize: '11px', color: TspSr.color.text.secondary, marginBottom: '2px' }}>Select document(s) and transmit securely</div>
                <select style={{ width: '100%', padding: '6px 10px', borderRadius: '5px', border: `1px solid ${TspSr.color.border.light}`, background: TspSr.color.bg.secondary, fontSize: '11px', color: TspSr.color.text.primary, fontFamily: TspSr.font.family }}>
                  <option>Motion to Compel — Meridian Oil Corp</option>
                  <option>Reply Brief — Summary Judgment</option>
                  <option>Expert Witness Declaration</option>
                </select>
                <select style={{ width: '100%', padding: '6px 10px', borderRadius: '5px', border: `1px solid ${TspSr.color.border.light}`, background: TspSr.color.bg.secondary, fontSize: '11px', color: TspSr.color.text.primary, fontFamily: TspSr.font.family }}>
                  <option>Davis & Marsh LLP (Coastal Energy)</option>
                  <option>Henderson & Park LLP</option>
                  <option>Other counsel…</option>
                </select>
                <div style={{ display: 'flex', gap: '5px', flexWrap: 'wrap' }}>
                  {['With redlines','Clean copy','With exhibits'].map(opt => (
                    <label key={opt} style={{ display: 'flex', alignItems: 'center', gap: '4px', fontSize: '10px', color: TspSr.color.text.secondary, cursor: 'pointer' }}>
                      <input type="checkbox" style={{ cursor: 'pointer' }} /> {opt}
                    </label>
                  ))}
                </div>
                <button style={{ ...st.btnPrimary, fontSize: '11px' }}>Send Securely →</button>
              </div>
            </div>
            <div style={st.card}>
              <div style={st.cardH}><span>Exchange Log</span></div>
              <div style={{ padding: '10px 16px' }}>
                {[
                  { dir: '↑', label: 'Sent Opposition Response',      time: 'Apr 20', color: st.cobalt },
                  { dir: '↓', label: 'Received Proposed Protective Order', time: 'Apr 17', color: st.emerald },
                  { dir: '↓', label: 'Received Rule 26(f) Draft',     time: 'Apr 14', color: st.emerald },
                  { dir: '↑', label: 'Sent Interrogatories Set One',   time: 'Apr 12', color: st.cobalt },
                ].map((ev, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '8px', paddingBottom: '8px', borderBottom: `1px solid ${TspSr.color.border.light}` }}>
                    <span style={{ fontSize: '11px', fontWeight: 700, color: ev.color, width: '12px', textAlign: 'center' }}>{ev.dir}</span>
                    <span style={{ flex: 1, fontSize: '10px', color: TspSr.color.text.secondary }}>{ev.label}</span>
                    <span style={{ fontSize: '10px', color: TspSr.color.text.tertiary }}>{ev.time}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

window.StudioSources = StudioSources;
