// ApiKeySetup — Paid: encrypted key on server. Preview: optional key in localStorage + claude-proxy-preview.

const API_KEY_STORAGE = 'bwc_anthropic_key';
const PREVIEW_KEY_STORAGE = 'bwc_preview_anthropic_key';

function getApiKey() {
  try { return localStorage.getItem(API_KEY_STORAGE) || ''; }
  catch { return ''; }
}

function getPreviewApiKey() {
  try { return localStorage.getItem(PREVIEW_KEY_STORAGE) || ''; }
  catch { return ''; }
}

function savePreviewApiKey(key) {
  try { localStorage.setItem(PREVIEW_KEY_STORAGE, (key || '').trim()); }
  catch {}
}

function saveApiKey(key) {
  try { localStorage.setItem(API_KEY_STORAGE, key); }
  catch {}
}

function clearApiKey() {
  try { localStorage.removeItem(API_KEY_STORAGE); }
  catch {}
}

async function callClaude(prompt, moduleId) {
  if (typeof window !== 'undefined' && window.__BWC_PREVIEW_MODE) {
    const mid = moduleId != null ? Number(moduleId) : 1;
    if (mid !== 1) throw new Error('PREVIEW_MODULE_ONLY');
    const anthropic_key = getPreviewApiKey();
    if (!anthropic_key) throw new Error('NO_ANTHROPIC_KEY');

    const response = await fetch('/api/claude-proxy-preview', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        prompt,
        model: 'claude-haiku-4-5-20251001',
        max_tokens: 1024,
        anthropic_key,
        module_id: 1,
      }),
    });

    if (!response.ok) {
      const err = await response.json().catch(() => ({}));
      if (response.status === 401) throw new Error('INVALID_KEY');
      if (response.status === 429) throw new Error('RATE_LIMITED');
      if (response.status === 403) throw new Error('PREVIEW_MODULE_ONLY');
      throw new Error(err.error || `Server error ${response.status}`);
    }
    const data = await response.json();
    return data.text;
  }

  const token = localStorage.getItem('bwc_session');
  if (!token) throw new Error('NO_SESSION');

  const response = await fetch('/api/claude-proxy', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({ prompt, model: 'claude-haiku-4-5-20251001', max_tokens: 1024 })
  });

  if (!response.ok) {
    const err = await response.json().catch(() => ({}));
    if (response.status === 401) throw new Error('NO_SESSION');
    if (response.status === 402) throw new Error(err.code || 'NO_ANTHROPIC_KEY');
    if (response.status === 429) throw new Error('RATE_LIMITED');
    throw new Error(err.error || `Server error ${response.status}`);
  }

  const data = await response.json();
  return data.text;
}

