// Settings — team, billing, workspace
function Settings() {
  const [tab, setTab] = React.useState('team');
  const tabs = [
    { id: 'workspace', label: 'Workspace' },
    { id: 'team', label: 'Team' },
    { id: 'billing', label: 'Billing & usage' },
    { id: 'api', label: 'API & webhooks' },
    { id: 'security', label: 'Security' },
    { id: 'notifications', label: 'Notifications' },
  ];

  return (
    <div>
      <div className="page-hd">
        <div className="page-hd-l">
          <div className="page-eyebrow">Settings · demiurge / ext · pro plan</div>
          <h1 className="page-title">Settings</h1>
          <div className="page-sub">Workspace, team, billing, and platform settings.</div>
        </div>
      </div>

      <div style={{ padding: '20px 24px 0', display: 'flex', gap: 4, borderBottom: '1px solid var(--border)' }}>
        {tabs.map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            padding: '10px 14px',
            fontSize: 13,
            color: tab === t.id ? 'var(--text)' : 'var(--text-dim)',
            borderBottom: tab === t.id ? '2px solid var(--violet)' : '2px solid transparent',
            marginBottom: -1,
          }}>{t.label}</button>
        ))}
      </div>

      <div style={{ padding: 24 }}>
        {tab === 'team' && <TeamTab/>}
        {tab === 'billing' && <BillingTab/>}
        {tab === 'workspace' && <WorkspaceTab/>}
        {tab === 'api' && <ApiTab/>}
        {tab === 'security' && <SecurityTab/>}
        {tab === 'notifications' && <NotifTab/>}
      </div>
    </div>
  );
}

