/* Tools, API Keys, Docs, Credits, Settings */

/* ───── TOOLS ───── */

function ToolsPage() {
  const [selected, setSelected] = React.useState(null);
  return (
    <div className="page-content">
      <div className="page-header">
        <h1 className="page-title">Tools</h1>
        <p className="page-subtitle">Composable video primitives. Run on a single clip or a whole index.</p>
      </div>

      <div style={{ display: 'flex', gap: 8, marginBottom: 16, flexWrap: 'wrap' }}>
        {['All', 'Search', 'Transcribe', 'Vision', 'Edit', 'Restore', 'Safety', 'Custom'].map((t, i) => (
          <button key={i} className={i === 0 ? 'btn btn-secondary btn-sm' : 'btn btn-ghost btn-sm'}
            style={i === 0 ? { borderColor: 'var(--accent)', color: 'var(--accent-text)', background: 'var(--accent-subtle)' } : {}}>
            {t}
          </button>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 14 }}>
        {MOCK_TOOLS.map(tool => {
          const Comp = Icon[tool.icon];
          return (
            <div key={tool.id} onClick={() => setSelected(tool)}
              className="card"
              style={{ padding: 20, cursor: 'pointer', transition: 'all var(--duration-fast)', position: 'relative' }}
              onMouseEnter={(e) => { e.currentTarget.style.borderColor = 'var(--accent)'; e.currentTarget.style.transform = 'translateY(-1px)'; e.currentTarget.style.boxShadow = 'var(--shadow-md)'; }}
              onMouseLeave={(e) => { e.currentTarget.style.borderColor = 'var(--border-default)'; e.currentTarget.style.transform = 'none'; e.currentTarget.style.boxShadow = 'none'; }}>
              {tool.new && <span className="badge badge-accent" style={{ position: 'absolute', top: 16, right: 16 }}>New</span>}
              {tool.popular && <span className="badge badge-neutral" style={{ position: 'absolute', top: 16, right: 16 }}>Popular</span>}
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14 }}>
                <div style={{
                  width: 40, height: 40, borderRadius: 8,
                  background: 'var(--accent-subtle)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                }}>
                  <Comp size={18} color="var(--accent)" />
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                    <h3 style={{ fontSize: 14, fontWeight: 600, margin: 0 }}>{tool.name}</h3>
                    <span className="mono" style={{ fontSize: 10, color: 'var(--text-tertiary)' }}>{tool.tag}</span>
                  </div>
                  <p style={{ fontSize: 12.5, color: 'var(--text-secondary)', margin: '0 0 12px', lineHeight: 1.5 }}>{tool.desc}</p>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <span className="mono" style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>{tool.cost}</span>
                    <span style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 12, color: 'var(--accent)', fontWeight: 500 }}>
                      Run <Icon.ArrowRight size={12} />
                    </span>
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {selected && <ToolModal tool={selected} onClose={() => setSelected(null)} />}
    </div>
  );
}

function ToolModal({ tool, onClose }) {
  const [running, setRunning] = React.useState(false);
  const [done, setDone] = React.useState(false);
  const Comp = Icon[tool.icon];
  const run = () => {
    setRunning(true);
    setTimeout(() => { setRunning(false); setDone(true); }, 1500);
  };

  return (
    <Modal onClose={onClose} title={null} width={620}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 6 }}>
        <div style={{ width: 44, height: 44, borderRadius: 10, background: 'var(--accent-subtle)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Comp size={20} color="var(--accent)" />
        </div>
        <div>
          <h2 style={{ fontSize: 18, fontWeight: 600, margin: 0 }}>{tool.name}</h2>
          <p style={{ fontSize: 13, color: 'var(--text-tertiary)', margin: '2px 0 0' }}>{tool.cost}</p>
        </div>
        <button onClick={onClose} className="btn btn-ghost btn-sm" style={{ marginLeft: 'auto', width: 28, padding: 0 }}><Icon.X size={14} /></button>
      </div>
      <p style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 24 }}>{tool.desc}</p>

      <div style={{ display: 'grid', gap: 14 }}>
        <div>
          <label className="label">Source</label>
          <select className="input">
            <option>From index — surveillance-jan-2026</option>
            <option>From index — product-demo-archive</option>
            <option>Upload a file…</option>
          </select>
        </div>
        <div>
          <label className="label">Output destination</label>
          <select className="input">
            <option>Save to workspace</option>
            <option>Send to webhook URL…</option>
            <option>Download when complete</option>
          </select>
        </div>
        {!done && !running && (
          <div style={{ marginTop: 8, padding: 12, background: 'var(--bg-inset)', borderRadius: 'var(--radius-md)', fontSize: 12, color: 'var(--text-secondary)' }}>
            Estimated cost: <span className="mono" style={{ color: 'var(--text-primary)', fontWeight: 500 }}>~84 credits</span>
          </div>
        )}
        {running && (
          <div style={{ padding: 16, background: 'var(--bg-inset)', borderRadius: 'var(--radius-md)', display: 'flex', alignItems: 'center', gap: 12 }}>
            <span className="spinner" />
            <span style={{ fontSize: 13 }}>Processing…</span>
          </div>
        )}
        {done && (
          <div style={{ padding: 16, background: 'var(--positive-bg)', borderRadius: 'var(--radius-md)', display: 'flex', alignItems: 'center', gap: 12, color: 'var(--positive)' }}>
            <Icon.Check2 size={16} />
            <span style={{ fontSize: 13, fontWeight: 500 }}>Job submitted. Check the activity feed.</span>
          </div>
        )}
      </div>

      <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 24, paddingTop: 16, borderTop: '1px solid var(--border-subtle)' }}>
        <button className="btn btn-secondary" onClick={onClose}>Cancel</button>
        <button className="btn btn-primary" onClick={run} disabled={running}>
          {done ? 'Run again' : <>Run {tool.name.toLowerCase()} <Icon.ArrowRight size={13} /></>}
        </button>
      </div>
    </Modal>
  );
}

