// WiseTokens — Extended pages: Status, Webhooks, Team/RBAC, Notifications, Reports, Compliance, Changelog

function Status() {
  const services = [
    { name: 'API Gateway', status: 'operational', uptime: 99.98, p50: 42, regions: ['US-East', 'EU', 'Singapore', 'Mumbai', 'São Paulo'] },
    { name: 'DeepSeek provider', status: 'operational', uptime: 99.97, p50: 380 },
    { name: 'Qwen provider', status: 'operational', uptime: 99.96, p50: 240 },
    { name: 'GLM provider', status: 'degraded', uptime: 99.41, p50: 780, note: 'Elevated latency in EU region' },
    { name: 'Billing & Stripe', status: 'operational', uptime: 100.00, p50: 120 },
    { name: 'Console / Dashboard', status: 'operational', uptime: 99.99, p50: 110 },
    { name: 'Webhooks', status: 'operational', uptime: 99.95, p50: 85 },
  ];
  const incidents = [
    { date: '2026-04-14', title: 'Brief GLM latency spike in EU', status: 'resolved', duration: '23m' },
    { date: '2026-04-02', title: 'Scheduled maintenance · Mumbai region', status: 'completed', duration: '15m' },
    { date: '2026-03-28', title: 'Stripe webhook delivery delay', status: 'resolved', duration: '8m' },
  ];
  return (
    <div className="page">
      <div className="page-h"><div><h1>Status</h1><div className="sub">Real-time uptime for every service and provider. Subscribe for incident notifications.</div></div>
        <div className="page-actions"><button className="btn"><Icon name="bell" size={13}/> Subscribe</button></div>
      </div>
      <div className="card" style={{ padding: 22, marginBottom: 18, display: 'flex', alignItems: 'center', gap: 14 }}>
        <div style={{ width: 10, height: 10, borderRadius: '50%', background: 'var(--warn)' }}/>
        <div style={{ flex: 1 }}>
          <div style={{ fontWeight: 500 }}>Partial degradation · GLM provider EU region</div>
          <div className="dim" style={{ fontSize: 12.5 }}>Failover to DeepSeek + Qwen active. User impact: negligible.</div>
        </div>
        <span className="dim mono" style={{ fontSize: 12 }}>since 14:02 UTC</span>
      </div>
      <div className="card" style={{ padding: 0, marginBottom: 18 }}>
        <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--line)' }}><h3 style={{ margin: 0, fontSize: 13, fontWeight: 500, textTransform: 'uppercase', color: 'var(--ink-2)', letterSpacing: '0.02em' }}>Services · last 90 days</h3></div>
        {services.map((s, i) => (
          <div key={s.name} style={{ padding: '14px 20px', borderBottom: i === services.length-1 ? 'none' : '1px solid var(--line)', display: 'grid', gridTemplateColumns: '1fr 340px 100px 80px', gap: 14, alignItems: 'center' }}>
            <div>
              <div style={{ fontWeight: 500, display: 'flex', alignItems: 'center', gap: 8 }}>
                <span style={{ width: 8, height: 8, borderRadius: '50%', background: s.status === 'operational' ? 'var(--ok)' : s.status === 'degraded' ? 'var(--warn)' : 'var(--err)' }}/>
                {s.name}
              </div>
              {s.note && <div className="dim" style={{ fontSize: 11.5, marginTop: 3 }}>{s.note}</div>}
            </div>
            <div style={{ display: 'flex', gap: 1.5 }}>
              {Array.from({length: 90}).map((_, j) => {
                const bad = (s.status === 'degraded' && j < 2) || (s.name === 'Billing & Stripe' && false) || Math.random() < 0.008;
                return <div key={j} style={{ flex: 1, height: 22, background: bad ? 'var(--warn)' : 'var(--ok)', opacity: bad ? 0.85 : 0.5, borderRadius: 1 }}/>;
              })}
            </div>
            <div className="mono tabular" style={{ textAlign: 'right', fontSize: 13 }}>{s.uptime.toFixed(2)}%</div>
            <div className="mono tabular dim" style={{ textAlign: 'right', fontSize: 12 }}>{s.p50}ms</div>
          </div>
        ))}
      </div>
      <div className="card" style={{ padding: 0 }}>
        <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--line)' }}><h3 style={{ margin: 0, fontSize: 13, fontWeight: 500, textTransform: 'uppercase', color: 'var(--ink-2)', letterSpacing: '0.02em' }}>Recent incidents</h3></div>
        <table className="table"><thead><tr><th>Date</th><th>Title</th><th>Duration</th><th>Status</th></tr></thead>
          <tbody>{incidents.map(i => (<tr key={i.date + i.title}><td className="dim">{i.date}</td><td>{i.title}</td><td className="mono">{i.duration}</td><td><span className="badge ok dot">{i.status}</span></td></tr>))}</tbody>
        </table>
      </div>
    </div>
  );
}

