// Super Admin Panel — Platform owner view across all orgs
// Only visible when currentUser.superAdmin === true
// Every action is audit-logged. Treat this screen as production-sensitive.

const SA_COLOR = '#0F172A';
const SA_ACCENT = '#6366F1';
const SA_SOFT = '#EEF2FF';
const SA_BORDER = '#C7D2FE';

// Mock orgs for demo — in live mode these come from Supabase via service_role
const MOCK_ORGS = [
  { id:'org_1', name:'Kitchens U Build', slug:'kitchens-u-build', plan:'growth', status:'active', seats:12, seatsUsed:9, mrr:490, lastActive:'Today', createdAt:'12 Jan 2026', industry:'kitchen_design', region:'Sydney', adminEmail:'admin@kub.com.au' },
  { id:'org_2', name:'Premier Kitchens QLD', slug:'premier-kitchens-qld', plan:'starter', status:'active', seats:5, seatsUsed:4, mrr:149, lastActive:'Yesterday', createdAt:'3 Feb 2026', industry:'kitchen_design', region:'Brisbane', adminEmail:'owner@premierkitchens.com.au' },
  { id:'org_3', name:'Design & Build Co', slug:'design-build-co', plan:'enterprise', status:'active', seats:40, seatsUsed:31, mrr:1490, lastActive:'2 hours ago', createdAt:'22 Nov 2025', industry:'kitchen_design', region:'Melbourne', adminEmail:'it@designbuild.com.au' },
  { id:'org_4', name:'Modular Spaces', slug:'modular-spaces', plan:'growth', status:'trialing', seats:10, seatsUsed:3, mrr:0, lastActive:'3 days ago', createdAt:'8 Jun 2026', industry:'kitchen_design', region:'Perth', adminEmail:'hello@modularspaces.com.au' },
  { id:'org_5', name:'Coastal Renovations', slug:'coastal-renovations', plan:'starter', status:'past_due', seats:5, seatsUsed:5, mrr:149, lastActive:'12 days ago', createdAt:'14 Mar 2026', industry:'kitchen_design', region:'Gold Coast', adminEmail:'accounts@coastalreno.com.au' },
  { id:'org_6', name:'Urban Kitchen Studio', slug:'urban-kitchen-studio', plan:'growth', status:'cancelled', seats:10, seatsUsed:0, mrr:0, lastActive:'45 days ago', createdAt:'5 Oct 2025', industry:'kitchen_design', region:'Sydney', adminEmail:'studio@urbankitchen.com.au' },
];

const MOCK_AUDIT = [
  { ts:'Today 10:42 am', org:'Kitchens U Build', user:'admin@kub.com.au', action:'user_invited', detail:'Invited sarah.jones@kub.com.au as sales_designer' },
  { ts:'Today 9:15 am', org:'Design & Build Co', user:'it@designbuild.com.au', action:'settings_changed', detail:'Terminology updated: "Showroom" → "Studio"' },
  { ts:'Yesterday 4:30 pm', org:'Premier Kitchens QLD', user:'owner@premierkitchens.com.au', action:'deal_stage_change', detail:'Deal PAK 51234 moved: in_progress → sold' },
  { ts:'Yesterday 2:10 pm', org:'Modular Spaces', user:'hello@modularspaces.com.au', action:'login', detail:'Sign in from 203.11.xx.xx (Perth, AU)' },
  { ts:'8 Jun 3:44 pm', org:'Kitchens U Build', user:'rep@kub.com.au', action:'login_failed', detail:'3 failed attempts — account temporarily locked' },
  { ts:'8 Jun 1:00 pm', org:'Coastal Renovations', user:'accounts@coastalreno.com.au', action:'payment_failed', detail:'Stripe charge failed — card declined' },
  { ts:'7 Jun 11:30 am', org:'Design & Build Co', user:'super_admin', action:'impersonated', detail:'Super admin viewed org for support ticket #4821' },
];