/* ───── API KEYS ───── */

function ApiKeysPage() {
  const [keys, setKeys] = React.useState(MOCK_API_KEYS);
  const [showCreate, setShowCreate] = React.useState(false);
  const [revealed, setRevealed] = React.useState({});

  const create = (name) => {
    setKeys([{ id: 'k' + Math.random().toString(36).slice(2, 5), name, key: 'vmn_live_' + Math.random().toString(36).slice(2, 14), created: 'just now', last: 'never', scopes: ['index:*', 'tools:*'] }, ...keys]);
    setShowCreate(false);
  };

  return (
    <div className="page-content">
      <div className="page-header" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 16 }}>
        <div>
          <h1 className="page-title">API Keys</h1>
          <p className="page-subtitle">Authenticate requests to the Vamana REST API and Python SDK.</p>
        </div>
        <button className="btn btn-primary" onClick={() => setShowCreate(true)}>
          <Icon.Plus size={14} /> New API key
        </button>
      </div>

      <div className="card">
        <div style={{
          display: 'grid', gridTemplateColumns: '180px 1fr 200px 110px 110px 30px',
          gap: 12, padding: '12px 20px',
          borderBottom: '1px solid var(--border-default)', background: 'var(--bg-inset)',
        }}>
          {['Name', 'Key', 'Scopes', 'Created', 'Last used', ''].map((h, i) => (
            <span key={i} className="eyebrow" style={{ fontSize: 10 }}>{h}</span>
          ))}
        </div>
        {keys.map((k, i) => (
          <div key={k.id} style={{
            display: 'grid', gridTemplateColumns: '180px 1fr 200px 110px 110px 30px',
            gap: 12, padding: '14px 20px', alignItems: 'center',
            borderBottom: i < keys.length - 1 ? '1px solid var(--border-subtle)' : 'none',
          }}>
            <span style={{ fontSize: 13, fontWeight: 500 }}>{k.name}</span>
            <div style={{ display: 'flex', gap: 6, alignItems: 'center', minWidth: 0 }}>
              <code style={{
                fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-secondary)',
                background: 'var(--bg-code)', padding: '4px 8px', borderRadius: 3, flex: 1,
                whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
              }}>
                {revealed[k.id] ? k.key.replace('••••••••••••', 'k7zT9aP3xQv8') : k.key}
              </code>
              <button className="btn btn-ghost btn-sm" onClick={() => setRevealed({ ...revealed, [k.id]: !revealed[k.id] })} style={{ width: 28, padding: 0 }}>
                {revealed[k.id] ? <Icon.EyeOff size={13} /> : <Icon.Eye size={13} />}
              </button>
              <button className="btn btn-ghost btn-sm" style={{ width: 28, padding: 0 }}><Icon.Copy size={13} /></button>
            </div>
            <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
              {k.scopes.map(s => <span key={s} className="badge badge-neutral">{s}</span>)}
            </div>
            <span style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>{k.created}</span>
            <span style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>{k.last}</span>
            <Icon.More size={14} color="var(--text-tertiary)" />
          </div>
        ))}
      </div>

      {/* SDK card */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginTop: 24 }}>
        <CodeCard title="Python SDK" lang="python" code={`from vamana import Vamana

client = Vamana(api_key="vmn_live_…")

# Search an index
results = client.indexes.search(
    index_id="idx_8a3f",
    query="person climbing fence at night",
    limit=5,
)
for r in results:
    print(r.timestamp, r.score, r.video_id)`} />
        <CodeCard title="cURL" lang="bash" code={`curl https://api.vamana.ai/v1/search \\
  -H "Authorization: Bearer vmn_live_…" \\
  -H "Content-Type: application/json" \\
  -d '{
    "index_id": "idx_8a3f",
    "query": "person climbing fence at night",
    "limit": 5
  }'`} />
      </div>

      {showCreate && <CreateKeyModal onCreate={create} onClose={() => setShowCreate(false)} />}
    </div>
  );
}

