/* account.jsx — menu da conta + páginas (Perfil, Configurações, API, Assinatura, Suporte) */
const {
  Button: ABtn, Input: AInp, Badge: ABadge, Separator: ASep, Alert: AAlert, AlertDescription: AAlertDesc, Dialog: ADialog, cn: acn,
  formatBRL: aBRL,
  IconUser: AUser, IconGear: AGear, IconSliders: ASliders, IconWallet: AWallet, IconLifebuoy: ALife,
  IconLogout: ALogout, IconChevron: AChevron, IconCheck: ACheck, IconBell: ABell, IconCreditCard: ACard,
  IconTrash: ATrash, IconCamera: ACam, IconDownload: ADown, IconStar: AStar, IconShield: AShield,
  IconBolt: ABolt, IconChart: AChartI, IconMail: AMail, IconAlert: AAlertI, IconArrowRight: AArrow, IconX: AX,
} = window;

const ACCOUNT_SECTIONS = [
  { key: 'perfil', label: 'Perfil', icon: AUser },
  { key: 'config', label: 'Configurações', icon: ASliders },
  { key: 'api', label: 'API', icon: AGear },
  { key: 'assinatura', label: 'Assinatura', icon: AWallet },
  { key: 'suporte', label: 'Suporte', icon: ALife },
];

/* =================== Menu da conta (dropdown no header) =================== */
function AccountMenu({ user, plan, apiConnected, onSelect, onLogout }) {
  const { useState, useRef, useEffect } = React;
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, []);
  const initial = (user.name || user.email || '?').trim().charAt(0).toUpperCase();
  const go = (k) => { setOpen(false); onSelect(k); };
  return (
    <div className="relative" ref={ref}>
      <button onClick={() => setOpen((o) => !o)}
        className="flex items-center gap-2 rounded-xl border border-edge bg-white/[0.04] py-1 pl-1 pr-2 transition-colors hover:bg-white/[0.07]">
        <span className="flex h-7 w-7 items-center justify-center rounded-lg bg-gradient-to-br from-brand to-coral text-xs font-bold text-ink">{initial}</span>
        <span className="hidden max-w-[120px] truncate text-sm text-zinc-200 sm:block">{user.name}</span>
        <AChevron size={15} className={acn('text-zinc-500 transition-transform', open && 'rotate-180')} />
      </button>

      {open && (
        <div className="absolute right-0 z-50 mt-2 w-64 overflow-hidden rounded-2xl border border-edge bg-[#161616] p-1.5 shadow-2xl shadow-black/60">
          <div className="flex items-center gap-3 rounded-xl px-2.5 py-2.5">
            <span className="flex h-10 w-10 items-center justify-center rounded-xl bg-gradient-to-br from-brand to-coral text-sm font-bold text-ink">{initial}</span>
            <div className="min-w-0">
              <div className="truncate text-sm font-semibold text-white">{user.name}</div>
              <div className="truncate text-xs text-zinc-500">{user.email}</div>
            </div>
            <ABadge variant={plan === 'pro' ? 'brand' : 'neutral'} className="ml-auto">{plan === 'pro' ? 'Pro' : 'Teste'}</ABadge>
          </div>
          <ASep className="my-1.5" />
          {ACCOUNT_SECTIONS.map((s) => (
            <button key={s.key} onClick={() => go(s.key)}
              className="flex w-full items-center gap-3 rounded-xl px-2.5 py-2 text-left text-sm text-zinc-300 transition-colors hover:bg-white/[0.06] hover:text-white">
              <s.icon size={17} className="text-zinc-500" />
              {s.label}
              {s.key === 'api' && <span className={acn('ml-auto h-2 w-2 rounded-full', apiConnected ? 'bg-emerald-400' : 'bg-zinc-600')} />}
            </button>
          ))}
          <ASep className="my-1.5" />
          <button onClick={() => { setOpen(false); onLogout(); }}
            className="flex w-full items-center gap-3 rounded-xl px-2.5 py-2 text-left text-sm text-zinc-300 transition-colors hover:bg-coral/10 hover:text-coral">
            <ALogout size={17} className="text-zinc-500" /> Sair da conta
          </button>
        </div>
      )}
    </div>
  );
}

