// Settings screen — org config, auth, integrations, team, data

const SETTINGS_NAV = [
  { group: 'Organization', items: [['general','General','building'],['team','Team','graph'],['billing','Billing & Plan','command']] },
  { group: 'Security', items: [['auth','Authentication','shield'],['access','API & Access','key'],['audit','Audit Log','clipboard']] },
  { group: 'Integrations', items: [['ai','AI Models','sparkle'],['channels','Ad Channels','radio'],['notif','Notifications','alert'],['hooks','Webhooks','bolt']] },
  { group: 'Data', items: [['data','Data Policies','shield'],['retain','Retention','refresh'],['io','Import / Export','arrow-right']] },
  { group: 'Advanced', items: [['sys','System Config','cog'],['dev','Developer','brain']] },
];

const Field = ({ label, hint, children }) => (
  <div style={{marginBottom: 14}}>
    <label style={{fontSize: 11, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.05em', display: 'block', marginBottom: 6}}>{label}</label>
    {children}
    {hint && <div style={{fontSize: 11, color: 'var(--text-4)', marginTop: 4}}>{hint}</div>}
  </div>
);

const setInput = { width: '100%', background: 'var(--bg-1)', border: '1px solid var(--border)', borderRadius: 8, padding: '8px 12px', fontSize: 13, color: 'var(--text-1)', fontFamily: 'var(--sans)', outline: 'none' };

const GeneralSec = () => {
  const SIZES = ['1–10','11–50','51–200','201–1000','1000+'];
  const GOALS = ['Map journeys','Reduce reporting','Catch anomalies','AI decisions','Unify ad data'];
  const [size, setSize] = React.useState('51–200');
  const [goals, setGoals] = React.useState(new Set(['Map journeys','Reduce reporting','Catch anomalies']));
  const [saved, setSaved] = React.useState(false);
  const toggleGoal = g => setGoals(prev => { const n = new Set(prev); n.has(g) ? n.delete(g) : n.add(g); return n; });
  const handleSave = () => {
    setSaved(true);
    setTimeout(() => setSaved(false), 2000);
  };
  return (
    <>
      <div style={{display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20}}>
        <h2 style={{margin: 0, fontSize: 20, fontWeight: 700}}>General</h2>
        {saved && <span style={{fontSize: 11, color: 'var(--emerald)'}}>✅ Saved</span>}
        {!saved && <span style={{fontSize: 11, color: 'var(--text-3)'}}>Last saved: 2 min ago</span>}
      </div>
      <div className="card">
        <Field label="Organization Name" hint="Appears in invoices and API response headers">
          <input defaultValue="Northwind Labs" style={setInput}/>
        </Field>
        <Field label="Industry">
          <select style={setInput}><option>eCommerce</option><option>B2B SaaS</option><option>Retail</option><option>Media</option></select>
        </Field>
        <Field label="Company Size">
          <div className="seg">
            {SIZES.map(s => <button key={s} className={size===s?'active':''} onClick={() => setSize(s)}>{s}</button>)}
          </div>
        </Field>
        <Field label="Primary Goals" hint="What brought you to AstraReach?">
          <div style={{display: 'flex', gap: 6, flexWrap: 'wrap'}}>
            {GOALS.map(g => (
              <button key={g} className={`filter-chip ${goals.has(g)?'active':''}`} onClick={() => toggleGoal(g)}>{g}</button>
            ))}
          </div>
        </Field>
        <Field label="Timezone">
          <input defaultValue="UTC+8 — Asia/Kuala_Lumpur" style={setInput}/>
        </Field>
        <Field label="Currency">
          <select style={setInput}><option>USD</option><option>EUR</option><option>GBP</option><option>MYR</option><option>SGD</option></select>
        </Field>
        <Field label="Logo Upload">
          <div style={{padding: 24, border: '2px dashed var(--border-strong)', borderRadius: 8, textAlign: 'center', color: 'var(--text-3)', fontSize: 12, cursor: 'pointer'}}
            onClick={() => window.alert('File picker: select PNG, SVG, or JPG up to 2MB')}>
            Drag your logo here or click to browse<br/>
            <span style={{fontSize: 10, color: 'var(--text-4)'}}>PNG, SVG, JPG (max 2MB)</span>
          </div>
        </Field>
        <div style={{display: 'flex', gap: 8, marginTop: 16}}>
          <button className="btn primary" onClick={handleSave}>Save Changes</button>
          <button className="btn ghost" onClick={() => { setSize('51–200'); setGoals(new Set(['Map journeys','Reduce reporting','Catch anomalies'])); }}>Discard</button>
        </div>
      </div>

      <div className="card" style={{marginTop: 14, borderColor: 'rgba(244,63,94,0.3)'}}>
        <div style={{color: 'var(--rose)', fontWeight: 600, fontSize: 14, marginBottom: 10}}>Danger Zone</div>
        <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 14}}>
          <div style={{flex: 1}}>
            <div style={{fontSize: 13, color: 'var(--text-1)', marginBottom: 4}}>Delete Organization</div>
            <div style={{fontSize: 11, color: 'var(--text-3)'}}>Permanently delete this org and all its data. Events, journeys, memory, API keys — everything. Irreversible.</div>
          </div>
          <button className="btn" style={{background: 'var(--rose)', color: '#fff', borderColor: 'var(--rose)'}}
            onClick={() => { if (window.confirm('This will permanently delete Northwind Labs and all its data. Type "DELETE" to confirm.')) window.alert('Delete requested — contact support to complete org deletion.'); }}>
            Delete Organization
          </button>
        </div>
      </div>
    </>
  );
};

const AuthSec = () => {
  const [mode, setMode] = React.useState('api');
  const [authRequired, setAuthRequired] = React.useState(false);
  const [rotating, setRotating] = React.useState(false);
  return (
    <>
      <h2 style={{margin: '0 0 20px', fontSize: 20, fontWeight: 700}}>Authentication</h2>
      <div className="card">
        <Field label="Auth Mode">
          <div style={{display: 'flex', flexDirection: 'column', gap: 10}}>
            {[
              ['api','API Key Only','All requests require X-API-Key or Bearer token. Simple and effective for server-to-server.'],
              ['jwt-api','Supabase JWT + API Key','Require both Supabase JWT and API key for maximum security. Best for multi-tenant apps.'],
              ['jwt','JWT Only','Use Supabase JWT tokens exclusively. Users authenticate via Supabase Auth.']
            ].map(([k, t, d]) => (
              <div key={k} onClick={() => setMode(k)} style={{
                padding: 14, border: `1px solid ${mode===k?'var(--accent)':'var(--border)'}`, borderRadius: 8, cursor: 'pointer',
                background: mode===k ? 'rgba(139,92,246,0.06)' : 'transparent',
              }}>
                <div style={{display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4}}>
                  <div style={{width: 14, height: 14, borderRadius: '50%', border: `1.5px solid ${mode===k?'var(--accent)':'var(--border-strong)'}`, display: 'flex', alignItems: 'center', justifyContent: 'center'}}>
                    {mode===k && <div style={{width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)'}}/>}
                  </div>
                  <span style={{fontWeight: 500}}>{t}</span>
                </div>
                <div style={{fontSize: 11, color: 'var(--text-3)', marginLeft: 22}}>{d}</div>
              </div>
            ))}
          </div>
        </Field>
      </div>
      <div className="card" style={{marginTop: 14}}>
        <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10}}>
          <div>
            <div style={{fontWeight: 500}}>Require authentication on all endpoints</div>
            <div style={{fontSize: 11, color: 'var(--text-3)', marginTop: 2}}>auth_required flag · currently {authRequired ? 'ON' : 'OFF'}</div>
          </div>
          <div className={`toggle ${authRequired ? 'on' : ''}`} onClick={() => setAuthRequired(v => !v)} style={{cursor: 'pointer'}}/>
        </div>
        {!authRequired && (
          <div style={{padding: 10, background: 'rgba(245,158,11,0.1)', border: '1px solid rgba(245,158,11,0.3)', borderRadius: 8, fontSize: 12, color: '#fbbf24'}}>
            ⚠️ Authentication is disabled. Any request can ingest events without a key. Only use this in development.
          </div>
        )}
        {authRequired && (
          <div style={{padding: 10, background: 'rgba(16,185,129,0.08)', border: '1px solid rgba(16,185,129,0.25)', borderRadius: 8, fontSize: 12, color: 'var(--emerald)'}}>
            ✅ All endpoints require a valid API key or JWT token.
          </div>
        )}
      </div>
      <div className="card" style={{marginTop: 14}}>
        <Field label="Identity Hash Secret (HMAC)" hint="Used to HMAC-hash identity keys. Changing this invalidates all existing identity links.">
          <input type="password" defaultValue="●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●" style={setInput}/>
        </Field>
        <button className="btn" style={{color: 'var(--amber)', borderColor: 'rgba(245,158,11,0.3)'}}
          onClick={() => {
            if (window.confirm('Rotating the HMAC secret will invalidate ALL existing identity links. This cannot be undone. Continue?')) {
              setRotating(true);
              setTimeout(() => { setRotating(false); window.alert('Secret rotated. All identity links will be re-hashed on next event ingestion.'); }, 800);
            }
          }}>
          {rotating ? 'Rotating…' : 'Rotate Secret →'}
        </button>
      </div>
    </>
  );
};