function CreateKeyModal({ onCreate, onClose }) {
  const [name, setName] = React.useState('');
  return (
    <Modal onClose={onClose} title="Create API key" width={480}>
      <div style={{ display: 'grid', gap: 14 }}>
        <div>
          <label className="label">Key name</label>
          <input className="input" autoFocus placeholder="e.g. backend-prod" value={name} onChange={(e) => setName(e.target.value)} />
        </div>
        <div>
          <label className="label">Scopes</label>
          {['Read indexes & search', 'Write indexes & encode', 'Run tools', 'Manage billing'].map((s, i) => (
            <Checkbox key={i} label={s} defaultChecked={i < 3} />
          ))}
        </div>
      </div>
      <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 24, paddingTop: 16, borderTop: '1px solid var(--border-subtle)' }}>
        <button className="btn btn-secondary" onClick={onClose}>Cancel</button>
        <button className="btn btn-primary" onClick={() => onCreate(name || 'untitled')}>Create key</button>
      </div>
    </Modal>
  );
}

function CodeCard({ title, lang, code }) {
  const [copied, setCopied] = React.useState(false);
  return (
    <div className="card" style={{ overflow: 'hidden' }}>
      <div style={{ padding: '10px 14px', borderBottom: '1px solid var(--border-subtle)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span className="eyebrow">{title}</span>
        <button className="btn btn-ghost btn-sm" onClick={() => { setCopied(true); setTimeout(() => setCopied(false), 1500); }}>
          {copied ? <Icon.Check size={12} color="var(--positive)" /> : <Icon.Copy size={12} />}
          <span style={{ fontSize: 11 }}>{copied ? 'Copied' : 'Copy'}</span>
        </button>
      </div>
      <pre style={{
        padding: 16, margin: 0, background: 'var(--bg-code)',
        fontFamily: 'var(--font-mono)', fontSize: 11.5,
        color: 'var(--text-primary)', lineHeight: 1.65,
        overflowX: 'auto',
      }}>{code}</pre>
    </div>
  );
}

/* ───── DOCS ───── */

function DocsPage() {
  const [section, setSection] = React.useState('quickstart');

  const sections = [
    { group: 'GETTING STARTED', items: [
      { id: 'quickstart', label: 'Quickstart' },
      { id: 'authentication', label: 'Authentication' },
      { id: 'concepts', label: 'Core concepts' },
    ]},
    { group: 'INDEXES', items: [
      { id: 'create-index', label: 'Create an index' },
      { id: 'search', label: 'Search' },
      { id: 'manage-index', label: 'Manage videos' },
    ]},
    { group: 'DWARF', items: [
      { id: 'encode', label: 'Encoding API' },
      { id: 'decode', label: 'Decoding & playback' },
      { id: 'format', label: '.dwarf file format' },
      { id: 'modal', label: 'Deploy on Modal' },
    ]},
    { group: 'TOOLS', items: [
      { id: 'embeddings', label: 'Embeddings' },
      { id: 'captioning', label: 'Captioning' },
      { id: 'highlights', label: 'Highlight extraction' },
      { id: 'segmentation', label: 'Scene segmentation' },
    ]},
    { group: 'REFERENCE', items: [
      { id: 'sdk', label: 'Python SDK' },
      { id: 'rest', label: 'REST API' },
      { id: 'errors', label: 'Errors & retries' },
      { id: 'limits', label: 'Rate limits' },
    ]},
  ];

  return (
    <div className="page-content" style={{ maxWidth: 1280, padding: '0' }}>
      <div style={{ display: 'grid', gridTemplateColumns: '220px 1fr 220px', gap: 0, minHeight: 'calc(100vh - 56px)' }}>
        {/* Left */}
        <aside style={{ borderRight: '1px solid var(--border-subtle)', padding: '32px 0' }}>
          <div style={{ padding: '0 20px 20px' }}>
            <div style={{ position: 'relative' }}>
              <Icon.Search size={13} color="var(--text-tertiary)"
                style={{ position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)' }} />
              <input className="input" placeholder="Search docs…" style={{ paddingLeft: 30, height: 32, fontSize: 12 }} />
            </div>
          </div>
          {sections.map((sec, i) => (
            <div key={i} style={{ marginBottom: 16 }}>
              <div className="eyebrow" style={{ padding: '8px 20px', fontSize: 10 }}>{sec.group}</div>
              {sec.items.map(it => (
                <button key={it.id} onClick={() => setSection(it.id)}
                  style={{
                    display: 'block', width: '100%', textAlign: 'left',
                    padding: '6px 20px',
                    fontSize: 13,
                    color: section === it.id ? 'var(--accent)' : 'var(--text-secondary)',
                    background: section === it.id ? 'var(--accent-muted)' : 'transparent',
                    fontWeight: section === it.id ? 500 : 400,
                    borderLeft: `2px solid ${section === it.id ? 'var(--accent)' : 'transparent'}`,
                    marginLeft: -1,
                  }}>
                  {it.label}
                </button>
              ))}
            </div>
          ))}
        </aside>

        {/* Center */}
        <main style={{ padding: '40px 48px', maxWidth: 760 }}>
          <div className="eyebrow" style={{ marginBottom: 8 }}>Getting started</div>
          <h1 style={{ fontSize: 32, fontWeight: 600, letterSpacing: '-0.02em', margin: '0 0 12px' }}>Quickstart</h1>
          <p style={{ fontSize: 15, color: 'var(--text-secondary)', lineHeight: 1.65, marginBottom: 28 }}>
            Get up and running with Vamana in under five minutes. Build a video index, search it with natural language,
            and stream compressed playback — all from your editor.
          </p>

          <h2 style={{ fontSize: 19, fontWeight: 600, margin: '32px 0 12px' }}>1. Install the SDK</h2>
          <CodeCard title="terminal" code={`pip install vamana`} />

          <h2 style={{ fontSize: 19, fontWeight: 600, margin: '32px 0 12px' }}>2. Create an index</h2>
          <p style={{ fontSize: 14, color: 'var(--text-secondary)', lineHeight: 1.65, marginBottom: 12 }}>
            Indexes are searchable collections of videos. Each video is automatically split into semantic
            segments and embedded with our Marengo model.
          </p>
          <div style={{ marginBottom: 16 }}>
            <CodeCard title="python" code={`from vamana import Vamana

client = Vamana(api_key="vmn_live_…")

index = client.indexes.create(
    name="surveillance-jan-2026",
    model="marengo-2.7",
    options={"index_audio": True, "auto_dwarf": True},
)
print(index.id)  # idx_8a3f`} />
          </div>

          <h2 style={{ fontSize: 19, fontWeight: 600, margin: '32px 0 12px' }}>3. Add videos</h2>
          <CodeCard title="python" code={`for path in glob.glob("./recordings/*.mp4"):
    client.videos.upload(index_id=index.id, file=path)`} />

          <h2 style={{ fontSize: 19, fontWeight: 600, margin: '32px 0 12px' }}>4. Search</h2>
          <CodeCard title="python" code={`results = client.indexes.search(
    index_id=index.id,
    query="person climbing fence at night",
    limit=5,
)

for r in results:
    print(f"{r.video} @ {r.timestamp}: {r.score:.2f}")`} />

          <div style={{ marginTop: 32, padding: 16, background: 'var(--accent-subtle)', borderRadius: 'var(--radius-md)', display: 'flex', gap: 12 }}>
            <Icon.Sparkles size={18} color="var(--accent)" />
            <div>
              <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--accent-text)', marginBottom: 4 }}>Next: encode with Dwarf</div>
              <div style={{ fontSize: 12.5, color: 'var(--accent-text)', lineHeight: 1.5 }}>
                Compress your archive 30–40× with our DCVC-RT models. <a style={{ textDecoration: 'underline', cursor: 'pointer' }}>Read the encode guide →</a>
              </div>
            </div>
          </div>
        </main>

        {/* Right */}
        <aside style={{ borderLeft: '1px solid var(--border-subtle)', padding: '40px 24px' }}>
          <div className="eyebrow" style={{ marginBottom: 12 }}>On this page</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {['Install the SDK', 'Create an index', 'Add videos', 'Search'].map((t, i) => (
              <a key={i} style={{
                fontSize: 12, color: i === 0 ? 'var(--accent)' : 'var(--text-secondary)',
                cursor: 'pointer',
                paddingLeft: 8, borderLeft: `2px solid ${i === 0 ? 'var(--accent)' : 'transparent'}`,
              }}>{t}</a>
            ))}
          </div>
          <div style={{ marginTop: 32, paddingTop: 20, borderTop: '1px solid var(--border-subtle)' }}>
            <div className="eyebrow" style={{ marginBottom: 10 }}>Resources</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, fontSize: 12 }}>
              <a style={{ color: 'var(--text-secondary)', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6 }}><Icon.Github size={12} /> GitHub repo</a>
              <a style={{ color: 'var(--text-secondary)', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6 }}><Icon.Book size={12} /> Cookbook</a>
              <a style={{ color: 'var(--text-secondary)', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6 }}><Icon.Mail size={12} /> Support</a>
            </div>
          </div>
        </aside>
      </div>
    </div>
  );
}

