/* ADMIN · Início — overview cockpit privilegiado.
   Estrutura intencional:
   1) Hero — saudação + 2 alertas de urgência (não escondemos problemas)
   2) Triage rail — 4-6 acções pendentes pessoais (decisões só para admin)
   3) State-of-org — 4 KPIs grandes (utilizadores, empresas, integrações, audit)
   4) Health card — sistema, AD drift, integrações com erro
   5) Activity 7d — chart + drill-downs
   "Inbox-zero" para o Fábio: o que precisa da minha atenção HOJE? */

const AdminOverview = ({ user, onNavigate }) => {
  const data = window.AdminUsersData;
  const total = data?.HEADER_KPIS?.total || 193;
  const portalActivo = data?.HEADER_KPIS?.portalActivo || 0;
  const apolloEnriched = data?.HEADER_KPIS?.apolloEnriched || 0;

  // Triage — acções pendentes que só ADMIN pode decidir
  const triageItems = [
    { id: 't1', sev: 'high',  icon: 'lock',     title: '3 utilizadores em drift com Active Directory',
      desc: 'Mário Pinto, Susana Cruz e Ricardo Borges saíram do AD mas continuam activos no portal. Decidir: arquivar, manter ou reactivar.',
      cta: 'Resolver drift', target: 'utilizadores', meta: 'Drift há 2 dias' },
    { id: 't2', sev: 'high',  icon: 'key',      title: 'API key Apollo expira em 7 dias',
      desc: 'Renovar manualmente no dashboard Apollo ou activar auto-rotation. 2.341 lookups/mês dependem desta key.',
      cta: 'Renovar agora', target: 'integracoes', meta: 'Expira 02 Out' },
    { id: 't3', sev: 'med',   icon: 'user',     title: '2 pedidos de elevação de permissões',
      desc: 'Joana Lopes (Marketing) pede acesso a Comercial · Carteira. Tiago Silva pede acesso ao módulo Financeiro.',
      cta: 'Rever pedidos', target: 'utilizadores', meta: 'Aguarda há 4h' },
    { id: 't4', sev: 'med',   icon: 'settings', title: 'Feature flag voice_widget em 47% scope',
      desc: 'Rollout parcial activo desde 18 Set. Métricas: 0 erros, 12 sessões/dia. Promover para 100% ou manter staging?',
      cta: 'Ver métricas', target: 'integracoes', meta: 'Decisão até 30 Set' },
    { id: 't5', sev: 'low',   icon: 'alert',    title: '1 login fora de horário (Marta Leal · 03:14)',
      desc: 'Marta Leal autenticou-se às 03:14 UTC do IP 89.114.x.x. Geo: Lisboa. Provavelmente legítimo, mas verifica.',
      cta: 'Ver no audit', target: 'audit', meta: 'há 7h' },
  ];

  const stateKpis = [
    { id: 'k1', label: 'Utilizadores', value: total, sub: `${portalActivo} no portal · ${total - portalActivo} só email`, target: 'utilizadores', tone: 'neutral' },
    { id: 'k2', label: 'Empresas',     value: 6,     sub: '4 marcas comerciais · PT+ES', target: 'empresas', tone: 'neutral' },
    { id: 'k3', label: 'Integrações',  value: '8/9', sub: '1 com erro: Cognism', target: 'integracoes', tone: 'warn' },
    { id: 'k4', label: 'Eventos audit · 24h', value: 47, sub: '3 alertas · 0 críticos', target: 'audit', tone: 'good' },
  ];

  const SevBadge = ({ sev }) => {
    const map = {
      high: { bg: 'oklch(0.95 0.07 30)',  fg: 'oklch(0.5 0.2 30)',   label: 'URGENTE' },
      med:  { bg: 'oklch(0.96 0.05 70)',  fg: 'oklch(0.45 0.18 70)', label: 'A REVER' },
      low:  { bg: 'oklch(0.96 0.02 250)', fg: 'oklch(0.5 0.04 250)', label: 'INFO' },
    };
    const s = map[sev] || map.low;
    return (
      <span style={{
        padding: '2px 7px', fontSize: 9.5, fontWeight: 700, letterSpacing: '0.06em',
        borderRadius: 3, background: s.bg, color: s.fg, fontFamily: 'var(--font-mono)',
      }}>{s.label}</span>
    );
  };

  const KpiTone = (tone) => ({
    neutral: { bar: 'var(--text-dim)' },
    good:    { bar: 'oklch(0.65 0.18 145)' },
    warn:    { bar: 'oklch(0.7 0.18 70)' },
    bad:     { bar: 'oklch(0.55 0.2 30)' },
  }[tone] || { bar: 'var(--text-dim)' });

  const goto = (target) => { if (target && onNavigate) onNavigate(target); };

  // 7d activity — sparkline de eventos audit por dia
  const activity7d = [12, 28, 19, 41, 33, 24, 47];
  const maxAct = Math.max(...activity7d);
  const days = ['Qui', 'Sex', 'Sáb', 'Dom', 'Seg', 'Ter', 'Hoje'];

  return (
    <div style={{ flex: 1, overflow: 'auto', background: 'var(--bg)' }}>
      <div style={{ maxWidth: 1280, margin: '0 auto', padding: '28px 32px 80px' }}>

        {/* Hero ─────────────────────────────────────────── */}
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 24, marginBottom: 22 }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em' }}>
              ADMIN · INÍCIO · {new Date().toLocaleDateString('pt-PT', { weekday: 'long', day: '2-digit', month: 'long' }).toUpperCase()}
            </div>
            <h1 className="font-display" style={{
              margin: '4px 0 6px', fontSize: 30, fontWeight: 600, letterSpacing: '-0.015em',
            }}>
              Bom dia, {user?.nome?.split(' ')[0] || 'Fábio'}.
            </h1>
            <p style={{ margin: 0, fontSize: 14, color: 'var(--text-muted)', lineHeight: 1.5, maxWidth: 720 }}>
              Console privilegiado · 5 acções pedem-te decisão hoje. Tudo o resto está estável.
            </p>
          </div>
          <div style={{
            padding: '8px 14px', borderRadius: 8, fontSize: 11,
            background: 'oklch(0.96 0.02 30)', color: 'oklch(0.45 0.18 30)',
            fontWeight: 600, fontFamily: 'var(--font-mono)', letterSpacing: '0.04em',
            border: '1px solid oklch(0.85 0.08 30)',
            display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0,
          }}>
            <Icon name="lock" size={11} />MODO ADMIN
          </div>
        </div>

        {/* State-of-org KPIs ─────────────────────────────── */}
        <div style={{
          display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12,
          marginBottom: 28,
        }}>
          {stateKpis.map(k => (
            <button key={k.id} onClick={() => goto(k.target)} style={{
              textAlign: 'left', padding: 16, borderRadius: 10,
              border: '1px solid var(--border)', background: 'var(--bg-elev)',
              cursor: 'pointer', position: 'relative', overflow: 'hidden',
              transition: 'border-color 0.15s, background 0.15s',
            }}
            onMouseEnter={e => e.currentTarget.style.borderColor = 'var(--text-muted)'}
            onMouseLeave={e => e.currentTarget.style.borderColor = 'var(--border)'}
            >
              <span style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 3, background: KpiTone(k.tone).bar }} />
              <div style={{ fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.06em', marginBottom: 6 }}>
                {k.label.toUpperCase()}
              </div>
              <div className="font-display" style={{ fontSize: 28, fontWeight: 600, letterSpacing: '-0.01em', lineHeight: 1 }}>
                {k.value}
              </div>
              <div style={{ marginTop: 6, fontSize: 11.5, color: 'var(--text-muted)', lineHeight: 1.4 }}>
                {k.sub}
              </div>
            </button>
          ))}
        </div>

        {/* Triage rail — duas colunas: lista + activity ─── */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 340px', gap: 18 }}>
          <section>
            <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 10 }}>
              <h2 className="font-display" style={{ margin: 0, fontSize: 16, fontWeight: 600 }}>Pede a tua decisão</h2>
              <span style={{ fontSize: 11, color: 'var(--text-dim)' }}>{triageItems.length} pendentes</span>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {triageItems.map(it => (
                <div key={it.id} style={{
                  padding: 14, borderRadius: 9,
                  border: '1px solid var(--border)', background: 'var(--bg-elev)',
                  display: 'grid', gridTemplateColumns: '32px 1fr auto', gap: 12,
                  alignItems: 'flex-start',
                }}>
                  <div style={{
                    width: 32, height: 32, borderRadius: 7,
                    background: it.sev === 'high' ? 'oklch(0.95 0.07 30)' : it.sev === 'med' ? 'oklch(0.96 0.05 70)' : 'var(--surface-muted)',
                    color: it.sev === 'high' ? 'oklch(0.5 0.2 30)' : it.sev === 'med' ? 'oklch(0.45 0.18 70)' : 'var(--text-muted)',
                    display: 'grid', placeItems: 'center', flexShrink: 0,
                  }}>
                    <Icon name={it.icon} size={15} />
                  </div>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 3 }}>
                      <SevBadge sev={it.sev} />
                      <span style={{ fontSize: 10.5, color: 'var(--text-dim)' }}>{it.meta}</span>
                    </div>
                    <div style={{ fontSize: 13.5, fontWeight: 600, lineHeight: 1.35, marginBottom: 3 }}>{it.title}</div>
                    <div style={{ fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.5 }}>{it.desc}</div>
                  </div>
                  <button onClick={() => goto(it.target)} style={{
                    padding: '6px 12px', borderRadius: 6, fontSize: 12, fontWeight: 500,
                    background: 'var(--text)', color: 'var(--bg)', border: 'none', cursor: 'pointer',
                    flexShrink: 0, alignSelf: 'flex-start',
                  }}>{it.cta}</button>
                </div>
              ))}
            </div>
          </section>

          <aside style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            {/* Health */}
            <div style={{ padding: 14, borderRadius: 10, border: '1px solid var(--border)', background: 'var(--bg-elev)' }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
                <h3 className="font-display" style={{ margin: 0, fontSize: 13, fontWeight: 600 }}>Saúde do sistema</h3>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 10.5, color: 'oklch(0.5 0.18 145)', fontWeight: 600 }}>
                  <span style={{ width: 7, height: 7, borderRadius: 7, background: 'oklch(0.65 0.18 145)' }} />OPERACIONAL
                </span>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6, fontSize: 11.5 }}>
                {[
                  { k: 'Identity (M365 SCIM)', v: 'OK · há 12 min', tone: 'good' },
                  { k: 'ERP (SAP B1)',         v: 'OK · há 28 min', tone: 'good' },
                  { k: 'AD ↔ Portal drift',    v: '3 users em drift', tone: 'warn' },
                  { k: 'Apollo credits',       v: '2.1k restantes', tone: 'good' },
                  { k: 'Backups (24h)',        v: '✓ ontem 02:00', tone: 'good' },
                  { k: 'Cognism',              v: 'desligado', tone: 'bad' },
                ].map(r => (
                  <div key={r.k} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8 }}>
                    <span style={{ color: 'var(--text-muted)' }}>{r.k}</span>
                    <span style={{
                      fontWeight: 500, fontSize: 11,
                      color: r.tone === 'good' ? 'var(--text)' : r.tone === 'warn' ? 'oklch(0.5 0.18 70)' : 'oklch(0.5 0.2 30)',
                    }}>{r.v}</span>
                  </div>
                ))}
              </div>
            </div>

            {/* Activity 7d */}
            <div style={{ padding: 14, borderRadius: 10, border: '1px solid var(--border)', background: 'var(--bg-elev)' }}>
              <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 12 }}>
                <h3 className="font-display" style={{ margin: 0, fontSize: 13, fontWeight: 600 }}>Eventos · 7 dias</h3>
                <button onClick={() => goto('audit')} style={{ background: 'transparent', border: 'none', color: 'var(--text-muted)', fontSize: 11, cursor: 'pointer' }}>Audit completo →</button>
              </div>
              <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6, height: 80 }}>
                {activity7d.map((v, i) => (
                  <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
                    <div style={{
                      width: '100%', height: `${(v / maxAct) * 64}px`,
                      background: i === activity7d.length - 1 ? 'oklch(0.55 0.2 30)' : 'oklch(0.85 0.04 250)',
                      borderRadius: 3,
                    }} />
                    <span style={{ fontSize: 9.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>{days[i]}</span>
                  </div>
                ))}
              </div>
              <div style={{ marginTop: 10, paddingTop: 10, borderTop: '1px solid var(--border)', fontSize: 11, color: 'var(--text-muted)' }}>
                <strong style={{ color: 'var(--text)' }}>47 hoje</strong> · pico em segunda (33), média 29/dia
              </div>
            </div>

            {/* Quick actions */}
            <div style={{ padding: 14, borderRadius: 10, border: '1px solid var(--border)', background: 'var(--bg-elev)' }}>
              <h3 className="font-display" style={{ margin: 0, fontSize: 13, fontWeight: 600, marginBottom: 8 }}>Acções rápidas</h3>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {[
                  { label: 'Convidar utilizador',    icon: 'user-plus',    target: 'utilizadores' },
                  { label: 'Rotacionar API key',     icon: 'key',          target: 'integracoes' },
                  { label: 'Forçar sync AD',         icon: 'refresh',      target: 'utilizadores' },
                  { label: 'Exportar audit (CSV)',   icon: 'download',     target: 'audit' },
                ].map(a => (
                  <button key={a.label} onClick={() => goto(a.target)} style={{
                    display: 'flex', alignItems: 'center', gap: 9,
                    padding: '7px 9px', borderRadius: 6, fontSize: 12,
                    background: 'transparent', border: '1px solid var(--border)',
                    color: 'var(--text)', cursor: 'pointer', textAlign: 'left',
                  }}>
                    <Icon name={a.icon} size={13} />{a.label}
                  </button>
                ))}
              </div>
            </div>
          </aside>
        </div>

      </div>
    </div>
  );
};

window.AdminOverview = AdminOverview;
