// Source detail drawer + Add source modal wizard

const { useState: useDs } = React;

function SourceDrawer({ vendorId, onClose }) {
  const [tab, setTab] = useDs('overview');
  if (!vendorId) return null;
  const v = VENDORS[vendorId];
  const connected = CONNECTED_SOURCES.find(s => s.id === vendorId);

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,.25)', zIndex: 90,
      display: 'flex', justifyContent: 'flex-end',
      animation: 'fadeIn 160ms'
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: 560, height: '100%', background: 'var(--surface)',
        borderLeft: '1px solid var(--border)',
        boxShadow: 'var(--shadow-1)',
        display: 'flex', flexDirection: 'column',
        animation: 'slideInR 240ms cubic-bezier(.2,.8,.2,1)'
      }}>
        {/* Header */}
        <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--border-subtle)' }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14 }}>
            <VendorLogo vendor={vendorId} size={44} radius={10}/>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="t-h2">{v.name}</div>
              <div className="mono-sm mono text-tertiary" style={{ marginTop: 2 }}>acme-inc.{v.name.toLowerCase()}.app</div>
              {connected && (
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 8 }}>
                  <StatusDot kind={connected.status === 'syncing' ? 'syncing' : connected.status === 'partial' ? 'partial' : 'live'}/>
                  <span className="mono-sm mono text-secondary">Connected · Last sync {connected.synced}</span>
                </div>
              )}
            </div>
            <button className="btn sm ghost" onClick={onClose}><Icons.X size={14}/></button>
          </div>
          <div className="segmented" style={{ marginTop: 16 }}>
            {['overview', 'scope', 'logs', 'danger'].map(t => (
              <button key={t} className={tab === t ? 'active' : ''} onClick={() => setTab(t)}>
                {t.charAt(0).toUpperCase() + t.slice(1)}
              </button>
            ))}
          </div>
        </div>

        {/* Body */}
        <div style={{ flex: 1, overflowY: 'auto', padding: 24 }}>
          {tab === 'overview' && connected && <OverviewTab source={connected} vendor={v}/>}
          {tab === 'overview' && !connected && (
            <div style={{ padding: 40, textAlign: 'center' }}>
              <div className="t-h3">Not connected yet</div>
              <div className="text-secondary t-small mt-4">Add this source to start indexing.</div>
              <button className="btn accent mt-16"><Icons.Plus size={13}/> Connect {v.name}</button>
            </div>
          )}
          {tab === 'scope' && <ScopeTab/>}
          {tab === 'logs' && <LogsTab/>}
          {tab === 'danger' && <DangerTab name={v.name}/>}
        </div>

        {/* Footer */}
        {connected && tab === 'overview' && (
          <div style={{ padding: '16px 24px', borderTop: '1px solid var(--border-subtle)', display: 'flex', gap: 8 }}>
            <button className="btn"><Icons.Refresh size={13}/> Sync now</button>
            <button className="btn"><Icons.Pause size={13}/> Pause</button>
            <button className="btn ghost">Reconfigure</button>
          </div>
        )}
      </div>
    </div>
  );
}

function OverviewTab({ source, vendor }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <MetaGrid rows={[
        ['Items indexed', source.volume],
        ['Size indexed', source.size || '—'],
        ['Relationships', source.rels ? `${source.rels} found` : '—'],
        ['Last full sync', '2h ago'],
        ['Next scheduled', 'in 58m'],
        ['Token expires', 'in 89 days'],
      ]}/>

      <div>
        <div className="t-micro text-tertiary" style={{ marginBottom: 8 }}>Rate limit headroom</div>
        <Progress value={62}/>
        <div className="mono-sm mono text-tertiary" style={{ marginTop: 4 }}>62% remaining · resets in 12m</div>
      </div>

      <Divider/>

      <div>
        <div className="t-h3">Retrieval usage · last 30d</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 12 }}>
          <KV k="Chunks served" v="7,412"/>
          <KV k="Retrievals that cited" v="1,203 of 14,889 (8.1%)"/>
          <KV k="Top clients" v="Claude Code · Codex"/>
          <KV k="Most-cited docs" v="#general, #eng-standup, onboarding.md" link/>
          <KV k="Last retrieved" v={source.used}/>
        </div>
      </div>

      <Divider/>

      <div>
        <div className="t-h3">Recent graph impact</div>
        <div style={{ display: 'flex', gap: 20, marginTop: 10 }}>
          <HeroStat label="Entities" value="+2,183"/>
          <HeroStat label="Chunks" value="+14,204"/>
          <HeroStat label="Today" value="" sub=""/>
        </div>
      </div>
    </div>
  );
}