function Webhooks({ onToast }) {
  const [hooks, setHooks] = React.useState([
    { id: 'wh_1', url: 'https://api.acme.ai/wt/hook', events: ['usage.threshold', 'billing.paid', 'key.revoked'], status: 'active', delivered: 2481, failed: 3 },
    { id: 'wh_2', url: 'https://hooks.slack.com/···/lowbalance', events: ['billing.low_balance'], status: 'active', delivered: 14, failed: 0 },
  ]);
  const eventCatalog = [
    { k: 'usage.threshold', d: 'Token usage crosses a threshold' },
    { k: 'billing.paid', d: 'Top-up successfully processed' },
    { k: 'billing.low_balance', d: 'Balance drops below configured floor' },
    { k: 'key.created', d: 'New API key is created' },
    { k: 'key.revoked', d: 'API key is revoked' },
    { k: 'request.failed', d: 'Upstream 5xx or timeout' },
    { k: 'tenant.created', d: 'New white-label tenant is provisioned' },
    { k: 'referral.commission', d: 'Commission earned on referred spend' },
  ];
  return (
    <div className="page">
      <div className="page-h"><div><h1>Webhooks</h1><div className="sub">Subscribe external endpoints to events. Signed with HMAC-SHA256. Retries: 3 with exponential backoff.</div></div>
        <div className="page-actions"><button className="btn primary"><Icon name="plus" size={13}/> New endpoint</button></div>
      </div>
      <div className="card" style={{ padding: 0, marginBottom: 18 }}>
        <table className="table"><thead><tr><th>Endpoint</th><th>Events</th><th className="right">Delivered</th><th className="right">Failed</th><th>Status</th><th></th></tr></thead>
          <tbody>{hooks.map(h => (
            <tr key={h.id}><td className="mono" style={{ fontSize: 12 }}>{h.url}</td>
              <td><div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>{h.events.map(e => <span key={e} className="badge">{e}</span>)}</div></td>
              <td className="num right tabular">{WT.fmt.num(h.delivered)}</td>
              <td className="num right tabular" style={{ color: h.failed > 0 ? 'var(--warn)' : 'inherit' }}>{h.failed}</td>
              <td><span className="badge ok dot">{h.status}</span></td>
              <td style={{ textAlign: 'right' }}><button className="btn sm">Test</button></td>
            </tr>
          ))}</tbody>
        </table>
      </div>
      <div className="card" style={{ padding: 22 }}>
        <div className="card-h"><h3>Available events</h3></div>
        <div className="grid grid-2" style={{ gap: 10 }}>
          {eventCatalog.map(e => (
            <div key={e.k} style={{ padding: 12, background: 'var(--bg-sunken)', border: '1px solid var(--line)', borderRadius: 5, display: 'flex', alignItems: 'center', gap: 10 }}>
              <code className="mono" style={{ fontSize: 11.5, color: 'var(--accent)' }}>{e.k}</code>
              <span className="dim" style={{ fontSize: 12 }}>{e.d}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function Team() {
  const members = [
    { email: 'alex@wisetokens.ai', role: 'Owner', joined: '2025-11-08', '2fa': true, last: '2m ago' },
    { email: 'priya@wisetokens.ai', role: 'Admin', joined: '2026-01-14', '2fa': true, last: '1h ago' },
    { email: 'marco@wisetokens.ai', role: 'Developer', joined: '2026-02-02', '2fa': false, last: '3d ago' },
    { email: 'finance@wisetokens.ai', role: 'Billing', joined: '2026-03-10', '2fa': true, last: '12h ago' },
    { email: 'ops-readonly@wisetokens.ai', role: 'Viewer', joined: '2026-04-01', '2fa': false, last: '5d ago' },
  ];
  const roles = [
    { r: 'Owner', p: ['All permissions', 'Manage billing', 'Manage tenants', 'Delete org'] },
    { r: 'Admin', p: ['Manage keys', 'Manage members', 'View billing', 'Configure routing'] },
    { r: 'Developer', p: ['Create/revoke own keys', 'Use playground', 'View own logs'] },
    { r: 'Billing', p: ['View all usage', 'Top up balance', 'Download invoices'] },
    { r: 'Viewer', p: ['Read-only dashboard', 'Read-only logs'] },
  ];
  return (
    <div className="page">
      <div className="page-h"><div><h1>Team & Roles</h1><div className="sub">Invite teammates and assign RBAC roles. Audit log captures every action.</div></div>
        <div className="page-actions"><button className="btn primary"><Icon name="plus" size={13}/> Invite member</button></div>
      </div>
      <div className="card" style={{ padding: 0, marginBottom: 18 }}>
        <table className="table"><thead><tr><th>Email</th><th>Role</th><th>2FA</th><th>Last active</th><th>Joined</th><th></th></tr></thead>
          <tbody>{members.map(m => (
            <tr key={m.email}><td style={{ fontWeight: 500 }}>{m.email}</td>
              <td><span className="badge accent">{m.role}</span></td>
              <td>{m['2fa'] ? <span className="badge ok dot">on</span> : <span className="badge warn dot">off</span>}</td>
              <td className="dim">{m.last}</td>
              <td className="dim">{m.joined}</td>
              <td style={{ textAlign: 'right' }}><button className="btn sm">Edit</button></td>
            </tr>
          ))}</tbody>
        </table>
      </div>
      <div className="card" style={{ padding: 22 }}>
        <div className="card-h"><h3>Role permissions</h3></div>
        <div className="grid grid-3" style={{ gap: 14 }}>
          {roles.map(r => (
            <div key={r.r} style={{ padding: 14, border: '1px solid var(--line)', borderRadius: 6, background: 'var(--bg-sunken)' }}>
              <div style={{ fontWeight: 500, fontSize: 13, marginBottom: 8 }}>{r.r}</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 4, fontSize: 12, color: 'var(--ink-2)' }}>
                {r.p.map(p => <div key={p}>· {p}</div>)}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function Notifications() {
  const items = [
    { t: 'Low balance warning', d: 'Balance dropped below $50. Auto top-up triggered.', time: '2m ago', unread: true, kind: 'billing' },
    { t: 'New API key created', d: '"staging" created by priya@wisetokens.ai', time: '1h ago', unread: true, kind: 'key' },
    { t: 'Referral commission earned', d: '+$18.20 from a***@acme.ai', time: '4h ago', unread: true, kind: 'broker' },
    { t: 'GLM provider latency elevated', d: 'Failover routed 14% traffic to DeepSeek.', time: '12h ago', unread: false, kind: 'system' },
    { t: 'Invoice paid', d: 'in_AX81 · $500 via Stripe', time: '2d ago', unread: false, kind: 'billing' },
    { t: 'Monthly usage report', d: 'March 2026 report ready to download.', time: '6d ago', unread: false, kind: 'report' },
  ];
  return (
    <div className="page">
      <div className="page-h"><div><h1>Notifications</h1><div className="sub">Inbox for account, billing, and system events. Configure channels in Settings.</div></div>
        <div className="page-actions"><button className="btn">Mark all read</button></div>
      </div>
      <div className="card" style={{ padding: 0 }}>
        {items.map((n, i) => (
          <div key={i} style={{ padding: '14px 20px', borderBottom: i === items.length-1 ? 'none' : '1px solid var(--line)', display: 'flex', gap: 14, alignItems: 'flex-start', background: n.unread ? 'var(--bg-hover)' : 'transparent' }}>
            <div style={{ width: 30, height: 30, borderRadius: 6, background: 'var(--bg-sunken)', color: 'var(--ink-2)', display: 'grid', placeItems: 'center', flexShrink: 0, border: '1px solid var(--line)' }}>
              <Icon name={n.kind === 'billing' ? 'wallet' : n.kind === 'key' ? 'key' : n.kind === 'broker' ? 'users' : n.kind === 'report' ? 'chart' : 'bell'} size={14}/>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <div style={{ fontWeight: 500, fontSize: 13 }}>{n.t} {n.unread && <span style={{ width: 6, height: 6, background: 'var(--accent)', borderRadius: '50%', display: 'inline-block', marginLeft: 6, verticalAlign: 'middle' }}/>}</div>
                <span className="dim" style={{ fontSize: 11 }}>{n.time}</span>
              </div>
              <div className="dim" style={{ fontSize: 12.5, marginTop: 2 }}>{n.d}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function Reports() {
  return (
    <div className="page">
      <div className="page-h"><div><h1>Reports</h1><div className="sub">Scheduled exports and cross-dimensional breakdowns. Power-user view.</div></div>
        <div className="page-actions"><button className="btn"><Icon name="plus" size={13}/> New report</button><button className="btn primary"><Icon name="download" size={13}/> Export</button></div>
      </div>
      <div className="grid grid-4" style={{ marginBottom: 18 }}>
        {[
          { l: 'Cost per 1M tok (blended)', v: '$0.48', d: 'vs. $5.20 upstream' },
          { l: 'Cache hit rate', v: '34.1%', d: 'semantic + exact' },
          { l: 'Avg tokens / request', v: '1,842', d: 'input + output' },
          { l: 'Retries triggered', v: '0.82%', d: 'of all calls' },
        ].map(s => (
          <div key={s.l} className="card"><div className="card-h"><h3>{s.l}</h3></div>
            <div className="stat"><div className="v">{s.v}</div><div className="d dim">{s.d}</div></div>
          </div>
        ))}
      </div>
      <div className="grid grid-2" style={{ marginBottom: 18, gap: 18 }}>
        <div className="card" style={{ padding: 22 }}>
          <div className="card-h"><h3>Spend by country · MTD</h3></div>
          <table className="table"><thead><tr><th>Country</th><th className="right">Requests</th><th className="right">Tokens</th><th className="right">Spend</th></tr></thead><tbody>
            {[
              ['🇺🇸 United States', 91420, '38.2M', 18.20],
              ['🇮🇳 India', 48920, '22.1M', 8.40],
              ['🇧🇷 Brazil', 31180, '14.8M', 5.90],
              ['🇩🇪 Germany', 24910, '11.2M', 4.80],
              ['🇮🇩 Indonesia', 15720, '7.1M', 2.30],
              ['🇳🇬 Nigeria', 8910, '3.9M', 1.10],
            ].map(r => <tr key={r[0]}><td>{r[0]}</td><td className="num right tabular">{WT.fmt.num(r[1])}</td><td className="num right tabular">{r[2]}</td><td className="num right tabular">${r[3].toFixed(2)}</td></tr>)}
          </tbody></table>
        </div>
        <div className="card" style={{ padding: 22 }}>
          <div className="card-h"><h3>Scheduled reports</h3></div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {[
              { name: 'Monthly usage summary', cadence: 'First of month · 08:00 UTC', to: 'alex@, finance@' },
              { name: 'Weekly cost breakdown by key', cadence: 'Mondays · 09:00 UTC', to: 'priya@' },
              { name: 'Referral payout statement', cadence: '15th of month', to: 'finance@' },
            ].map(r => (
              <div key={r.name} style={{ padding: 12, border: '1px solid var(--line)', borderRadius: 5, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <div><div style={{ fontWeight: 500, fontSize: 13 }}>{r.name}</div><div className="dim" style={{ fontSize: 11.5 }}>{r.cadence} · to {r.to}</div></div>
                <button className="btn sm">Edit</button>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function Compliance() {
  return (
    <div className="page">
      <div className="page-h"><div><h1>Security & Compliance</h1><div className="sub">Certifications, data handling, and audit logs.</div></div></div>
      <div className="grid grid-4" style={{ marginBottom: 18 }}>
        {[
          { t: 'SOC 2 Type II', sub: 'Annual audit · 2025 passed' },
          { t: 'PCI DSS SAQ-A', sub: 'Via Stripe Connect' },
          { t: 'GDPR + CCPA', sub: 'EU + CA data rights' },
          { t: 'TLS 1.3', sub: 'Enforced on all endpoints' },
        ].map(c => (
          <div key={c.t} className="card" style={{ padding: 18 }}>
            <div style={{ width: 32, height: 32, borderRadius: 6, background: 'var(--accent-bg)', color: 'var(--accent)', display: 'grid', placeItems: 'center', marginBottom: 10 }}><Icon name="shield" size={16}/></div>
            <div style={{ fontWeight: 500, fontSize: 13 }}>{c.t}</div>
            <div className="dim" style={{ fontSize: 11.5, marginTop: 2 }}>{c.sub}</div>
          </div>
        ))}
      </div>
      <div className="card" style={{ padding: 22, marginBottom: 18 }}>
        <div className="card-h"><h3>Data handling</h3></div>
        <div className="grid grid-2" style={{ gap: 14 }}>
          {[
            { t: 'Request retention', d: 'Prompts & completions retained for 30 days for debugging. Configurable to 0.' },
            { t: 'No training on your data', d: 'Your traffic is never used to train any model we host or resell.' },
            { t: 'Token-level encryption', d: 'API keys SHA-256 hashed at rest. TLS 1.3 in transit. KMS-backed key rotation.' },
            { t: 'Right to erasure', d: 'One-click purge of prompts, completions, and billing exports on request.' },
          ].map(r => (
            <div key={r.t} style={{ padding: 14, background: 'var(--bg-sunken)', border: '1px solid var(--line)', borderRadius: 5 }}>
              <div style={{ fontWeight: 500, fontSize: 13, marginBottom: 4 }}>{r.t}</div>
              <div className="dim" style={{ fontSize: 12 }}>{r.d}</div>
            </div>
          ))}
        </div>
      </div>
      <div className="card" style={{ padding: 0 }}>
        <div style={{ padding: '14px 20px', borderBottom: '1px solid var(--line)' }}><h3 style={{ margin: 0, fontSize: 13, fontWeight: 500, textTransform: 'uppercase', color: 'var(--ink-2)', letterSpacing: '0.02em' }}>Audit log · last 10 events</h3></div>
        <table className="table"><thead><tr><th>Time</th><th>Actor</th><th>Action</th><th>Resource</th><th>IP</th></tr></thead><tbody>
          {[
            ['2026-04-18 14:22', 'alex@', 'key.revoke', 'legacy-crawler', '203.0.113.4', 'US'],
            ['2026-04-18 11:08', 'priya@', 'key.create', 'staging', '198.51.100.21', 'US'],
            ['2026-04-17 22:40', 'alex@', 'billing.topup', '$500', '203.0.113.4', 'US'],
            ['2026-04-17 14:02', 'system', 'routing.failover', 'GLM→DeepSeek', '—', '—'],
            ['2026-04-16 08:11', 'marco@', 'member.2fa_off', 'self', '198.51.100.7', 'BR'],
          ].map((r, i) => (<tr key={i}><td className="dim">{r[0]}</td><td>{r[1]}</td><td><code className="mono">{r[2]}</code></td><td>{r[3]}</td><td className="mono dim">{r[4]} <span className="dim" style={{ fontSize: 10 }}>· {r[5]}</span></td></tr>))}
        </tbody></table>
      </div>
    </div>
  );
}

function SDKs() {
  const sdks = [
    { lang: 'Python', v: '0.8.2', cmd: 'pip install wisetokens', icon: 'code' },
    { lang: 'Node.js / TS', v: '0.6.1', cmd: 'npm i @wisetokens/sdk', icon: 'code' },
    { lang: 'Go', v: '0.3.0', cmd: 'go get github.com/wisetokens/go-sdk', icon: 'code' },
    { lang: 'Java', v: '0.2.0', cmd: 'maven: com.wisetokens:sdk:0.2.0', icon: 'code' },
    { lang: 'Ruby', v: '0.1.4', cmd: 'gem install wisetokens', icon: 'code' },
    { lang: 'OpenAI SDK drop-in', v: 'compatible', cmd: 'set base_url = "https://api.wisetokens.ai/v1"', icon: 'bolt' },
  ];
  return (
    <div className="page">
      <div className="page-h"><div><h1>SDKs & Integrations</h1><div className="sub">First-party SDKs or drop in as a base-URL swap on any OpenAI client.</div></div></div>
      <div className="grid grid-3">{sdks.map(s => (
        <div key={s.lang} className="card" style={{ padding: 20 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
            <div style={{ width: 30, height: 30, borderRadius: 6, background: 'var(--accent-bg)', color: 'var(--accent)', display: 'grid', placeItems: 'center' }}><Icon name={s.icon} size={15}/></div>
            <div><div style={{ fontWeight: 500, fontSize: 13 }}>{s.lang}</div><div className="mono dim" style={{ fontSize: 11 }}>v{s.v}</div></div>
          </div>
          <pre className="code" style={{ fontSize: 11.5, padding: 10 }}>{s.cmd}</pre>
          <button className="btn sm" style={{ marginTop: 10, width: '100%' }}><Icon name="download" size={12}/> Get started</button>
        </div>
      ))}</div>
    </div>
  );
}

function Changelog() {
  const entries = [
    { date: '2026-04-18', tag: 'feature', title: 'Qwen 3 Max with 256K context is live', body: 'Routing now includes Qwen 3 Max for long-context tasks. Available on the cost-first and balanced strategies.' },
    { date: '2026-04-10', tag: 'feature', title: 'USDT payments (TRC20 + ERC20)', body: 'Top up via USDT in addition to Stripe and PayPal. Auto-credited within 2 confirmations.' },
    { date: '2026-04-02', tag: 'fix', title: 'Fixed Stripe webhook delivery for EU cards', body: 'Idempotency key collision resolved for retries on 3DS flows.' },
    { date: '2026-03-28', tag: 'feature', title: 'Broker tier 3 unlocked', body: 'Commission increases to 12% after $5k referred spend, 15% after $20k.' },
    { date: '2026-03-18', tag: 'feature', title: 'Multi-language console (hi, pt, id, de)', body: 'Hindi, Portuguese (Brazil), Bahasa Indonesia, and German added to the console. API responses unchanged.' },
    { date: '2026-03-10', tag: 'security', title: 'IP allowlist per API key', body: 'Restrict key usage by IP CIDR ranges. Configure under Keys → Edit.' },
  ];
  return (
    <div className="page">
      <div className="page-h"><div><h1>Changelog</h1><div className="sub">What's new, fixed, and deprecated. Subscribe via RSS or email.</div></div>
        <div className="page-actions"><button className="btn"><Icon name="bell" size={13}/> Subscribe</button></div>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 18, maxWidth: 760 }}>
        {entries.map(e => (
          <div key={e.date + e.title} className="card" style={{ padding: 22 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
              <span className="mono dim" style={{ fontSize: 12 }}>{e.date}</span>
              <span className={'badge ' + (e.tag === 'feature' ? 'accent' : e.tag === 'fix' ? 'info' : 'ok')}>{e.tag}</span>
            </div>
            <div style={{ fontWeight: 500, fontSize: 15, marginBottom: 6 }}>{e.title}</div>
            <div className="dim" style={{ fontSize: 13 }}>{e.body}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { Status, Webhooks, Team, Notifications, Reports, Compliance, SDKs, Changelog });
