// Claude connection UI: top-bar chip + modal for pasting key.
// Depends on: window.CG (cg-claude.js), Icons

function ClaudeChip({ onClick }) {
  const [, setTick] = React.useState(0);
  React.useEffect(() => CG.onStatus(() => setTick(t => t + 1)), []);
  const connected = CG.hasKey();
  return (
    <button
      className="btn btn-sm"
      onClick={onClick}
      title={connected ? 'Claude connected · click to manage' : 'connect Claude to enable live agents'}
      style={{
        borderColor: connected ? 'var(--green)' : 'var(--ink)',
        color: connected ? 'var(--green)' : 'var(--ink)',
      }}
    >
      <span style={{
        width: 7, height: 7, borderRadius: '50%',
        background: connected ? 'var(--green)' : 'var(--ink-3)',
        display: 'inline-block',
        boxShadow: connected ? '0 0 0 2px oklch(85% 0.15 145 / 0.4)' : 'none',
      }} />
      {connected ? 'claude · live' : 'connect claude'}
    </button>
  );
}

function ClaudeModal({ open, onClose }) {
  const [key, setKey] = React.useState(() => CG.getKey());
  const [mode, setMode] = React.useState(() => CG.getMode());
  const [testing, setTesting] = React.useState(false);
  const [testResult, setTestResult] = React.useState(null);
  const [showKey, setShowKey] = React.useState(false);

  React.useEffect(() => {
    if (open) {
      setKey(CG.getKey());
      setMode(CG.getMode());
      setTestResult(null);
    }
  }, [open]);

  if (!open) return null;

  const onSave = () => {
    CG.setKey(key);
    CG.setMode(mode);
    setTestResult({ ok: true, msg: 'saved · stored locally in your browser only' });
  };

  const onTest = async () => {
    if (!key.trim()) { setTestResult({ ok: false, msg: 'paste a key first' }); return; }
    CG.setKey(key);
    setTesting(true);
    setTestResult(null);
    try {
      const r = await CG.call({
        agentId: '_connection_test',
        model: 'haiku',
        system: 'Respond with exactly the word "connected".',
        messages: [{ role: 'user', content: 'ping' }],
        maxTokens: 20,
        persist: false,
      });
      setTestResult({ ok: true, msg: 'connected · ' + (r.text || '(empty)').slice(0, 60) });
    } catch (e) {
      setTestResult({ ok: false, msg: e.message });
    } finally {
      setTesting(false);
    }
  };

  const onDisconnect = () => {
    CG.clearKey();
    setKey('');
    setTestResult({ ok: true, msg: 'disconnected · key removed from localStorage' });
  };

  const onClearAll = () => {
    if (!confirm('clear all stored exchange logs and ledger entries? (keeps your API key)')) return;
    CG.resetAllLogs();
    CG.resetLedger();
    setTestResult({ ok: true, msg: 'all stored exchanges + ledger wiped' });
  };

  return (
    <div
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 50,
        background: 'oklch(20% 0.02 60 / 0.35)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 24,
      }}
    >
      <div
        onClick={e => e.stopPropagation()}
        className="paper-card"
        style={{ maxWidth: 560, width: '100%', padding: 28, position: 'relative' }}
      >
        <div className="tape" style={{ top: -8, left: 36, transform: 'rotate(-3deg)' }} />

        <div className="tiny" style={{ marginBottom: 4 }}>connection</div>
        <h2 style={{ margin: '0 0 4px', fontSize: '1.4rem' }}>hook Clarguments up to Claude.</h2>
        <p className="micro" style={{ textTransform: 'none', letterSpacing: 0, lineHeight: 1.45, color: 'var(--ink-3)', marginBottom: 18 }}>
          we call <span className="mono">api.anthropic.com</span> directly from your browser with your own key. it's stored in <span className="mono">localStorage</span> on this device and sent only to Anthropic. nothing routes through us.
        </p>

        <div className="tiny mb-2">anthropic api key</div>
        <div style={{ display: 'flex', gap: 6, marginBottom: 6 }}>
          <input
            className="paper-input"
            type={showKey ? 'text' : 'password'}
            placeholder="sk-ant-..."
            value={key}
            onChange={e => setKey(e.target.value)}
            style={{ fontFamily: 'var(--font-mono)', fontSize: '0.8rem', flex: 1 }}
          />
          <button className="btn btn-sm" onClick={() => setShowKey(v => !v)} title="show/hide">
            {showKey ? 'hide' : 'show'}
          </button>
        </div>
        <div className="micro" style={{ textTransform: 'none', letterSpacing: 0, color: 'var(--ink-3)', marginBottom: 18 }}>
          get one at <span className="mono">console.anthropic.com</span> · needs billing enabled.
        </div>

        <div className="tiny mb-2">scenario data</div>
        <div style={{ display: 'flex', gap: 6, marginBottom: 18 }}>
          {[
            { v: 'fresh', l: 'fresh · start from blank' },
            { v: 'canned', l: 'canned · replay scripted scenario' },
          ].map(o => (
            <div
              key={o.v}
              className={`seat-chip ${mode === o.v ? 'active' : ''}`}
              onClick={() => setMode(o.v)}
              style={{ flex: 1, justifyContent: 'center', border: '1px solid var(--rule)' }}
            >{o.l}</div>
          ))}
        </div>

        {testResult && (
          <div style={{
            padding: '10px 12px',
            background: testResult.ok ? 'var(--green-soft)' : 'oklch(92% 0.06 25)',
            borderLeft: `2px solid ${testResult.ok ? 'var(--green)' : 'var(--red)'}`,
            marginBottom: 14,
            fontSize: '0.85rem',
            lineHeight: 1.4,
          }}>
            {testResult.msg}
          </div>
        )}

        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          <button className="btn btn-primary" onClick={onSave}>save</button>
          <button className="btn" onClick={onTest} disabled={testing}>
            {testing ? 'testing…' : 'test connection'}
          </button>
          <div style={{ flex: 1 }} />
          {CG.hasKey() && <button className="btn btn-sm" onClick={onDisconnect}>disconnect</button>}
          <button className="btn btn-sm" onClick={onClearAll}>wipe stored data</button>
          <button className="btn btn-sm" onClick={onClose}>close</button>
        </div>

        <div className="dashed" style={{ margin: '18px 0 10px' }} />
        <div className="micro" style={{ textTransform: 'none', letterSpacing: 0, color: 'var(--ink-3)', lineHeight: 1.4 }}>
          <b>what uses what:</b> haiku for live flag-checking (cheap, fast). sonnet for coach feedback, callout cards, refiner framings (richer reasoning).
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ClaudeChip, ClaudeModal });