/* =================== Controles auxiliares =================== */
function Toggle({ checked, onChange }) {
  return (
    <button onClick={() => onChange(!checked)} role="switch" aria-checked={checked}
      className={acn('relative inline-flex h-6 w-11 shrink-0 items-center rounded-full transition-colors', checked ? 'bg-brand' : 'bg-white/[0.15]')}>
      <span className={acn('inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform', checked ? 'translate-x-6' : 'translate-x-1')} />
    </button>
  );
}
function Row({ title, desc, children }) {
  return (
    <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-3 py-3.5">
      <div className="min-w-0">
        <div className="text-sm font-medium text-zinc-200">{title}</div>
        {desc && <div className="mt-0.5 text-xs text-zinc-500">{desc}</div>}
      </div>
      {children}
    </div>
  );
}
function FieldA({ label, children }) {
  return <label className="block"><span className="mb-1.5 block text-xs font-medium text-zinc-400">{label}</span>{children}</label>;
}
function SectionCard({ title, desc, children, footer }) {
  return (
    <div className="rounded-2xl border border-edge bg-panel">
      <div className="border-b border-edge px-4 py-5 sm:px-6">
        <h2 className="font-syne text-lg font-bold text-white">{title}</h2>
        {desc && <p className="mt-1 text-sm text-zinc-500">{desc}</p>}
      </div>
      <div className="px-4 py-5 sm:px-6">{children}</div>
      {footer && <div className="flex flex-wrap items-center justify-start gap-2 border-t border-edge px-4 py-4 sm:px-6">{footer}</div>}
    </div>
  );
}

/* =================== Diálogo: excluir conta =================== */
function DeleteAccountDialog({ open, onClose }) {
  const { useState, useEffect } = React;
  const [txt, setTxt] = useState('');
  const phrase = 'Excluir minha conta';
  const ok = txt.trim() === phrase;
  useEffect(() => { if (open) setTxt(''); }, [open]);
  return (
    <ADialog open={open} onClose={onClose}>
      <div className="p-6">
        <div className="mb-4 flex items-center gap-3">
          <span className="flex h-11 w-11 items-center justify-center rounded-2xl bg-danger/12 text-danger"><ATrash size={20} /></span>
          <div>
            <h2 className="font-syne text-lg font-bold text-white">Excluir conta</h2>
            <p className="text-xs text-zinc-500">Esta ação é permanente e não pode ser desfeita.</p>
          </div>
        </div>
        <AAlert tone="coral" className="mb-4">
          <span className="mt-0.5"><AAlertI size={17} /></span>
          <AAlertDesc className="text-coral/90">
            Você perderá seus produtos monitorados, histórico de ganhos e configurações. Não há como recuperar.
          </AAlertDesc>
        </AAlert>
        <label className="block">
          <span className="mb-1.5 block text-sm text-zinc-300">Para confirmar, digite <span className="font-semibold text-white">“{phrase}”</span> abaixo:</span>
          <AInp value={txt} onChange={(e) => setTxt(e.target.value)} placeholder={phrase} autoFocus />
        </label>
      </div>
      <div className="flex items-center justify-end gap-2 border-t border-edge px-6 py-4">
        <ABtn variant="ghost" onClick={onClose}>Cancelar</ABtn>
        <button
          disabled={!ok}
          onClick={onClose}
          className={acn('inline-flex h-11 items-center justify-center gap-2 rounded-xl px-5 text-sm font-semibold transition-all',
            ok ? 'btn-danger-solid' : 'cursor-not-allowed bg-danger/40 text-white')}>
          <ATrash size={16} /> Excluir minha conta
        </button>
      </div>
    </ADialog>
  );
}