function ScopeTab() {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <div>
        <div className="t-h3">Channels</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 10 }}>
          <Radio checked label="All public channels" hint="recommended"/>
          <Radio label="Selected channels"/>
          <Radio label="All public + specific private"/>
        </div>
      </div>
      <div>
        <div className="t-h3">History</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 10 }}>
          <Radio checked label="Last 12 months"/>
          <Radio label="All-time"/>
          <Radio label="Custom"/>
        </div>
      </div>
      <div>
        <div className="t-h3">Exclude</div>
        <div style={{ display: 'flex', gap: 6, marginTop: 10, flexWrap: 'wrap' }}>
          <span className="chip">#random <Icons.X size={10}/></span>
          <span className="chip">#memes <Icons.X size={10}/></span>
          <button className="btn sm"><Icons.Plus size={11}/> Add</button>
        </div>
      </div>
    </div>
  );
}

function LogsTab() {
  return (
    <div className="mono-sm mono" style={{
      background: 'var(--bg)', border: '1px solid var(--border-subtle)',
      borderRadius: 8, padding: 12, color: 'var(--text-secondary)',
      maxHeight: 480, overflowY: 'auto',
    }}>
      {[
        '10:42:11  INFO   started incremental sync',
        '10:42:12  INFO   fetching channel list (34 channels)',
        '10:42:14  INFO   sync #general 2,481 new msgs',
        '10:42:19  INFO   sync #eng-standup 142 new msgs',
        '10:42:22  WARN   skipping #legal-private · missing scope channels:history',
        '10:42:31  INFO   embedded 5,241 chunks in 12.4s',
        '10:42:33  INFO   graph resolution complete · 38 new edges',
        '10:42:34  INFO   sync complete · 7,344 msgs · 2.1s flush',
      ].map((l, i) => <div key={i} style={{ padding: '3px 0' }}>{l}</div>)}
    </div>
  );
}

function DangerTab({ name }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      <DangerRow title="Rotate token" desc="Force re-authentication on next sync."/>
      <DangerRow title="Purge indexed data" desc="Delete all chunks and graph entries from this source. Irreversible." danger/>
      <DangerRow title={`Disconnect ${name}`} desc="Remove the integration. Indexed data is retained until purged." danger/>
    </div>
  );
}
function DangerRow({ title, desc, danger }) {
  return (
    <div style={{
      padding: '14px 16px',
      border: `1px solid ${danger ? 'var(--error-bg)' : 'var(--border-subtle)'}`,
      borderRadius: 8,
      display: 'flex', alignItems: 'center', gap: 12,
    }}>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 13, fontWeight: 500, color: danger ? 'var(--error)' : 'var(--text-primary)' }}>{title}</div>
        <div className="t-small text-secondary mt-4">{desc}</div>
      </div>
      <button className="btn sm" style={danger ? { color: 'var(--error)', borderColor: 'var(--error-bg)' } : {}}>Run</button>
    </div>
  );
}

function MetaGrid({ rows }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
      {rows.map(([k, v], i) => (
        <div key={i} style={{ padding: 12, border: '1px solid var(--border-subtle)', borderRadius: 8 }}>
          <div className="mono-sm mono text-tertiary">{k}</div>
          <div style={{ fontSize: 14, fontWeight: 500, marginTop: 4 }}>{v}</div>
        </div>
      ))}
    </div>
  );
}
function KV({ k, v, link }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', gap: 16, fontSize: 13 }}>
      <span className="text-secondary">{k}</span>
      <span style={{ textAlign: 'right', color: link ? 'var(--accent-text)' : 'var(--text-primary)' }}>{v}</span>
    </div>
  );
}
function Radio({ checked, label, hint }) {
  return (
    <label style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 13, cursor: 'pointer' }}>
      <span style={{
        width: 14, height: 14, borderRadius: '50%',
        border: `1.5px solid ${checked ? 'var(--accent)' : 'var(--border-strong)'}`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        {checked && <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)' }}/>}
      </span>
      {label}
      {hint && <span className="mono-sm mono text-tertiary">— {hint}</span>}
    </label>
  );
}
function Divider() { return <div style={{ height: 1, background: 'var(--border-subtle)' }}/>; }