function ApiKeyPanel({ onClose, isOverlay = false, previewMode = false }) {
  const [previewInput, setPreviewInput] = React.useState(() => getPreviewApiKey());
  const hasKey = previewMode ? !!getPreviewApiKey() : localStorage.getItem('bwc_has_api_key') === '1';

  if (previewMode) {
    const content = (
      <div style={{ width:'100%', maxWidth: isOverlay ? 480 : '100%', background:'#080808', border:'1px solid #1a1a1a' }}>
        <div style={{ padding:'20px 22px 16px', borderBottom:'1px solid #111', display:'flex', justifyContent:'space-between', alignItems:'center' }}>
          <div>
            <div style={{ fontFamily:'Syne,sans-serif', fontWeight:700, fontSize:16, color:'#fff' }}>Your Anthropic API key</div>
            <div style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, letterSpacing:'0.16em', color:'#444', textTransform:'uppercase', marginTop:4 }}>Free Module 1 preview</div>
          </div>
          {onClose && <button onClick={onClose} style={{ background:'none', border:'none', color:'#444', cursor:'pointer', fontSize:18, padding:'2px 6px' }}>×</button>}
        </div>
        <div style={{ padding:'20px 22px' }}>
          <div style={{ background:'#0a0d14', border:'1px solid #111', borderLeft:'3px solid #3B82F6', padding:'14px 16px', marginBottom:18 }}>
            <div style={{ fontFamily:'Inter,sans-serif', fontSize:13, color:'#888', lineHeight:1.65 }}>
              Paste your key from <a href="https://console.anthropic.com" target="_blank" rel="noopener noreferrer" style={{ color:'#88aadd' }}>console.anthropic.com</a>. It stays in <strong style={{ color:'#aaa' }}>your browser</strong> only and is sent through our proxy for AI review — we don’t store it. You pay Anthropic directly for usage.
            </div>
          </div>
          <label style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, letterSpacing:'0.16em', color:'#555', textTransform:'uppercase', display:'block', marginBottom:8 }}>API key</label>
          <input type="password" value={previewInput} onChange={e => setPreviewInput(e.target.value)} placeholder="sk-ant-..."
            style={{ width:'100%', background:'#060606', border:'1px solid #1a1a1a', color:'#fff', fontFamily:'JetBrains Mono,monospace', fontSize:12, padding:'12px 14px', marginBottom:14, boxSizing:'border-box' }} />
          <button onClick={() => { savePreviewApiKey(previewInput); onClose && onClose(); }} style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, letterSpacing:'0.18em', textTransform:'uppercase', background:'#C9A84C', color:'#000', border:'none', padding:'10px 18px', cursor:'pointer', fontWeight:600, width:'100%' }}>
            Save key
          </button>
          <div style={{ fontFamily:'Inter,sans-serif', fontSize:12, color:'#444', marginTop:16, lineHeight:1.6 }}>
            Want the full course and server-stored keys? <a href="/#pricing" style={{ color:'#C9A84C' }}>Get access →</a>
          </div>
        </div>
      </div>
    );
    if (!isOverlay) return content;
    return (
      <div style={{ position:'fixed', inset:0, zIndex:200, background:'rgba(0,0,0,0.92)', display:'flex', alignItems:'center', justifyContent:'center', padding:24 }}
        onClick={onClose}>
        <div onClick={e => e.stopPropagation()} style={{ width:'100%', maxWidth:480 }}>{content}</div>
      </div>
    );
  }

  const content = (
    <div style={{ width:'100%', maxWidth: isOverlay ? 480 : '100%', background:'#080808', border:'1px solid #1a1a1a' }}>
      <div style={{ padding:'20px 22px 16px', borderBottom:'1px solid #111', display:'flex', justifyContent:'space-between', alignItems:'center' }}>
        <div>
          <div style={{ fontFamily:'Syne,sans-serif', fontWeight:700, fontSize:16, color:'#fff' }}>Anthropic API Key</div>
          <div style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, letterSpacing:'0.16em', color:'#444', textTransform:'uppercase', marginTop:4 }}>Managed in your dashboard</div>
        </div>
        {onClose && <button onClick={onClose} style={{ background:'none', border:'none', color:'#444', cursor:'pointer', fontSize:18, padding:'2px 6px' }}>×</button>}
      </div>
      <div style={{ padding:'20px 22px' }}>
        <div style={{ background:'#0a0d14', border:'1px solid #111', borderLeft:'3px solid #3B82F6', padding:'14px 16px', marginBottom:20 }}>
          <div style={{ fontFamily:'JetBrains Mono,monospace', fontSize:9, letterSpacing:'0.18em', color:'#3B82F6', textTransform:'uppercase', marginBottom:8 }}>Security</div>
          <div style={{ fontFamily:'Inter,sans-serif', fontSize:13, color:'#777', lineHeight:1.65 }}>
            Your Anthropic key is <strong style={{ color:'#aaa' }}>encrypted and stored server-side</strong>. It is never sent to your browser. All AI code reviews are proxied through our server.
          </div>
        </div>
        <div style={{ fontFamily:'Inter,sans-serif', fontSize:14, color: hasKey ? '#C9A84C' : '#888', marginBottom:16 }}>
          {hasKey ? '✓ API key configured' : 'No API key configured yet.'}
        </div>
        <a href="/dashboard" style={{ display:'inline-flex', fontFamily:'JetBrains Mono,monospace', fontSize:9, letterSpacing:'0.18em', textTransform:'uppercase', background:'#C9A84C', color:'#000', border:'none', padding:'10px 18px', cursor:'pointer', fontWeight:600, textDecoration:'none' }}>
          {hasKey ? 'Manage in Dashboard →' : 'Add Key in Dashboard →'}
        </a>
      </div>
    </div>
  );

  if (!isOverlay) return content;
  return (
    <div style={{ position:'fixed', inset:0, zIndex:200, background:'rgba(0,0,0,0.92)', display:'flex', alignItems:'center', justifyContent:'center', padding:24 }}
      onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{ width:'100%', maxWidth:480 }}>{content}</div>
    </div>
  );
}

Object.assign(window, { ApiKeyPanel, getApiKey, getPreviewApiKey, callClaude, API_KEY_STORAGE, PREVIEW_KEY_STORAGE });