/* =================== Seção: Perfil =================== */
function SecPerfil({ user, onUpdateUser }) {
  const { useState } = React;
  const [name, setName] = useState(user.name || '');
  const [email, setEmail] = useState(user.email || '');
  const [phone, setPhone] = useState(user.phone || '');
  const [saved, setSaved] = useState(false);
  const [delOpen, setDelOpen] = useState(false);
  const initial = (name || email || '?').trim().charAt(0).toUpperCase();
  const save = () => { onUpdateUser({ ...user, name, email, phone }); setSaved(true); setTimeout(() => setSaved(false), 2000); };
  return (
    <div className="space-y-5">
      <SectionCard title="Informações pessoais" desc="Como você aparece no AchaMais."
        footer={<><ABtn onClick={save}>Salvar alterações</ABtn><span className={acn('ml-3 text-sm text-brand transition-opacity', saved ? 'opacity-100' : 'opacity-0')}>Alterações salvas ✓</span></>}>
        <div className="mb-6 flex items-center gap-4">
          <span className="flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-brand to-coral text-2xl font-bold text-ink">{initial}</span>
          <div>
            <ABtn variant="secondary" size="sm"><ACam size={15} /> Alterar foto</ABtn>
            <p className="mt-1.5 text-xs text-zinc-500">JPG ou PNG, até 2&nbsp;MB.</p>
          </div>
        </div>
        <div className="grid gap-4 sm:grid-cols-2">
          <FieldA label="Nome completo"><AInp value={name} onChange={(e) => setName(e.target.value)} placeholder="Seu nome" /></FieldA>
          <FieldA label="Telefone"><AInp value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="(00) 00000-0000" /></FieldA>
          <FieldA label="E-mail"><AInp type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="voce@email.com" /></FieldA>
        </div>
      </SectionCard>

      <SectionCard title="Segurança" desc="Mantenha sua conta protegida.">
        <Row title="Senha" desc="Última alteração há 3 meses"><ABtn variant="outline" size="sm">Alterar senha</ABtn></Row>
        <ASep />
        <Row title="Verificação em duas etapas" desc="Adicione uma camada extra de proteção"><ABtn variant="outline" size="sm">Ativar</ABtn></Row>
      </SectionCard>

      <SectionCard title="Zona de perigo" desc="Ações irreversíveis.">
        <Row title="Excluir conta" desc="Remove permanentemente sua conta e todos os dados.">
          <button onClick={() => setDelOpen(true)}
            className="inline-flex h-9 shrink-0 items-center justify-center gap-2 whitespace-nowrap rounded-xl bg-danger/12 px-3 text-sm font-semibold text-danger transition-colors hover:bg-danger/20">
            <ATrash size={15} /> Excluir conta
          </button>
        </Row>
      </SectionCard>

      <DeleteAccountDialog open={delOpen} onClose={() => setDelOpen(false)} />
    </div>
  );
}

