// STUDIO — Versions tab (improvements 15–16: side-by-side comparison, document branching)
const { useState: useStVs } = React;
const TspVs = window.ArbiterTokens;

function StudioVersions() {
  const st   = window.__st;
  const data = window.STUDIO_DATA;
  const [subTab,    setSubTab]    = useStVs('history');
  const [compareA,  setCompareA]  = useStVs('v1.8');
  const [compareB,  setCompareB]  = useStVs('v1.7');
  const [activeBranch, setActiveBranch] = useStVs('main');

  const branchColor = (name) => data.branches.find(b => b.name === name)?.color || st.gold;

  const deltaColor = (d) => {
    if (!d) return TspVs.color.text.tertiary;
    if (d.startsWith('+')) return '#059669';
    if (d.startsWith('-')) return '#B91C1C';
    return TspVs.color.text.secondary;
  };

  // Simulated diff lines for comparison panel
  const diffLines = [
    { type: 'context', text: 'UNITED STATES DISTRICT COURT' },
    { type: 'context', text: 'SOUTHERN DISTRICT OF NEW YORK' },
    { type: 'context', text: '' },
    { type: 'removed', text: 'Plaintiff hereby moves this Court pursuant to Federal Rule of Civil Procedure 37(a)(3)(B)(iv) for an order compelling Defendant Coastal Energy LLC to produce all documents responsive to Plaintiff\'s First Request for Production.' },
    { type: 'added',   text: 'Plaintiff hereby moves this Court pursuant to Federal Rule of Civil Procedure 37(a)(3)(B)(iv) for an order compelling Defendant Coastal Energy LLC to produce all documents responsive to Plaintiff\'s First Request for Production. This motion is supported by the expert opinion of Dr. Rajiv Patel and the declaration attached hereto as Exhibit A.' },
    { type: 'context', text: '' },
    { type: 'context', text: 'I. INTRODUCTION' },
    { type: 'context', text: '' },
    { type: 'removed', text: 'This dispute arises from Coastal Energy\'s systematic failure to comply with its discovery obligations under Rules 26 and 37 of the Federal Rules of Civil Procedure.' },
    { type: 'removed', text: 'Despite repeated meet-and-confer efforts, Coastal has produced only 842 documents out of an estimated 14,000.' },
    { type: 'added',   text: 'This dispute arises from Coastal Energy\'s willful and systematic failure to comply with its discovery obligations under Rules 26 and 37 of the Federal Rules of Civil Procedure, rising to the level of sanctionable conduct under Rule 37(b) and this Court\'s inherent power.' },
    { type: 'added',   text: 'Despite repeated meet-and-confer efforts spanning four months, Coastal has produced only 842 documents — representing less than 6% of the estimated 14,204 documents identified by Plaintiff\'s ESI vendor.' },
    { type: 'context', text: '' },
    { type: 'context', text: 'II. LEGAL STANDARD' },
    { type: 'context', text: '' },
    { type: 'context', text: 'A court may compel discovery where a party fails to respond to properly served requests. Fed. R. Civ. P. 37(a)(3)(B).' },
  ];

  const filtVersions = activeBranch === 'all'
    ? data.versions
    : data.versions.filter(v => v.branch === activeBranch);

  return (
    <div>
      {/* Sub-tab */}
      <div style={{ display: 'flex', gap: '0', borderBottom: `1px solid ${TspVs.color.border.light}`, marginBottom: '16px' }}>
        {[['history','◈ Version History'],['compare','⇔ Compare Versions'],['branches',' Branches']].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 : TspVs.color.text.secondary, borderBottom: subTab === id ? `2px solid ${st.gold}` : '2px solid transparent', fontFamily: TspVs.font.family, marginBottom: '-1px' }}>
            {label}
          </button>
        ))}
      </div>

      {/* ── Version History ───────────────────────────────────────── */}
      {subTab === 'history' && (
        <div>
          {/* Branch filter */}
          <div style={{ display: 'flex', gap: '6px', marginBottom: '12px', alignItems: 'center' }}>
            <span style={{ fontSize: '11px', color: TspVs.color.text.tertiary, marginRight: '4px' }}>Branch:</span>
            {[['all','All branches',TspVs.color.text.secondary], ...data.branches.map(b => [b.name, b.label, b.color])].map(([val, label, color]) => (
              <button key={val} onClick={() => setActiveBranch(val)}
                style={{ ...st.btnSecondary, fontSize: '11px', padding: '3px 10px', background: activeBranch === val ? `${color}15` : TspVs.color.bg.card, borderColor: activeBranch === val ? color : TspVs.color.border.light, color: activeBranch === val ? color : TspVs.color.text.secondary }}>
                {label}
              </button>
            ))}
          </div>

          <div style={st.card}>
            <div style={{ display: 'grid', gridTemplateColumns: '0.6fr 2.8fr 1fr 0.7fr 0.7fr 0.7fr', borderBottom: `1px solid ${TspVs.color.border.light}` }}>
              {['Version', 'Changes', 'Author', 'Words', 'Delta', 'Branch'].map(h => <div key={h} style={st.th}>{h}</div>)}
            </div>
            {filtVersions.map((v, i) => (
              <div key={v.v} style={{ display: 'grid', gridTemplateColumns: '0.6fr 2.8fr 1fr 0.7fr 0.7fr 0.7fr', background: v.tag === 'Current' ? st.goldBg : i % 2 === 0 ? 'transparent' : TspVs.color.bg.secondary }}>
                <div style={{ ...st.td, gap: '6px' }}>
                  <span style={{ fontFamily: TspVs.font.mono, fontSize: '11px', fontWeight: v.tag === 'Current' ? 700 : 400, color: v.tag === 'Current' ? st.gold : TspVs.color.text.primary }}>{v.v}</span>
                  {v.tag && <span style={{ ...st.tag, background: v.tag === 'Current' ? st.goldBg : v.tag === 'Branch' ? 'rgba(124,58,237,0.08)' : TspVs.color.bg.secondary, color: v.tag === 'Current' ? st.gold : v.tag === 'Branch' ? '#7C3AED' : TspVs.color.text.tertiary, fontSize: '9px' }}>{v.tag}</span>}
                </div>
                <div style={{ ...st.td, flexDirection: 'column', alignItems: 'flex-start', gap: '1px' }}>
                  <span style={{ fontSize: '11px', color: TspVs.color.text.primary }}>{v.changes}</span>
                  <span style={{ fontSize: '10px', color: TspVs.color.text.tertiary }}>{v.time}</span>
                </div>
                <div style={{ ...st.td, fontSize: '11px' }}>{v.author}</div>
                <div style={{ ...st.td, fontSize: '11px', fontFamily: TspVs.font.mono }}>{v.words.toLocaleString()}</div>
                <div style={{ ...st.td, fontSize: '11px', fontFamily: TspVs.font.mono, fontWeight: 600, color: deltaColor(v.delta) }}>{v.delta}</div>
                <div style={st.td}>
                  <span style={{ fontSize: '10px', fontWeight: 600, color: branchColor(v.branch), background: `${branchColor(v.branch)}15`, padding: '2px 7px', borderRadius: '4px', border: `1px solid ${branchColor(v.branch)}30` }}>
                    {data.branches.find(b => b.name === v.branch)?.label || v.branch}
                  </span>
                </div>
              </div>
            ))}
          </div>

          <div style={{ display: 'flex', gap: '8px', marginTop: '10px' }}>
            <button style={{ ...st.btnSecondary, fontSize: '11px' }}>Restore Selected Version</button>
            <button style={{ ...st.btnSecondary, fontSize: '11px' }}>Download Version</button>
            <button style={{ ...st.btnPrimary, fontSize: '11px', marginLeft: 'auto' }}> Create Branch from Version</button>
          </div>
        </div>
      )}

      {/* ── Compare Versions ──────────────────────────────────────── */}
      {subTab === 'compare' && (
        <div>
          {/* Version selectors */}
          <div style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: '16px', padding: '12px 16px', background: TspVs.color.bg.card, border: `1px solid ${TspVs.color.border.light}`, borderRadius: TspVs.radius.lg }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flex: 1 }}>
              <span style={{ fontSize: '11px', color: TspVs.color.text.secondary, fontWeight: 600, whiteSpace: 'nowrap' }}>Base version:</span>
              <select value={compareB} onChange={e => setCompareB(e.target.value)}
                style={{ flex: 1, padding: '6px 10px', borderRadius: '5px', border: `1px solid ${TspVs.color.border.light}`, background: TspVs.color.bg.secondary, fontSize: '11px', color: TspVs.color.text.primary, fontFamily: TspVs.font.mono }}>
                {data.versions.map(v => <option key={v.v} value={v.v}>{v.v} — {v.time} ({v.author})</option>)}
              </select>
            </div>
            <span style={{ fontSize: '16px', color: TspVs.color.text.tertiary }}>⇔</span>
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px', flex: 1 }}>
              <span style={{ fontSize: '11px', color: TspVs.color.text.secondary, fontWeight: 600, whiteSpace: 'nowrap' }}>Compare to:</span>
              <select value={compareA} onChange={e => setCompareA(e.target.value)}
                style={{ flex: 1, padding: '6px 10px', borderRadius: '5px', border: `1px solid ${TspVs.color.border.light}`, background: TspVs.color.bg.secondary, fontSize: '11px', color: TspVs.color.text.primary, fontFamily: TspVs.font.mono }}>
                {data.versions.map(v => <option key={v.v} value={v.v}>{v.v} — {v.time} ({v.author})</option>)}
              </select>
            </div>
          </div>

          {/* Diff legend */}
          <div style={{ display: 'flex', gap: '14px', marginBottom: '10px', alignItems: 'center' }}>
            <span style={{ fontSize: '11px', color: TspVs.color.text.tertiary }}>Legend:</span>
            {[['rgba(5,150,105,0.15)','#059669','Added'],['rgba(185,28,28,0.12)','#B91C1C','Removed'],['transparent','none','Unchanged']].map(([bg, border, label]) => (
              <div key={label} style={{ display: 'flex', alignItems: 'center', gap: '5px' }}>
                <div style={{ width: '14px', height: '14px', background: bg, border: `1px solid ${border === 'none' ? TspVs.color.border.light : border}`, borderRadius: '2px' }} />
                <span style={{ fontSize: '11px', color: TspVs.color.text.secondary }}>{label}</span>
              </div>
            ))}
            <div style={{ marginLeft: 'auto', fontSize: '11px', color: TspVs.color.text.tertiary }}>
              Showing {compareB} → {compareA}
            </div>
          </div>

          {/* Side-by-side diff */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0', border: `1px solid ${TspVs.color.border.light}`, borderRadius: TspVs.radius.lg, overflow: 'hidden' }}>
            {/* Headers */}
            <div style={{ padding: '10px 16px', background: TspVs.color.bg.secondary, borderBottom: `1px solid ${TspVs.color.border.light}`, borderRight: `1px solid ${TspVs.color.border.light}`, display: 'flex', alignItems: 'center', gap: '8px' }}>
              <span style={{ fontFamily: TspVs.font.mono, fontSize: '12px', fontWeight: 700, color: '#B91C1C' }}>{compareB}</span>
              <span style={{ fontSize: '11px', color: TspVs.color.text.tertiary }}>{data.versions.find(v => v.v === compareB)?.author}</span>
            </div>
            <div style={{ padding: '10px 16px', background: TspVs.color.bg.secondary, borderBottom: `1px solid ${TspVs.color.border.light}`, display: 'flex', alignItems: 'center', gap: '8px' }}>
              <span style={{ fontFamily: TspVs.font.mono, fontSize: '12px', fontWeight: 700, color: '#059669' }}>{compareA}</span>
              <span style={{ fontSize: '11px', color: TspVs.color.text.tertiary }}>{data.versions.find(v => v.v === compareA)?.author}</span>
            </div>
            {/* Left pane */}
            <div style={{ padding: '12px 16px', background: TspVs.color.bg.card, borderRight: `1px solid ${TspVs.color.border.light}`, fontFamily: '"Georgia", serif', fontSize: '11px', lineHeight: 1.7, maxHeight: '360px', overflowY: 'auto' }}>
              {diffLines.map((line, i) => (
                <div key={i} style={{ padding: '1px 6px', marginBottom: '1px', borderRadius: '2px', background: line.type === 'removed' ? 'rgba(185,28,28,0.12)' : 'transparent', borderLeft: line.type === 'removed' ? '3px solid #B91C1C' : '3px solid transparent' }}>
                  {line.type !== 'added' && (
                    <span style={{ color: line.type === 'removed' ? '#B91C1C' : TspVs.color.text.primary, textDecoration: line.type === 'removed' ? 'line-through' : 'none' }}>
                      {line.text || '\u00A0'}
                    </span>
                  )}
                  {line.type === 'added' && <span style={{ color: TspVs.color.text.tertiary }}>&nbsp;</span>}
                </div>
              ))}
            </div>
            {/* Right pane */}
            <div style={{ padding: '12px 16px', background: TspVs.color.bg.card, fontFamily: '"Georgia", serif', fontSize: '11px', lineHeight: 1.7, maxHeight: '360px', overflowY: 'auto' }}>
              {diffLines.map((line, i) => (
                <div key={i} style={{ padding: '1px 6px', marginBottom: '1px', borderRadius: '2px', background: line.type === 'added' ? 'rgba(5,150,105,0.15)' : 'transparent', borderLeft: line.type === 'added' ? '3px solid #059669' : '3px solid transparent' }}>
                  {line.type !== 'removed' && (
                    <span style={{ color: line.type === 'added' ? '#059669' : TspVs.color.text.primary }}>
                      {line.text || '\u00A0'}
                    </span>
                  )}
                  {line.type === 'removed' && <span style={{ color: TspVs.color.text.tertiary }}>&nbsp;</span>}
                </div>
              ))}
            </div>
          </div>

          <div style={{ display: 'flex', gap: '8px', marginTop: '10px' }}>
            <button style={{ ...st.btnSecondary, fontSize: '11px' }}>Accept All Changes from {compareA}</button>
            <button style={{ ...st.btnSecondary, fontSize: '11px' }}>Export Redlined PDF</button>
          </div>
        </div>
      )}

      {/* ── Branch Management ─────────────────────────────────────── */}
      {subTab === 'branches' && (
        <div>
          <div style={{ padding: '10px 16px', background: st.goldBg, border: `1px solid ${st.goldBorder}`, borderRadius: TspVs.radius.lg, marginBottom: '16px' }}>
            <div style={{ fontSize: '12px', fontWeight: 600, color: st.goldDeep, marginBottom: '2px' }}> Document Branching</div>
            <div style={{ fontSize: '11px', color: TspVs.color.text.secondary }}>Create parallel versions for different strategies without losing the main track. Branches can be merged or promoted at any time.</div>
          </div>

          {data.branches.map(branch => {
            const branchVs = data.versions.filter(v => v.branch === branch.name);
            return (
              <div key={branch.name} style={{ ...st.card, marginBottom: '12px' }}>
                <div style={{ padding: '12px 16px', borderBottom: `1px solid ${TspVs.color.border.light}`, display: 'flex', alignItems: 'center', gap: '12px' }}>
                  <div style={{ width: '10px', height: '10px', borderRadius: '50%', background: branch.color, flexShrink: 0 }} />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: '13px', fontWeight: 700, color: branch.color }}>{branch.label}</div>
                    <div style={{ fontSize: '10px', color: TspVs.color.text.tertiary, marginTop: '1px' }}>{branchVs.length} version{branchVs.length !== 1 ? 's' : ''} · {branch.active ? 'Active' : 'Archived'}</div>
                  </div>
                  <div style={{ display: 'flex', gap: '6px' }}>
                    {branch.name !== 'main' && <button style={{ ...st.btnSecondary, fontSize: '10px', padding: '3px 8px' }}>Merge into Main</button>}
                    {branch.name !== 'main' && <button style={{ ...st.btnSecondary, fontSize: '10px', padding: '3px 8px' }}>Promote to Main</button>}
                    {branch.name === 'main' && <span style={{ ...st.tag, background: st.goldBg, color: st.gold }}>Primary</span>}
                  </div>
                </div>

                {/* Branch timeline */}
                <div style={{ padding: '12px 20px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '0', overflowX: 'auto' }}>
                    {branchVs.map((v, i) => (
                      <React.Fragment key={v.v}>
                        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flexShrink: 0, minWidth: '80px' }}>
                          <div style={{ width: '32px', height: '32px', borderRadius: '50%', background: `${branch.color}18`, border: `2px solid ${branch.color}`, display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: '6px' }}>
                            <span style={{ fontFamily: TspVs.font.mono, fontSize: '9px', fontWeight: 700, color: branch.color }}>{v.v.replace(/-[a-z-]+/,'')}</span>
                          </div>
                          <div style={{ textAlign: 'center', maxWidth: '76px' }}>
                            <div style={{ fontSize: '10px', color: TspVs.color.text.secondary, lineHeight: 1.3 }}>{v.author}</div>
                            <div style={{ fontSize: '9px', color: TspVs.color.text.tertiary, lineHeight: 1.3 }}>{v.time}</div>
                          </div>
                        </div>
                        {i < branchVs.length - 1 && (
                          <div style={{ height: '2px', flex: 1, minWidth: '24px', background: branch.color, opacity: 0.3, marginBottom: '24px', flexShrink: 1 }} />
                        )}
                      </React.Fragment>
                    ))}
                    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flexShrink: 0, marginLeft: '16px', marginBottom: '24px' }}>
                      <button style={{ ...st.btnGhost, width: '32px', height: '32px', borderRadius: '50%', padding: '0', border: `2px dashed ${TspVs.color.border.light}`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '16px', color: TspVs.color.text.tertiary }}>+</button>
                    </div>
                  </div>
                </div>
              </div>
            );
          })}

          <button style={{ ...st.btnPrimary, fontSize: '11px' }}> Create New Branch</button>
        </div>
      )}
    </div>
  );
}

window.StudioVersions = StudioVersions;
