// Painel administrativo — visível apenas para usuários com role='admin'.

const PLAN_COLORS = {
  trial: '#5EE3A8',
  mensal: '#6FB8FF',
  semestral: '#FFB547',
  anual: '#B197FC',
  essencial: '#6FB8FF',
  premium: '#FFB547',
};

function formatDate(iso) {
  if (!iso) return '—';
  try {
    const d = new Date(iso);
    return d.toLocaleDateString('pt-BR', { day: '2-digit', month: 'short' });
  } catch (e) { return '—'; }
}
function daysAgo(iso) {
  if (!iso) return null;
  const ms = new Date() - new Date(iso);
  return Math.max(0, Math.floor(ms / (1000 * 60 * 60 * 24)));
}

const AdminScreen = ({ navigate, showToast }) => {
  const [profiles, setProfiles] = React.useState([]);
  const [metrics, setMetrics] = React.useState(null);
  const [revenue, setRevenue] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [filter, setFilter] = React.useState('todos');
  const [sortBy, setSortBy] = React.useState('recent'); // 'recent' | 'oldest' | 'name'
  const [search, setSearch] = React.useState('');
  const [selected, setSelected] = React.useState(null);
  const [aiUsage, setAiUsage] = React.useState(null);

  const refresh = async () => {
    if (!window.AdminAPI) return;
    setLoading(true);
    const [list, mtr, ai] = await Promise.all([
      window.AdminAPI.listAllProfiles(),
      window.AdminAPI.getUsageMetrics(),
      window.SofiaAPI ? window.SofiaAPI.getCurrentMonthCost() : Promise.resolve(null),
    ]);
    setProfiles(list);
    setMetrics(mtr);
    setRevenue(window.AdminAPI.getRevenueMetrics(list));
    setAiUsage(ai);
    setLoading(false);
  };

  React.useEffect(() => { refresh(); }, []);

  const handleExport = () => {
    if (!window.AdminAPI) return;
    const ok = window.AdminAPI.exportProfilesCSV(filtered);
    showToast(ok ? `${filtered.length} assinante(s) exportados` : 'Erro ao exportar');
  };

  // MRR por plano (em R$/mês)
  const PLAN_MRR = {
    mensal: 29.90,
    semestral: 149.40 / 6,    // 24.90
    anual: 238.80 / 12,       // 19.90
    // legado
    essencial: 29.90,
    premium: 59.90,
    trial: 0,
  };
  const PAYING_PLANS = ['mensal', 'semestral', 'anual', 'essencial', 'premium'];

  const filtered = profiles
    .filter(p => {
      if (filter === 'pagantes' && !PAYING_PLANS.includes(p.plan)) return false;
      if (filter === 'trial' && p.plan !== 'trial') return false;
      if (filter === 'inativos' && p.is_active) return false;
      if (filter === 'mensal' && p.plan !== 'mensal') return false;
      if (filter === 'semestral' && p.plan !== 'semestral') return false;
      if (filter === 'anual' && p.plan !== 'anual') return false;
      if (search && !(p.email || '').toLowerCase().includes(search.toLowerCase()) && !(p.name || '').toLowerCase().includes(search.toLowerCase())) return false;
      return true;
    })
    .sort((a, b) => {
      if (sortBy === 'recent') return new Date(b.created_at || 0) - new Date(a.created_at || 0);
      if (sortBy === 'oldest') return new Date(a.created_at || 0) - new Date(b.created_at || 0);
      if (sortBy === 'name') return (a.name || a.email || '').localeCompare(b.name || b.email || '');
      return 0;
    });

  const recent = (window.AdminAPI && window.AdminAPI.getRecentSignups) ? window.AdminAPI.getRecentSignups(profiles, 5) : [];

  const totalUsers = profiles.length;
  const totalAdmins = profiles.filter(p => p.role === 'admin').length;
  const totalInactive = profiles.filter(p => !p.is_active).length;
  const totalTrial = profiles.filter(p => p.plan === 'trial').length;
  const totalPayers = profiles.filter(p => PAYING_PLANS.includes(p.plan)).length;
  const totalMensal = profiles.filter(p => p.plan === 'mensal').length;
  const totalSemestral = profiles.filter(p => p.plan === 'semestral').length;
  const totalAnual = profiles.filter(p => p.plan === 'anual').length;
  const mrr = profiles
    .filter(p => p.is_active)
    .reduce((sum, p) => sum + (PLAN_MRR[p.plan] || 0), 0);

  const updatePlan = async (userId, plan) => {
    const res = await window.AdminAPI.setUserPlan(userId, plan);
    if (res.ok) { showToast('Plano atualizado'); refresh(); setSelected(null); }
    else showToast('Erro ao atualizar plano');
  };
  const toggleActive = async (userId, isActive) => {
    const res = await window.AdminAPI.setUserActive(userId, !isActive);
    if (res.ok) { showToast(isActive ? 'Conta suspensa' : 'Conta reativada'); refresh(); setSelected(null); }
    else showToast('Erro ao alterar status');
  };
  const toggleRole = async (userId, role) => {
    const next = role === 'admin' ? 'user' : 'admin';
    if (window.confirm && !window.confirm(next === 'admin' ? 'Promover este usuário a ADMIN?' : 'Remover privilégios de admin deste usuário?')) return;
    const res = await window.AdminAPI.setUserRole(userId, next);
    if (res.ok) { showToast(next === 'admin' ? 'Promovido a admin' : 'Privilégios removidos'); refresh(); setSelected(null); }
    else showToast('Erro ao alterar role');
  };

  return (
    <div style={{ paddingBottom: 110 }}>
      <Header title="Painel Admin" subtitle="GESTÃO DA PLATAFORMA" onBack={() => navigate('more')} right={
        <div style={{ display: 'flex', gap: 6 }}>
          <button onClick={handleExport} title="Exportar CSV" style={{
            background: CDV.surfaceHi, border: `1px solid ${CDV.stroke}`, width: 38, height: 38, borderRadius: 99,
            color: CDV.textDim, display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: 'pointer',
          }}><Icon name="pdf" size={16} /></button>
          <button onClick={refresh} title="Recarregar" style={{
            background: CDV.surfaceHi, border: `1px solid ${CDV.stroke}`, width: 38, height: 38, borderRadius: 99,
            color: CDV.textDim, display: 'flex', alignItems: 'center', justifyContent: 'center',
            cursor: 'pointer',
          }}><Icon name="refresh" size={16} /></button>
        </div>
      } />

      {/* Cards de métricas principais */}
      <div style={{ padding: '0 22px 16px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        <MetricCard label="Usuários" big={totalUsers} extra={`${totalAdmins} admin${totalAdmins === 1 ? '' : 's'}`} icon="user" color={CDV.brand} />
        <MetricCard label="MRR estimado" big={`R$ ${mrr.toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`} extra="Recorrência mensal" icon="wallet" color={CDV.mint} />
        <MetricCard label="Pagantes" big={totalPayers} extra={`${totalMensal}M · ${totalSemestral}S · ${totalAnual}A`} icon="diamond" color={CDV.amber} />
        <MetricCard label="Em trial" big={totalTrial} extra="3 dias grátis" icon="sparkle" color={CDV.sky} />
        {revenue && (
          <>
            <MetricCard
              label="LTV total"
              big={`R$ ${revenue.ltvTotal.toLocaleString('pt-BR', { minimumFractionDigits: 0, maximumFractionDigits: 0 })}`}
              extra="Receita projetada 12 meses"
              icon="trophy" color={CDV.brand}
            />
            <MetricCard
              label="Conversão T→P"
              big={`${revenue.conversion.toFixed(1)}%`}
              extra={`${revenue.paying} pagam · ${revenue.trial} testando`}
              icon="insight" color={CDV.coral}
            />
          </>
        )}
      </div>

      {/* Sofia IA — gasto do mês */}
      <div style={{ padding: '0 22px 16px' }}>
        <div style={{
          padding: 14, borderRadius: 16,
          background: `linear-gradient(135deg, ${CDV.brand}14, ${CDV.surface} 70%)`,
          border: `1px solid ${CDV.brand}26`,
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <div style={{
            width: 40, height: 40, borderRadius: 12, background: CDV.brandGrad,
            display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff',
            boxShadow: '0 6px 16px -8px rgba(124,92,255,0.6)', flexShrink: 0,
          }}><Icon name="sparkle" size={20} /></div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 11, color: CDV.brand, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase' }}>Sofia IA · Mês</div>
            <div style={{ fontSize: 19, fontWeight: 800, color: CDV.text, marginTop: 2 }}>
              {aiUsage ? `R$ ${(aiUsage.cost * 5.5).toFixed(2)}` : '—'}
            </div>
            <div style={{ fontSize: 10, color: CDV.textDim, marginTop: 2 }}>
              {aiUsage
                ? `${aiUsage.calls} chamadas · ${aiUsage.users} usuário${aiUsage.users === 1 ? '' : 's'}`
                : 'Sem chave OpenAI configurada'}
            </div>
          </div>
        </div>
      </div>

      {/* Atividade recente */}
      {recent.length > 0 && (
        <div style={{ padding: '0 22px 16px' }}>
          <div style={{
            padding: 14, borderRadius: 16,
            background: `linear-gradient(135deg, ${CDV.brand}10 0%, ${CDV.surface} 60%)`,
            border: `1px solid ${CDV.brand}20`,
          }}>
            <div style={{ fontSize: 11, color: CDV.brand, fontWeight: 700, letterSpacing: 0.5, textTransform: 'uppercase', marginBottom: 10 }}>
              Atividade recente
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {recent.map(p => (
                <div key={p.user_id} onClick={() => setSelected(p)} style={{
                  display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer',
                  padding: '6px 0', borderBottom: `1px solid ${CDV.divider}`,
                }}>
                  <div style={{
                    width: 28, height: 28, borderRadius: 99,
                    background: `linear-gradient(135deg, ${PLAN_COLORS[p.plan] || CDV.brand}, ${PLAN_COLORS[p.plan] || CDV.brand}aa)`,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    color: '#fff', fontSize: 12, fontWeight: 700, flexShrink: 0,
                  }}>{((p.name || p.email || '?').charAt(0).toUpperCase())}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12, color: CDV.text, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      {p.email}
                    </div>
                    <div style={{ fontSize: 10, color: CDV.textDim, marginTop: 1 }}>
                      {p.plan} · entrou em {formatDate(p.created_at)}
                    </div>
                  </div>
                  <Pill color={PLAN_COLORS[p.plan] || CDV.textDim} size="sm">{p.plan}</Pill>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* Métricas de uso */}
      {metrics && (
        <div style={{ padding: '0 22px 18px' }}>
          <div style={{
            padding: 14, borderRadius: 16,
            background: 'linear-gradient(135deg, rgba(177,151,252,0.10), rgba(94,227,168,0.06))',
            border: `1px solid ${CDV.stroke}`,
          }}>
            <div style={{ fontSize: 11, color: CDV.brand, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase', marginBottom: 8 }}>Engajamento agregado</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10 }}>
              <MiniMetric value={metrics.totalUserStates} label="Ativos" />
              <MiniMetric value={metrics.totalTasks} label="Tarefas" />
              <MiniMetric value={metrics.totalHabits} label="Hábitos" />
              <MiniMetric value={metrics.totalGoals} label="Metas" />
            </div>
          </div>
          {totalInactive > 0 && (
            <div style={{
              marginTop: 10, padding: 10, borderRadius: 12,
              background: CDV.coral + '14', border: `1px solid ${CDV.coral}30`,
              fontSize: 12, color: CDV.coral, fontWeight: 500,
            }}>
              ⚠ {totalInactive} conta{totalInactive === 1 ? '' : 's'} suspensa{totalInactive === 1 ? '' : 's'}
            </div>
          )}
        </div>
      )}

      {/* Busca */}
      <div style={{ padding: '0 22px 12px' }}>
        <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Buscar por email ou nome..."
          style={{
            width: '100%', height: 44, borderRadius: 12, border: `1px solid ${CDV.stroke}`,
            background: CDV.surface, color: CDV.text, padding: '0 14px', fontSize: 13,
            outline: 'none', fontFamily: 'inherit',
          }} />
      </div>

      {/* Ordenação */}
      <div style={{ padding: '0 22px 8px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
        <div style={{ fontSize: 11, color: CDV.textDim, fontWeight: 600, letterSpacing: 0.3 }}>Ordenar por</div>
        <div style={{ display: 'flex', gap: 4, background: CDV.surface, border: `1px solid ${CDV.stroke}`, borderRadius: 8, padding: 2 }}>
          {[
            { id: 'recent', label: 'Recentes' },
            { id: 'oldest', label: 'Antigos' },
            { id: 'name', label: 'Nome' },
          ].map(s => (
            <button key={s.id} onClick={() => setSortBy(s.id)} style={{
              height: 26, padding: '0 10px', borderRadius: 6,
              background: sortBy === s.id ? CDV.surfaceHi2 : 'transparent',
              color: sortBy === s.id ? CDV.text : CDV.textDim,
              border: 'none', fontSize: 11, fontWeight: 600, fontFamily: 'inherit', cursor: 'pointer',
            }}>{s.label}</button>
          ))}
        </div>
      </div>

      {/* Filtros */}
      <div style={{ padding: '0 22px 14px', display: 'flex', gap: 6, overflowX: 'auto' }}>
        {[
          { id: 'todos', label: `Todos · ${totalUsers}` },
          { id: 'pagantes', label: `Pagantes · ${totalPayers}` },
          { id: 'mensal', label: `Mensal · ${totalMensal}` },
          { id: 'semestral', label: `Semestral · ${totalSemestral}` },
          { id: 'anual', label: `Anual · ${totalAnual}` },
          { id: 'trial', label: `Trial · ${totalTrial}` },
          { id: 'inativos', label: `Suspensos · ${totalInactive}` },
        ].map(f => (
          <button key={f.id} onClick={() => setFilter(f.id)} style={{
            flex: '0 0 auto', height: 32, padding: '0 12px', borderRadius: 99,
            background: filter === f.id ? CDV.text : CDV.surface,
            color: filter === f.id ? '#000' : CDV.textDim,
            border: `1px solid ${filter === f.id ? 'transparent' : CDV.stroke}`,
            fontSize: 12, fontWeight: 600, fontFamily: 'inherit',
          }}>{f.label}</button>
        ))}
      </div>

      {/* Lista */}
      {loading ? (
        <div style={{ padding: 30, textAlign: 'center', color: CDV.textDim, fontSize: 13 }}>Carregando...</div>
      ) : filtered.length === 0 ? (
        <div style={{ padding: '0 22px' }}>
          <div style={{ padding: 30, borderRadius: 16, background: CDV.surface, border: `1px dashed ${CDV.stroke}`, color: CDV.textDim, fontSize: 13, textAlign: 'center' }}>
            Nenhum usuário encontrado com esse filtro.
          </div>
        </div>
      ) : (
        <div style={{ padding: '0 22px 18px', display: 'flex', flexDirection: 'column', gap: 6 }}>
          {filtered.map(p => <ProfileRow key={p.user_id} p={p} onClick={() => setSelected(p)} />)}
        </div>
      )}

      <Sheet open={!!selected} onClose={() => setSelected(null)} title="Detalhes do usuário">
        {selected && (
          <ProfileActions p={selected} onSetPlan={updatePlan} onToggleActive={toggleActive} onToggleRole={toggleRole} />
        )}
      </Sheet>
    </div>
  );
};

const MetricCard = ({ label, big, extra, icon, color }) => (
  <div style={{
    background: CDV.surface, border: `1px solid ${CDV.stroke}`, borderRadius: 18,
    padding: 14, display: 'flex', flexDirection: 'column', gap: 8, minHeight: 96,
  }}>
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
      <div style={{ fontSize: 11, color: CDV.textDim, fontWeight: 600, letterSpacing: 0.3, textTransform: 'uppercase' }}>{label}</div>
      <div style={{ width: 26, height: 26, borderRadius: 8, background: color + '22', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Icon name={icon} size={13} color={color} />
      </div>
    </div>
    <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: -0.5, color: CDV.text }}>{big}</div>
    <div style={{ fontSize: 11, color: CDV.textDim }}>{extra}</div>
  </div>
);

const MiniMetric = ({ value, label }) => (
  <div style={{ textAlign: 'center' }}>
    <div style={{ fontSize: 18, fontWeight: 700, color: CDV.text, letterSpacing: -0.3 }}>{value}</div>
    <div style={{ fontSize: 10, color: CDV.textDim, marginTop: 2 }}>{label}</div>
  </div>
);

const ProfileRow = ({ p, onClick }) => {
  const planColor = PLAN_COLORS[p.plan] || CDV.textDim;
  const isAdmin = p.role === 'admin';
  return (
    <button onClick={onClick} style={{
      padding: 12, borderRadius: 14,
      background: p.is_active ? CDV.surface : CDV.surface,
      opacity: p.is_active ? 1 : 0.6,
      border: `1px solid ${isAdmin ? CDV.brand + '40' : CDV.stroke}`,
      display: 'flex', alignItems: 'center', gap: 12, fontFamily: 'inherit', textAlign: 'left',
      color: CDV.text, cursor: 'pointer',
    }}>
      <div style={{
        width: 38, height: 38, borderRadius: 12,
        background: `linear-gradient(135deg, ${planColor}, ${isAdmin ? CDV.brand : planColor + 'aa'})`,
        display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff',
        fontSize: 14, fontWeight: 700, flexShrink: 0,
      }}>{((p.name || p.email || '?').charAt(0).toUpperCase())}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: CDV.text, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {p.name || p.email || '—'}
          </div>
          {isAdmin && <Pill color={CDV.brand} size="sm">admin</Pill>}
          {!p.is_active && <Pill color={CDV.coral} size="sm">suspenso</Pill>}
        </div>
        <div style={{ fontSize: 11, color: CDV.textDim, marginTop: 2 }}>{p.email}</div>
      </div>
      <Pill color={planColor} bg={planColor + '1a'} size="sm">{p.plan}</Pill>
      <Icon name="chevronRight" size={14} color={CDV.textMuted} />
    </button>
  );
};

const ProfileActions = ({ p, onSetPlan, onToggleActive, onToggleRole }) => {
  const days = daysAgo(p.created_at);
  const PLAN_MRR_LOCAL = { mensal: 29.90, semestral: 149.40 / 6, anual: 238.80 / 12, essencial: 29.90, premium: 59.90 };
  const mrr = PLAN_MRR_LOCAL[p.plan] || 0;
  const revenueEstimated = mrr * Math.max(1, Math.floor((days || 0) / 30));
  return (
  <div style={{ padding: '8px 22px 28px' }}>
    <div style={{ fontSize: 18, fontWeight: 700, color: CDV.text, letterSpacing: -0.3 }}>{p.name || p.email}</div>
    <div style={{ fontSize: 12, color: CDV.textDim, marginTop: 2 }}>{p.email}</div>
    <div style={{ fontSize: 11, color: CDV.textMuted, marginTop: 6 }}>
      ID: <span style={{ fontFamily: fontMono, fontSize: 10 }}>{p.user_id}</span>
    </div>
    <div style={{ display: 'flex', gap: 6, marginTop: 10, flexWrap: 'wrap' }}>
      <Pill color={p.role === 'admin' ? CDV.brand : CDV.textDim} size="sm">{p.role}</Pill>
      <Pill color={PLAN_COLORS[p.plan] || CDV.textDim} size="sm">{p.plan}</Pill>
      <Pill color={p.is_active ? CDV.mint : CDV.coral} size="sm">{p.is_active ? 'ativo' : 'suspenso'}</Pill>
    </div>

    {/* Stats do user */}
    <div style={{ marginTop: 14, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
      <UserStatBox label="Dias no app" value={days != null ? days : '—'} color={CDV.brand} />
      <UserStatBox label="MRR" value={mrr > 0 ? `R$ ${mrr.toFixed(2)}` : '—'} color={CDV.mint} />
      <UserStatBox label="Receita estim." value={revenueEstimated > 0 ? `R$ ${revenueEstimated.toFixed(0)}` : '—'} color={CDV.amber} />
    </div>

    {/* Timeline */}
    <div style={{ marginTop: 14, fontSize: 12, color: CDV.textDim, fontWeight: 600, letterSpacing: 0.4, textTransform: 'uppercase', marginBottom: 8 }}>Linha do tempo</div>
    <div style={{ padding: 12, borderRadius: 12, background: CDV.surfaceHi, border: `1px solid ${CDV.stroke}` }}>
      <TimelineItem icon="user" color={CDV.brand} label="Criou conta" detail={formatDate(p.created_at)} first />
      {p.trial_ends_at && (
        <TimelineItem
          icon="sparkle"
          color={CDV.mint}
          label="Trial iniciado"
          detail={`expira em ${formatDate(p.trial_ends_at)}`}
        />
      )}
      {p.plan !== 'trial' && (
        <TimelineItem
          icon="diamond"
          color={PLAN_COLORS[p.plan] || CDV.brand}
          label={`Plano ${p.plan} ativado`}
          detail={`MRR R$ ${mrr.toFixed(2)}`}
        />
      )}
      <TimelineItem icon="check" color={CDV.textDim} label="Última atualização" detail={formatDate(p.updated_at)} last />
    </div>

    <div style={{ marginTop: 18, fontSize: 12, color: CDV.textDim, fontWeight: 600, letterSpacing: 0.4, textTransform: 'uppercase', marginBottom: 8 }}>Plano</div>
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 18 }}>
      {[
        { id: 'trial', label: 'Trial' },
        { id: 'mensal', label: 'Mensal' },
        { id: 'semestral', label: 'Semestral' },
        { id: 'anual', label: 'Anual' },
      ].map(plan => {
        const active = p.plan === plan.id;
        const color = PLAN_COLORS[plan.id] || CDV.textDim;
        return (
          <button key={plan.id} onClick={() => onSetPlan(p.user_id, plan.id)} style={{
            height: 42, borderRadius: 12,
            background: active ? color + '22' : CDV.surfaceHi,
            border: `1.5px solid ${active ? color : CDV.stroke}`,
            color: active ? color : CDV.textDim,
            fontSize: 13, fontWeight: 600, fontFamily: 'inherit',
          }}>{plan.label}</button>
        );
      })}
    </div>

    <button onClick={() => onToggleActive(p.user_id, p.is_active)} style={{
      width: '100%', height: 48, borderRadius: 12,
      background: p.is_active ? CDV.coral + '14' : CDV.mint + '14',
      border: `1px solid ${(p.is_active ? CDV.coral : CDV.mint)}40`,
      color: p.is_active ? CDV.coral : CDV.mint,
      fontSize: 13, fontWeight: 600, fontFamily: 'inherit', marginBottom: 10,
    }}>{p.is_active ? 'Suspender conta' : 'Reativar conta'}</button>

    <button onClick={() => onToggleRole(p.user_id, p.role)} style={{
      width: '100%', height: 44, borderRadius: 12,
      background: 'transparent', border: `1px solid ${CDV.brand}40`,
      color: CDV.brand, fontSize: 13, fontWeight: 600, fontFamily: 'inherit',
    }}>{p.role === 'admin' ? 'Remover privilégio de admin' : 'Promover a admin'}</button>
  </div>
  );
};

const UserStatBox = ({ label, value, color }) => (
  <div style={{
    padding: 10, borderRadius: 10,
    background: `linear-gradient(135deg, ${color}14 0%, ${CDV.surface} 60%)`,
    border: `1px solid ${color}25`,
  }}>
    <div style={{ fontSize: 9, color, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase' }}>{label}</div>
    <div style={{ fontSize: 15, fontWeight: 700, color: CDV.text, marginTop: 4, letterSpacing: -0.3 }}>{value}</div>
  </div>
);

const TimelineItem = ({ icon, color, label, detail, first, last }) => (
  <div style={{ display: 'flex', gap: 10, position: 'relative', paddingBottom: last ? 0 : 12 }}>
    <div style={{ position: 'relative', flexShrink: 0 }}>
      <div style={{
        width: 24, height: 24, borderRadius: 99,
        background: `linear-gradient(135deg, ${color}38, ${color}14)`,
        border: `1px solid ${color}40`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        boxShadow: `0 0 8px ${color}40`,
      }}><Icon name={icon} size={11} color={color} /></div>
      {!last && (
        <div style={{
          position: 'absolute', top: 24, left: 11, bottom: -12, width: 2,
          background: `linear-gradient(180deg, ${color}40, ${CDV.divider})`,
        }} />
      )}
    </div>
    <div style={{ flex: 1, minWidth: 0, paddingTop: 2 }}>
      <div style={{ fontSize: 12, fontWeight: 600, color: CDV.text }}>{label}</div>
      <div style={{ fontSize: 11, color: CDV.textDim, marginTop: 1 }}>{detail}</div>
    </div>
  </div>
);

Object.assign(window, { AdminScreen });