function TeamTab() {
  return (
    <div className="panel">
      <div className="panel-hd">
        <h3>Team members · {TEAM.length}</h3>
        <button className="btn primary sm"><Icon.Plus className="icon"/>Invite</button>
      </div>
      <table className="dem">
        <thead>
          <tr><th>Member</th><th>Role</th><th>Email</th><th>Last active</th><th></th></tr>
        </thead>
        <tbody>
          {TEAM.map((m, i) => (
            <tr key={i}>
              <td>
                <div className="row">
                  <div style={{ width: 32, height: 32, borderRadius: '50%', background: 'linear-gradient(135deg, rgba(139, 107, 255, 0.3), rgba(75, 232, 255, 0.2))', border: '1px solid var(--border)', display: 'grid', placeItems: 'center', fontSize: 11, fontFamily: 'var(--font-mono)', fontWeight: 600 }}>{m.avatar}</div>
                  <span>{m.name}</span>
                </div>
              </td>
              <td>
                <span className="tag violet">{m.role.split(' · ')[0]}</span>
                <span className="dim mono" style={{ fontSize: 11, marginLeft: 6 }}>{m.role.split(' · ')[1]}</span>
              </td>
              <td className="mono dim" style={{ fontSize: 12 }}>{m.email}</td>
              <td className="mono dim" style={{ fontSize: 11 }}>{m.last}</td>
              <td><Icon.More style={{ width: 14, height: 14, color: 'var(--text-faint)' }}/></td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function BillingTab() {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div className="panel" style={{ background: 'linear-gradient(135deg, rgba(139, 107, 255, 0.04), rgba(75, 232, 255, 0.02))', borderColor: 'rgba(139, 107, 255, 0.2)' }}>
        <div className="panel-body" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: 22 }}>
          <div>
            <div className="mono faint" style={{ fontSize: 10, letterSpacing: '0.12em', marginBottom: 8 }}>CURRENT PLAN</div>
            <div className="serif" style={{ fontSize: 24, fontStyle: 'italic' }}>Pro</div>
            <div className="mono dim" style={{ fontSize: 11, marginTop: 4 }}>£500 / month · billed annually</div>
          </div>
          <div>
            <div className="mono faint" style={{ fontSize: 10, letterSpacing: '0.12em', marginBottom: 8 }}>OPERATOR BUDGET · MTD</div>
            <div className="serif" style={{ fontSize: 24, fontStyle: 'italic' }}>£1,842</div>
            <div className="mono dim" style={{ fontSize: 11, marginTop: 4 }}>of £5,000 cap · 36% used</div>
            <div className="bar-track" style={{ marginTop: 6, height: 4 }}>
              <div className="bar-fill" style={{ width: '36%' }}/>
            </div>
          </div>
          <div>
            <div className="mono faint" style={{ fontSize: 10, letterSpacing: '0.12em', marginBottom: 8 }}>NEXT INVOICE</div>
            <div className="serif" style={{ fontSize: 24, fontStyle: 'italic' }}>£2,342</div>
            <div className="mono dim" style={{ fontSize: 11, marginTop: 4 }}>est. on Jun 1 · 10 days</div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', gap: 6 }}>
            <button className="btn primary">Upgrade to Scale</button>
            <button className="btn ghost sm">View invoices</button>
          </div>
        </div>
      </div>

      <PaymentMethodPanel/>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <div className="panel">
          <div className="panel-hd">
            <h3>Usage this cycle</h3>
            <span className="mono faint" style={{ fontSize: 10 }}>MAY 1 – MAY 22</span>
          </div>
          <div className="panel-body" style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            {[
              { l: 'Agent compute', v: 1842, max: 5000, unit: '£' },
              { l: 'Voice minutes', v: 414, max: 2000, unit: 'min' },
              { l: 'SMS sent', v: 1820, max: 10000, unit: '' },
              { l: 'Emails sent', v: 28640, max: 100000, unit: '' },
              { l: 'Workflow runs', v: 8412, max: 50000, unit: '' },
            ].map(u => (
              <div key={u.l}>
                <div className="row" style={{ justifyContent: 'space-between', marginBottom: 6 }}>
                  <span style={{ fontSize: 12 }}>{u.l}</span>
                  <span className="mono dim" style={{ fontSize: 11 }}>{u.unit === '£' ? '£' : ''}{u.v.toLocaleString()}{u.unit !== '£' ? ' ' + u.unit : ''} <span className="faint">/ {u.unit === '£' ? '£' : ''}{u.max.toLocaleString()}{u.unit !== '£' ? ' ' + u.unit : ''}</span></span>
                </div>
                <div className="bar-track" style={{ height: 4 }}>
                  <div className="bar-fill flat" style={{ width: `${(u.v / u.max) * 100}%` }}/>
                </div>
              </div>
            ))}
          </div>
        </div>
        <div className="panel">
          <div className="panel-hd"><h3>Recent invoices</h3></div>
          <table className="dem">
            <tbody>
              {[
                { date: '30 Apr 2026', total: 2412, method: 'card', status: 'paid' },
                { date: '31 Mar 2026', total: 2184, method: 'crypto', status: 'paid' },
                { date: '28 Feb 2026', total: 1942, method: 'card', status: 'paid' },
                { date: '31 Jan 2026', total: 1684, method: 'card', status: 'paid' },
                { date: '31 Dec 2025', total: 1412, method: 'crypto', status: 'paid' },
              ].map(inv => (
                <tr key={inv.date}>
                  <td className="mono" style={{ fontSize: 12 }}>{inv.date}</td>
                  <td className="num">£{inv.total.toLocaleString()}</td>
                  <td><span className="mono faint" style={{ fontSize: 10, letterSpacing: '0.1em' }}>{inv.method === 'crypto' ? '◈ USDC' : '▦ CARD'}</span></td>
                  <td><span className="tag live">PAID</span></td>
                  <td><button className="btn ghost sm">Download</button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

function WorkspaceTab() {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 14 }}>
      <div className="panel">
        <div className="panel-hd"><h3>Workspace</h3></div>
        <div className="panel-body" style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <FormField label="WORKSPACE NAME">
            <input style={inputStyle2} defaultValue="Demiurge · ext"/>
          </FormField>
          <FormField label="WORKSPACE URL">
            <div className="row">
              <span className="mono dim" style={{ fontSize: 12 }}>app.demiurge.systems/</span>
              <input style={{ ...inputStyle2, flex: 1 }} defaultValue="ext"/>
            </div>
          </FormField>
          <FormField label="DEFAULT TIMEZONE">
            <select style={inputStyle2}>
              <option>Europe / London (GMT / BST)</option>
              <option>Europe / Berlin (CET / CEST)</option>
              <option>America / New York (ET)</option>
            </select>
          </FormField>
          <FormField label="BRAND COLOR">
            <div className="row">
              <span style={{ width: 32, height: 32, borderRadius: 6, background: 'var(--iridescent)' }}/>
              <input style={{ ...inputStyle2, fontFamily: 'var(--font-mono)' }} defaultValue="#8b6bff"/>
            </div>
          </FormField>
        </div>
      </div>
      <div className="panel">
        <div className="panel-hd"><h3>Danger zone</h3></div>
        <div className="panel-body" style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <DangerRow t="Pause all operators" sub="Temporarily halt every agent. Queue is preserved." cta="Pause all"/>
          <DangerRow t="Export workspace data" sub="Download all contacts, conversations, and agent logs." cta="Export"/>
          <DangerRow t="Delete workspace" sub="Permanent. All data is destroyed. Cannot be undone." cta="Delete" red/>
        </div>
      </div>
    </div>
  );
}

function ApiTab() {
  return (
    <div className="panel">
      <div className="panel-hd">
        <h3>API keys & webhooks</h3>
        <button className="btn primary sm"><Icon.Plus className="icon"/>New key</button>
      </div>
      <table className="dem">
        <thead><tr><th>Name</th><th>Key</th><th>Created</th><th>Last used</th><th>Status</th><th></th></tr></thead>
        <tbody>
          {[
            { n: 'Production · backend', k: 'dem_live_8a9c…2f4e', d: 'Mar 12, 2026', l: '2m ago', s: 'live' },
            { n: 'Staging · backend', k: 'dem_test_4c8d…91ab', d: 'Mar 12, 2026', l: '4h ago', s: 'live' },
            { n: 'Webhook receiver · Slack', k: 'dem_hook_2f1a…cd34', d: 'Apr 2, 2026', l: '11s ago', s: 'live' },
            { n: 'Old laptop · revoke me', k: 'dem_live_9aac…11ff', d: 'Jan 8, 2026', l: '4d ago', s: 'paused' },
          ].map((k, i) => (
            <tr key={i}>
              <td>{k.n}</td>
              <td className="mono" style={{ fontSize: 11, color: 'var(--text-dim)' }}>{k.k}</td>
              <td className="mono dim" style={{ fontSize: 11 }}>{k.d}</td>
              <td className="mono dim" style={{ fontSize: 11 }}>{k.l}</td>
              <td><StatusTag status={k.s}/></td>
              <td><Icon.More style={{ width: 14, height: 14, color: 'var(--text-faint)' }}/></td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function SecurityTab() {
  return (
    <div className="panel">
      <div className="panel-hd"><h3>Security</h3></div>
      <div className="panel-body" style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        <ToggleRow t="SSO required for workspace" sub="All members must authenticate via your SSO provider." on/>
        <ToggleRow t="Two-factor authentication" sub="Require 2FA for all members." on/>
        <ToggleRow t="IP allowlist" sub="Restrict API access to allowed IP ranges." off/>
        <ToggleRow t="Agent decision audit log" sub="Capture every agent decision with full reasoning trace." on/>
        <ToggleRow t="PII redaction in logs" sub="Auto-redact email addresses, phone numbers, and credit cards." on/>
      </div>
    </div>
  );
}

function NotifTab() {
  return (
    <div className="panel">
      <div className="panel-hd"><h3>What should ping you?</h3></div>
      <div className="panel-body" style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        <ToggleRow t="Agent escalation · awaiting human" sub="When an operator hands off to you." on/>
        <ToggleRow t="Meeting booked" sub="When an agent books a meeting on your calendar." on/>
        <ToggleRow t="Budget threshold reached" sub="80% / 100% of daily or monthly cap." on/>
        <ToggleRow t="Integration degraded" sub="Slack-level: rate limits, auth failures, downtime." on/>
        <ToggleRow t="Weekly digest" sub="Sunday 8pm summary of the week ahead." off/>
        <ToggleRow t="New template available" sub="When Demiurge or the community publishes a relevant template." off/>
      </div>
    </div>
  );
}

const inputStyle2 = {
  padding: '8px 12px',
  background: 'rgba(0, 0, 0, 0.25)',
  border: '1px solid var(--border)',
  borderRadius: 'var(--radius)',
  fontSize: 12,
  width: '100%',
  color: 'var(--text)',
};
function FormField({ label, children }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <span className="mono faint" style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.1em' }}>{label}</span>
      {children}
    </div>
  );
}
function ToggleRow({ t, sub, on }) {
  const [v, setV] = React.useState(on);
  return (
    <div className="row" style={{ justifyContent: 'space-between', gap: 18 }}>
      <div>
        <div style={{ fontSize: 13, marginBottom: 4 }}>{t}</div>
        <div className="dim" style={{ fontSize: 11, lineHeight: 1.5 }}>{sub}</div>
      </div>
      <button onClick={() => setV(!v)} style={{
        width: 36, height: 20, borderRadius: 20,
        background: v ? 'var(--iridescent)' : 'rgba(255, 255, 255, 0.08)',
        position: 'relative',
        transition: 'all 0.2s',
        flexShrink: 0,
      }}>
        <span style={{
          position: 'absolute',
          top: 2, left: v ? 18 : 2,
          width: 16, height: 16, borderRadius: '50%',
          background: v ? '#07091a' : 'rgba(255, 255, 255, 0.5)',
          transition: 'all 0.2s',
        }}/>
      </button>
    </div>
  );
}
function DangerRow({ t, sub, cta, red }) {
  return (
    <div className="row" style={{ justifyContent: 'space-between', gap: 18 }}>
      <div>
        <div style={{ fontSize: 13, marginBottom: 4 }}>{t}</div>
        <div className="dim" style={{ fontSize: 11, lineHeight: 1.5 }}>{sub}</div>
      </div>
      <button className="btn" style={red ? { color: 'var(--danger)', borderColor: 'rgba(255, 93, 110, 0.3)' } : {}}>{cta}</button>
    </div>
  );
}

function PaymentMethodPanel() {
  const [method, setMethod] = React.useState('card');
  return (
    <div className="panel">
      <div className="panel-hd">
        <h3>Payment method</h3>
        <span className="mono faint" style={{ fontSize: 10, letterSpacing: '0.12em' }}>SECURE · STRIPE + COINBASE COMMERCE</span>
      </div>
      <div className="panel-body" style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12 }}>
          <PayMethodCard id="card" glyph="▦" name="Card · Stripe" sub="Visa · •••• 4422 · exp 09/27" selected={method === 'card'} onSelect={() => setMethod('card')} badge="DEFAULT"/>
          <PayMethodCard id="invoice" glyph="⊟" name="Direct Debit" sub="GBP · auto-collect · BACS" selected={method === 'invoice'} onSelect={() => setMethod('invoice')}/>
          <PayMethodCard id="crypto" glyph="◈" name="Crypto · self-custody" sub="USDC · ETH · BTC · on-chain or Coinbase Commerce" selected={method === 'crypto'} onSelect={() => setMethod('crypto')} featured/>
        </div>
        {method === 'crypto' && <CryptoPanel/>}
      </div>
    </div>
  );
}

function PayMethodCard({ glyph, name, sub, selected, onSelect, badge, featured }) {
  return (
    <div onClick={onSelect} style={{
      padding: 16,
      background: selected
        ? (featured
          ? 'linear-gradient(135deg, rgba(75, 232, 255, 0.08), rgba(139, 107, 255, 0.12), rgba(255, 122, 217, 0.06))'
          : 'rgba(139, 107, 255, 0.06)')
        : 'rgba(0, 0, 0, 0.2)',
      border: `1px solid ${selected ? (featured ? 'rgba(139, 107, 255, 0.5)' : 'rgba(139, 107, 255, 0.3)') : 'var(--border)'}`,
      borderRadius: 'var(--radius-lg)',
      cursor: 'pointer',
      display: 'flex', flexDirection: 'column', gap: 10,
      position: 'relative',
      overflow: 'hidden',
      transition: 'all 0.15s',
    }}>
      {featured && (
        <div style={{
          position: 'absolute', top: 0, right: 0,
          padding: '2px 8px',
          background: 'var(--iridescent)',
          color: '#07091a',
          fontFamily: 'var(--font-mono)',
          fontSize: 9,
          fontWeight: 700,
          letterSpacing: '0.12em',
          borderBottomLeftRadius: 6,
        }}>NEW</div>
      )}
      <div className="row" style={{ justifyContent: 'space-between' }}>
        <div className="row" style={{ gap: 10 }}>
          <div style={{
            width: 38, height: 38,
            borderRadius: 8,
            background: selected ? 'var(--iridescent)' : 'rgba(255, 255, 255, 0.06)',
            color: selected ? '#07091a' : 'var(--text)',
            display: 'grid', placeItems: 'center',
            fontSize: 18,
            fontFamily: 'var(--font-mono)',
            fontWeight: 700,
          }}>{glyph}</div>
          <div>
            <div className="row" style={{ gap: 8 }}>
              <span style={{ fontSize: 13, fontWeight: 500 }}>{name}</span>
              {badge && <span className="tag live" style={{ fontSize: 9 }}>{badge}</span>}
            </div>
            <span className="dim" style={{ fontSize: 11, lineHeight: 1.4 }}>{sub}</span>
          </div>
        </div>
        <span style={{
          width: 16, height: 16, borderRadius: '50%',
          border: `1px solid ${selected ? 'transparent' : 'var(--border-strong)'}`,
          background: selected ? 'var(--iridescent)' : 'transparent',
          display: 'grid', placeItems: 'center',
          flexShrink: 0,
        }}>
          {selected && <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#07091a' }}/>}
        </span>
      </div>
    </div>
  );
}

function CryptoPanel() {
  const [chain, setChain] = React.useState('base');
  const chains = [
    { id: 'base',  name: 'Base',      sub: 'L2 · gas <£0.01',  color: '#0052ff' },
    { id: 'eth',   name: 'Ethereum',  sub: 'mainnet · £3-£8',  color: '#627eea' },
    { id: 'sol',   name: 'Solana',    sub: 'L1 · gas ≈£0.001', color: '#9945ff' },
    { id: 'op',    name: 'Optimism',  sub: 'L2 · gas <£0.01',  color: '#ff0420' },
  ];
  const tokens = ['USDC', 'USDT', 'DAI', 'ETH', 'WBTC'];
  return (
    <div style={{
      padding: 18,
      background: 'linear-gradient(135deg, rgba(75, 232, 255, 0.04), rgba(139, 107, 255, 0.06), rgba(255, 122, 217, 0.03))',
      border: '1px solid rgba(139, 107, 255, 0.2)',
      borderRadius: 'var(--radius-lg)',
      display: 'flex', flexDirection: 'column', gap: 16,
    }}>
      <div className="row" style={{ gap: 8 }}>
        <Icon.Sparkles className="gradient-text" style={{ width: 14, height: 14 }}/>
        <span className="mono gradient-text" style={{ fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', fontWeight: 600 }}>Crypto checkout · Coinbase Commerce + on-chain</span>
      </div>

      <div>
        <div className="mono faint" style={{ fontSize: 10, letterSpacing: '0.12em', marginBottom: 8 }}>SETTLEMENT CHAIN</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
          {chains.map(c => (
            <button key={c.id} onClick={() => setChain(c.id)} style={{
              padding: '10px 12px',
              background: chain === c.id ? `linear-gradient(135deg, ${c.color}25, ${c.color}08)` : 'rgba(255, 255, 255, 0.03)',
              border: `1px solid ${chain === c.id ? c.color + '70' : 'var(--border)'}`,
              borderRadius: 'var(--radius)',
              textAlign: 'left',
              display: 'flex', flexDirection: 'column', gap: 4,
              cursor: 'pointer',
              transition: 'all 0.15s',
            }}>
              <span style={{ fontSize: 12, fontWeight: 500, color: chain === c.id ? c.color : 'var(--text)' }}>{c.name}</span>
              <span className="mono faint" style={{ fontSize: 10 }}>{c.sub}</span>
            </button>
          ))}
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr 1.2fr', gap: 14 }}>
        <div>
          <div className="mono faint" style={{ fontSize: 10, letterSpacing: '0.12em', marginBottom: 6 }}>ACCEPTED TOKENS</div>
          <div className="row" style={{ flexWrap: 'wrap', gap: 4 }}>
            {tokens.map(t => (
              <span key={t} className="tag" style={{ background: 'rgba(75, 232, 255, 0.06)', color: 'var(--cyan)', borderColor: 'rgba(75, 232, 255, 0.3)' }}>{t}</span>
            ))}
          </div>
        </div>
        <div>
          <div className="mono faint" style={{ fontSize: 10, letterSpacing: '0.12em', marginBottom: 6 }}>SETTLEMENT</div>
          <div style={{ fontSize: 12 }}>Auto-convert to GBP</div>
          <div className="mono faint" style={{ fontSize: 10 }}>or hold as stablecoin</div>
        </div>
        <div>
          <div className="mono faint" style={{ fontSize: 10, letterSpacing: '0.12em', marginBottom: 6 }}>RECEIVE ADDRESS</div>
          <div className="row" style={{ gap: 6 }}>
            <span className="mono" style={{ fontSize: 11, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1 }}>0x4a8c…2f4e</span>
            <button className="btn ghost sm" style={{ padding: '2px 6px', fontSize: 10 }}>Copy</button>
          </div>
          <div className="mono faint" style={{ fontSize: 10, marginTop: 2 }}>verified · ENS demiurge.eth</div>
        </div>
      </div>

      <div className="row" style={{ padding: 12, background: 'rgba(75, 232, 255, 0.06)', border: '1px solid rgba(75, 232, 255, 0.2)', borderRadius: 'var(--radius)', gap: 10 }}>
        <Icon.Check style={{ width: 16, height: 16, color: 'var(--cyan)', flexShrink: 0 }}/>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 12 }}>Next invoice (£2,342) will be settled via <span style={{ color: chains.find(c => c.id === chain).color }}>{chains.find(c => c.id === chain).name}</span></div>
          <div className="mono faint" style={{ fontSize: 10 }}>Coinbase Commerce checkout link sent 3 days before due date · webhook verified · auto-recorded as PAID</div>
        </div>
      </div>

      <div className="row" style={{ gap: 8 }}>
        <button className="btn primary">Save crypto settings</button>
        <button className="btn">Test with £1 payment</button>
        <button className="btn ghost" style={{ marginLeft: 'auto' }}>Disconnect</button>
      </div>
    </div>
  );
}

window.Settings = Settings;
