// 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 = () => (
  <>
    <div style={{display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20}}>
      <h2 style={{margin: 0, fontSize: 20, fontWeight: 700}}>General</h2>
      <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">
          {['1–10','11–50','51–200','201–1000','1000+'].map(s => <button key={s} className={s==='51–200'?'active':''}>{s}</button>)}
        </div>
      </Field>
      <Field label="Primary Goals" hint="What brought you to AstraReach?">
        <div style={{display: 'flex', gap: 6, flexWrap: 'wrap'}}>
          {['Map journeys','Reduce reporting','Catch anomalies','AI decisions','Unify ad data'].map((g, i) => (
            <button key={g} className={`filter-chip ${i<3?'active':''}`}>{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}}>
          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">Save Changes</button>
        <button className="btn ghost">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)'}}>Delete Organization</button>
      </div>
    </div>
  </>
);

const AuthSec = () => {
  const [mode, setMode] = React.useState('api');
  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 OFF</div>
          </div>
          <div className="toggle"/>
        </div>
        <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>
      </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)'}}>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)'}}>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)'}}>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>

    <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)']].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 = () => (
  <>
    <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 on"/>
      </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}}>
          <span className="badge violet">alerts@northwind.com ×</span>
          <span className="badge violet">growth-ops@northwind.com ×</span>
          <input placeholder="Add email..." 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 ${s==='HIGH'?'active':''}`}>{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 on"/>
      </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)'}}>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"/>
      </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}}>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>
          {[['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]].map((r, i) => (
            <tr key={i}>
              <td style={{color: 'var(--text-1)', fontFamily: 'var(--mono)', fontSize: 11}}>{r[0]}</td>
              {[r[1], r[2], r[3]].map((v, j) => (
                <td key={j} style={{textAlign: 'center'}}>
                  <div className={`toggle ${v?'on':''}`} style={{display: 'inline-block', opacity: j===2?0.4:1}}/>
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
      <button className="btn primary" style={{marginTop: 14}}>Send Test to All Channels →</button>
    </div>
  </>
);

const TeamSec = () => (
  <>
    <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 placeholder="colleague@northwind.com" style={{...setInput, flex: 2}}/>
        <select 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}}>Send Invitation →</button>
      </div>
    </div>
  </>
);

const ChannelsCredSec = () => (
  <>
    <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)'}}>Validate Credentials →</button>
          <button className="btn ghost" style={{color: 'var(--rose)'}}>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>
      <button className="btn" style={{background: 'var(--emerald)', color: '#001', borderColor: 'var(--emerald)'}}>Run Sync Now →</button>
    </div>
  </>
);

const DataSec = () => (
  <>
    <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">90 days</span></div>
      <input type="range" min="30" max="365" defaultValue="90" 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 90 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={{fontWeight: 600}}>Block PII in Memory</div>
        <div className="toggle on" style={{opacity: 0.6}}/>
      </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 on"/>
      </div>
      <div style={{fontSize: 12, color: 'var(--text-3)'}}>Events with consent_granted=false are stored for audit but excluded from analysis and identity resolution.</div>
    </div>
  </>
);

const SysSec = () => (
  <>
    <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={l==='INFO'?'active':''}>{l}</button>)}
        </div>
      </Field>
      <div style={{display: 'flex', gap: 8, marginTop: 10}}>
        <button className="btn ghost">Download System Config</button>
        <button className="btn ghost">Copy Config for CI →</button>
      </div>
    </div>
  </>
);

const IOSec = () => (
  <>
    <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</div>
      {[
        ['Events (NDJSON)','All events in date range'],
        ['Actors (CSV)','Resolved actor profiles'],
        ['Decisions (JSON)','Decision log with reflexions'],
        ['Journey snapshots','All saved Markov snapshots'],
      ].map(([label,desc])=>(
        <div key={label} style={{display:'flex',alignItems:'center',justifyContent:'space-between',
          padding:'10px 0',borderTop:'1px solid var(--border)'}}>
          <div>
            <div style={{fontSize:13}}>{label}</div>
            <div style={{fontSize:11,color:'var(--text-3)'}}>{desc}</div>
          </div>
          <button className="btn" style={{fontSize:11}}>Export →</button>
        </div>
      ))}
    </div>
    <div className="card">
      <div style={{fontWeight:600,marginBottom:12}}>📥 Import</div>
      <div style={{fontSize:13,color:'var(--text-2)',marginBottom:12}}>
        Import events from CSV or NDJSON. Rows validated and deduplicated by event_id.
      </div>
      <div style={{border:'2px dashed var(--border)',borderRadius:8,padding:'32px 20px',
        textAlign:'center',color:'var(--text-3)',cursor:'pointer'}}
        onClick={()=>document.getElementById('settings-import-file').click()}>
        <div style={{fontSize:13,marginBottom:4}}>Drop file or click to browse</div>
        <div style={{fontSize:11,fontFamily:'var(--mono)'}}>CSV or NDJSON · max 10MB</div>
        <input type="file" id="settings-import-file" accept=".csv,.ndjson,.jsonl"
          style={{display:'none'}}
          onChange={e=>{
  const f=e.target.files[0]; if(!f)return;
  const reader=new FileReader();
  reader.onload=ev=>{
    const lines=ev.target.result.trim().split('\n').filter(Boolean);
    if(lines.length<2){alert('File has no data rows.');return;}
    const headers=lines[0].split(',').map(h=>h.trim().replace(/"/g,''));
    const preview=lines.slice(1,4).map(l=>{
      const vals=l.split(',');
      return Object.fromEntries(headers.map((h,i)=>[h,(vals[i]||'').trim().replace(/"/g,'')]));
    });
    const total=lines.length-1;
    const ok=window.confirm(
      'Import '+total+' row(s)?\n\nPreview (first 3):\n'+
      preview.map(r=>JSON.stringify(r)).join('\n')+
      '\n\nClick OK to import.'
    );
    if(!ok)return;
    const allRows=lines.slice(1).map(l=>{
      const vals=l.split(',');
      return Object.fromEntries(headers.map((h,i)=>[h,(vals[i]||'').trim().replace(/"/g,'')]));
    });
    const SIZE=50; const chunks=[];
    for(let i=0;i<allRows.length;i+=SIZE)chunks.push(allRows.slice(i,i+SIZE));
    let acc=0,rej=0;
    Promise.all(chunks.map(chunk=>
      arFetch('/v1/events:ingest',{method:'POST',body:JSON.stringify({events:chunk.map(r=>({
        event_id:r.event_id||r.id||crypto.randomUUID(),
        name:r.event_name||r.name||'imported_event',
        ts:r.ts||r.timestamp||new Date().toISOString(),
        actor:r.actor_email?{email:r.actor_email}:{anon_id:crypto.randomUUID()},
        props:Object.fromEntries(Object.entries(r).filter(([k])=>
          !['event_id','id','event_name','name','ts','timestamp','actor_email'].includes(k)))
      }))})})
      .then(d=>{acc+=(d.accepted||0);rej+=(d.rejected||0);})
      .catch(()=>{})
    )).then(()=>alert('Import complete: '+acc+' accepted, '+rej+' rejected.'));
  };
  reader.readAsText(f);
}}/>
      </div>
    </div>
  </>
);

const HooksSec = () => (
  <>
    <h2 style={{margin:'0 0 20px',fontSize:20,fontWeight:700}}>Webhooks</h2>
    <div className="card">
      <div style={{fontSize:13,color:'var(--text-2)',marginBottom:16,lineHeight:1.6}}>
        Webhook subscriptions are managed through the Partner API screen.
        HMAC-SHA256 signed delivery with retry and exponential backoff.
      </div>
      <div style={{display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:10,marginBottom:16}}>
        {[['Active','3'],['Deliveries 24h','847'],['Success rate','99.2%']].map(([l,v])=>(
          <div key={l} style={{background:'var(--bg-3)',borderRadius:8,padding:'10px 12px'}}>
            <div style={{fontSize:10,color:'var(--text-3)',textTransform:'uppercase',letterSpacing:'0.08em'}}>{l}</div>
            <div style={{fontSize:18,fontWeight:600,marginTop:4}}>{v}</div>
          </div>
        ))}
      </div>
      <button className="btn primary"
        onClick={()=>window.AR_NAVIGATE&&window.AR_NAVIGATE('partner')}>
        Manage webhooks →
      </button>
    </div>
  </>
);

const DevSec = () => (
  <>
    <h2 style={{margin:'0 0 20px',fontSize:20,fontWeight:700}}>Developer</h2>
    <div className="card" style={{marginBottom:14}}>
      <Field label="API Base URL" hint="Used by SDKs and curl examples">
        <input style={setInput} defaultValue={window.API_BASE||'https://astrareach.fly.dev'}/>
      </Field>
      <Field label="Python SDK">
        <div style={{fontFamily:'var(--mono)',fontSize:13}}>
          astrareach-sdk 0.1.0 <span style={{color:'var(--emerald)'}}>✓ latest</span>
        </div>
      </Field>
      <Field label="OpenAPI Spec">
        <a href={(window.API_BASE||'')+'/openapi.json'} target="_blank" rel="noopener noreferrer"
          style={{fontSize:12,color:'var(--accent)',fontFamily:'var(--mono)'}}>
          /openapi.json →
        </a>
      </Field>
    </div>
    <div className="card">
      <div style={{fontWeight:600,marginBottom:10}}>Debug tools</div>
      <div style={{display:'flex',flexDirection:'column',gap:8}}>
        <button className="btn"
          onClick={() => {
            if (typeof window.arCheckConnectivity === 'function') {
              window.arCheckConnectivity().then(ok =>
                alert(ok ? '✓ API reachable at ' + (window.API_BASE || 'unknown') : '✗ API unreachable — check API_BASE in Tweaks')
              );
            } else {
              alert('Connectivity check unavailable. Set API_BASE in Tweaks panel first.');
            }
          }}>
          Test API connectivity
        </button>
        <button className="btn"
          onClick={()=>{ if(window.confirm('This will sign you out and reload. Continue?')){ localStorage.clear(); window.location.reload(); } }}>
          Clear local storage + reload
        </button>
      </div>
    </div>
  </>
);

const BillingSec = () => (
  <>
    <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:20}}>
      <h2 style={{margin:0,fontSize:20,fontWeight:700}}>Billing & Plan</h2>
      <button className="btn primary">Upgrade plan →</button>
    </div>
    <div className="card" style={{marginBottom:14}}>
      <div style={{display:'flex',justifyContent:'space-between',alignItems:'center'}}>
        <div>
          <div style={{fontSize:16,fontWeight:700}}>Growth</div>
          <div style={{fontSize:12,color:'var(--text-3)'}}>250K actors / mo · $1,200/mo</div>
        </div>
        <span className="badge green">Active</span>
      </div>
      <div style={{marginTop:14,display:'grid',gridTemplateColumns:'repeat(3,1fr)',gap:10}}>
        {[['Actors used','184,210 / 250,000'],['NL queries','Unlimited'],['Next renewal','Jun 1, 2026']].map(([l,v])=>(
          <div key={l} style={{background:'var(--bg-3)',borderRadius:8,padding:'10px 12px'}}>
            <div style={{fontSize:10,color:'var(--text-3)',textTransform:'uppercase',letterSpacing:'0.08em'}}>{l}</div>
            <div style={{fontSize:14,fontWeight:600,marginTop:4}}>{v}</div>
          </div>
        ))}
      </div>
    </div>
    <div className="card">
      <div style={{fontWeight:600,marginBottom:10}}>Payment method</div>
      <div style={{display:'flex',alignItems:'center',gap:10,fontSize:13}}>
        <span>💳</span>
        <span>Visa ending 6411</span>
        <span style={{color:'var(--text-3)',fontSize:11}}>Expires 09/28</span>
        <button className="btn ghost" style={{marginLeft:'auto',fontSize:11}}>Update →</button>
      </div>
    </div>
  </>
);

const AccessSec = () => (
  <>
    <h2 style={{margin:'0 0 20px',fontSize:20,fontWeight:700}}>API & Access</h2>
    <div className="card" style={{marginBottom:14}}>
      <Field label="API Keys" hint="Manage individual keys from the API Keys screen">
        <div style={{display:'flex',alignItems:'center',gap:10}}>
          <span style={{fontSize:13}}>3 active keys</span>
          <button className="btn ghost" style={{fontSize:11}}
            onClick={()=>window.AR_NAVIGATE&&window.AR_NAVIGATE('keys')}>
            Manage keys →
          </button>
        </div>
      </Field>
      <Field label="Rate Limit" hint="Requests per minute per API key">
        <input style={setInput} defaultValue="600 req/min"/>
      </Field>
      <Field label="IP Allowlist (CIDR)" hint="One CIDR per line. Leave empty to allow all IPs.">
        <textarea style={{...setInput,height:80,resize:'vertical'}}
          placeholder={'e.g. 203.0.113.0/24\n198.51.100.0/24'}/>
      </Field>
      <Field label="Source Allowlist" hint="Restrict ingestion to these source identifiers (comma-separated)">
        <input style={setInput} placeholder="e.g. web, app, crm"/>
      </Field>
    </div>
  </>
);

const AUDIT_ROWS = [
  { ts:'2026-05-05 14:32', actor:'ak_prod_***', action:'POST /v1/events:ingest', status:'200', detail:'847 events' },
  { ts:'2026-05-05 14:28', actor:'ak_prod_***', action:'GET /v1/decisions', status:'200', detail:'' },
  { ts:'2026-05-05 13:55', actor:'ak_prod_***', action:'POST /v1/community/sync', status:'200', detail:'23 mentions' },
  { ts:'2026-05-04 22:11', actor:'ak_dev_***',  action:'POST /v1/auth/login', status:'401', detail:'' },
  { ts:'2026-05-04 09:00', actor:'scheduler',   action:'GET /v1/channels/sync', status:'200', detail:'3 channels' },
];
const AuditSec = () => (
  <>
    <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:20}}>
      <h2 style={{margin:0,fontSize:20,fontWeight:700}}>Audit Log</h2>
      <button className="btn" style={{fontSize:11}}>Export CSV →</button>
    </div>
    <div className="card">
      <div style={{fontSize:11,color:'var(--text-3)',marginBottom:12,fontFamily:'var(--mono)'}}>
        API calls · auth events · scheduler runs · last 30 days
      </div>
      <table style={{width:'100%',borderCollapse:'collapse',fontSize:12}}>
        <thead>
          <tr style={{borderBottom:'1px solid var(--border)'}}>
            {['Timestamp','Actor','Action','Status','Details'].map(h=>(
              <th key={h} style={{textAlign:'left',padding:'6px 8px',color:'var(--text-3)',fontWeight:500,fontSize:11}}>{h}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {AUDIT_ROWS.map((r,i)=>(
            <tr key={i} style={{borderBottom:'1px solid var(--border)'}}>
              <td style={{padding:'8px',fontFamily:'var(--mono)',fontSize:10,color:'var(--text-3)'}}>{r.ts}</td>
              <td style={{padding:'8px',fontFamily:'var(--mono)',fontSize:11}}>{r.actor}</td>
              <td style={{padding:'8px',fontFamily:'var(--mono)',fontSize:11,color:'var(--text-2)'}}>{r.action}</td>
              <td style={{padding:'8px'}}>
                <span style={{fontFamily:'var(--mono)',fontSize:11,
                  color:r.status.startsWith('2')?'var(--emerald)':'var(--rose)'}}>
                  {r.status}
                </span>
              </td>
              <td style={{padding:'8px',fontSize:11,color:'var(--text-3)'}}>{r.detail}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  </>
);

const RetainSec = () => (
  <>
    <h2 style={{margin:'0 0 20px',fontSize:20,fontWeight:700}}>Data Retention</h2>
    <div className="card">
      <Field label="Event Retention" hint="Raw events deleted after this period">
        <div className="seg">
          {['30d','90d','180d','365d','Forever'].map((d,i)=>(
            <button key={d} className={i===2?'active':''}>{d}</button>
          ))}
        </div>
      </Field>
      <Field label="Journey Snapshot Retention" hint="Older snapshots pruned automatically">
        <div className="seg">
          {['7d','30d','90d','365d'].map((d,i)=>(
            <button key={d} className={i===2?'active':''}>{d}</button>
          ))}
        </div>
      </Field>
      <Field label="Anomaly History" hint="Detected anomaly records retained for">
        <div className="seg">
          {['30d','90d','1y'].map((d,i)=>(
            <button key={d} className={i===1?'active':''}>{d}</button>
          ))}
        </div>
      </Field>
      <Field label="GDPR Right to Erasure" hint="Soft-delete events within 24h of consent revocation">
        <div style={{display:'flex',alignItems:'center',gap:8,fontSize:13}}>
          <span className="badge green">Enabled</span>
          <span style={{color:'var(--text-3)'}}>Consent revocations processed nightly</span>
        </div>
      </Field>
    </div>
  </>
);

const SettingsScreen = () => {
  const [sec, setSec] = React.useState(() => {
    const s = window.AR_SETTINGS_SECTION || 'general';
    window.AR_SETTINGS_SECTION = null;
    return s;
  });
  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 === 'ai' && <AISec/>}
        {sec === 'notif' && <NotifSec/>}
        {sec === 'team' && <TeamSec/>}
        {sec === 'channels' && <ChannelsCredSec/>}
        {sec === 'data' && <DataSec/>}
        {sec === 'sys' && <SysSec/>}
        {sec === 'io' && <IOSec/>}
        {sec === 'hooks' && <HooksSec/>}
        {sec === 'dev' && <DevSec/>}
        {sec === 'billing' && <BillingSec/>}
        {sec === 'access' && <AccessSec/>}
        {sec === 'audit' && <AuditSec/>}
        {sec === 'retain' && <RetainSec/>}
        {!['general','auth','ai','notif','team','channels','data','sys','billing','access','audit','retain','io','hooks','dev'].includes(sec) && (
          <div style={{padding: 40, textAlign: 'center', color: 'var(--text-3)'}}>
            <div style={{fontSize: 14, marginBottom: 6}}>Section coming soon</div>
            <div style={{fontSize: 12}}>This settings section is not yet implemented in the prototype.</div>
          </div>
        )}
      </div>
    </div>
  );
};

window.SettingsScreen = SettingsScreen;