/* =================== Seção: Configurações =================== */
function SecConfig() {
  const { useState } = React;
  const [prefs, setPrefs] = useState({ bestAlert: true, weekly: true, news: false, sound: false });
  const [platform, setPlatform] = useState('all');
  const [sort, setSort] = useState('comm');
  const [vw, setVw] = useState('card');
  const set = (k, v) => setPrefs((p) => ({ ...p, [k]: v }));
  const Seg = ({ value, onChange, opts }) => (
    <div className="inline-flex rounded-xl border border-edge bg-white/[0.04] p-1">
      {opts.map(([v, l]) => (
        <button key={v} onClick={() => onChange(v)}
          className={acn('whitespace-nowrap rounded-lg px-3 py-1.5 text-sm font-medium transition-all', value === v ? 'bg-white/[0.1] text-white shadow-sm' : 'text-zinc-400 hover:text-zinc-200')}>{l}</button>
      ))}
    </div>
  );
  return (
    <div className="space-y-5">
      <SectionCard title="Preferências de busca" desc="O ponto de partida de cada pesquisa.">
        <Row title="Plataforma padrão" desc="Onde buscar por padrão"><Seg value={platform} onChange={setPlatform} opts={[['all', 'Todas'], ['ml', 'ML'], ['shopee', 'Shopee']]} /></Row>
        <ASep />
        <Row title="Ordenação padrão" desc="Como ordenar os resultados"><Seg value={sort} onChange={setSort} opts={[['comm', 'Comissão R$'], ['price', 'Preço'], ['pct', '%']]} /></Row>
        <ASep />
        <Row title="Visualização padrão" desc="Cards ou lista"><Seg value={vw} onChange={setVw} opts={[['card', 'Cards'], ['list', 'Lista']]} /></Row>
      </SectionCard>

      <SectionCard title="Notificações" desc="Escolha o que quer receber por e-mail."
        footer={<ABtn>Salvar preferências</ABtn>}>
        <Row title="Alertas de melhor comissão" desc="Avisar quando um produto monitorado ficar mais vantajoso"><Toggle checked={prefs.bestAlert} onChange={(v) => set('bestAlert', v)} /></Row>
        <ASep />
        <Row title="Resumo semanal" desc="Um panorama dos seus ganhos toda segunda"><Toggle checked={prefs.weekly} onChange={(v) => set('weekly', v)} /></Row>
        <ASep />
        <Row title="Novidades e dicas" desc="Recursos novos e boas práticas para afiliados"><Toggle checked={prefs.news} onChange={(v) => set('news', v)} /></Row>
        <ASep />
        <Row title="Som de notificação" desc="Tocar um som ao encontrar uma grande oportunidade"><Toggle checked={prefs.sound} onChange={(v) => set('sound', v)} /></Row>
      </SectionCard>
    </div>
  );
}

/* =================== Seção: API =================== */
function SecApi({ mlToken, shopeeToken, onSaveTokens }) {
  const { useState } = React;
  const [ml, setMl] = useState(mlToken);
  const [sp, setSp] = useState(shopeeToken);
  const [saved, setSaved] = useState(false);
  const save = () => { onSaveTokens({ ml: ml.trim(), shopee: sp.trim() }); setSaved(true); setTimeout(() => setSaved(false), 2000); };
  const Status = ({ on }) => (
    <span className={acn('inline-flex items-center gap-1.5 rounded-full border px-2.5 py-0.5 text-[11px] font-semibold', on ? 'border-emerald-500/30 bg-emerald-500/10 text-emerald-400' : 'border-edge text-zinc-500')}>
      <span className={acn('h-1.5 w-1.5 rounded-full', on ? 'bg-emerald-400' : 'bg-zinc-600')} />{on ? 'Conectada' : 'Não conectada'}
    </span>
  );
  return (
    <div className="space-y-5">
      <SectionCard title="Conexões de API" desc="Conecte as plataformas para buscar ofertas reais."
        footer={<><ABtn onClick={save}>Salvar tokens</ABtn><span className={acn('ml-3 text-sm text-brand transition-opacity', saved ? 'opacity-100' : 'opacity-0')}>Tokens salvos ✓</span></>}>
        <div className="space-y-5">
          <div className="rounded-xl border border-edge bg-white/[0.02] p-4">
            <div className="mb-3 flex items-center justify-between">
              <span className="flex items-center gap-2 text-sm font-semibold text-zinc-100"><span className="h-2.5 w-2.5 rounded-full bg-gold" /> Mercado Livre</span>
              <Status on={true} />
            </div>
            <AInp value={ml} onChange={(e) => setMl(e.target.value)} placeholder="Access token (opcional)" className="font-mono text-xs" />
            <p className="mt-2 text-xs text-zinc-500">A busca pública já funciona sem token. Informe um access token para acesso autenticado e limites maiores.</p>
          </div>

          <div className="rounded-xl border border-edge bg-white/[0.02] p-4">
            <div className="mb-3 flex items-center justify-between">
              <span className="flex items-center gap-2 text-sm font-semibold text-zinc-100"><span className="h-2.5 w-2.5 rounded-full bg-coral" /> Shopee Afiliados</span>
              <Status on={!!sp.trim()} />
            </div>
            <AInp value={sp} onChange={(e) => setSp(e.target.value)} placeholder="Bearer token…" className="font-mono text-xs" />
            <p className="mt-2 text-xs text-zinc-500">Obrigatório para incluir as ofertas da Shopee na busca.</p>
          </div>
        </div>
      </SectionCard>

      <AAlert tone="neutral">
        <span className="mt-0.5 text-zinc-500"><AShield size={17} /></span>
        <AAlertDesc className="text-zinc-400">
          <span className="font-medium text-zinc-300">Suas chaves ficam só na sua sessão.</span> Nada é salvo nos nossos servidores — ao recarregar a página, os tokens são apagados. Você revoga o acesso quando quiser.
        </AAlertDesc>
      </AAlert>
    </div>
  );
}