// Add connector modal
function AddConnectorFlow({ open, vendorId, onClose, onComplete }) {
  const [step, setStep] = useDs(1);
  React.useEffect(() => { if (open) setStep(1); }, [open, vendorId]);
  if (!open) return null;
  const v = vendorId ? VENDORS[vendorId] : VENDORS.chatroom;
  const actualId = vendorId || 'chatroom';

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,.4)', zIndex: 95,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: 640, background: 'var(--surface-raised)',
        borderRadius: 12, border: '1px solid var(--border)',
        boxShadow: 'var(--shadow-2)', overflow: 'hidden',
        animation: 'slideUp 240ms cubic-bezier(.2,.8,.2,1)'
      }}>
        {/* Header */}
        <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--border-subtle)', display: 'flex', alignItems: 'center', gap: 12 }}>
          <VendorLogo vendor={actualId} size={28}/>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14, fontWeight: 500 }}>Add {v.name}</div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
            {[1,2,3].map(n => (
              <span key={n} style={{
                width: 20, height: 4, borderRadius: 2,
                background: n <= step ? 'var(--accent)' : 'var(--border)'
              }}/>
            ))}
          </div>
          <button className="btn sm ghost" onClick={onClose}><Icons.X size={14}/></button>
        </div>

        {/* Body */}
        <div style={{ padding: 28, minHeight: 280 }}>
          {step === 1 && <Step1Auth v={v}/>}
          {step === 2 && <Step2Scope/>}
          {step === 3 && <Step3Sync v={v}/>}
        </div>

        {/* Footer */}
        <div style={{ padding: '14px 20px', borderTop: '1px solid var(--border-subtle)', display: 'flex', gap: 8, justifyContent: 'space-between' }}>
          <button className="btn ghost" onClick={step === 1 ? onClose : () => setStep(step - 1)}>
            {step === 1 ? 'Cancel' : '← Back'}
          </button>
          {step === 1 && <button className="btn accent" onClick={() => setStep(2)}>Authorize with {v.name}</button>}
          {step === 2 && <button className="btn accent" onClick={() => setStep(3)}>Start initial sync</button>}
          {step === 3 && <button className="btn" onClick={onClose}>Go to Connectors →</button>}
        </div>
      </div>
    </div>
  );
}

function Step1Auth({ v }) {
  return (
    <div>
      <div className="t-h2">Authorize {v.name}</div>
      <div className="text-secondary t-body mt-4">Parcle will ask for these permissions:</div>
      <ul style={{ margin: '16px 0', padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {['Read all public channels', 'Read message history', 'Read user directory (names only)'].map(p => (
          <li key={p} style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 13 }}>
            <Icons.Check size={14} style={{ color: 'var(--success)' }}/> {p}
          </li>
        ))}
      </ul>
      <div className="t-small text-tertiary" style={{ padding: 12, background: 'var(--bg)', borderRadius: 8, borderLeft: '2px solid var(--accent)', marginTop: 16 }}>
        Parcle never writes back to your source. Read-only by default.
      </div>
    </div>
  );
}
function Step2Scope() {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <div className="t-h2">What should Parcle index?</div>
      <div>
        <div className="t-h3">Channels</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 10 }}>
          <Radio checked label="All public channels" hint="recommended"/>
          <Radio label="Selected channels"/>
          <Radio label="All public + specific private"/>
        </div>
      </div>
      <div>
        <div className="t-h3">History</div>
        <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
          <span className="chip accent">Last 12 months</span>
          <span className="chip">All-time</span>
          <span className="chip">Custom</span>
        </div>
      </div>
    </div>
  );
}
function Step3Sync({ v }) {
  return (
    <div>
      <div className="t-h2">Syncing {v.name} — you can close this</div>
      <div className="text-secondary t-body mt-4">We'll notify you when the initial sync is complete.</div>
      <div style={{ marginTop: 24 }}>
        <Progress value={42} height={6}/>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 10 }}>
          <span className="mono-sm mono text-secondary">172,480 of ~410k messages</span>
          <span className="mono-sm mono text-secondary">42%</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { SourceDrawer, AddConnectorFlow });