const AISec = () => (
  <>
    <div style={{marginBottom: 20}}>
      <h2 style={{margin: 0, fontSize: 20, fontWeight: 700}}>AI Models</h2>
      <div style={{fontSize: 12, color: 'var(--text-3)', marginTop: 4}}>Configure LLM providers for NL query, insights, and decisions</div>
    </div>

    <div className="card">
      <div style={{display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14}}>
        <div style={{display: 'flex', alignItems: 'center', gap: 10}}>
          <div style={{width: 32, height: 32, borderRadius: 8, background: '#10A37F', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontWeight: 700}}>AI</div>
          <div>
            <div style={{fontWeight: 600}}>OpenAI</div>
            <div style={{fontSize: 11, color: 'var(--text-3)'}}>Reliability fallback</div>
          </div>
        </div>
        <span className="badge green">Connected</span>
      </div>
      <Field label="API Key">
        <div style={{display: 'flex', gap: 8}}>
          <input type="password" defaultValue="sk-proj-●●●●●●●●●●●●●●●●●●●●●●●●●●" style={setInput}/>
          <button className="btn" style={{flexShrink: 0, color: 'var(--cyan)'}} onClick={() => arFetch('/v1/system/capabilities').then(() => window.alert('✅ OpenAI — gpt-4o-mini reachable')).catch(() => window.alert('❌ OpenAI connection failed — check API key'))}>Test →</button>
        </div>
        <div style={{fontSize: 11, color: 'var(--emerald)', marginTop: 6}}>✅ Connected — gpt-4o-mini reachable</div>
      </Field>
      <Field label="Model">
        <select style={setInput}>
          <option>gpt-4o-mini — Recommended · cost-efficient</option>
          <option>gpt-4o — High capability</option>
          <option>gpt-3.5-turbo — Budget option</option>
        </select>
      </Field>
      <Field label="Max Tokens (1000)">
        <input type="range" min="100" max="4000" defaultValue="1000" style={{width: '100%'}}/>
      </Field>
      <Field label="Temperature (0.7)">
        <input type="range" min="0" max="10" defaultValue="7" style={{width: '100%'}}/>
        <div style={{display: 'flex', justifyContent: 'space-between', fontSize: 10, color: 'var(--text-4)', marginTop: 4}}><span>Precise</span><span>Creative</span></div>
      </Field>
      <div style={{padding: 10, background: 'rgba(16,185,129,0.08)', border: '1px solid rgba(16,185,129,0.25)', borderRadius: 8, fontSize: 12, color: '#6ee7b7', marginTop: 8}}>
        Monthly estimate: <b>~$4.20/month</b> at current usage
      </div>
    </div>

    <div className="card" style={{marginTop: 14}}>
      <div style={{display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14}}>
        <div style={{display: 'flex', alignItems: 'center', gap: 10}}>
          <div style={{width: 32, height: 32, borderRadius: 8, background: '#F55036', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontWeight: 700}}>Gq</div>
          <div>
            <div style={{fontWeight: 600}}>Groq</div>
            <div style={{fontSize: 11, color: 'var(--cyan)'}}>Faster, cheaper</div>
          </div>
        </div>
        <span className="badge green">Connected</span>
      </div>
      <Field label="API Key">
        <div style={{display: 'flex', gap: 8}}>
          <input type="password" defaultValue="gsk_●●●●●●●●●●●●●●●●●●●●●●●●●●" style={setInput}/>
          <button className="btn" style={{flexShrink: 0, color: 'var(--cyan)'}} onClick={() => arFetch('/v1/system/capabilities').then(() => window.alert('✅ Groq — llama-3.3-70b reachable')).catch(() => window.alert('❌ Groq connection failed — check API key'))}>Test →</button>
        </div>
      </Field>
      <Field label="Model">
        <select style={setInput}>
          <option>llama-3.3-70b — Preferred · AstraReach default</option>
          <option>mixtral-8x7b</option>
          <option>llama-3.1-8b — Ultra-fast, lower quality</option>
        </select>
      </Field>
      <div style={{padding: 10, background: 'rgba(139,92,246,0.08)', border: '1px solid rgba(139,92,246,0.25)', borderRadius: 8, fontSize: 12, color: '#c4b5fd'}}>
        AstraReach uses Groq as the primary LLM with OpenAI as fallback. Configure both for maximum reliability.
      </div>
    </div>

    {/* Anthropic card */}
    <div className="card" style={{marginTop: 14}}>
      <div style={{display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14}}>
        <div style={{display: 'flex', alignItems: 'center', gap: 10}}>
          <div style={{width: 32, height: 32, borderRadius: 8, background: '#D97706', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontWeight: 700, fontSize: 13}}>A</div>
          <div>
            <div style={{fontWeight: 600}}>Anthropic</div>
            <div style={{fontSize: 11, color: 'var(--text-3)'}}>Claude 3.5 Sonnet / Haiku</div>
          </div>
        </div>
        <span className="badge plain">Not configured</span>
      </div>
      <Field label="API Key">
        <div style={{display: 'flex', gap: 8}}>
          <input type="password" placeholder="sk-ant-api03-…" style={setInput}/>
          <button className="btn" style={{flexShrink: 0, color: 'var(--cyan)'}} onClick={() => window.alert('Set ANTHROPIC_API_KEY in your .env to enable Claude models')}>Test →</button>
        </div>
      </Field>
      <Field label="Model">
        <select style={setInput}>
          <option>claude-3-5-sonnet-20241022 — Recommended</option>
          <option>claude-3-5-haiku-20241022 — Fast, cheap</option>
          <option>claude-3-opus-20240229 — Highest capability</option>
        </select>
      </Field>
    </div>

    {/* OpenRouter card */}
    <div className="card" style={{marginTop: 14}}>
      <div style={{display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14}}>
        <div style={{display: 'flex', alignItems: 'center', gap: 10}}>
          <div style={{width: 32, height: 32, borderRadius: 8, background: '#6D28D9', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontWeight: 700, fontSize: 12}}>OR</div>
          <div>
            <div style={{fontWeight: 600}}>OpenRouter</div>
            <div style={{fontSize: 11, color: 'var(--text-3)'}}>Route across 200+ models</div>
          </div>
        </div>
        <span className="badge plain">Not configured</span>
      </div>
      <Field label="API Key">
        <div style={{display: 'flex', gap: 8}}>
          <input type="password" placeholder="sk-or-v1-…" style={setInput}/>
          <button className="btn" style={{flexShrink: 0, color: 'var(--cyan)'}} onClick={() => window.alert('Set OPENROUTER_API_KEY in your .env to enable OpenRouter model routing')}>Test →</button>
        </div>
      </Field>
      <Field label="Default Route">
        <select style={setInput}>
          <option>auto — Lowest cost capable of task</option>
          <option>mistralai/mistral-large — Cost efficient</option>
          <option>google/gemini-pro-1.5 — Long context</option>
          <option>meta-llama/llama-3.1-70b-instruct — Open source</option>
        </select>
      </Field>
    </div>

    {/* DeepSeek card */}
    <div className="card" style={{marginTop: 14}}>
      <div style={{display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14}}>
        <div style={{display: 'flex', alignItems: 'center', gap: 10}}>
          <div style={{width: 32, height: 32, borderRadius: 8, background: '#0EA5E9', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontWeight: 700, fontSize: 12}}>DS</div>
          <div>
            <div style={{fontWeight: 600}}>DeepSeek</div>
            <div style={{fontSize: 11, color: 'var(--text-3)'}}>Ultra-cheap, strong reasoning</div>
          </div>
        </div>
        <span className="badge plain">Not configured</span>
      </div>
      <Field label="API Key">
        <div style={{display: 'flex', gap: 8}}>
          <input type="password" placeholder="sk-…" style={setInput}/>
          <button className="btn" style={{flexShrink: 0, color: 'var(--cyan)'}} onClick={() => window.alert('Set DEEPSEEK_API_KEY in your .env to enable DeepSeek R1/V3 models')}>Test →</button>
        </div>
      </Field>
      <Field label="Model">
        <select style={setInput}>
          <option>deepseek-reasoner (R1) — Best reasoning</option>
          <option>deepseek-chat (V3) — Fast, cheap</option>
        </select>
      </Field>
    </div>

    <div className="card" style={{marginTop: 14}}>
      <div style={{fontWeight: 600, marginBottom: 10}}>Provider Priority</div>
      <div style={{display: 'flex', flexDirection: 'column', gap: 6}}>
        {[[1,'Groq','primary','var(--emerald)'],[2,'OpenAI','fallback','var(--accent)'],[3,'Anthropic','optional','var(--amber)'],[4,'OpenRouter','optional','var(--text-3)'],[5,'DeepSeek','optional','var(--cyan)']].map(([n, name, tag, color]) => (
          <div key={name} style={{display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', background: 'var(--bg-1)', border: '1px solid var(--border)', borderRadius: 8}}>
            <span style={{color: 'var(--text-4)', cursor: 'grab'}}>⋮⋮</span>
            <span className="mono" style={{fontSize: 11, color: 'var(--text-3)'}}>{n}.</span>
            <div style={{width: 10, height: 10, borderRadius: '50%', background: color}}/>
            <span style={{flex: 1, fontWeight: 500}}>{name}</span>
            <span className="badge plain" style={{fontSize: 10}}>{tag}</span>
          </div>
        ))}
      </div>
    </div>
  </>
);

const NotifSec = () => {
  const [emailOn, setEmailOn] = React.useState(true);
  const [slackOn, setSlackOn] = React.useState(true);
  const [sev, setSev] = React.useState('HIGH');
  const [emails, setEmails] = React.useState(['alerts@northwind.com','growth-ops@northwind.com']);
  const [emailInput, setEmailInput] = React.useState('');
  const [routing, setRouting] = React.useState({anomaly_detected:[1,1,0],key_expiring:[1,0,0],sync_failed:[0,1,0],churn_risk:[1,1,0],milestone_reached:[0,1,0]});
  const addEmail = () => {
    const v = emailInput.trim();
    if (v && v.includes('@') && !emails.includes(v)) { setEmails(e => [...e, v]); setEmailInput(''); }
  };
  const toggleRouting = (type, ch) => setRouting(prev => { const n = {...prev, [type]: [...prev[type]]}; n[type][ch] = n[type][ch] ? 0 : 1; return n; });
  return (
    <>
      <div style={{marginBottom: 20}}>
        <h2 style={{margin: 0, fontSize: 20, fontWeight: 700}}>Notifications</h2>
        <div style={{fontSize: 12, color: 'var(--text-3)', marginTop: 4}}>Route alerts to your team channels</div>
      </div>

      <div className="card">
        <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14}}>
          <div style={{fontWeight: 600}}>📧 Email Notifications</div>
          <div className={`toggle ${emailOn?'on':''}`} onClick={() => setEmailOn(v => !v)} style={{cursor:'pointer'}}/>
        </div>
        <Field label="Recipients">
          <div style={{display: 'flex', gap: 4, flexWrap: 'wrap', padding: 8, background: 'var(--bg-1)', border: '1px solid var(--border)', borderRadius: 8}}>
            {emails.map(e => (
              <span key={e} className="badge violet" style={{cursor:'pointer'}} onClick={() => setEmails(prev => prev.filter(x => x !== e))}>{e} ×</span>
            ))}
            <input placeholder="Add email…" value={emailInput} onChange={e => setEmailInput(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && addEmail()}
              style={{flex: 1, minWidth: 120, background: 'transparent', border: 'none', color: 'var(--text-1)', fontSize: 12, outline: 'none'}}/>
          </div>
        </Field>
        <Field label="Minimum severity">
          <div style={{display: 'flex', gap: 4}}>
            {['CRITICAL','HIGH','MEDIUM','ALL'].map(s => (
              <button key={s} className={`filter-chip ${sev===s?'active':''}`} onClick={() => setSev(s)}>{s}</button>
            ))}
          </div>
        </Field>
      </div>

      <div className="card" style={{marginTop: 14}}>
        <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14}}>
          <div style={{fontWeight: 600}}>💬 Slack Webhook</div>
          <div className={`toggle ${slackOn?'on':''}`} onClick={() => setSlackOn(v => !v)} style={{cursor:'pointer'}}/>
        </div>
        <Field label="Webhook URL">
          <div style={{display: 'flex', gap: 8}}>
            <input defaultValue="https://hooks.slack.com/services/T0●●●●●●●/B0●●●●●●●/●●●●●●●●●" style={setInput}/>
            <button className="btn" style={{flexShrink: 0, color: 'var(--cyan)'}} onClick={() => window.alert('✅ Test message sent to #marketing-alerts')}>Test →</button>
          </div>
        </Field>
        <Field label="Channel">
          <div style={{fontSize: 12, color: 'var(--text-2)'}}>#marketing-alerts <span style={{color: 'var(--text-4)', fontSize: 11}}>(auto-detected)</span></div>
        </Field>
      </div>

      <div className="card" style={{marginTop: 14, opacity: 0.85}}>
        <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10}}>
          <div style={{display: 'flex', alignItems: 'center', gap: 8}}>
            <div style={{fontWeight: 600}}>📟 PagerDuty</div>
            <span className="badge amber">🔒 Scale plan</span>
          </div>
          <div className="toggle" style={{cursor:'pointer', opacity: 0.6}} onClick={() => window.alert('PagerDuty is available on the Scale plan ($3,000+/mo). Upgrade in Settings → Billing to unlock CRITICAL alert escalation.')}/>
        </div>
        <div style={{fontSize: 12, color: 'var(--text-3)', marginBottom: 10}}>Escalate CRITICAL alerts to on-call rotations</div>
        <button className="btn" style={{background: 'var(--amber)', color: '#001', borderColor: 'var(--amber)', fontSize: 12}} onClick={() => window.alert('Upgrade to Scale plan to unlock PagerDuty integration.')}>Upgrade to Scale →</button>
      </div>

      <div className="card" style={{marginTop: 14}}>
        <div style={{fontWeight: 600, marginBottom: 12}}>Alert Routing Matrix</div>
        <table className="data-table" style={{fontSize: 12}}>
          <thead><tr><th>Alert Type</th><th style={{textAlign:'center'}}>Email</th><th style={{textAlign:'center'}}>Slack</th><th style={{textAlign:'center'}}>PagerDuty</th></tr></thead>
          <tbody>
            {Object.entries(routing).map(([type, vals]) => (
              <tr key={type}>
                <td style={{color: 'var(--text-1)', fontFamily: 'var(--mono)', fontSize: 11}}>{type}</td>
                {vals.map((v, j) => (
                  <td key={j} style={{textAlign: 'center'}}>
                    <div className={`toggle ${v?'on':''}`} style={{display: 'inline-block', opacity: j===2?0.4:1, cursor: j===2?'not-allowed':'pointer'}}
                      onClick={() => j < 2 && toggleRouting(type, j)}/>
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
        <button className="btn primary" style={{marginTop: 14}} onClick={() => window.alert('Test notification sent to Email' + (slackOn ? ' + Slack' : '') + '.')}>Send Test to All Channels →</button>
      </div>
    </>
  );
};

const TeamSec = () => {
  const emailRef = React.useRef(null);
  const roleRef = React.useRef(null);
  const sendInvite = () => {
    const email = emailRef.current?.value?.trim();
    const role = roleRef.current?.value || 'Member';
    if (!email) { window.alert('Please enter an email address to invite.'); return; }
    if (!email.includes('@') || !email.includes('.')) { window.alert('Please enter a valid email address.'); return; }
    arFetch('/v1/auth/invite', { method: 'POST', body: JSON.stringify({ email, role }) })
      .then(() => { window.alert('✅ Invitation sent to ' + email + ' as ' + role + '.'); if (emailRef.current) emailRef.current.value = ''; })
      .catch(() => { window.alert('✅ Invitation sent to ' + email + ' as ' + role + '. (demo mode)'); if (emailRef.current) emailRef.current.value = ''; });
  };
  return (
  <>
    <h2 style={{margin: '0 0 20px', fontSize: 20, fontWeight: 700}}>Team</h2>
    <div className="card" style={{padding: 0, overflow: 'hidden'}}>
      <table className="data-table">
        <thead><tr><th></th><th>Name</th><th>Email</th><th>Role</th><th>Joined</th><th>Last Active</th><th></th></tr></thead>
        <tbody>
          {[
            ['AR','Ava Ramirez','ava@northwind.com','Owner','Jan 12, 2025','2m ago'],
            ['KP','Kenji Park','kenji@northwind.com','Admin','Feb 8, 2025','1h ago'],
            ['ML','Maya Lee','maya@northwind.com','Member','Mar 3, 2025','Yesterday'],
          ].map((r, i) => (
            <tr key={i}>
              <td><div style={{width: 28, height: 28, borderRadius: '50%', background: 'linear-gradient(135deg, var(--accent), var(--cyan))', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 600}}>{r[0]}</div></td>
              <td style={{color: 'var(--text-1)'}}>{r[1]}</td>
              <td className="mono" style={{fontSize: 11}}>{r[2]}</td>
              <td><span className={`badge ${r[3]==='Owner'?'violet':r[3]==='Admin'?'cyan':'plain'}`}>{r[3]}</span></td>
              <td>{r[4]}</td>
              <td>{r[5]}</td>
              <td style={{textAlign: 'right', color: i === 0 ? 'var(--text-4)' : 'var(--rose)', cursor: i === 0 ? 'default' : 'pointer', fontSize: 11}}>{i === 0 ? '—' : 'Remove'}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
    <div style={{marginTop: 12}}>
      <div style={{fontSize: 12, color: 'var(--text-2)', marginBottom: 6}}>3 of 12 seats used</div>
      <div className="progress"><div style={{width: '25%', background: 'var(--emerald)'}}/></div>
    </div>
    <div className="card" style={{marginTop: 14}}>
      <div style={{fontWeight: 600, marginBottom: 12}}>Invite Team Member</div>
      <div style={{display: 'flex', gap: 8}}>
        <input ref={emailRef} placeholder="colleague@northwind.com" style={{...setInput, flex: 2}}/>
        <select ref={roleRef} style={{...setInput, flex: 1}}><option>Member</option><option>Admin</option></select>
        <button className="btn" style={{background: 'var(--emerald)', color: '#001', borderColor: 'var(--emerald)', flexShrink: 0}} onClick={sendInvite}>Send Invitation →</button>
      </div>
    </div>
  </>
  );
};

const ChannelsCredSec = () => {
  const [validating, setValidating] = React.useState({});
  const [syncing, setSyncing] = React.useState(false);
  const [syncMsg, setSyncMsg] = React.useState(null);
  const validateCreds = (platform) => {
    setValidating(v => ({...v, [platform]: true}));
    arFetch('/v1/channels/status')
      .then(() => { window.alert('✅ ' + platform + ' credentials valid — API reachable'); })
      .catch(() => { window.alert('❌ ' + platform + ' validation failed — check credentials'); })
      .finally(() => setValidating(v => ({...v, [platform]: false})));
  };
  const runSync = () => {
    setSyncing(true); setSyncMsg(null);
    arFetch('/v1/channels/sync', { method: 'POST', body: JSON.stringify({}) })
      .then(() => setSyncMsg({ ok: true, text: '✅ Sync triggered — data will refresh in ~2 minutes' }))
      .catch(() => setSyncMsg({ ok: false, text: '⚠ Sync failed — API server may be offline' }))
      .finally(() => setSyncing(false));
  };
  return (
    <>
      <div style={{marginBottom: 20}}>
        <h2 style={{margin: 0, fontSize: 20, fontWeight: 700}}>Ad Channels</h2>
        <div style={{fontSize: 12, color: 'var(--text-3)', marginTop: 4}}>Credentials for Meta Ads and Google Ads data sync</div>
      </div>
      {['Meta Ads','Google Ads'].map(name => (
        <div key={name} className="card" style={{marginBottom: 14}}>
          <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14}}>
            <div style={{fontWeight: 600}}>{name} Credentials</div>
            <span className="badge green">Connected</span>
          </div>
          {name === 'Meta Ads' ? (
            <>
              <Field label="App ID"><input defaultValue="123456789012345" style={setInput}/></Field>
              <Field label="App Secret"><input type="password" defaultValue="●●●●●●●●●●●●●●●●●●" style={setInput}/></Field>
              <Field label="Ad Account ID"><input defaultValue="act_123456789" style={setInput}/></Field>
            </>
          ) : (
            <>
              <Field label="Developer Token"><input type="password" defaultValue="●●●●●●●●●●●●●●" style={setInput}/></Field>
              <Field label="Customer ID"><input defaultValue="123-456-7890" style={setInput}/></Field>
              <Field label="Refresh Token"><input type="password" defaultValue="●●●●●●●●●●●●●●●●●●●●●●" style={setInput}/></Field>
            </>
          )}
          <div style={{display: 'flex', gap: 8}}>
            <button className="btn" style={{color: 'var(--cyan)'}} disabled={!!validating[name]} onClick={() => validateCreds(name)}>
              {validating[name] ? 'Validating…' : 'Validate Credentials →'}
            </button>
            <button className="btn ghost" style={{color: 'var(--rose)'}} onClick={() => window.alert(name + ' disconnect is not yet available in this prototype. Contact support to revoke access.')}>Disconnect</button>
          </div>
        </div>
      ))}
      <div className="card">
        <div style={{fontWeight: 600, marginBottom: 10}}>Channel Sync Schedule</div>
        <div style={{fontSize: 12, color: 'var(--text-2)', marginBottom: 10}}>Current: <b>Nightly at 02:00 UTC</b> (APScheduler)</div>
        <div style={{display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 8}}>
          <Field label="Time"><input defaultValue="02:00" style={setInput}/></Field>
          <Field label="Timezone"><input defaultValue="UTC" style={setInput}/></Field>
          <Field label="Frequency"><select style={setInput}><option>Daily</option><option>Weekly</option><option>Manual only</option></select></Field>
        </div>
        {syncMsg && (
          <div style={{marginTop: 10, padding: '8px 12px', background: syncMsg.ok ? 'rgba(16,185,129,0.08)' : 'rgba(244,63,94,0.08)', border: `1px solid ${syncMsg.ok ? 'rgba(16,185,129,0.25)' : 'rgba(244,63,94,0.25)'}`, borderRadius: 8, fontSize: 12, color: syncMsg.ok ? 'var(--emerald)' : 'var(--rose)'}}>
            {syncMsg.text}
          </div>
        )}
        <button className="btn" style={{background: 'var(--emerald)', color: '#001', borderColor: 'var(--emerald)', marginTop: 10}} disabled={syncing} onClick={runSync}>
          {syncing ? 'Syncing…' : 'Run Sync Now →'}
        </button>
      </div>
    </>
  );
};

const DataSec = () => {
  const [retention, setRetention] = React.useState(90);
  const [consent, setConsent] = React.useState(true);
  return (
    <>
      <h2 style={{margin: '0 0 20px', fontSize: 20, fontWeight: 700}}>Data Policies</h2>
      <div className="card">
        <div style={{fontWeight: 600, marginBottom: 10}}>Event Retention</div>
        <div style={{fontSize: 12, color: 'var(--text-2)', marginBottom: 12}}>Current: <span className="badge cyan">{retention} days</span></div>
        <input type="range" min="30" max="365" value={retention} onChange={e => setRetention(Number(e.target.value))} style={{width: '100%'}}/>
        <div style={{display: 'flex', justifyContent: 'space-between', fontSize: 10, color: 'var(--text-4)', marginTop: 4}}><span>30d</span><span>365d</span></div>
        <div style={{fontSize: 11, color: 'var(--text-3)', marginTop: 10}}>Events older than {retention} days will be automatically deleted. Memory items have independent TTL.</div>
      </div>
      <div className="card" style={{marginTop: 14}}>
        <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10}}>
          <div style={{display: 'flex', alignItems: 'center', gap: 8}}>
            <div style={{fontWeight: 600}}>Block PII in Memory</div>
            <span style={{
              background: 'rgba(16,185,129,0.12)', color: 'var(--emerald)',
              borderRadius: 4, padding: '1px 7px', fontSize: 10, fontWeight: 700,
              letterSpacing: '0.04em',
            }}>ENFORCED</span>
          </div>
          <div
            title="PII blocking is a compliance requirement and cannot be disabled. Use HMAC-hashed identifiers instead."
            style={{
              display: 'flex', alignItems: 'center', gap: 6,
              cursor: 'not-allowed',
            }}
            onClick={() => {
              const el = document.getElementById('pii-lock-tooltip');
              if (el) { el.style.opacity = 1; setTimeout(() => { el.style.opacity = 0; }, 2500); }
            }}
          >
            <div className="toggle on" style={{opacity: 0.45, pointerEvents: 'none'}}/>
            <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" style={{color:'var(--text-4)',flexShrink:0}}>
              <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
              <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
            </svg>
          </div>
        </div>
        <div id="pii-lock-tooltip" style={{
          fontSize: 11, color: 'var(--amber)', marginBottom: 8,
          background: 'rgba(245,158,11,0.08)', border: '1px solid rgba(245,158,11,0.25)',
          borderRadius: 6, padding: '6px 10px',
          opacity: 0, transition: 'opacity 0.2s ease',
        }}>
          🔒 PII blocking is mandatory for GDPR/CCPA compliance and cannot be disabled. To store user identifiers, hash them first using HMAC-SHA256.
        </div>
        <div style={{fontSize: 12, color: 'var(--text-3)', marginBottom: 10}}>AstraReach automatically rejects memory writes containing raw email addresses or phone numbers. This cannot be disabled — use HMAC-hashed values instead.</div>
        <div style={{display: 'flex', gap: 6}}>
          <span className="badge green">GDPR Compliant</span>
          <span className="badge green">CCPA Compliant</span>
        </div>
      </div>
      <div className="card" style={{marginTop: 14}}>
        <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10}}>
          <div style={{fontWeight: 600}}>Respect consent flags on events</div>
          <div className={`toggle ${consent?'on':''}`} style={{cursor:'pointer'}} onClick={() => setConsent(v => !v)}/>
        </div>
        <div style={{fontSize: 12, color: 'var(--text-3)'}}>
          {consent
            ? 'Events with consent_granted=false are stored for audit but excluded from analysis and identity resolution.'
            : '⚠ Consent flags are ignored. All events are processed regardless of consent state. Not recommended for GDPR compliance.'}
        </div>
      </div>
    </>
  );
};

const PlannedSec = ({ title, description, integrations = [] }) => (
  <>
    <h2 style={{margin: '0 0 16px', fontSize: 20, fontWeight: 700}}>{title}</h2>
    <div className="card" style={{borderColor: 'rgba(245,158,11,0.35)'}}>
      <div style={{display: 'flex', gap: 10, alignItems: 'flex-start', marginBottom: 14}}>
        <span style={{fontSize: 22}}>🛠</span>
        <div>
          <div style={{fontWeight: 600, color: 'var(--amber)', marginBottom: 4}}>Planned — requires external integration</div>
          <div style={{fontSize: 13, color: 'var(--text-2)', lineHeight: 1.6}}>{description}</div>
        </div>
      </div>
      {integrations.length > 0 && (
        <div>
          <div style={{fontSize: 10, color: 'var(--text-4)', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 8}}>Requires</div>
          <div style={{display: 'flex', gap: 6, flexWrap: 'wrap'}}>
            {integrations.map(i => <span key={i} className="badge amber" style={{fontSize: 11}}>{i}</span>)}
          </div>
        </div>
      )}
      <div style={{marginTop: 14, padding: '10px 12px', background: 'var(--bg-1)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 12, color: 'var(--text-3)', fontFamily: 'var(--mono)'}}>
        See CLAUDE.md → "Pending integrations" for implementation notes.
      </div>
    </div>
  </>
);

const MOCK_KEYS = [
  { prefix: 'ar_live_k1a2b3', label: 'Production SDK', created: 'Jan 12 2025', lastUsed: '2m ago', status: 'active' },
  { prefix: 'ar_live_x9y8z7', label: 'Internal Analytics', created: 'Feb 08 2025', lastUsed: '1h ago', status: 'active' },
  { prefix: 'ar_live_m3n4o5', label: 'Staging Ingest', created: 'Mar 03 2025', lastUsed: '3d ago', status: 'active' },
  { prefix: 'ar_live_q6r7s8', label: 'Dashboard Temp', created: 'Apr 01 2025', lastUsed: '28d ago', status: 'expiring' },
  { prefix: 'ar_live_t9u0v1', label: 'Legacy Pipeline', created: 'Dec 01 2024', lastUsed: '92d ago', status: 'inactive' },
];

const AccessSec = () => (
  <>
    <h2 style={{margin: '0 0 20px', fontSize: 20, fontWeight: 700}}>API Keys</h2>
    <div className="card" style={{textAlign: 'center', padding: 40}}>
      <div style={{fontSize: 36, marginBottom: 12}}>🔑</div>
      <div style={{fontWeight: 600, fontSize: 15, marginBottom: 8}}>Manage API Keys</div>
      <div style={{fontSize: 13, color: 'var(--text-3)', marginBottom: 20, maxWidth: 320, margin: '0 auto 20px'}}>
        Create, rotate, and revoke API keys from the dedicated API Keys dashboard. View rate limits, source restrictions, and usage analytics.
      </div>
      <button className="btn primary" style={{justifyContent: 'center'}} onClick={() => window.AR_NAVIGATE && window.AR_NAVIGATE('keys')}>
        Go to API Keys →
      </button>
    </div>
  </>
);

const AUDIT_ROWS = [
  { ts: '2025-04-28 07:52', actor: 'ava@northwind.com', action: 'api_key.create', resource: 'ar_live_k1a2b3', ip: '203.0.113.42', result: 'success' },
  { ts: '2025-04-28 06:31', actor: 'kenji@northwind.com', action: 'settings.update', resource: 'auth_mode', ip: '198.51.100.7', result: 'success' },
  { ts: '2025-04-28 05:14', actor: 'system', action: 'channel.sync', resource: 'meta_ads', ip: '—', result: 'success' },
  { ts: '2025-04-28 02:00', actor: 'system', action: 'channel.sync', resource: 'google_ads', ip: '—', result: 'warn' },
  { ts: '2025-04-27 23:08', actor: 'maya@northwind.com', action: 'memory.purge', resource: '2 items', ip: '203.0.113.55', result: 'success' },
  { ts: '2025-04-27 18:45', actor: 'ava@northwind.com', action: 'api_key.revoke', resource: 'ar_live_t9u0v1', ip: '203.0.113.42', result: 'success' },
  { ts: '2025-04-27 14:22', actor: 'unknown', action: 'auth.failed', resource: '—', ip: '45.33.32.156', result: 'error' },
];

const AuditSec = () => {
  const [filter, setFilter] = React.useState('all');
  const rows = filter === 'all' ? AUDIT_ROWS : AUDIT_ROWS.filter(r => r.result === filter);
  return (
    <>
      <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20}}>
        <h2 style={{margin: 0, fontSize: 20, fontWeight: 700}}>Audit Log</h2>
        <button className="btn" onClick={() => {
          const csv = ['Timestamp,Actor,Action,Resource,IP,Result', ...AUDIT_ROWS.map(r => [r.ts, r.actor, r.action, r.resource, r.ip, r.result].join(','))].join('\n');
          const blob = new Blob([csv], {type: 'text/csv'});
          const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = 'audit_log.csv'; a.click();
        }}>⬇ Export CSV</button>
      </div>

      <div style={{display: 'flex', gap: 6, marginBottom: 14}}>
        {[['all','All'],['success','Success'],['warn','Warn'],['error','Error']].map(([k, label]) => (
          <button key={k} className={`filter-chip ${filter === k ? 'active' : ''}`} onClick={() => setFilter(k)}>{label}</button>
        ))}
      </div>

      <div className="card" style={{padding: 0, overflow: 'hidden'}}>
        <table className="data-table" style={{fontSize: 11}}>
          <thead><tr><th>Timestamp</th><th>Actor</th><th>Action</th><th>Resource</th><th>IP</th><th>Result</th></tr></thead>
          <tbody>
            {rows.map((r, i) => (
              <tr key={i}>
                <td className="mono" style={{color: 'var(--text-3)', whiteSpace: 'nowrap'}}>{r.ts}</td>
                <td className="mono">{r.actor}</td>
                <td className="mono" style={{color: 'var(--cyan)'}}>{r.action}</td>
                <td className="mono" style={{color: 'var(--text-2)'}}>{r.resource}</td>
                <td className="mono" style={{color: 'var(--text-4)'}}>{r.ip}</td>
                <td>
                  <span className={`badge ${r.result === 'success' ? 'green' : r.result === 'warn' ? 'amber' : 'rose'}`} style={{fontSize: 10}}>
                    {r.result}
                  </span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div style={{fontSize: 11, color: 'var(--text-4)', marginTop: 8}}>Showing {rows.length} of {AUDIT_ROWS.length} events. Full log retained per data retention policy.</div>
    </>
  );
};

const IOSec = () => {
  const [exporting, setExporting] = React.useState(null); // key of in-flight export
  const [importStatus, setImportStatus] = React.useState(null); // {ok, text}
  const [importing, setImporting] = React.useState(false);
  const [zipStatus, setZipStatus] = React.useState(null);
  const fileInputRef = React.useRef(null);

  const EXPORTS = [
    { label: 'Events (JSON)',         resource: 'events',     fmt: 'json' },
    { label: 'Events (CSV)',          resource: 'events',     fmt: 'csv'  },
    { label: 'Identity Graph (JSON)', resource: 'identities', fmt: 'json' },
    { label: 'Decisions (JSON)',      resource: 'decisions',  fmt: 'json' },
    { label: 'Memory Items (JSON)',   resource: 'memory',     fmt: 'json' },
    { label: 'Journey Graph (JSON)',  resource: 'journey',    fmt: 'json' },
  ];

  const downloadExport = async (resource, fmt, label) => {
    const key = `${resource}-${fmt}`;
    setExporting(key);
    try {
      const res = await fetch(`${window.API_BASE || ''}/v1/${resource}/export?format=${fmt}`, {
        headers: { 'X-API-Key': window.API_KEY || localStorage.getItem('ar_api_key') || '', ...(localStorage.getItem('ar_token') ? { Authorization: `Bearer ${localStorage.getItem('ar_token')}` } : {}) },
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const blob = await res.blob();
      const ext = fmt === 'csv' ? 'csv' : 'json';
      const a = document.createElement('a');
      a.href = URL.createObjectURL(blob);
      a.download = `astrareach_${resource}_${new Date().toISOString().slice(0,10)}.${ext}`;
      a.click();
    } catch (_) {
      // Endpoint not yet implemented — fall back to client-side stub data download
      const stub = JSON.stringify({ exported_at: new Date().toISOString(), resource, format: fmt, note: 'stub export — connect API for real data' }, null, 2);
      const blob = new Blob([stub], { type: fmt === 'csv' ? 'text/csv' : 'application/json' });
      const a = document.createElement('a');
      a.href = URL.createObjectURL(blob);
      a.download = `astrareach_${resource}_stub.${fmt === 'csv' ? 'csv' : 'json'}`;
      a.click();
    } finally {
      // FIX: only clear this key's export state, not a concurrent one
      setExporting(prev => prev === key ? null : prev);
    }
  };

  const exportZip = async () => {
    setZipStatus({ ok: null, text: 'Queuing export…' });
    try {
      await arFetch('/v1/export/zip', { method: 'POST', body: JSON.stringify({ email: localStorage.getItem('ar_user_email') || 'admin@org.com' }) });
      setZipStatus({ ok: true, text: '✅ Export queued — you\'ll receive an email when ready.' });
    } catch (_) {
      setZipStatus({ ok: false, text: '⚠ Export endpoint not yet live — contact support@astrareach.io to request a full export.' });
    }
    setTimeout(() => setZipStatus(null), 6000);
  };

  const handleFile = async (file) => {
    if (!file) return;
    if (file.size > 10 * 1024 * 1024) { setImportStatus({ ok: false, text: '⚠ File exceeds 10 MB limit.' }); return; }
    setImporting(true);
    setImportStatus({ ok: null, text: `Uploading ${file.name}…` });
    try {
      const text = await file.text();
      let events;
      try {
        // Try JSON array first, then NDJSON
        const parsed = JSON.parse(text);
        events = Array.isArray(parsed) ? parsed : [parsed];
      } catch (_) {
        events = text.trim().split('\n').filter(Boolean).map(l => JSON.parse(l));
      }
      await arFetch('/v1/events/batch', { method: 'POST', body: JSON.stringify({ events }) });
      setImportStatus({ ok: true, text: `✅ ${events.length} events ingested from ${file.name}` });
    } catch (err) {
      setImportStatus({ ok: false, text: `⚠ Import failed — ${err.message || 'check file format'}` });
    } finally {
      setImporting(false);
    }
  };

  return (
    <>
      <h2 style={{margin: '0 0 20px', fontSize: 20, fontWeight: 700}}>Import / Export</h2>

      <div className="card" style={{marginBottom: 14}}>
        <div style={{fontWeight: 600, marginBottom: 12}}>Export Data</div>
        <div style={{display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 8, marginBottom: 14}}>
          {EXPORTS.map(({ label, resource, fmt }) => {
            const key = `${resource}-${fmt}`;
            const busy = exporting === key;
            return (
              <button key={label} className="btn" disabled={busy}
                style={{flexDirection: 'column', gap: 4, padding: '10px 12px', height: 'auto', opacity: busy ? 0.6 : 1}}
                onClick={() => downloadExport(resource, fmt, label)}>
                {busy
                  ? <div style={{width: 13, height: 13, border: '2px solid var(--text-4)', borderTopColor: 'var(--accent)', borderRadius: '50%', animation: 'ar-spin 0.7s linear infinite'}} />
                  : <Icon name="arrow-right" size={13} style={{transform: 'rotate(90deg)'}}/>
                }
                <span style={{fontSize: 11}}>{label}</span>
              </button>
            );
          })}
        </div>
        <button className="btn primary" style={{width: '100%', justifyContent: 'center'}} onClick={exportZip}>
          ⬇ Export All Data (ZIP)
        </button>
        {zipStatus && (
          <div style={{marginTop: 8, padding: '7px 10px', borderRadius: 6, fontSize: 12,
            background: zipStatus.ok === true ? 'rgba(16,185,129,0.08)' : zipStatus.ok === false ? 'rgba(244,63,94,0.08)' : 'rgba(139,92,246,0.08)',
            color: zipStatus.ok === true ? '#10B981' : zipStatus.ok === false ? '#F43F5E' : 'var(--text-2)',
            border: `1px solid ${zipStatus.ok === true ? 'rgba(16,185,129,0.25)' : zipStatus.ok === false ? 'rgba(244,63,94,0.25)' : 'rgba(139,92,246,0.25)'}`,
          }}>
            {zipStatus.text}
          </div>
        )}
        <div style={{fontSize: 11, color: 'var(--text-3)', marginTop: 8}}>Exports are scoped to your org. Large exports are emailed when ready.</div>
      </div>

      <div className="card">
        <div style={{fontWeight: 600, marginBottom: 12}}>Import Events</div>
        <input
          ref={fileInputRef}
          type="file"
          accept=".json,.ndjson,.jsonl"
          style={{display: 'none'}}
          onChange={e => { handleFile(e.target.files[0]); e.target.value = ''; }}
        />
        <div
          style={{padding: 32, border: `2px dashed ${importing ? 'var(--accent)' : 'var(--border-strong)'}`, borderRadius: 10, textAlign: 'center', color: 'var(--text-3)', fontSize: 12, cursor: 'pointer', transition: 'border-color 0.2s'}}
          onDragOver={e => e.preventDefault()}
          onDrop={e => { e.preventDefault(); handleFile(e.dataTransfer.files[0]); }}
          onClick={() => !importing && fileInputRef.current?.click()}
        >
          <div style={{fontSize: 28, marginBottom: 8}}>{importing ? '⏳' : '📁'}</div>
          <div style={{marginBottom: 4}}>{importing ? 'Uploading…' : 'Drop JSON Lines file here or click to browse'}</div>
          <div style={{fontSize: 11, color: 'var(--text-4)'}}>Format: one JSON event per line · max 10MB · POSTs to /v1/events/batch</div>
        </div>
        {importStatus && (
          <div style={{marginTop: 8, padding: '7px 10px', borderRadius: 6, fontSize: 12,
            background: importStatus.ok === true ? 'rgba(16,185,129,0.08)' : importStatus.ok === false ? 'rgba(244,63,94,0.08)' : 'rgba(139,92,246,0.08)',
            color: importStatus.ok === true ? '#10B981' : importStatus.ok === false ? '#F43F5E' : 'var(--text-2)',
            border: `1px solid ${importStatus.ok === true ? 'rgba(16,185,129,0.25)' : importStatus.ok === false ? 'rgba(244,63,94,0.25)' : 'rgba(139,92,246,0.25)'}`,
          }}>
            {importStatus.text}
          </div>
        )}
        <div style={{marginTop: 10, padding: 10, background: 'var(--bg-1)', border: '1px solid var(--border)', borderRadius: 8, fontSize: 12, color: 'var(--text-3)'}}>
          Accepted: <span className="mono" style={{fontSize: 11}}>application/x-ndjson</span>, <span className="mono" style={{fontSize: 11}}>application/json</span> (array)
        </div>
      </div>
    </>
  );
};

const SysSec = () => {
  const [logLevel, setLogLevel] = React.useState('INFO');
  const downloadConfig = () => {
    const cfg = JSON.stringify({db_pool_size:10,db_max_overflow:20,db_pool_timeout:30,db_pool_recycle:3600,log_level:logLevel,auth_required:false}, null, 2);
    const blob = new Blob([cfg], {type:'application/json'});
    const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = 'astrareach-config.json'; a.click();
  };
  const copyConfig = () => {
    const cfg = `LOG_LEVEL=${logLevel}\nDB_POOL_SIZE=10\nDB_MAX_OVERFLOW=20\nDB_POOL_TIMEOUT=30\nDB_POOL_RECYCLE=3600\nAUTH_REQUIRED=false`;
    navigator.clipboard?.writeText(cfg).then(() => window.alert('✅ Config copied — paste into your .env file'));
  };
  return (
    <>
      <h2 style={{margin: '0 0 8px', fontSize: 20, fontWeight: 700}}>System Configuration</h2>
      <div style={{padding: 10, background: 'rgba(245,158,11,0.1)', border: '1px solid rgba(245,158,11,0.3)', borderRadius: 8, fontSize: 12, color: '#fbbf24', marginBottom: 16}}>
        ⚠️ Changes here affect infrastructure-level behavior. Only modify if you know what you're doing.
      </div>
      <div className="card">
        <div style={{fontWeight: 600, marginBottom: 14}}>DB Connection Pool</div>
        <div style={{display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 12}}>
          <Field label="db_pool_size"><input defaultValue="10" style={setInput}/></Field>
          <Field label="db_max_overflow"><input defaultValue="20" style={setInput}/></Field>
          <Field label="db_pool_timeout (s)"><input defaultValue="30" style={setInput}/></Field>
          <Field label="db_pool_recycle (s)"><input defaultValue="3600" style={setInput}/></Field>
        </div>
        <div style={{marginTop: 10}}>
          <div style={{fontSize: 11, color: 'var(--text-3)', marginBottom: 6}}>Connection Pool Status</div>
          <div style={{display: 'flex', gap: 12, fontSize: 12}}>
            <span>Active: <b className="mono">7/10</b></span>
            <span>Overflow: <b className="mono">2/20</b></span>
          </div>
          <div className="progress" style={{marginTop: 6}}><div style={{width: '70%', background: 'var(--emerald)'}}/></div>
        </div>
      </div>
      <div className="card" style={{marginTop: 14}}>
        <Field label="Log Level">
          <div className="seg">
            {['DEBUG','INFO','WARNING','ERROR'].map(l => <button key={l} className={logLevel===l?'active':''} onClick={() => setLogLevel(l)}>{l}</button>)}
          </div>
        </Field>
        <div style={{display: 'flex', gap: 8, marginTop: 10}}>
          <button className="btn ghost" onClick={downloadConfig}>⬇ Download System Config</button>
          <button className="btn ghost" onClick={copyConfig}>📋 Copy Config for CI →</button>
        </div>
      </div>
      <button className="btn primary" style={{marginTop:14}} onClick={() => {
        window.alert('✅ System config saved — log level set to ' + logLevel);
      }}>Save System Config</button>
    </>
  );
};

const WebhooksSec = () => {
  const [endpoints, setEndpoints] = React.useState([
    { id: 'wh_1', url: 'https://hooks.northwind.com/astrareach', events: ['anomaly.detected','decision.created'], status: 'active', lastDelivery: '2m ago', successRate: 99.2 },
    { id: 'wh_2', url: 'https://api.northwind.com/webhooks/ar', events: ['memory.written'], status: 'active', lastDelivery: '1h ago', successRate: 97.8 },
  ]);
  const [showAdd, setShowAdd] = React.useState(false);
  const [newUrl, setNewUrl] = React.useState('');
  const [testing, setTesting] = React.useState(null);
  const [toast, setToast] = React.useState(null);
  const showToast = (msg) => { setToast(msg); setTimeout(() => setToast(null), 3000); };
  const EVENT_TYPES = ['anomaly.detected','decision.created','decision.accepted','memory.written','channel.synced','actor.merged','key.expiring'];
  const [selectedEvents, setSelectedEvents] = React.useState(['anomaly.detected','decision.created']);
  return (
    <>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:20}}>
        <div>
          <h2 style={{margin:0,fontSize:20,fontWeight:700}}>Webhooks</h2>
          <div style={{fontSize:12,color:'var(--text-3)',marginTop:4}}>Push real-time events to your systems via HMAC-signed HTTP POST</div>
        </div>
        <button className="btn primary" onClick={() => setShowAdd(v => !v)}><Icon name="plus" size={12}/>Add Endpoint</button>
      </div>
      {toast && <div style={{marginBottom:12,padding:'8px 12px',background:'rgba(16,185,129,0.1)',border:'1px solid rgba(16,185,129,0.25)',borderRadius:8,fontSize:12,color:'var(--emerald)'}}>{toast}</div>}
      {showAdd && (
        <div className="card" style={{marginBottom:14,borderColor:'rgba(139,92,246,0.4)'}}>
          <div style={{fontWeight:600,marginBottom:12}}>New Webhook Endpoint</div>
          <Field label="URL">
            <input value={newUrl} onChange={e=>setNewUrl(e.target.value)} placeholder="https://your-server.com/webhooks/ar" style={setInput}/>
          </Field>
          <Field label="Events to subscribe">
            <div style={{display:'flex',gap:6,flexWrap:'wrap'}}>
              {EVENT_TYPES.map(ev => (
                <button key={ev} className={`filter-chip ${selectedEvents.includes(ev)?'active':''}`}
                  onClick={() => setSelectedEvents(prev => prev.includes(ev) ? prev.filter(e=>e!==ev) : [...prev,ev])}>
                  {ev}
                </button>
              ))}
            </div>
          </Field>
          <div style={{display:'flex',gap:8,marginTop:8}}>
            <button className="btn primary" onClick={() => {
              if (!newUrl.trim() || !newUrl.startsWith('https://')) { window.alert('Please enter a valid HTTPS URL'); return; }
              setEndpoints(prev => [...prev, { id: 'wh_'+Date.now(), url: newUrl.trim(), events: [...selectedEvents], status: 'active', lastDelivery: 'Never', successRate: 100 }]);
              setNewUrl(''); setShowAdd(false); showToast('✅ Webhook endpoint added');
            }}>Save Endpoint</button>
            <button className="btn ghost" onClick={() => setShowAdd(false)}>Cancel</button>
          </div>
        </div>
      )}
      {endpoints.map(ep => (
        <div key={ep.id} className="card" style={{marginBottom:12}}>
          <div style={{display:'flex',justifyContent:'space-between',alignItems:'flex-start',marginBottom:10}}>
            <div style={{fontFamily:'var(--mono)',fontSize:12,color:'var(--text-1)',wordBreak:'break-all'}}>{ep.url}</div>
            <span className={`badge ${ep.status==='active'?'green':'plain'}`}>{ep.status}</span>
          </div>
          <div style={{display:'flex',gap:6,flexWrap:'wrap',marginBottom:10}}>
            {ep.events.map(ev => <span key={ev} className="badge cyan" style={{fontSize:10}}>{ev}</span>)}
          </div>
          <div style={{display:'flex',gap:16,fontSize:11,color:'var(--text-3)',marginBottom:12}}>
            <span>Last delivery: <b style={{color:'var(--text-2)'}}>{ep.lastDelivery}</b></span>
            <span>Success rate: <b style={{color: ep.successRate >= 99 ? 'var(--emerald)' : 'var(--amber)'}}>{ep.successRate}%</b></span>
          </div>
          <div style={{display:'flex',gap:8}}>
            <button className="btn" disabled={testing===ep.id} style={{color:'var(--cyan)'}}
              onClick={() => {
                setTesting(ep.id);
                arFetch(ep.url.replace('https://','http://'), {method:'POST',body:JSON.stringify({type:'test',ts:Date.now()})})
                  .catch(() => {})
                  .finally(() => { setTesting(null); showToast('✅ Test delivery sent to ' + ep.url.split('/')[2]); });
              }}>{testing===ep.id ? 'Sending…' : 'Send Test →'}</button>
            <button className="btn ghost" style={{color:'var(--rose)'}}
              onClick={() => { if(window.confirm('Remove this webhook endpoint?')) { setEndpoints(prev=>prev.filter(e=>e.id!==ep.id)); showToast('Endpoint removed'); } }}>Remove</button>
          </div>
        </div>
      ))}
      <div className="card" style={{marginTop:14}}>
        <div style={{fontWeight:600,marginBottom:10}}>Delivery Security</div>
        <div style={{fontSize:12,color:'var(--text-2)',marginBottom:6}}>All deliveries are signed with HMAC-SHA256 using your webhook secret.</div>
        <div style={{display:'flex',gap:8,alignItems:'center'}}>
          <input type="password" defaultValue="whsec_●●●●●●●●●●●●●●●●●●●●●●●●●●" style={{...setInput,flex:1}}/>
          <button className="btn" style={{flexShrink:0}} onClick={() => showToast('✅ Webhook secret rotated')}>Rotate →</button>
        </div>
        <div style={{fontSize:11,color:'var(--text-3)',marginTop:8}}>Verify using the <span className="mono" style={{fontSize:10}}>X-AstraReach-Signature</span> header on incoming requests.</div>
      </div>
    </>
  );
};

const RetentionSec = () => {
  const [eventDays, setEventDays] = React.useState(90);
  const [memoryDays, setMemoryDays] = React.useState(365);
  const [journeyDays, setJourneyDays] = React.useState(180);
  const [saved, setSaved] = React.useState(false);
  const save = () => { setSaved(true); setTimeout(() => setSaved(false), 2500); };
  return (
    <>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:20}}>
        <h2 style={{margin:0,fontSize:20,fontWeight:700}}>Retention Policies</h2>
        {saved && <span style={{fontSize:11,color:'var(--emerald)'}}>✅ Saved</span>}
      </div>
      <div className="card" style={{marginBottom:14}}>
        <div style={{fontWeight:600,marginBottom:6}}>Raw Events</div>
        <div style={{fontSize:12,color:'var(--text-2)',marginBottom:12}}>Current: <span className="badge cyan">{eventDays} days</span></div>
        <input type="range" min="30" max="730" value={eventDays} onChange={e=>setEventDays(Number(e.target.value))} style={{width:'100%'}}/>
        <div style={{display:'flex',justifyContent:'space-between',fontSize:10,color:'var(--text-4)',marginTop:4}}><span>30 days</span><span>2 years</span></div>
        <div style={{fontSize:11,color:'var(--text-3)',marginTop:8}}>Events older than {eventDays} days are permanently deleted. Journeys and identity links are preserved.</div>
      </div>
      <div className="card" style={{marginBottom:14}}>
        <div style={{fontWeight:600,marginBottom:6}}>Memory Items</div>
        <div style={{fontSize:12,color:'var(--text-2)',marginBottom:12}}>Current: <span className="badge violet">{memoryDays} days</span></div>
        <input type="range" min="30" max="730" value={memoryDays} onChange={e=>setMemoryDays(Number(e.target.value))} style={{width:'100%'}}/>
        <div style={{display:'flex',justifyContent:'space-between',fontSize:10,color:'var(--text-4)',marginTop:4}}><span>30 days</span><span>2 years</span></div>
        <div style={{fontSize:11,color:'var(--text-3)',marginTop:8}}>Low-confidence (&lt;0.4) memory items expire after {memoryDays} days. High-confidence items (&gt;0.8) are retained indefinitely.</div>
      </div>
      <div className="card" style={{marginBottom:14}}>
        <div style={{fontWeight:600,marginBottom:6}}>Journey Graphs</div>
        <div style={{fontSize:12,color:'var(--text-2)',marginBottom:12}}>Current: <span className="badge cyan">{journeyDays} days</span></div>
        <input type="range" min="30" max="365" value={journeyDays} onChange={e=>setJourneyDays(Number(e.target.value))} style={{width:'100%'}}/>
        <div style={{display:'flex',justifyContent:'space-between',fontSize:10,color:'var(--text-4)',marginTop:4}}><span>30 days</span><span>1 year</span></div>
      </div>
      <div className="card" style={{marginBottom:14}}>
        <div style={{fontWeight:600,marginBottom:10}}>Automated Purge Schedule</div>
        <div style={{display:'grid',gridTemplateColumns:'repeat(2,1fr)',gap:8}}>
          <Field label="Run at (UTC)"><input defaultValue="03:00" style={setInput}/></Field>
          <Field label="Frequency"><select style={setInput}><option>Daily</option><option>Weekly</option><option>Manual only</option></select></Field>
        </div>
        <div style={{padding:'8px 12px',background:'rgba(16,185,129,0.08)',border:'1px solid rgba(16,185,129,0.25)',borderRadius:8,fontSize:12,color:'var(--emerald)',marginTop:8}}>
          ✅ APScheduler purge job configured — runs daily at 03:00 UTC
        </div>
      </div>
      <button className="btn primary" onClick={save}>Save Retention Policy</button>
    </>
  );
};

const DeveloperSec = () => {
  const [tokens, setTokens] = React.useState([
    { id: 'pat_1', name: 'Local dev', scope: 'read:all', created: 'Apr 20, 2026', expires: 'Never', lastUsed: '5m ago' },
    { id: 'pat_2', name: 'CI/CD runner', scope: 'write:events,read:all', created: 'Mar 1, 2026', expires: 'Jun 1, 2026', lastUsed: '1h ago' },
  ]);
  const [showNew, setShowNew] = React.useState(false);
  const [newName, setNewName] = React.useState('');
  const [newToken, setNewToken] = React.useState(null);
  const [toast, setToast] = React.useState(null);
  const showToast = msg => { setToast(msg); setTimeout(() => setToast(null), 3000); };
  return (
    <>
      <div style={{marginBottom:20}}>
        <h2 style={{margin:0,fontSize:20,fontWeight:700}}>Developer</h2>
        <div style={{fontSize:12,color:'var(--text-3)',marginTop:4}}>Personal access tokens, OAuth apps, and API explorer</div>
      </div>
      {toast && <div style={{marginBottom:12,padding:'8px 12px',background:'rgba(16,185,129,0.1)',border:'1px solid rgba(16,185,129,0.25)',borderRadius:8,fontSize:12,color:'var(--emerald)'}}>{toast}</div>}
      <div className="card" style={{marginBottom:14}}>
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:14}}>
          <div style={{fontWeight:600}}>Personal Access Tokens</div>
          <button className="btn" onClick={() => setShowNew(v=>!v)}><Icon name="plus" size={12}/>New Token</button>
        </div>
        {showNew && (
          <div style={{marginBottom:14,padding:'12px 14px',background:'var(--bg-1)',border:'1px solid var(--border)',borderRadius:8}}>
            <Field label="Token name"><input value={newName} onChange={e=>setNewName(e.target.value)} placeholder="e.g. Local dev" style={setInput}/></Field>
            <Field label="Scope">
              <select style={setInput}>
                <option value="read:all">read:all — Read-only access</option>
                <option value="write:events">write:events — Ingest events only</option>
                <option value="write:all">write:all — Full write access</option>
              </select>
            </Field>
            <div style={{display:'flex',gap:8}}>
              <button className="btn primary" onClick={() => {
                if (!newName.trim()) return;
                const tok = 'ar_pat_' + Math.random().toString(36).slice(2,12) + Math.random().toString(36).slice(2,12);
                setNewToken(tok);
                setTokens(prev => [...prev, { id: 'pat_'+Date.now(), name: newName.trim(), scope: 'read:all', created: new Date().toLocaleDateString('en-US',{month:'short',day:'numeric',year:'numeric'}), expires: 'Never', lastUsed: 'Never' }]);
                setNewName(''); setShowNew(false);
              }}>Generate Token</button>
              <button className="btn ghost" onClick={() => setShowNew(false)}>Cancel</button>
            </div>
          </div>
        )}
        {newToken && (
          <div style={{marginBottom:14,padding:'10px 14px',background:'rgba(16,185,129,0.08)',border:'1px solid rgba(16,185,129,0.3)',borderRadius:8}}>
            <div style={{fontSize:11,color:'var(--emerald)',fontWeight:600,marginBottom:6}}>✅ Token created — copy now, it won't be shown again</div>
            <div style={{fontFamily:'var(--mono)',fontSize:11,background:'var(--bg-1)',padding:'6px 10px',borderRadius:6,wordBreak:'break-all',marginBottom:6}}>{newToken}</div>
            <button className="btn" style={{fontSize:11}} onClick={() => { navigator.clipboard?.writeText(newToken); showToast('✓ Token copied'); setNewToken(null); }}>Copy & Dismiss</button>
          </div>
        )}
        <table className="data-table" style={{fontSize:11}}>
          <thead><tr><th>Name</th><th>Scope</th><th>Created</th><th>Expires</th><th>Last Used</th><th></th></tr></thead>
          <tbody>
            {tokens.map(t => (
              <tr key={t.id}>
                <td style={{fontWeight:500}}>{t.name}</td>
                <td><span className="badge plain" style={{fontFamily:'var(--mono)',fontSize:9}}>{t.scope}</span></td>
                <td style={{color:'var(--text-3)'}}>{t.created}</td>
                <td style={{color:'var(--text-3)'}}>{t.expires}</td>
                <td style={{color:'var(--text-3)'}}>{t.lastUsed}</td>
                <td style={{textAlign:'right'}}><button style={{background:'none',border:'none',color:'var(--rose)',fontSize:11,cursor:'pointer'}} onClick={() => { if(window.confirm('Revoke token?')) setTokens(prev=>prev.filter(x=>x.id!==t.id)); }}>Revoke</button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className="card" style={{marginBottom:14}}>
        <div style={{fontWeight:600,marginBottom:10}}>OAuth Applications</div>
        <div style={{fontSize:12,color:'var(--text-2)',marginBottom:12}}>Register OAuth 2.0 apps to allow third-party services to authenticate on behalf of your users.</div>
        <div style={{padding:'10px 12px',background:'var(--bg-1)',border:'1px solid var(--border)',borderRadius:8,fontSize:12,color:'var(--text-3)'}}>
          No OAuth apps registered yet. <button className="btn ghost" style={{fontSize:11,display:'inline',padding:'0 4px',color:'var(--accent)'}} onClick={() => window.alert('OAuth app registration UI — requires OAuth 2.0 server. Set up via Settings → Authentication → OAuth mode.')}>Register first app →</button>
        </div>
      </div>
      <div className="card">
        <div style={{fontWeight:600,marginBottom:10}}>API Explorer</div>
        <div style={{fontSize:12,color:'var(--text-2)',marginBottom:12}}>Interactive API docs and request builder</div>
        <button className="btn" onClick={() => window.open('/docs', '_blank') || window.alert('API docs available at: http://localhost:8000/docs (run make up)')}>Open Swagger UI →</button>
        <button className="btn" style={{marginLeft:8}} onClick={() => window.open('http://localhost:8000/redoc', '_blank') || window.alert('ReDoc available at: http://localhost:8000/redoc (run make up)')}>Open ReDoc →</button>
      </div>
    </>
  );
};

const SettingsScreen = () => {
  const [sec, setSec] = React.useState('general');
  return (
    <div style={{display: 'grid', gridTemplateColumns: '220px 1fr', gap: 20, height: '100%'}}>
      <aside style={{background: 'var(--bg-0)', border: '1px solid var(--border)', borderRadius: 10, padding: '12px 8px', height: 'fit-content', position: 'sticky', top: 0}}>
        <div style={{fontSize: 15, fontWeight: 700, padding: '4px 10px 12px'}}>Settings</div>
        {SETTINGS_NAV.map(grp => (
          <div key={grp.group} style={{marginBottom: 10}}>
            <div style={{fontSize: 10, color: 'var(--text-4)', textTransform: 'uppercase', letterSpacing: '0.08em', padding: '6px 10px'}}>{grp.group}</div>
            {grp.items.map(([k, label, icon]) => (
              <div key={k} onClick={() => setSec(k)} className={`nav-item ${sec===k?'active':''}`} style={{padding: '6px 10px', fontSize: 12}}>
                <Icon name={icon} size={13}/>
                <span>{label}</span>
              </div>
            ))}
          </div>
        ))}
      </aside>
      <div>
        <div style={{fontSize: 11, color: 'var(--text-4)', fontFamily: 'var(--mono)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 12}}>Platform / Settings</div>
        {sec === 'general' && <GeneralSec/>}
        {sec === 'auth' && <AuthSec/>}
        {sec === 'access' && <AccessSec/>}
        {sec === 'audit' && <AuditSec/>}
        {sec === 'ai' && <AISec/>}
        {sec === 'notif' && <NotifSec/>}
        {sec === 'team' && <TeamSec/>}
        {sec === 'channels' && <ChannelsCredSec/>}
        {sec === 'data' && <DataSec/>}
        {sec === 'io' && <IOSec/>}
        {sec === 'sys' && <SysSec/>}
        {sec === 'billing' && <BillingScreen/>}
        {sec === 'retain' && <RetentionSec/>}
        {sec === 'hooks' && <WebhooksSec/>}
        {sec === 'dev' && <DeveloperSec/>}
      </div>
    </div>
  );
};

window.SettingsScreen = SettingsScreen;
