// STUDIO — Drafts tab (improvements 9–10: matter workspace view, bulk operations)
const { useState: useStDr } = React;
const TspDr = window.ArbiterTokens;

function StudioDrafts() {
  const st   = window.__st;
  const data = window.STUDIO_DATA;
  const [view,      setView]      = useStDr('list');
  const [filter,    setFilter]    = useStDr('All');
  const [selected,  setSelected]  = useStDr([]);
  const [expanded,  setExpanded]  = useStDr(['meridian', 'technova']);

  const statuses = ['All', 'Draft', 'In Review', 'Approved', 'Pending', 'Signed', 'Published'];
  const filtered = filter === 'All' ? data.drafts : data.drafts.filter(d => d.status === filter);

  const toggleSelect = (id) => setSelected(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
  const toggleAll    = ()   => setSelected(selected.length === filtered.length ? [] : filtered.map(d => d.id));
  const toggleFolder = (id) => setExpanded(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);

  const bulkActions = ['Assign reviewer', 'Change status', 'Publish batch', 'Archive selected', 'Generate review package'];

  return (
    <div>
      {/* Toolbar */}
      <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '14px', flexWrap: 'wrap' }}>
        {/* View toggle */}
        <div style={{ display: 'flex', background: TspDr.color.bg.secondary, borderRadius: '6px', padding: '2px', border: `1px solid ${TspDr.color.border.light}` }}>
          {[['list', '≡ List'], ['workspace', '◰ Workspace']].map(([v, label]) => (
            <button key={v} onClick={() => setView(v)}
              style={{ padding: '4px 12px', fontSize: '11px', fontWeight: 500, borderRadius: '4px', border: 'none', cursor: 'pointer', fontFamily: TspDr.font.family, background: view === v ? TspDr.color.bg.card : 'transparent', color: view === v ? st.gold : TspDr.color.text.secondary, boxShadow: view === v ? '0 1px 3px rgba(0,0,0,0.08)' : 'none', transition: 'all 0.12s' }}>
              {label}
            </button>
          ))}
        </div>

        {view === 'list' && (
          <div style={{ display: 'flex', gap: '5px', flexWrap: 'wrap' }}>
            {statuses.map(s => (
              <button key={s} onClick={() => setFilter(s)}
                style={{ ...st.btnSecondary, background: filter === s ? st.goldBg : TspDr.color.bg.card, color: filter === s ? st.gold : TspDr.color.text.secondary, borderColor: filter === s ? st.gold : TspDr.color.border.light, fontSize: '11px', padding: '4px 10px' }}>
                {s}
              </button>
            ))}
          </div>
        )}
        <div style={{ marginLeft: 'auto', display: 'flex', gap: '6px' }}>
          <button style={st.btnSecondary}>↑ Import</button>
          <button style={st.btnPrimary}>+ New Draft</button>
        </div>
      </div>

      {/* ── List view ─────────────────────────────────────────────── */}
      {view === 'list' && (
        <div>
          <div style={st.card}>
            {/* Table header */}
            <div style={{ display: 'grid', gridTemplateColumns: '32px 2.2fr 1.5fr 0.9fr 0.9fr 0.8fr 0.8fr 0.75fr', borderBottom: `1px solid ${TspDr.color.border.light}` }}>
              <div style={{ ...st.th, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <input type="checkbox" style={{ cursor: 'pointer' }} checked={selected.length === filtered.length && filtered.length > 0} onChange={toggleAll} />
              </div>
              {['Title', 'Matter', 'Type', 'Status', 'Owner', 'Modified', 'Size'].map(h => (
                <div key={h} style={st.th}>{h}</div>
              ))}
            </div>
            {filtered.map((d, i) => (
              <div key={d.id} style={{ display: 'grid', gridTemplateColumns: '32px 2.2fr 1.5fr 0.9fr 0.9fr 0.8fr 0.8fr 0.75fr', background: selected.includes(d.id) ? st.goldBg : i % 2 === 0 ? 'transparent' : TspDr.color.bg.secondary, transition: 'background 0.1s' }}>
                <div style={{ ...st.td, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <input type="checkbox" style={{ cursor: 'pointer' }} checked={selected.includes(d.id)} onChange={() => toggleSelect(d.id)} />
                </div>
                <div style={st.td}>
                  <div style={{ fontWeight: 600, color: st.gold, cursor: 'pointer', marginBottom: '2px', fontSize: '12px' }}>{d.title}</div>
                  {d.reviewers > 0 && <span style={{ fontSize: '10px', color: TspDr.color.text.tertiary }}>◉ {d.reviewers} reviewer{d.reviewers > 1 ? 's' : ''}</span>}
                </div>
                <div style={{ ...st.td, fontSize: '11px', color: TspDr.color.text.secondary }}>{d.matter}</div>
                <div style={st.td}><span style={{ ...st.tag, background: TspDr.color.bg.secondary, color: TspDr.color.text.secondary }}>{d.type}</span></div>
                <div style={st.td}><span style={{ ...st.tag, ...st.docStatusColor(d.status) }}>{d.status}</span></div>
                <div style={{ ...st.td, fontSize: '11px' }}>{d.owner}</div>
                <div style={{ ...st.td, fontSize: '11px', color: TspDr.color.text.secondary }}>{d.modified}</div>
                <div style={{ ...st.td, fontSize: '11px', color: TspDr.color.text.secondary }}>{d.size}</div>
              </div>
            ))}
          </div>

          {/* Bulk action bar */}
          {selected.length > 0 && (
            <div style={{ position: 'sticky', bottom: 0, display: 'flex', alignItems: 'center', gap: '10px', padding: '10px 16px', background: TspDr.color.bg.card, border: `1px solid ${st.gold}`, borderRadius: TspDr.radius.lg, boxShadow: '0 -4px 20px rgba(201,168,76,0.15)', marginTop: '8px' }}>
              <span style={{ fontSize: '12px', fontWeight: 600, color: st.gold }}>{selected.length} selected</span>
              <div style={{ width: '1px', height: '16px', background: TspDr.color.border.light }} />
              {bulkActions.map(a => (
                <button key={a} style={{ ...st.btnSecondary, fontSize: '11px' }}>{a}</button>
              ))}
              <button onClick={() => setSelected([])} style={{ marginLeft: 'auto', ...st.btnGhost, color: TspDr.color.text.tertiary, fontSize: '11px' }}>Clear x</button>
            </div>
          )}
        </div>
      )}

      {/* ── Workspace view (matter folders) ──────────────────────── */}
      {view === 'workspace' && (
        <div>
          {data.matterFolders.map(m => {
            const mDocs = data.drafts.filter(d => d.matterId === m.id);
            const isOpen = expanded.includes(m.id);
            return (
              <div key={m.id} style={{ ...st.card, marginBottom: '10px' }}>
                {/* Matter header */}
                <div onClick={() => toggleFolder(m.id)}
                  style={{ padding: '12px 16px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: '12px', background: isOpen ? st.goldBg : 'transparent', borderBottom: isOpen ? `1px solid ${TspDr.color.border.light}` : 'none' }}>
                  <span style={{ fontSize: '12px', color: isOpen ? st.gold : TspDr.color.text.tertiary, transition: 'transform 0.15s', display: 'inline-block', transform: isOpen ? 'rotate(90deg)' : 'none' }}>▶</span>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: '13px', fontWeight: 600, color: isOpen ? st.gold : TspDr.color.text.primary }}>{m.name}</div>
                    <div style={{ fontSize: '11px', color: TspDr.color.text.tertiary, marginTop: '1px' }}>{m.type} · {m.partner} · {mDocs.length} document{mDocs.length !== 1 ? 's' : ''}</div>
                  </div>
                  <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                    {m.deadline && <span style={{ fontSize: '10px', color: TspDr.color.text.tertiary }}>⊙ Due {m.deadline}</span>}
                    <span style={{ ...st.tag, background: 'rgba(5,150,105,0.08)', color: '#059669' }}>{m.status}</span>
                  </div>
                </div>

                {/* Folders */}
                {isOpen && (
                  <div style={{ padding: '8px 12px 12px' }}>
                    {m.folders.map(folder => {
                      const folderDocs = data.drafts.filter(d => folder.docIds.includes(d.id));
                      return (
                        <div key={folder.name} style={{ marginBottom: '8px' }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: '6px', padding: '5px 8px', marginBottom: '4px' }}>
                            <span style={{ fontSize: '12px', color: TspDr.color.text.tertiary }}>▤</span>
                            <span style={{ fontSize: '11px', fontWeight: 600, color: TspDr.color.text.secondary, textTransform: 'uppercase', letterSpacing: '0.05em' }}>{folder.name}</span>
                            <span style={{ fontSize: '10px', color: TspDr.color.text.tertiary }}>({folderDocs.length})</span>
                            <button style={{ ...st.btnGhost, marginLeft: 'auto', fontSize: '10px', padding: '1px 7px' }}>+ Add</button>
                          </div>
                          {folderDocs.length === 0 ? (
                            <div style={{ padding: '8px 28px', fontSize: '11px', color: TspDr.color.text.tertiary, fontStyle: 'italic' }}>No documents yet</div>
                          ) : (
                            folderDocs.map(d => (
                              <div key={d.id} style={{ display: 'flex', alignItems: 'center', gap: '10px', padding: '8px 10px 8px 28px', borderRadius: '5px', marginBottom: '2px', background: TspDr.color.bg.secondary, border: `1px solid ${TspDr.color.border.light}`, cursor: 'pointer' }}>
                                <span style={{ fontSize: '12px', color: TspDr.color.text.tertiary }}>◈</span>
                                <div style={{ flex: 1 }}>
                                  <div style={{ fontSize: '12px', fontWeight: 500, color: st.gold }}>{d.title}</div>
                                  <div style={{ fontSize: '10px', color: TspDr.color.text.tertiary }}>{d.type} · {d.size} · {d.modified}</div>
                                </div>
                                <span style={{ ...st.tag, ...st.docStatusColor(d.status) }}>{d.status}</span>
                                <span style={{ fontSize: '11px', color: TspDr.color.text.secondary }}>{d.owner}</span>
                              </div>
                            ))
                          )}
                        </div>
                      );
                    })}
                    <button style={{ ...st.btnSecondary, width: '100%', fontSize: '11px', marginTop: '4px' }}>+ New Document in {m.name}</button>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

window.StudioDrafts = StudioDrafts;