/* =================== Seção: Assinatura =================== */
function SecAssinatura({ plan, onUpgrade, onCancelPlan }) {
  const { useState } = React;
  const [confirm, setConfirm] = useState(false);
  const invoices = plan === 'pro' ? [
    { id: 'AM-2026-006', date: '06 jun 2026', value: 298.8, status: 'Pago' },
  ] : [];
  if (plan !== 'pro') {
    return (
      <div className="space-y-5">
        <SectionCard title="Seu plano" desc="Você está no teste grátis.">
          <div className="flex flex-col items-start justify-between gap-4 sm:flex-row sm:items-center">
            <div>
              <div className="flex items-center gap-2"><span className="font-syne text-xl font-bold text-white">Teste grátis</span><ABadge variant="brand">5 dias restantes</ABadge></div>
              <p className="mt-1 text-sm text-zinc-500">Acesso completo por 7 dias. Assine o Pro para não perder nada quando acabar.</p>
            </div>
            <ABtn onClick={onUpgrade}>Assinar o Pro <AArrow size={16} /></ABtn>
          </div>
        </SectionCard>
        <SectionCard title="Por que assinar o Pro?" desc="Tudo que você desbloqueia.">
          <ul className="grid gap-3 sm:grid-cols-2">
            {[[ABolt, 'Buscas ilimitadas'], [AChartI, 'Gerador de links com sub-id'], [AStar, 'Alertas de melhor comissão'], [ADown, 'Monitoramento ilimitado']].map(([Ic, t], i) => (
              <li key={i} className="flex items-center gap-3 rounded-xl border border-edge bg-white/[0.02] px-4 py-3 text-sm text-zinc-200"><Ic size={17} className="text-brand" /> {t}</li>
            ))}
          </ul>
        </SectionCard>
      </div>
    );
  }
  return (
    <div className="space-y-5">
      <SectionCard title="Seu plano"
        footer={<>
          <ABtn variant="outline" size="sm">Trocar para mensal</ABtn>
          {!confirm
            ? <ABtn variant="outline" size="sm" className="border-coral/40 text-coral hover:bg-coral/10" onClick={() => setConfirm(true)}>Cancelar assinatura</ABtn>
            : <span className="flex items-center gap-2"><span className="text-sm text-zinc-400">Confirmar?</span><ABtn variant="ghost" size="sm" onClick={() => setConfirm(false)}>Não</ABtn><ABtn size="sm" className="bg-coral text-white hover:bg-coral/90" onClick={() => { setConfirm(false); onCancelPlan(); }}>Sim, cancelar</ABtn></span>}
        </>}>
        <div className="relative overflow-hidden rounded-xl border border-brand/30 bg-brand/[0.06] p-5">
          <div className="pointer-events-none absolute -right-8 -top-8 h-28 w-28 rounded-full opacity-30 blur-2xl" style={{ background: 'radial-gradient(circle, rgba(22,191,163,.6), transparent 70%)' }} />
          <div className="flex flex-wrap items-center gap-2">
            <span className="font-syne text-xl font-bold text-white">AchaMais Pro</span>
            <ABadge variant="brand">Anual</ABadge>
            <ABadge variant="brand" className="ml-auto">Ativo</ABadge>
          </div>
          <div className="mt-4 grid grid-cols-2 gap-4 sm:grid-cols-3">
            <div><div className="text-xs text-zinc-500">Valor</div><div className="text-sm font-semibold text-white">{aBRL(24.9)}/mês</div></div>
            <div><div className="text-xs text-zinc-500">Cobrança</div><div className="text-sm font-semibold text-white">Anual · {aBRL(298.8)}</div></div>
            <div><div className="text-xs text-zinc-500">Renova em</div><div className="text-sm font-semibold text-white">06 jun 2027</div></div>
          </div>
        </div>
      </SectionCard>

      <SectionCard title="Forma de pagamento">
        <Row title={<span className="flex items-center gap-2"><ACard size={17} className="text-zinc-400" /> Mastercard •••• 4242</span>} desc="Expira em 12/29">
          <ABtn variant="outline" size="sm">Trocar cartão</ABtn>
        </Row>
      </SectionCard>

      <SectionCard title="Histórico de faturas">
        <div className="overflow-x-auto rounded-xl border border-edge">
          <table className="w-full min-w-[420px] text-sm">
            <thead><tr className="border-b border-edge bg-white/[0.02] text-left text-xs uppercase tracking-wide text-zinc-500">
              <th className="px-4 py-2.5 font-medium">Fatura</th><th className="px-4 py-2.5 font-medium">Data</th><th className="px-4 py-2.5 font-medium">Valor</th><th className="px-4 py-2.5 font-medium">Status</th><th className="px-4 py-2.5"></th>
            </tr></thead>
            <tbody>
              {invoices.map((inv) => (
                <tr key={inv.id} className="border-b border-edge/60 last:border-0">
                  <td className="px-4 py-3 font-mono text-xs text-zinc-300">{inv.id}</td>
                  <td className="px-4 py-3 text-zinc-400">{inv.date}</td>
                  <td className="px-4 py-3 tabular-nums text-zinc-200">{aBRL(inv.value)}</td>
                  <td className="px-4 py-3"><ABadge variant="brand">{inv.status}</ABadge></td>
                  <td className="px-4 py-3 text-right"><button className="inline-flex items-center gap-1 text-xs text-zinc-400 hover:text-white"><ADown size={14} /> PDF</button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </SectionCard>
    </div>
  );
}

/* =================== Seção: Suporte =================== */
function SecSuporte() {
  const { useState } = React;
  const [openF, setOpenF] = useState(0);
  const faqs = [
    { q: 'De onde vêm os preços e comissões?', a: 'Buscamos em tempo real nas APIs do Mercado Livre e da Shopee Afiliados. As comissões do ML usam a tabela oficial por categoria; as da Shopee vêm direto da sua conta de afiliada.' },
    { q: 'Preciso conectar as duas plataformas?', a: 'Não. A busca no Mercado Livre funciona sem configuração. Para ver ofertas da Shopee, basta colar seu token de afiliada na seção API.' },
    { q: 'Meus tokens estão seguros?', a: 'Sim. As chaves ficam apenas na memória da sua sessão e nunca são salvas nos nossos servidores. Ao recarregar, elas são apagadas.' },
    { q: 'Como funciona o cancelamento?', a: 'Você pode cancelar o Pro a qualquer momento pela seção Assinatura. O acesso continua até o fim do período já pago, sem multa.' },
  ];
  return (
    <div className="space-y-5">
      <div className="grid gap-4 sm:grid-cols-3">
        {[
          { icon: AMail, title: 'E-mail', desc: 'suporte@achamais.com.br', cta: 'Enviar e-mail' },
          { icon: ALife, title: 'Chat ao vivo', desc: 'Seg a sex, 9h às 18h', cta: 'Iniciar chat' },
          { icon: ABell, title: 'Status', desc: 'Todos os sistemas ok', cta: 'Ver status' },
        ].map((c) => (
          <div key={c.title} className="rounded-2xl border border-edge bg-panel p-5">
            <span className="flex h-10 w-10 items-center justify-center rounded-xl bg-brand/10 text-brand"><c.icon size={19} /></span>
            <h3 className="mt-3 font-semibold text-white">{c.title}</h3>
            <p className="mt-0.5 text-sm text-zinc-500">{c.desc}</p>
            <button className="mt-3 inline-flex items-center gap-1 text-sm font-medium text-brand hover:underline">{c.cta} <AArrow size={14} /></button>
          </div>
        ))}
      </div>

      <SectionCard title="Perguntas frequentes">
        <div className="divide-y divide-edge">
          {faqs.map((f, i) => (
            <div key={i} className="py-1">
              <button onClick={() => setOpenF(openF === i ? -1 : i)} className="flex w-full items-center justify-between gap-4 py-3 text-left">
                <span className="text-sm font-medium text-zinc-100">{f.q}</span>
                <AChevron size={17} className={acn('shrink-0 text-zinc-500 transition-transform', openF === i && 'rotate-180')} />
              </button>
              {openF === i && <p className="pb-3 pr-8 text-sm leading-relaxed text-zinc-400">{f.a}</p>}
            </div>
          ))}
        </div>
      </SectionCard>

      <SectionCard title="Enviar uma mensagem" desc="Responderemos em até 1 dia útil."
        footer={<ABtn>Enviar mensagem</ABtn>}>
        <div className="space-y-4">
          <FieldA label="Assunto"><AInp placeholder="Sobre o que você precisa de ajuda?" /></FieldA>
          <FieldA label="Mensagem">
            <textarea rows={4} placeholder="Descreva sua dúvida ou problema…"
              className="w-full rounded-lg border border-edge bg-white/[0.04] p-3 text-sm text-zinc-100 placeholder:text-zinc-500 transition-all focus:border-brand/60 focus:outline-none focus:ring-2 focus:ring-brand/25" />
          </FieldA>
        </div>
      </SectionCard>
    </div>
  );
}

/* =================== Página da conta (layout) =================== */
function AccountPage({ section, onSection, user, onUpdateUser, plan, onUpgrade, onCancelPlan, mlToken, shopeeToken, onSaveTokens }) {
  const current = ACCOUNT_SECTIONS.find((s) => s.key === section) || ACCOUNT_SECTIONS[0];
  return (
    <main className="mx-auto w-full max-w-5xl flex-1 px-5 py-8">
      <div className="mb-6">
        <h1 className="font-syne text-2xl font-extrabold tracking-tight text-white">Minha conta</h1>
        <p className="mt-1 text-sm text-zinc-500">Gerencie seu perfil, preferências, APIs e assinatura.</p>
      </div>

      <div className="grid gap-6 lg:grid-cols-[220px_1fr]">
        {/* nav lateral */}
        <aside className="min-w-0 lg:sticky lg:top-24 lg:self-start">
          <nav className="flex flex-wrap gap-1.5 rounded-2xl border border-edge bg-panel p-1.5 lg:flex-col lg:flex-nowrap lg:gap-1">
            {ACCOUNT_SECTIONS.map((s) => (
              <button key={s.key} onClick={() => onSection(s.key)}
                className={acn('flex items-center gap-2 rounded-xl px-3 py-2 text-sm font-medium transition-all lg:gap-2.5 lg:py-2.5',
                  section === s.key ? 'bg-brand/12 text-brand' : 'text-zinc-400 hover:bg-white/[0.04] hover:text-zinc-200')}>
                <s.icon size={17} /> {s.label}
              </button>
            ))}
          </nav>
        </aside>

        {/* conteúdo */}
        <div className="min-w-0">
          {section === 'perfil' && <SecPerfil user={user} onUpdateUser={onUpdateUser} />}
          {section === 'config' && <SecConfig />}
          {section === 'api' && <SecApi mlToken={mlToken} shopeeToken={shopeeToken} onSaveTokens={onSaveTokens} />}
          {section === 'assinatura' && <SecAssinatura plan={plan} onUpgrade={onUpgrade} onCancelPlan={onCancelPlan} />}
          {section === 'suporte' && <SecSuporte />}
        </div>
      </div>
    </main>
  );
}

Object.assign(window, { AccountMenu, AccountPage });