/* ───── CREDITS ───── */

function CreditsPage({ credits, onAddCredits }) {
  const [tab, setTab] = React.useState('plan');

  const plans = [
    { id: 'free', name: 'Free', price: '$0', sub: '/ month', features: ['200 credits / mo', '1 index, up to 5 hours', 'Community support', 'Marengo 2.7 model'] },
    { id: 'pro', name: 'Pro', price: '$49', sub: '/ month', features: ['10,000 credits / mo', 'Unlimited indexes, 500 hr', 'Email support · 24h', 'All models · Dwarf encode', 'Custom fine-tuning add-on'], current: true },
    { id: 'team', name: 'Team', price: '$249', sub: '/ month', features: ['60,000 credits / mo', 'Up to 10 seats', 'Priority support', 'SSO + audit logs', 'Webhook integrations'] },
    { id: 'enterprise', name: 'Enterprise', price: 'Custom', sub: '', features: ['Volume discounts', 'On-prem / VPC deploy', 'Dedicated GPU pool', 'SLA + SOC2', 'Solutions engineering'] },
  ];

  return (
    <div className="page-content">
      <div className="page-header">
        <h1 className="page-title">Credits & Billing</h1>
        <p className="page-subtitle">Vamana credits power every API call, encode job, and tool run.</p>
      </div>

      {/* Balance card */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 16, marginBottom: 32 }}>
        <div className="card" style={{ padding: 24, position: 'relative', overflow: 'hidden' }}>
          <div className="eyebrow" style={{ marginBottom: 8 }}>Current balance</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
            <span className="mono" style={{ fontSize: 44, fontWeight: 500, letterSpacing: '-0.03em', color: 'var(--text-primary)', lineHeight: 1 }}>
              {credits.toLocaleString()}
            </span>
            <span style={{ fontSize: 14, color: 'var(--text-tertiary)' }}>credits</span>
          </div>
          <div style={{ marginTop: 12, display: 'flex', gap: 24, fontSize: 12, color: 'var(--text-secondary)' }}>
            <span>Plan: <strong style={{ color: 'var(--text-primary)' }}>Pro</strong></span>
            <span>Renews <strong style={{ color: 'var(--text-primary)' }}>May 1, 2026</strong></span>
            <span>Used this cycle: <strong style={{ color: 'var(--text-primary)' }}>2,238 / 10,000</strong></span>
          </div>

          <div style={{ marginTop: 20, height: 6, background: 'var(--border-subtle)', borderRadius: 3, overflow: 'hidden' }}>
            <div style={{ width: '22%', height: '100%', background: 'linear-gradient(90deg, var(--accent), var(--accent-light))', borderRadius: 3 }} />
          </div>

          <div style={{ marginTop: 20, display: 'flex', gap: 8 }}>
            <button className="btn btn-primary" onClick={() => onAddCredits(5000)}>
              <Icon.Plus size={14} /> Add credits
            </button>
            <button className="btn btn-secondary">Manage plan</button>
          </div>
        </div>

        <div className="card card-padded">
          <div className="eyebrow" style={{ marginBottom: 8 }}>Add-on credit packs</div>
          <p style={{ fontSize: 12, color: 'var(--text-secondary)', marginBottom: 16 }}>One-time top-ups. Never expire while subscription is active.</p>
          {[
            { credits: 1000, price: 10 },
            { credits: 10000, price: 90, save: '10%' },
            { credits: 100000, price: 800, save: '20%' },
          ].map((p, i) => (
            <button key={i} onClick={() => onAddCredits(p.credits)}
              style={{
                width: '100%', padding: '10px 14px', marginBottom: 8,
                display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-md)',
                background: 'var(--bg-surface)', textAlign: 'left',
                transition: 'all var(--duration-fast)',
              }}
              onMouseEnter={(e) => e.currentTarget.style.borderColor = 'var(--accent)'}
              onMouseLeave={(e) => e.currentTarget.style.borderColor = 'var(--border-subtle)'}>
              <div>
                <div className="mono" style={{ fontSize: 13, fontWeight: 500 }}>+{p.credits.toLocaleString()} credits</div>
                {p.save && <div style={{ fontSize: 10, color: 'var(--positive)', marginTop: 2 }}>Save {p.save}</div>}
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <span className="mono" style={{ fontSize: 13, fontWeight: 500 }}>${p.price}</span>
                <Icon.ArrowRight size={12} color="var(--text-tertiary)" />
              </div>
            </button>
          ))}
        </div>
      </div>

      {/* Tabs */}
      <div style={{ borderBottom: '1px solid var(--border-default)', marginBottom: 24, display: 'flex', gap: 4 }}>
        {[
          { id: 'plan', label: 'Plans' },
          { id: 'usage', label: 'Usage history' },
          { id: 'invoices', label: 'Invoices' },
          { id: 'method', label: 'Payment method' },
        ].map(t => (
          <button key={t.id} onClick={() => setTab(t.id)}
            style={{
              padding: '12px 14px',
              fontSize: 13, color: tab === t.id ? 'var(--text-primary)' : 'var(--text-secondary)',
              fontWeight: tab === t.id ? 500 : 400,
              borderBottom: `2px solid ${tab === t.id ? 'var(--accent)' : 'transparent'}`,
              marginBottom: -1,
            }}>
            {t.label}
          </button>
        ))}
      </div>

      {tab === 'plan' && (
        <div style={{ padding: '64px 32px', textAlign: 'center', maxWidth: 560, margin: '0 auto' }}>
          <div style={{
            width: 56, height: 56, borderRadius: 12, margin: '0 auto 20px',
            background: 'var(--bg-inset)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <Icon.Coins size={24} color="var(--text-tertiary)" />
          </div>
          <div className="eyebrow" style={{ marginBottom: 10 }}>// Pricing — coming soon</div>
          <h3 style={{ fontSize: 22, fontWeight: 600, letterSpacing: '-0.01em', margin: '0 0 10px' }}>
            Plans yet to be decided
          </h3>
          <p style={{ fontSize: 14, color: 'var(--text-secondary)', lineHeight: 1.6, margin: '0 0 24px' }}>
            We're still finalizing how Vamana is metered and packaged across Dwarf, Mellon, and Anvesha. Until plans go live, your workspace runs on a complimentary preview tier — no limits, no surprises.
          </p>
          <div style={{
            display: 'inline-flex', alignItems: 'center', gap: 10,
            padding: '12px 16px', borderRadius: 'var(--radius-md)',
            background: 'var(--accent-subtle)', color: 'var(--accent-text)',
            fontSize: 13,
          }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)' }} />
            <span>Preview access · all infrastructure unlocked</span>
          </div>
          <div style={{ marginTop: 32, display: 'flex', justifyContent: 'center', gap: 8 }}>
            <button className="btn btn-secondary"><Icon.Mail size={13} /> Get notified when plans launch</button>
            <button className="btn btn-primary">Talk to the team <Icon.ArrowRight size={13} /></button>
          </div>
        </div>
      )}

      {tab === 'usage' && (
        <div className="card">
          <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--border-subtle)' }}>
            <h3 style={{ fontSize: 14, fontWeight: 600, margin: 0 }}>Last 30 days · 8,422 credits</h3>
          </div>
          <div style={{ padding: 24, display: 'flex', alignItems: 'flex-end', gap: 4, height: 200 }}>
            {Array.from({ length: 30 }).map((_, i) => {
              const h = 20 + Math.sin(i * 0.4) * 30 + Math.random() * 50;
              return (
                <div key={i} style={{
                  flex: 1, height: `${h}%`,
                  background: i > 25 ? 'var(--accent)' : 'var(--accent-subtle)',
                  borderRadius: 2,
                }} />
              );
            })}
          </div>
          {/* Breakdown */}
          <div style={{ padding: '16px 20px', borderTop: '1px solid var(--border-subtle)' }}>
            {[
              { name: 'Embedding (Marengo 2.7)', used: 3812, color: 'var(--accent)' },
              { name: 'Captioning', used: 2104, color: '#D97706' },
              { name: 'Dwarf encoding', used: 1428, color: '#6B6966' },
              { name: 'Search queries', used: 624, color: '#9C9A96' },
              { name: 'Highlights + segmentation', used: 454, color: '#C4C3BE' },
            ].map((s, i) => (
              <div key={i} style={{ padding: '10px 0', borderTop: i > 0 ? '1px solid var(--border-subtle)' : 'none', display: 'flex', alignItems: 'center', gap: 12 }}>
                <span style={{ width: 10, height: 10, borderRadius: 2, background: s.color }} />
                <span style={{ flex: 1, fontSize: 13 }}>{s.name}</span>
                <span className="mono" style={{ fontSize: 12, color: 'var(--text-secondary)' }}>{s.used.toLocaleString()} credits</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {tab === 'invoices' && (
        <div className="card">
          <div style={{
            display: 'grid', gridTemplateColumns: '120px 1fr 110px 110px 100px 30px',
            gap: 12, padding: '12px 20px',
            borderBottom: '1px solid var(--border-default)', background: 'var(--bg-inset)',
          }}>
            {['Date', 'Description', 'Amount', 'Status', 'Invoice', ''].map((h, i) => (
              <span key={i} className="eyebrow" style={{ fontSize: 10 }}>{h}</span>
            ))}
          </div>
          {[
            { date: 'Apr 1, 2026', desc: 'Pro plan · monthly', amt: '$49.00', status: 'Paid', no: 'INV-2026-04-001' },
            { date: 'Apr 12, 2026', desc: 'Add-on · 10,000 credits', amt: '$90.00', status: 'Paid', no: 'INV-2026-04-018' },
            { date: 'Mar 1, 2026', desc: 'Pro plan · monthly', amt: '$49.00', status: 'Paid', no: 'INV-2026-03-001' },
            { date: 'Feb 1, 2026', desc: 'Pro plan · monthly', amt: '$49.00', status: 'Paid', no: 'INV-2026-02-001' },
          ].map((inv, i) => (
            <div key={i} style={{
              display: 'grid', gridTemplateColumns: '120px 1fr 110px 110px 100px 30px',
              gap: 12, padding: '12px 20px', alignItems: 'center',
              borderBottom: '1px solid var(--border-subtle)', fontSize: 13,
            }}>
              <span style={{ color: 'var(--text-secondary)' }}>{inv.date}</span>
              <span>{inv.desc}</span>
              <span className="mono">{inv.amt}</span>
              <span className="badge badge-positive">{inv.status}</span>
              <span className="mono" style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>{inv.no}</span>
              <Icon.Download size={13} color="var(--text-tertiary)" />
            </div>
          ))}
        </div>
      )}

      {tab === 'method' && (
        <div className="card card-padded" style={{ maxWidth: 480 }}>
          <h4 style={{ fontSize: 14, fontWeight: 600, margin: '0 0 16px' }}>Payment method</h4>
          <div style={{ padding: 16, border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-md)', display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{ width: 44, height: 30, background: '#1A1F71', borderRadius: 4, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'white', fontSize: 11, fontWeight: 700, fontFamily: 'serif', fontStyle: 'italic' }}>VISA</div>
            <div>
              <div className="mono" style={{ fontSize: 13 }}>•••• •••• •••• 4242</div>
              <div style={{ fontSize: 11, color: 'var(--text-tertiary)', marginTop: 2 }}>Expires 09/2028 · Default</div>
            </div>
            <button className="btn btn-ghost btn-sm" style={{ marginLeft: 'auto' }}>Replace</button>
          </div>
          <button className="btn btn-secondary" style={{ marginTop: 14 }}>
            <Icon.Plus size={13} /> Add another method
          </button>
        </div>
      )}
    </div>
  );
}

/* ───── SETTINGS ───── */

function SettingsPage({ user, onLogout }) {
  const [section, setSection] = React.useState('profile');
  const sections = [
    { id: 'profile', label: 'Profile', icon: 'User' },
    { id: 'workspace', label: 'Workspace', icon: 'Box' },
    { id: 'team', label: 'Team', icon: 'User' },
    { id: 'webhooks', label: 'Webhooks', icon: 'Globe' },
    { id: 'security', label: 'Security', icon: 'Lock' },
    { id: 'preferences', label: 'Preferences', icon: 'Settings' },
  ];

  return (
    <div className="page-content">
      <div className="page-header">
        <h1 className="page-title">Settings</h1>
        <p className="page-subtitle">Manage your account, workspace, and team.</p>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '200px 1fr', gap: 32, alignItems: 'start' }}>
        <aside style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          {sections.map(s => {
            const Comp = Icon[s.icon];
            return (
              <button key={s.id} onClick={() => setSection(s.id)}
                style={{
                  display: 'flex', alignItems: 'center', gap: 10,
                  padding: '8px 12px',
                  fontSize: 13, color: section === s.id ? 'var(--accent)' : 'var(--text-secondary)',
                  background: section === s.id ? 'var(--accent-muted)' : 'transparent',
                  fontWeight: section === s.id ? 500 : 400,
                  borderRadius: 'var(--radius-md)', textAlign: 'left',
                }}>
                <Comp size={14} /> {s.label}
              </button>
            );
          })}
        </aside>

        <div>
          {section === 'profile' && (
            <div className="card card-padded" style={{ maxWidth: 600 }}>
              <h3 style={{ fontSize: 15, fontWeight: 600, margin: '0 0 4px' }}>Profile</h3>
              <p style={{ fontSize: 13, color: 'var(--text-secondary)', margin: '0 0 24px' }}>Visible to teammates in shared workspaces.</p>

              <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginBottom: 24 }}>
                <Avatar user={user} size={64} />
                <div>
                  <button className="btn btn-secondary btn-sm">Upload photo</button>
                  <div style={{ marginTop: 6, fontSize: 11, color: 'var(--text-tertiary)' }}>JPG or PNG, up to 1 MB</div>
                </div>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                <div>
                  <label className="label">Full name</label>
                  <input className="input" defaultValue={user.name} />
                </div>
                <div>
                  <label className="label">Email</label>
                  <input className="input" defaultValue={user.email} />
                </div>
                <div>
                  <label className="label">Role</label>
                  <select className="input"><option>Engineer</option><option>Researcher</option><option>PM</option><option>Founder</option></select>
                </div>
                <div>
                  <label className="label">Time zone</label>
                  <select className="input"><option>America / Los Angeles</option><option>America / New York</option><option>Europe / London</option></select>
                </div>
              </div>

              <div style={{ marginTop: 20, display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
                <button className="btn btn-secondary">Cancel</button>
                <button className="btn btn-primary">Save changes</button>
              </div>
            </div>
          )}

          {section === 'workspace' && (
            <div className="card card-padded" style={{ maxWidth: 600 }}>
              <h3 style={{ fontSize: 15, fontWeight: 600, margin: '0 0 24px' }}>Workspace</h3>
              <div style={{ marginBottom: 14 }}>
                <label className="label">Workspace name</label>
                <input className="input" defaultValue="Acme Surveillance" />
              </div>
              <div style={{ marginBottom: 14 }}>
                <label className="label">Workspace ID</label>
                <input className="input mono" defaultValue="ws_a8f3k2" disabled />
              </div>
              <div>
                <label className="label">Default region</label>
                <select className="input"><option>us-west (Oregon)</option><option>us-east (Virginia)</option><option>eu-west (Ireland)</option><option>ap-south (Mumbai)</option></select>
              </div>
            </div>
          )}

          {section === 'team' && (
            <div className="card" style={{ maxWidth: 720 }}>
              <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--border-subtle)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <h3 style={{ fontSize: 14, fontWeight: 600, margin: 0 }}>Team members · 4</h3>
                <button className="btn btn-primary btn-sm"><Icon.Plus size={12} /> Invite</button>
              </div>
              {[
                { name: user.name, email: user.email, role: 'Owner', you: true },
                { name: 'Priya Sharma', email: 'priya@acme.com', role: 'Admin' },
                { name: 'Raj Patel', email: 'raj@acme.com', role: 'Member' },
                { name: 'Sara Chen', email: 'sara@acme.com', role: 'Viewer' },
              ].map((m, i) => (
                <div key={i} style={{
                  padding: '14px 20px',
                  borderBottom: i < 3 ? '1px solid var(--border-subtle)' : 'none',
                  display: 'flex', alignItems: 'center', gap: 14,
                }}>
                  <Avatar user={m} size={32} />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 500 }}>{m.name} {m.you && <span className="badge badge-neutral" style={{ marginLeft: 6 }}>You</span>}</div>
                    <div style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>{m.email}</div>
                  </div>
                  <select className="input" style={{ width: 110, height: 32, fontSize: 12 }} defaultValue={m.role}>
                    <option>Owner</option><option>Admin</option><option>Member</option><option>Viewer</option>
                  </select>
                </div>
              ))}
            </div>
          )}

          {section === 'webhooks' && (
            <div className="card card-padded" style={{ maxWidth: 720 }}>
              <h3 style={{ fontSize: 15, fontWeight: 600, margin: '0 0 4px' }}>Webhooks</h3>
              <p style={{ fontSize: 13, color: 'var(--text-secondary)', margin: '0 0 20px' }}>Receive HTTP callbacks when jobs complete.</p>
              <div style={{ padding: 14, border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-md)', display: 'flex', alignItems: 'center', gap: 12 }}>
                <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--positive)' }} />
                <code style={{ flex: 1, fontFamily: 'var(--font-mono)', fontSize: 12 }}>https://api.acme.com/vamana/webhooks</code>
                <span className="badge badge-positive">Active</span>
                <button className="btn btn-ghost btn-sm"><Icon.More size={13} /></button>
              </div>
              <button className="btn btn-secondary" style={{ marginTop: 14 }}><Icon.Plus size={13} /> Add endpoint</button>
            </div>
          )}

          {section === 'security' && (
            <div style={{ maxWidth: 600 }}>
              <div className="card card-padded" style={{ marginBottom: 16 }}>
                <h3 style={{ fontSize: 15, fontWeight: 600, margin: '0 0 16px' }}>Security</h3>
                {[
                  { label: 'Two-factor authentication', sub: 'Required for owners', status: 'enabled' },
                  { label: 'SSO via Google Workspace', sub: 'Sign in with your work email', status: 'enabled' },
                  { label: 'IP allowlist', sub: 'Restrict API access by IP range', status: 'disabled' },
                ].map((s, i) => (
                  <div key={i} style={{ padding: '12px 0', borderTop: i > 0 ? '1px solid var(--border-subtle)' : 'none', display: 'flex', alignItems: 'center', gap: 12 }}>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 13, fontWeight: 500 }}>{s.label}</div>
                      <div style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>{s.sub}</div>
                    </div>
                    {s.status === 'enabled'
                      ? <span className="badge badge-positive">Enabled</span>
                      : <button className="btn btn-secondary btn-sm">Enable</button>}
                  </div>
                ))}
              </div>
              <button onClick={onLogout} className="btn btn-secondary" style={{ color: 'var(--negative)' }}>
                <Icon.Logout size={13} /> Sign out everywhere
              </button>
            </div>
          )}

          {section === 'preferences' && (
            <div className="card card-padded" style={{ maxWidth: 600 }}>
              <h3 style={{ fontSize: 15, fontWeight: 600, margin: '0 0 16px' }}>Preferences</h3>
              {[
                { label: 'Email me on job completion', def: true },
                { label: 'Email weekly usage summary', def: true },
                { label: 'Show keyboard shortcuts hints', def: false },
                { label: 'Use compact density', def: false },
              ].map((p, i) => <Checkbox key={i} label={p.label} defaultChecked={p.def} />)}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ToolsPage, ApiKeysPage, DocsPage, CreditsPage, SettingsPage });