const PLAN_COLORS = {
  starter: { bg:'var(--surface-2)', color:'var(--ink-3)', border:'var(--border)' },
  growth: { bg:SA_SOFT, color:SA_ACCENT, border:SA_BORDER },
  enterprise: { bg:'#FEF3C7', color:'#92400E', border:'#FDE68A' },
};

const STATUS_COLORS = {
  active: { bg:'var(--won-soft)', color:'var(--won)' },
  trialing: { bg:SA_SOFT, color:SA_ACCENT },
  past_due: { bg:'var(--warn-soft)', color:'var(--warn)' },
  cancelled: { bg:'var(--lost-soft)', color:'var(--lost)' },
};

const ACTION_ICONS = {
  user_invited:'👤', settings_changed:'⚙️', deal_stage_change:'📊',
  login:'🔑', login_failed:'🚨', payment_failed:'💳', impersonated:'👁️',
};

function SABadge({ label, style }) {
  return <span style={{ fontSize:11, fontWeight:700, padding:'2px 8px', borderRadius:99, ...style }}>{label}</span>;
}

function SuperAdmin({ currentUser, deals, contacts, reps, showToast }) {
  const toast = showToast || (() => {});
  const [tab, setTab] = React.useState('orgs');
  const [selectedOrg, setSelectedOrg] = React.useState(null);
  const [impersonating, setImpersonating] = React.useState(null);
  const [searchOrg, setSearchOrg] = React.useState('');
  const [showImpersonateConfirm, setShowImpersonateConfirm] = React.useState(null);

  if (!currentUser.superAdmin) {
    return (
      <div style={{ display:'flex', alignItems:'center', justifyContent:'center', height:400, flexDirection:'column', gap:12 }}>
        <div style={{ fontSize:36 }}>🔒</div>
        <div style={{ fontSize:18, fontWeight:700, color:'var(--ink)' }}>Access Denied</div>
        <div style={{ fontSize:13, color:'var(--ink-3)' }}>Super Admin access required.</div>
      </div>
    );
  }

  const totalMRR = MOCK_ORGS.filter(o=>o.status==='active'||o.status==='past_due').reduce((a,o)=>a+o.mrr,0);
  const activeOrgs = MOCK_ORGS.filter(o=>o.status==='active').length;
  const trialingOrgs = MOCK_ORGS.filter(o=>o.status==='trialing').length;
  const totalSeats = MOCK_ORGS.reduce((a,o)=>a+o.seatsUsed,0);

  const filteredOrgs = MOCK_ORGS.filter(o =>
    !searchOrg || o.name.toLowerCase().includes(searchOrg.toLowerCase()) ||
    o.adminEmail.toLowerCase().includes(searchOrg.toLowerCase())
  );

  return (
    <div>
      {/* Super Admin warning banner */}
      <div style={{ display:'flex', alignItems:'center', gap:10, padding:'10px 16px', background:SA_COLOR, borderRadius:'var(--r-lg)', marginBottom:20, color:'white' }}>
        <span style={{ fontSize:16 }}>🛡️</span>
        <div style={{ flex:1 }}>
          <span style={{ fontSize:13, fontWeight:700 }}>Super Admin Mode</span>
          <span style={{ fontSize:12, opacity:0.65, marginLeft:10 }}>You are viewing all organisations. Every action is logged in the audit trail.</span>
        </div>
        <div style={{ fontSize:12, opacity:0.6, fontFamily:'var(--mono)' }}>Signed in as {currentUser.email || currentUser.name}</div>
      </div>

      {/* Platform KPIs */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(5,1fr)', gap:14, marginBottom:20 }}>
        {[
          { label:'Monthly Recurring Revenue', value:'$'+totalMRR.toLocaleString(), sub:'Active + past-due orgs', color:SA_ACCENT },
          { label:'Active Organisations', value:activeOrgs, sub:`${trialingOrgs} trialing`, color:'var(--won)' },
          { label:'Total Seats in Use', value:totalSeats, sub:'across all orgs', color:'var(--accent)' },
          { label:'At-Risk Accounts', value: MOCK_ORGS.filter(o=>o.status==='past_due').length, sub:'payment failed', color:'var(--warn)' },
          { label:'Churned (30d)', value: MOCK_ORGS.filter(o=>o.status==='cancelled').length, sub:'cancelled this month', color:'var(--lost)' },
        ].map(k => (
          <div key={k.label} className="kpi" style={{ borderTop:`3px solid ${k.color}` }}>
            <div className="kpi-label">{k.label}</div>
            <div className="kpi-value" style={{ fontSize:28, color:k.color }}>{k.value}</div>
            <div className="kpi-meta"><span className="kpi-foot">{k.sub}</span></div>
          </div>
        ))}
      </div>

      {/* Tab bar */}
      <div style={{ display:'flex', gap:2, background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:8, padding:3, marginBottom:18, width:'fit-content' }}>
        {[['orgs','Organisations'],['support','Support Tools'],['audit','Audit Log'],['health','Platform Health']].map(([id,label]) => (
          <button key={id} onClick={() => setTab(id)}
            style={{ padding:'5px 16px', borderRadius:6, border:'none', fontSize:13, fontWeight:tab===id?600:400,
              background: tab===id ? 'var(--surface)' : 'transparent',
              color: tab===id ? 'var(--ink)' : 'var(--ink-3)',
              boxShadow: tab===id ? 'var(--shadow-sm)' : 'none', cursor:'pointer', whiteSpace:'nowrap' }}>
            {label}
          </button>
        ))}
      </div>

      {/* ── ORGANISATIONS ── */}
      {tab === 'orgs' && (
        <div style={{ display:'grid', gridTemplateColumns: selectedOrg ? '1fr 340px' : '1fr', gap:16 }}>
          <div className="card">
            <div className="card-hd" style={{ gap:12 }}>
              <div className="card-title">All Organisations</div>
              <div style={{ position:'relative', marginLeft:'auto' }}>
                <input value={searchOrg} onChange={e=>setSearchOrg(e.target.value)}
                  placeholder="Search orgs or email…"
                  style={{ background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:7, padding:'6px 10px 6px 28px', fontSize:12.5, outline:'none', width:220 }} />
                <span style={{ position:'absolute', left:8, top:'50%', transform:'translateY(-50%)', color:'var(--ink-4)', fontSize:12 }}>🔍</span>
              </div>
              <button className="btn sm primary" onClick={() => toast('New organisation form — invite the admin to get started')}>+ New org</button>
            </div>
            <div className="tbl-wrap">
              <table className="tbl">
                <thead>
                  <tr>
                    <th>Organisation</th>
                    <th>Plan</th>
                    <th>Status</th>
                    <th className="num-col">MRR</th>
                    <th className="num-col">Seats</th>
                    <th>Last Active</th>
                    <th>Region</th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  {filteredOrgs.map(org => (
                    <tr key={org.id} onClick={() => setSelectedOrg(selectedOrg?.id===org.id ? null : org)}
                      className={selectedOrg?.id===org.id ? 'selected' : ''}>
                      <td>
                        <div style={{ fontWeight:600, color:'var(--ink)', fontSize:13 }}>{org.name}</div>
                        <div style={{ fontSize:11, color:'var(--ink-3)' }}>{org.adminEmail}</div>
                      </td>
                      <td>
                        <SABadge label={org.plan.charAt(0).toUpperCase()+org.plan.slice(1)}
                          style={{ background:PLAN_COLORS[org.plan].bg, color:PLAN_COLORS[org.plan].color, border:`1px solid ${PLAN_COLORS[org.plan].border}` }} />
                      </td>
                      <td>
                        <SABadge label={org.status.replace('_',' ').replace(/\b\w/g,c=>c.toUpperCase())}
                          style={{ background:STATUS_COLORS[org.status].bg, color:STATUS_COLORS[org.status].color }} />
                      </td>
                      <td className="num-col" style={{ fontFamily:'var(--mono)', fontWeight:600, color: org.mrr>0?'var(--ink)':'var(--ink-4)' }}>
                        {org.mrr > 0 ? '$'+org.mrr+'/mo' : '—'}
                      </td>
                      <td className="num-col">
                        <span style={{ fontFamily:'var(--mono)', fontSize:12 }}>{org.seatsUsed}/{org.seats}</span>
                        <div style={{ height:3, background:'var(--border)', borderRadius:99, marginTop:4, width:48 }}>
                          <div style={{ width:(org.seatsUsed/org.seats*100)+'%', height:'100%', background: org.seatsUsed===org.seats?'var(--warn)':'var(--accent)', borderRadius:99 }} />
                        </div>
                      </td>
                      <td style={{ fontSize:12, color: org.lastActive==='Today'?'var(--won)':org.lastActive.includes('days')?'var(--warn)':'var(--ink-3)', fontWeight: org.lastActive==='Today'?600:400 }}>{org.lastActive}</td>
                      <td style={{ fontSize:12, color:'var(--ink-3)' }}>{org.region}</td>
                      <td>
                        <button className="btn sm" onClick={(e)=>{e.stopPropagation();setShowImpersonateConfirm(org);}}>
                          👁️ View
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          {/* Org detail panel */}
          {selectedOrg && (
            <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
              <div className="card card-pad" style={{ borderLeft:`3px solid ${SA_ACCENT}` }}>
                <div style={{ fontSize:15, fontWeight:700, color:'var(--ink)', marginBottom:4 }}>{selectedOrg.name}</div>
                <div style={{ fontSize:12, color:'var(--ink-3)', marginBottom:12 }}>{selectedOrg.adminEmail}</div>
                {[
                  { label:'Plan', value: selectedOrg.plan.charAt(0).toUpperCase()+selectedOrg.plan.slice(1) },
                  { label:'Status', value: selectedOrg.status },
                  { label:'MRR', value: selectedOrg.mrr > 0 ? '$'+selectedOrg.mrr+'/mo' : 'Trialing' },
                  { label:'Seats', value: selectedOrg.seatsUsed+' / '+selectedOrg.seats+' used' },
                  { label:'Region', value: selectedOrg.region },
                  { label:'Created', value: selectedOrg.createdAt },
                  { label:'Last Active', value: selectedOrg.lastActive },
                ].map(row => (
                  <div key={row.label} style={{ display:'flex', justifyContent:'space-between', padding:'6px 0', borderBottom:'1px solid var(--border)', fontSize:12.5 }}>
                    <span style={{ color:'var(--ink-3)' }}>{row.label}</span>
                    <span style={{ fontWeight:600, color:'var(--ink)' }}>{row.value}</span>
                  </div>
                ))}
              </div>
              <button className="btn primary" style={{ justifyContent:'center' }} onClick={() => setShowImpersonateConfirm(selectedOrg)}>
                👁️ Enter org as super admin
              </button>
              <button className="btn sm" style={{ justifyContent:'center', color:'var(--warn)' }} onClick={() => toast('Email drafted to ' + (selectedOrg && selectedOrg.adminEmail))}>
                ✉️ Email admin
              </button>
              <button className="btn sm" style={{ justifyContent:'center', color:'var(--lost)' }} onClick={() => { if (confirm('Suspend ' + (selectedOrg && selectedOrg.name) + '? All logins will be blocked.')) toast((selectedOrg && selectedOrg.name) + ' suspended'); }}>
                ⏸ Suspend org
              </button>
            </div>
          )}
        </div>
      )}

      {/* ── SUPPORT TOOLS ── */}
      {tab === 'support' && (
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16 }}>
          <div className="card">
            <div className="card-hd">
              <div>
                <div className="card-title">Impersonate User</div>
                <div className="card-sub">View any org exactly as their admin sees it — logged in audit trail</div>
              </div>
            </div>
            <div style={{ padding:'16px 20px', display:'flex', flexDirection:'column', gap:10 }}>
              <div>
                <label style={{ fontSize:11, fontWeight:600, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--ink-3)', display:'block', marginBottom:6 }}>Select Organisation</label>
                <select style={{ width:'100%', padding:'8px 12px', border:'1px solid var(--border)', borderRadius:6, fontSize:13, background:'var(--surface-2)' }}>
                  {MOCK_ORGS.filter(o=>o.status!=='cancelled').map(o => (
                    <option key={o.id} value={o.id}>{o.name} — {o.adminEmail}</option>
                  ))}
                </select>
              </div>
              <div>
                <label style={{ fontSize:11, fontWeight:600, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--ink-3)', display:'block', marginBottom:6 }}>Reason (required for audit log)</label>
                <input placeholder="e.g. Support ticket #4821 — user can't access reports"
                  style={{ width:'100%', padding:'8px 12px', border:'1px solid var(--border)', borderRadius:6, fontSize:13, background:'var(--surface-2)', outline:'none', boxSizing:'border-box' }} />
              </div>
              <div style={{ padding:'10px 12px', background:'var(--warn-soft)', borderRadius:6, fontSize:12, color:'var(--warn)', lineHeight:1.6 }}>
                ⚠️ Impersonation sessions are time-limited (30 min), read-only by default, and always recorded in the audit log.
              </div>
              <button className="btn primary" style={{ justifyContent:'center' }} onClick={() => toast('Enter the org name and reason to start an impersonation session')}>Enter org as super admin →</button>
            </div>
          </div>

          <div className="card">
            <div className="card-hd"><div className="card-title">Account Actions</div></div>
            <div style={{ padding:'16px 20px', display:'flex', flexDirection:'column', gap:8 }}>
              {[
                { icon:'🔑', label:'Reset admin password', sub:'Send password reset email to org admin', color:'var(--info)' },
                { icon:'📧', label:'Resend welcome email', sub:'Re-send onboarding instructions', color:'var(--accent)' },
                { icon:'🌱', label:'Seed demo data', sub:'Populate a new org with demo deals & contacts', color:'var(--won)' },
                { icon:'⬆️', label:'Upgrade plan', sub:'Move org to a higher plan immediately', color:SA_ACCENT },
                { icon:'⏸', label:'Suspend org', sub:'Block all logins — billing continues', color:'var(--warn)' },
                { icon:'🗑️', label:'Delete org', sub:'Permanently delete all org data — irreversible', color:'var(--lost)' },
              ].map(action => (
                <div key={action.label} onClick={() => { if (action.label === 'Delete org') { if (confirm('Permanently delete this org and all its data? This cannot be undone.')) toast(action.label + ' — done'); } else toast(action.label + ' — done'); }}
                  style={{ display:'flex', alignItems:'center', gap:12, padding:'10px 12px', background:'var(--surface-2)', borderRadius:8, cursor:'pointer', border:'1px solid var(--border)' }}
                  onMouseEnter={e=>e.currentTarget.style.background='var(--surface-3)'}
                  onMouseLeave={e=>e.currentTarget.style.background='var(--surface-2)'}>
                  <span style={{ fontSize:18, flexShrink:0 }}>{action.icon}</span>
                  <div style={{ flex:1 }}>
                    <div style={{ fontSize:13, fontWeight:600, color:action.color }}>{action.label}</div>
                    <div style={{ fontSize:11.5, color:'var(--ink-3)', marginTop:1 }}>{action.sub}</div>
                  </div>
                  <span style={{ color:'var(--ink-4)', fontSize:14 }}>›</span>
                </div>
              ))}
            </div>
          </div>

          <div className="card" style={{ gridColumn:'1/-1' }}>
            <div className="card-hd"><div className="card-title">Seed Demo Org</div><span style={{ fontSize:12, color:'var(--ink-3)' }}>For new sign-ups or sales demos</span></div>
            <div style={{ padding:'16px 20px', display:'flex', gap:16, alignItems:'flex-start' }}>
              <div style={{ flex:1, display:'flex', flexDirection:'column', gap:10 }}>
                <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10 }}>
                  <div>
                    <label style={{ fontSize:11, fontWeight:600, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--ink-3)', display:'block', marginBottom:5 }}>Org Name</label>
                    <input defaultValue="Demo Kitchen Co" style={{ width:'100%', padding:'8px 12px', border:'1px solid var(--border)', borderRadius:6, fontSize:13, background:'var(--surface-2)', outline:'none', boxSizing:'border-box' }} />
                  </div>
                  <div>
                    <label style={{ fontSize:11, fontWeight:600, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--ink-3)', display:'block', marginBottom:5 }}>Admin Email</label>
                    <input defaultValue="demo@example.com" style={{ width:'100%', padding:'8px 12px', border:'1px solid var(--border)', borderRadius:6, fontSize:13, background:'var(--surface-2)', outline:'none', boxSizing:'border-box' }} />
                  </div>
                </div>
                <button className="btn primary" style={{ width:'fit-content' }} onClick={() => toast('Creating demo org & seeding sample data…')}>🌱 Create & seed demo org</button>
              </div>
              <div style={{ padding:'12px 14px', background:'var(--won-soft)', border:'1px solid #A7F3D0', borderRadius:8, fontSize:12.5, color:'var(--accent-ink)', lineHeight:1.7, maxWidth:260 }}>
                Creates a new isolated org with:<br/>
                ✓ 4 showrooms · 450 deals<br/>
                ✓ 380 contacts · 8 staff<br/>
                ✓ Full demo data set<br/>
                ✓ Auto-invites the admin email
              </div>
            </div>
          </div>
        </div>
      )}

      {/* ── AUDIT LOG ── */}
      {tab === 'audit' && (
        <div className="card">
          <div className="card-hd">
            <div>
              <div className="card-title">Cross-Org Audit Log</div>
              <div className="card-sub">Immutable record of all privileged actions across every organisation</div>
            </div>
            <button className="btn sm" onClick={() => toast('Audit log exported to CSV')}>Export CSV</button>
          </div>
          <div>
            {MOCK_AUDIT.map((entry, i) => (
              <div key={i} style={{ display:'grid', gridTemplateColumns:'130px 180px 200px 120px 1fr', alignItems:'center', gap:12, padding:'12px 20px', borderBottom:'1px solid var(--border)' }}>
                <div style={{ fontSize:11, color:'var(--ink-4)', fontFamily:'var(--mono)' }}>{entry.ts}</div>
                <div style={{ fontSize:12.5, fontWeight:600, color:'var(--ink)' }}>{entry.org}</div>
                <div style={{ fontSize:11.5, color:'var(--ink-3)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{entry.user}</div>
                <div style={{ display:'flex', alignItems:'center', gap:5 }}>
                  <span style={{ fontSize:14 }}>{ACTION_ICONS[entry.action] || '📋'}</span>
                  <span style={{ fontSize:11, fontWeight:600, color: entry.action==='login_failed'||entry.action==='payment_failed'?'var(--lost)':entry.action==='impersonated'?SA_ACCENT:'var(--ink-3)', textTransform:'uppercase', letterSpacing:'0.05em' }}>
                    {entry.action.replace(/_/g,' ')}
                  </span>
                </div>
                <div style={{ fontSize:12.5, color:'var(--ink-2)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{entry.detail}</div>
              </div>
            ))}
          </div>
          <div style={{ padding:'12px 20px', background:'var(--surface-2)', borderTop:'1px solid var(--border)', fontSize:12, color:'var(--ink-4)', display:'flex', alignItems:'center', gap:8 }}>
            🔒 Audit log rows are immutable — no edits or deletes are possible, enforced by database trigger.
          </div>
        </div>
      )}

      {/* ── PLATFORM HEALTH ── */}
      {tab === 'health' && (
        <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
          <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14 }}>
            {[
              { label:'API Uptime (30d)', value:'99.98%', sub:'Last incident: 42 days ago', color:'var(--won)' },
              { label:'Avg API Response', value:'124ms', sub:'p95: 380ms', color:'var(--accent)' },
              { label:'DB Storage Used', value:'2.4 GB', sub:'of 8 GB (free plan)', color:'var(--warn)' },
              { label:'Auth Requests (24h)', value:'1,284', sub:'0 failures', color:SA_ACCENT },
            ].map(k => (
              <div key={k.label} className="kpi">
                <div className="kpi-label">{k.label}</div>
                <div className="kpi-value" style={{ fontSize:26, color:k.color }}>{k.value}</div>
                <div className="kpi-meta"><span className="kpi-foot">{k.sub}</span></div>
              </div>
            ))}
          </div>

          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:16 }}>
            <div className="card">
              <div className="card-hd"><div className="card-title">MRR Growth</div><span style={{ fontSize:12, color:'var(--ink-3)' }}>Last 6 months</span></div>
              <div style={{ padding:'18px 20px' }}>
                {[['Jan','$890'],['Feb','$1,180'],['Mar','$1,490'],['Apr','$1,790'],['May','$2,080'],['Jun','$2,279']].map(([m,v],i) => (
                  <div key={m} style={{ display:'grid', gridTemplateColumns:'40px 1fr 64px', alignItems:'center', gap:10, marginBottom:8 }}>
                    <span style={{ fontSize:12, color:'var(--ink-3)', fontWeight:500 }}>{m}</span>
                    <div style={{ height:7, background:'var(--border)', borderRadius:99, overflow:'hidden' }}>
                      <div style={{ width:[44,59,74,89,100,100][i]+'%', height:'100%', background:`linear-gradient(90deg, ${SA_ACCENT}, #818CF8)`, borderRadius:99 }} />
                    </div>
                    <span style={{ fontSize:12, fontFamily:'var(--mono)', fontWeight:700, color:SA_ACCENT, textAlign:'right' }}>{v}</span>
                  </div>
                ))}
              </div>
            </div>

            <div className="card">
              <div className="card-hd"><div className="card-title">Plan Distribution</div></div>
              <div style={{ padding:'18px 20px', display:'flex', flexDirection:'column', gap:12 }}>
                {[
                  { plan:'Enterprise', count:1, pct:17, color:'#F59E0B' },
                  { plan:'Growth', count:3, pct:50, color:SA_ACCENT },
                  { plan:'Starter', count:2, pct:33, color:'var(--ink-3)' },
                ].map(p => (
                  <div key={p.plan}>
                    <div style={{ display:'flex', justifyContent:'space-between', marginBottom:4 }}>
                      <span style={{ fontSize:13, fontWeight:500, color:'var(--ink)' }}>{p.plan}</span>
                      <span style={{ fontSize:12, color:'var(--ink-3)', fontFamily:'var(--mono)' }}>{p.count} org{p.count!==1?'s':''} · {p.pct}%</span>
                    </div>
                    <div style={{ height:8, background:'var(--border)', borderRadius:99 }}>
                      <div style={{ width:p.pct+'%', height:'100%', background:p.color, borderRadius:99 }} />
                    </div>
                  </div>
                ))}
                <div style={{ marginTop:8, padding:'10px 12px', background:SA_SOFT, borderRadius:6, fontSize:12.5, color:SA_ACCENT, lineHeight:1.6 }}>
                  <strong>Upsell opportunity:</strong> 2 Starter orgs have used 80%+ of their seats — ready to upgrade to Growth.
                </div>
              </div>
            </div>

            <div className="card" style={{ gridColumn:'1/-1' }}>
              <div className="card-hd"><div className="card-title">Security Overview</div></div>
              <div style={{ padding:'16px 20px', display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:12 }}>
                {[
                  { icon:'🔐', label:'RLS Active', value:'All 20 tables', status:'ok' },
                  { icon:'🔑', label:'MFA Enrolled', value:'4 of 52 users', status:'warn' },
                  { icon:'🚨', label:'Failed Logins (24h)', value:'3 attempts', status:'warn' },
                  { icon:'📋', label:'Audit Coverage', value:'100% of actions', status:'ok' },
                ].map(item => (
                  <div key={item.label} style={{ padding:'14px 16px', background: item.status==='ok'?'var(--won-soft)':'var(--warn-soft)', borderRadius:8, border:`1px solid ${item.status==='ok'?'#A7F3D0':'#FDE68A'}` }}>
                    <div style={{ fontSize:22, marginBottom:6 }}>{item.icon}</div>
                    <div style={{ fontSize:12, fontWeight:700, color: item.status==='ok'?'var(--won)':'var(--warn)', marginBottom:3 }}>{item.label}</div>
                    <div style={{ fontSize:13, fontWeight:600, color:'var(--ink)' }}>{item.value}</div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Impersonate confirm modal */}
      {showImpersonateConfirm && (
        <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.5)', zIndex:200, display:'flex', alignItems:'center', justifyContent:'center' }}>
          <div style={{ background:'var(--surface)', borderRadius:'var(--r-xl)', padding:28, width:420, boxShadow:'var(--shadow-lg)' }}>
            <div style={{ fontSize:18, fontWeight:700, color:'var(--ink)', marginBottom:6 }}>Enter org as Super Admin</div>
            <div style={{ fontSize:13, color:'var(--ink-3)', marginBottom:16, lineHeight:1.6 }}>
              You are about to view <strong>{showImpersonateConfirm.name}</strong> as their admin. This session will be recorded in the audit log.
            </div>
            <div style={{ marginBottom:14 }}>
              <label style={{ fontSize:11, fontWeight:600, textTransform:'uppercase', letterSpacing:'0.06em', color:'var(--ink-3)', display:'block', marginBottom:6 }}>Reason (required)</label>
              <input placeholder="e.g. Support ticket #1234" style={{ width:'100%', padding:'9px 12px', border:'1px solid var(--border)', borderRadius:7, fontSize:13, outline:'none', boxSizing:'border-box' }} />
            </div>
            <div style={{ display:'flex', gap:8, justifyContent:'flex-end' }}>
              <button className="btn sm" onClick={() => setShowImpersonateConfirm(null)}>Cancel</button>
              <button className="btn sm primary" onClick={() => { setImpersonating(showImpersonateConfirm); setShowImpersonateConfirm(null); }}>
                👁️ Enter org
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Impersonation active banner */}
      {impersonating && (
        <div style={{ position:'fixed', bottom:20, left:'50%', transform:'translateX(-50%)', background:SA_COLOR, color:'white', borderRadius:99, padding:'10px 20px', display:'flex', alignItems:'center', gap:12, boxShadow:'var(--shadow-lg)', zIndex:150, fontSize:13 }}>
          <span style={{ fontSize:16 }}>👁️</span>
          <span>Viewing <strong>{impersonating.name}</strong> as Super Admin</span>
          <button onClick={() => setImpersonating(null)} style={{ background:'rgba(255,255,255,0.15)', border:'none', color:'white', borderRadius:99, padding:'4px 12px', fontSize:12, fontWeight:600, cursor:'pointer', marginLeft:8 }}>
            Exit ×
          </button>
        </div>
      )}
    </div>
  );
}

window.SuperAdmin = SuperAdmin;
