/* screens-config.jsx — Planos & Configurações (Mitryus integration) */

// ============================================================
// PLANOS — catálogo fixo + simulador personalizado em tabs
// ============================================================
function PlanosScreen() {
  const [view, setView] = useState("catalogo");
  return (
    <div className="space-y-6">
      <div className="flex items-center justify-center">
        <div className="inline-flex p-1 rounded-xl border border-[var(--border)] bg-[var(--panel)] gap-0.5">
          <button
            onClick={() => setView("catalogo")}
            className={`px-4 py-2 text-[12.5px] font-medium rounded-lg flex items-center gap-2 transition-all ${view === "catalogo" ? "bg-[var(--panel-2)] text-[var(--fg)] shadow-[var(--shadow-sm)]" : "text-[var(--fg-muted)] hover:text-[var(--fg)]"}`}
          >
            <Icon name="layers" className="w-3.5 h-3.5" />
            Planos fixos
          </button>
          <button
            onClick={() => setView("simulador")}
            className={`px-4 py-2 text-[12.5px] font-medium rounded-lg flex items-center gap-2 transition-all ${view === "simulador" ? "bg-[var(--panel-2)] text-[var(--fg)] shadow-[var(--shadow-sm)]" : "text-[var(--fg-muted)] hover:text-[var(--fg)]"}`}
          >
            <Icon name="calculator" className="w-3.5 h-3.5" />
            Simular sob medida
            <span className="badge badge-accent text-[8px]">NOVO</span>
          </button>
        </div>
      </div>

      {view === "simulador" ? <SimuladorPlano /> : <PlanosCatalogoFixo />}
    </div>
  );
}

function PlanosCatalogoFixo() {
  const [billing, setBilling] = useState("anual");
  const PLANS = [
    {
      id: "starter",
      name: "Essencial",
      tag: "Loja única começando",
      icon: "sparkle",
      price: { mensal: 690, anual: 552 },
      desc: "O básico pra colocar a operação no mapa: KPIs essenciais, integração com seu ERP e suporte.",
      color: "var(--fg-muted)",
      limits: { lojas: "1 loja", users: "5 usuários", freq: "Atualização diária" },
      includes: [
        { f: "Home + Visão Geral + Análise de Produtos", on: true },
        { f: "Conector Mitryus · 1 instância", on: true },
        { f: "1 loja · 5 usuários", on: true },
        { f: "Histórico 12 meses", on: true },
        { f: "Atualização diária dos dados", on: true },
        { f: "Setup, treinamento e onboarding incluso", on: true, hi: true },
        { f: "Suporte por e-mail · 5d úteis", on: true },
        { f: "Previsão de Vendas", on: false },
        { f: "Ruptura & Cobertura", on: false },
        { f: "Versão mobile + Open to Buy", on: false },
      ],
    },
    {
      id: "pro",
      name: "Profissional",
      tag: "Sweet spot multi-loja",
      icon: "rocket",
      featured: true,
      price: { mensal: 1690, anual: 1352 },
      desc: "Para redes em crescimento que precisam de visão de rede + módulos de inteligência ativos.",
      color: "var(--accent)",
      limits: { lojas: "até 3 lojas", users: "15 usuários", freq: "Atualização a cada hora" },
      includes: [
        { f: "Tudo do Essencial", on: true },
        { f: "Até 3 lojas · 15 usuários", on: true },
        { f: "Histórico 24 meses", on: true },
        { f: "Atualização horária dos dados", on: true },
        { f: "Previsão de Vendas · 4–12 sem", on: true, hi: true },
        { f: "Ruptura & Cobertura · rede + filial", on: true, hi: true },
        { f: "Versão mobile do dashboard", on: true, hi: true },
        { f: "Cadastro de Pedidos automatizado", on: true },
        { f: "Alertas inteligentes (e-mail, WhatsApp)", on: true },
        { f: "Suporte prioritário · 1d útil", on: true },
      ],
    },
    {
      id: "max",
      name: "Avançado",
      tag: "Operação completa",
      icon: "crown",
      price: { mensal: 2990, anual: 2392 },
      desc: "Pacote completo de inteligência comercial. Pensado pra grupos com 4–6 lojas e operação 360°.",
      color: "var(--accent-2)",
      limits: { lojas: "até 6 lojas", users: "30 usuários", freq: "Atualização a cada 15 min" },
      includes: [
        { f: "Tudo do Profissional", on: true },
        { f: "Até 6 lojas · 30 usuários", on: true },
        { f: "Histórico 36 meses", on: true },
        { f: "Atualização a cada 15 minutos", on: true, hi: true },
        { f: "Open to Buy (OTB) incluso", on: true, hi: true },
        { f: "Calendário de meta + Curva ABC", on: true, hi: true },
        { f: "Performance Radar + HealthScore", on: true },
        { f: "API + Webhooks ilimitados", on: true },
        { f: "Customer Success dedicado", on: true },
        { f: "Suporte prioritário · 4h", on: true },
      ],
    },
    {
      id: "enterprise",
      name: "Enterprise",
      tag: "Grupos grandes",
      icon: "shield",
      price: { mensal: null, anual: null },
      desc: "Para redes com 7+ lojas, e-commerce, omni-channel e necessidades específicas.",
      color: "var(--pink)",
      limits: { lojas: "Lojas ilimitadas", users: "Usuários ilimitados", freq: "Streaming sub-minuto" },
      includes: [
        { f: "Tudo do Avançado", on: true },
        { f: "Lojas + usuários ilimitados", on: true },
        { f: "Streaming Mitryus · sub-minuto", on: true, hi: true },
        { f: "White-label completo (domínio + logo)", on: true, hi: true },
        { f: "Modelo ML customizado por categoria", on: true, hi: true },
        { f: "Single Sign-On (SAML / OIDC)", on: true },
        { f: "SLA 99,95% · 24×7", on: true },
        { f: "Multi-tenant gerenciado", on: true },
      ],
    },
  ];

  return (
    <div className="space-y-8">
      <div className="text-center max-w-2xl mx-auto">
        <div className="flex items-center justify-center gap-2 mb-2">
          <span className="neon-dot" />
          <span className="text-[11px] uppercase tracking-[0.18em] text-[var(--accent)] font-semibold">Planos · escalável por necessidade</span>
        </div>
        <h2 className="text-[28px] font-semibold tracking-tight">Pensado pra crescer com a sua operação</h2>
        <p className="text-[13px] text-[var(--fg-muted)] mt-2">
          Setup, treinamento e onboarding já <span className="text-[var(--fg)] font-medium">embutidos</span> em todos os planos.
          Pague uma mensalidade só e tenha acesso ao time, ao produto e à evolução contínua.
        </p>

        <div className="inline-flex mt-5 p-1 rounded-xl border border-[var(--border)] bg-[var(--panel)]">
          <button onClick={() => setBilling("mensal")} className={`px-4 py-2 text-[12px] font-medium rounded-lg transition-all ${billing === "mensal" ? "bg-[var(--panel-2)] shadow-sm" : "text-[var(--fg-muted)]"}`}>Mensal</button>
          <button onClick={() => setBilling("anual")} className={`px-4 py-2 text-[12px] font-medium rounded-lg transition-all flex items-center gap-2 ${billing === "anual" ? "bg-[var(--panel-2)] shadow-sm" : "text-[var(--fg-muted)]"}`}>
            Anual
            <span className="badge badge-accent text-[9px] py-0">-20%</span>
          </button>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4 items-stretch">
        {PLANS.map((plan) => (
          <div key={plan.id} className={`relative flex flex-col ${plan.featured ? "panel-hi gradient-border" : "panel"} p-5 ${plan.featured ? "xl:-translate-y-2 xl:scale-[1.02]" : ""} transition-all`}>
            {plan.featured && (
              <div className="absolute -top-2.5 left-1/2 -translate-x-1/2">
                <span className="badge badge-accent">Mais escolhido</span>
              </div>
            )}
            <div className="flex items-center gap-2.5">
              <div className="w-10 h-10 rounded-xl flex items-center justify-center" style={{ background: `color-mix(in oklch, ${plan.color} 14%, transparent)`, border: `1px solid color-mix(in oklch, ${plan.color} 35%, transparent)`, color: plan.color }}>
                <Icon name={plan.icon} className="w-4 h-4" />
              </div>
              <div>
                <div className="text-[15px] font-semibold">{plan.name}</div>
                <div className="text-[10px] text-[var(--fg-faint)] uppercase tracking-wider">{plan.tag}</div>
              </div>
            </div>

            <div className="mt-5">
              {plan.price[billing] ? (
                <>
                  <div className="flex items-baseline gap-1.5">
                    <span className="text-[14px] text-[var(--fg-muted)]">R$</span>
                    <span className="num text-[36px] font-semibold tracking-tight leading-none">{new Intl.NumberFormat("pt-BR").format(plan.price[billing])}</span>
                    <span className="text-[12px] text-[var(--fg-muted)]">/ mês</span>
                  </div>
                  <div className="text-[10.5px] text-[var(--fg-faint)] mt-1">
                    {billing === "anual"
                      ? <>cobrado anualmente · economia de <span className="text-[var(--accent)] font-semibold">R$ {new Intl.NumberFormat("pt-BR").format((plan.price.mensal - plan.price.anual) * 12)}/ano</span></>
                      : "cobrado mensalmente · sem fidelidade"}
                  </div>
                </>
              ) : (
                <>
                  <div className="num text-[26px] font-semibold tracking-tight">Sob consulta</div>
                  <div className="text-[10.5px] text-[var(--fg-faint)] mt-1">Pacote customizado · falar com vendas</div>
                </>
              )}
            </div>

            <p className="text-[12px] text-[var(--fg-muted)] mt-3 min-h-[44px] leading-snug">{plan.desc}</p>

            {/* Limits highlight */}
            <div className="mt-3 grid grid-cols-1 gap-1.5 p-3 rounded-lg bg-[var(--panel-2)] border border-[var(--border-soft)]">
              <div className="flex items-center gap-2 text-[11px]"><Icon name="store" className="w-3.5 h-3.5 text-[var(--fg-muted)]" /> {plan.limits.lojas}</div>
              <div className="flex items-center gap-2 text-[11px]"><Icon name="users" className="w-3.5 h-3.5 text-[var(--fg-muted)]" /> {plan.limits.users}</div>
              <div className="flex items-center gap-2 text-[11px]"><Icon name="zap" className="w-3.5 h-3.5 text-[var(--fg-muted)]" /> {plan.limits.freq}</div>
            </div>

            <button className={`btn ${plan.featured ? "btn-primary" : ""} w-full justify-center mt-4`}>
              {plan.price[billing] ? "Começar agora" : "Falar com vendas"}
              <Icon name="arrow-right" className="w-4 h-4" />
            </button>

            <div className="mt-4 pt-4 border-t border-[var(--border)] space-y-1.5 flex-1">
              {plan.includes.map((f, i) => (
                <div key={i} className={`flex items-start gap-2 ${!f.on ? "opacity-40" : ""}`}>
                  <Icon name={f.on ? (f.hi ? "sparkles" : "check") : "x"} className={`w-3 h-3 shrink-0 mt-0.5 ${f.on ? (f.hi ? "text-[var(--accent)]" : "text-[var(--pos)]") : "text-[var(--fg-faint)]"}`} />
                  <span className={`text-[11.5px] ${f.hi ? "font-medium" : ""}`}>{f.f}</span>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>

      {/* "Por que uma mensalidade só?" anchoring block */}
      <div className="panel p-6 relative overflow-hidden">
        <div className="absolute -top-10 -right-10 w-64 h-64 rounded-full bg-[var(--accent-glow)] blur-3xl pointer-events-none" />
        <div className="relative">
          <div className="flex items-center gap-2 mb-2">
            <span className="neon-dot" />
            <span className="text-[10px] uppercase tracking-[0.18em] text-[var(--accent)] font-semibold">Por que cobramos só uma mensalidade?</span>
          </div>
          <h3 className="text-[18px] font-semibold tracking-tight">Tudo embutido. Sem surpresa no boleto.</h3>
          <p className="text-[12px] text-[var(--fg-muted)] mt-1.5 max-w-3xl">
            Outras plataformas cobram setup, treinamento e suporte como extras. A gente prefere construir uma relação previsível —
            você sabe quanto vai pagar todo mês e o time DashM evolui o produto continuamente, sem cobrança por feature.
          </p>
          <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3 mt-5">
            {[
              { icon: "wrench", t: "Setup incluso", d: "Implantação + integração Mitryus sem cobrança extra." },
              { icon: "graduation-cap", t: "Treinamento incluso", d: "Onboarding da equipe e materiais de apoio." },
              { icon: "rocket", t: "Evolução contínua", d: "Novos módulos liberados sem upgrade obrigatório." },
              { icon: "calendar-x", t: "Sem fidelidade", d: "Saída a qualquer momento. Você paga só o mês corrente." },
              { icon: "map-pin", t: "Atendimento local", d: "Equipe presencial em Ponta Grossa e região." },
              { icon: "shield-check", t: "Dados criptografados", d: "TLS, MFA, RLS por loja e backups diários." },
            ].map((m) => (
              <div key={m.t} className="p-3 rounded-xl bg-[var(--panel-2)] border border-[var(--border)]">
                <Icon name={m.icon} className="w-4 h-4 text-[var(--accent)] mb-2" />
                <div className="text-[12px] font-medium">{m.t}</div>
                <div className="text-[10.5px] text-[var(--fg-muted)] mt-1 leading-snug">{m.d}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Add-ons */}
      <div className="panel p-6">
        <SectionHead title="Add-ons opcionais" subtitle="Cobre necessidades pontuais sem mudar de plano" icon="puzzle" />
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
          {[
            { nome: "Loja adicional", desc: "Cada loja acima do limite do plano.", price: "R$ 290/mês", icon: "store" },
            { nome: "Nova integração ERP", desc: "Conectar um ERP diferente do Mitryus.", price: "R$ 200/mês + R$ 1.500 setup", icon: "plug" },
            { nome: "Treinamento presencial", desc: "Workshop com a equipe na sua loja.", price: "R$ 800 one-time", icon: "graduation-cap" },
            { nome: "Relatório customizado", desc: "Dashboard sob medida para um caso específico.", price: "R$ 350 por relatório", icon: "file-bar-chart-2" },
            { nome: "Hora extra de desenvolvimento", desc: "Customizações pontuais.", price: "R$ 180/h", icon: "code" },
            { nome: "Consultoria estratégica", desc: "Acompanhamento mensal com analista DashM.", price: "R$ 1.200/mês", icon: "compass" },
          ].map((a) => (
            <div key={a.nome} className="p-4 rounded-xl border border-[var(--border)] bg-[var(--panel-2)] hover:border-[var(--accent)] transition-colors group">
              <div className="flex items-start justify-between mb-2">
                <div className="w-9 h-9 rounded-lg bg-[var(--panel)] border border-[var(--border)] flex items-center justify-center">
                  <Icon name={a.icon} className="w-4 h-4 text-[var(--accent)]" />
                </div>
                <span className="text-[10px] text-[var(--fg-muted)] uppercase tracking-wider font-mono">{a.price}</span>
              </div>
              <div className="text-[13px] font-medium">{a.nome}</div>
              <div className="text-[11px] text-[var(--fg-muted)] mt-1 leading-snug">{a.desc}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Comparison table */}
      <div className="panel overflow-hidden">
        <div className="px-5 py-4 border-b border-[var(--border)]">
          <SectionHead title="Comparativo completo" subtitle="Veja as diferenças entre os planos lado a lado" icon="list-checks" />
        </div>
        <div className="overflow-x-auto">
          <table className="dm-table">
            <thead>
              <tr>
                <th className="w-[34%]">Recurso</th>
                <th className="text-center">Essencial</th>
                <th className="text-center" style={{ color: "var(--accent)" }}>Profissional</th>
                <th className="text-center">Avançado</th>
                <th className="text-center">Enterprise</th>
              </tr>
            </thead>
            <tbody>
              {[
                ["Lojas inclusas", "1", "até 3", "até 6", "Ilimitadas"],
                ["Usuários", "5", "15", "30", "Ilimitados"],
                ["Frequência de atualização", "Diária", "Horária", "15 min", "Sub-minuto"],
                ["Histórico", "12 meses", "24 meses", "36 meses", "Ilimitado"],
                ["Previsão de Vendas", false, true, true, true],
                ["Ruptura & Cobertura", false, true, true, true],
                ["Cadastro de Pedidos automatizado", false, true, true, true],
                ["Versão mobile", false, true, true, true],
                ["Open to Buy (OTB)", false, false, true, true],
                ["Calendário de meta + Curva ABC", false, false, true, true],
                ["API + Webhooks", false, true, true, true],
                ["SSO (SAML/OIDC)", false, false, false, true],
                ["White-label completo", false, false, "Add-on", true],
                ["SLA", "99,5%", "99,9%", "99,9%", "99,95%"],
                ["Suporte", "E-mail · 5d", "Prioritário · 1d", "Prioritário · 4h", "24×7 dedicado"],
                ["Setup + onboarding", true, true, true, true],
              ].map((row, i) => (
                <tr key={i}>
                  <td className="font-medium">{row[0]}</td>
                  {row.slice(1).map((cell, j) => (
                    <td key={j} className="text-center">
                      {typeof cell === "boolean" ? (
                        <Icon name={cell ? "check-circle-2" : "x"} className={`w-4 h-4 inline ${cell ? "text-[var(--pos)]" : "text-[var(--fg-faint)]"}`} />
                      ) : (
                        <span className="num text-[12.5px] font-mono">{cell}</span>
                      )}
                    </td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

// ============================================================
// CONFIGURAÇÕES (with Mitryus integration tab)
// ============================================================
function ConfigScreen() {
  const [tab, setTab] = useState("integracoes");
  const tabs = [
    { id: "integracoes", label: "Integrações", icon: "plug" },
    { id: "branding",    label: "Branding & White-label", icon: "palette" },
    { id: "usuarios",    label: "Usuários & Permissões", icon: "users" },
    { id: "seguranca",   label: "Segurança",       icon: "shield-check" },
    { id: "billing",     label: "Cobrança",        icon: "credit-card" },
  ];

  return (
    <div className="space-y-6">
      <div className="panel p-1.5 flex gap-1 overflow-x-auto">
        {tabs.map((t) => (
          <button
            key={t.id}
            onClick={() => setTab(t.id)}
            className={`flex items-center gap-2 px-4 py-2.5 rounded-lg text-[12.5px] font-medium whitespace-nowrap transition-all ${tab === t.id ? "bg-[var(--panel-2)] text-[var(--fg)]" : "text-[var(--fg-muted)] hover:text-[var(--fg)]"}`}
          >
            <Icon name={t.icon} className="w-3.5 h-3.5" />
            {t.label}
          </button>
        ))}
      </div>

      {tab === "integracoes" && <IntegracoesTab />}
      {tab === "branding" && <BrandingTab />}
      {tab === "usuarios" && <UsuariosTab />}
      {tab === "seguranca" && <SegurancaTab />}
      {tab === "billing" && <BillingTab />}
    </div>
  );
}

function IntegracoesTab() {
  return (
    <div className="space-y-5">
      {/* Mitryus core integration */}
      <div className="panel-hi p-6 relative overflow-hidden">
        <div className="absolute -top-16 -right-16 w-64 h-64 rounded-full bg-[var(--accent-glow)] blur-3xl pointer-events-none" />
        <div className="relative grid grid-cols-1 lg:grid-cols-[1.4fr_1fr] gap-6">
          <div>
            <div className="flex items-center gap-3 mb-3">
              <div className="w-12 h-12 rounded-xl bg-gradient-to-br from-[var(--accent)] to-[var(--accent-2)] flex items-center justify-center text-[#ffffff] font-bold text-[16px]">
                M
              </div>
              <div>
                <div className="text-[16px] font-semibold">Mitryus · ERP Core</div>
                <div className="text-[11px] text-[var(--fg-muted)] flex items-center gap-1.5"><span className="w-1.5 h-1.5 rounded-full bg-[var(--pos)] pulse-glow" /> Conectado · sincronizando há 2 min</div>
              </div>
              <span className="ml-auto badge badge-pos">Core · ativo</span>
            </div>
            <p className="text-[12.5px] text-[var(--fg-muted)] leading-relaxed">
              Conector nativo da plataforma. Sincroniza catálogo, estoque, vendas, NFs, recebimentos e clientes.
              Toda a inteligência (previsão, ruptura, cobertura) depende deste canal estar saudável.
            </p>

            <div className="mt-5 grid grid-cols-2 md:grid-cols-4 gap-3">
              {[
                { label: "Entidades sincronizadas", value: "12/12" },
                { label: "Registros últimas 24h", value: "1,2M" },
                { label: "Latência média", value: "1,8s" },
                { label: "Health check", value: "100%" },
              ].map((m) => (
                <div key={m.label} className="p-3 rounded-lg bg-[var(--panel-2)] border border-[var(--border)]">
                  <div className="text-[10px] uppercase tracking-wider text-[var(--fg-muted)]">{m.label}</div>
                  <div className="num text-[18px] font-semibold mt-0.5">{m.value}</div>
                </div>
              ))}
            </div>
          </div>

          <div className="space-y-3">
            <div className="p-4 rounded-xl border border-[var(--border)] bg-[var(--panel)]">
              <div className="text-[10px] uppercase tracking-wider text-[var(--fg-muted)] mb-2">Endpoint</div>
              <div className="font-mono text-[11px] text-[var(--fg)] break-all">https://api.mitryus.io/v3/tenant/demo</div>
              <div className="mt-3 flex items-center gap-2">
                <Btn variant="ghost" icon="copy">Copiar</Btn>
                <Btn variant="ghost" icon="external-link">Console</Btn>
              </div>
            </div>
            <div className="grid grid-cols-2 gap-2">
              <Btn icon="refresh-cw">Resync agora</Btn>
              <Btn variant="primary" icon="settings-2">Configurar</Btn>
            </div>
          </div>
        </div>

        {/* Entity sync rows */}
        <div className="mt-6 pt-5 border-t border-[var(--border)] grid grid-cols-2 lg:grid-cols-4 gap-2">
          {[
            { e: "Produtos", n: "8.420", t: "2 min", ok: true },
            { e: "Estoque", n: "1.240 filiais", t: "1 min", ok: true },
            { e: "Vendas (NFC-e)", n: "stream live", t: "12s", ok: true },
            { e: "Clientes", n: "284 mil", t: "15 min", ok: true },
            { e: "Pedidos compra", n: "183 ativos", t: "5 min", ok: true },
            { e: "Recebimentos", n: "stream live", t: "8s", ok: true },
            { e: "Fotos catálogo", n: "12.418", t: "1h", ok: true },
            { e: "Calendário comercial", n: "—", t: "24h", ok: true },
          ].map((s) => (
            <div key={s.e} className="flex items-center gap-2 p-2.5 rounded-lg bg-[var(--panel-2)] border border-[var(--border)]">
              <div className={`w-1.5 h-1.5 rounded-full ${s.ok ? "bg-[var(--pos)] pulse-glow" : "bg-[var(--neg)]"}`} />
              <div className="flex-1 min-w-0">
                <div className="text-[11.5px] font-medium truncate">{s.e}</div>
                <div className="text-[10px] text-[var(--fg-faint)]">{s.n}</div>
              </div>
              <div className="text-[10px] font-mono text-[var(--fg-faint)]">{s.t}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Available integrations */}
      <div className="panel p-5">
        <SectionHead title="Conectores disponíveis" subtitle="Conecte canais adicionais — marketplaces, e-commerce, BI" icon="puzzle" />
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3">
          {[
            { name: "BigQuery", desc: "Data warehouse Google", icon: "database", status: "ativo", color: "var(--info)" },
            { name: "Supabase", desc: "Auth + Storage", icon: "shield-check", status: "ativo", color: "var(--pos)" },
            { name: "WhatsApp Business", desc: "Alertas via WA", icon: "message-circle", status: "ativo", color: "var(--pos)" },
            { name: "Power BI", desc: "Export dashboards", icon: "bar-chart-3", status: "disponível", color: "var(--fg-muted)" },
            { name: "Marketplace · Genérico", desc: "API REST", icon: "shopping-bag", status: "disponível", color: "var(--fg-muted)" },
            { name: "E-commerce · API", desc: "Sync pedidos online", icon: "globe", status: "disponível", color: "var(--fg-muted)" },
            { name: "ClickUp", desc: "Tarefas operacionais", icon: "list-checks", status: "disponível", color: "var(--fg-muted)" },
            { name: "Webhook genérico", desc: "Push eventos custom", icon: "webhook", status: "disponível", color: "var(--fg-muted)" },
          ].map((c) => (
            <div key={c.name} className="p-4 rounded-xl border border-[var(--border)] bg-[var(--panel-2)] hover:border-[var(--accent)] transition-colors">
              <div className="flex items-center justify-between mb-3">
                <div className="w-9 h-9 rounded-lg flex items-center justify-center" style={{ background: `color-mix(in oklch, ${c.color} 14%, transparent)`, color: c.color, border: `1px solid color-mix(in oklch, ${c.color} 40%, transparent)` }}>
                  <Icon name={c.icon} className="w-4 h-4" />
                </div>
                {c.status === "ativo" ? (
                  <span className="badge badge-pos">conectado</span>
                ) : (
                  <span className="badge">disponível</span>
                )}
              </div>
              <div className="text-[13px] font-medium">{c.name}</div>
              <div className="text-[11px] text-[var(--fg-muted)] mt-0.5">{c.desc}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function BrandingTab() {
  const [palette, setPalette] = useState("aurora");
  const palettes = {
    aurora:  { name: "Aurora (default)", colors: ["#4cf3d2", "#a78bfa", "#ff5c8d"] },
    sunset:  { name: "Sunset",            colors: ["#ff8a4c", "#ff5c7a", "#a78bfa"] },
    forest:  { name: "Forest",            colors: ["#34d399", "#6ee7b7", "#fbbf24"] },
    ocean:   { name: "Ocean",             colors: ["#60a5fa", "#22d3ee", "#a78bfa"] },
    mono:    { name: "Monochrome",        colors: ["#e8ecf2", "#8a93a3", "#5b6373"] },
  };

  return (
    <div className="grid grid-cols-1 lg:grid-cols-[1.4fr_1fr] gap-5">
      <div className="space-y-5">
        <div className="panel p-5">
          <SectionHead title="Identidade visual" subtitle="Configurações aplicadas a todos os usuários do seu tenant" icon="palette" />
          <div className="space-y-5">
            <FormField label="Nome da plataforma" icon="type">
              <input className="input" defaultValue="DashM · OS" />
            </FormField>
            <div className="grid grid-cols-2 gap-4">
              <FormField label="Logo (claro)" icon="image">
                <div className="placeholder-stripes rounded-lg h-20 flex items-center justify-center text-[10px] font-mono text-[var(--fg-faint)] cursor-pointer hover:border-[var(--accent)]">
                  <Icon name="upload" className="w-4 h-4 mr-1.5" /> arraste o SVG aqui
                </div>
              </FormField>
              <FormField label="Logo (escuro)" icon="image">
                <div className="placeholder-stripes rounded-lg h-20 flex items-center justify-center text-[10px] font-mono text-[var(--fg-faint)] cursor-pointer hover:border-[var(--accent)]">
                  <Icon name="upload" className="w-4 h-4 mr-1.5" /> arraste o SVG aqui
                </div>
              </FormField>
            </div>
            <div>
              <label className="text-[10px] uppercase tracking-wider font-semibold text-[var(--fg-muted)] mb-2 block">Paleta neon</label>
              <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-2">
                {Object.entries(palettes).map(([k, p]) => (
                  <button
                    key={k}
                    onClick={() => setPalette(k)}
                    className={`p-3 rounded-xl border text-left transition-all ${palette === k ? "border-[var(--accent)] bg-[var(--accent-soft)]" : "border-[var(--border)] hover:border-[var(--fg-muted)] bg-[var(--panel-2)]"}`}
                  >
                    <div className="flex gap-1 mb-2">
                      {p.colors.map((c, i) => (
                        <div key={i} className="w-5 h-5 rounded" style={{ background: c, boxShadow: `0 0 8px ${c}` }} />
                      ))}
                    </div>
                    <div className="text-[11px] font-medium">{p.name}</div>
                  </button>
                ))}
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <FormField label="Tipografia">
                <SelectInput value="Geist" options={["Geist", "Inter", "Manrope", "Söhne", "Custom"]} onChange={() => {}} />
              </FormField>
              <FormField label="Domínio personalizado">
                <input className="input font-mono text-[12px]" defaultValue="dashboard.suaempresa.com.br" />
              </FormField>
            </div>
          </div>
        </div>

        <div className="panel p-5">
          <SectionHead title="Mensagens & textos" subtitle="Customize copy de partes-chave da plataforma" icon="message-square" />
          <div className="space-y-3">
            <FormField label="Saudação da Home">
              <input className="input" defaultValue="Bem-vindo de volta · sua operação em tempo real." />
            </FormField>
            <FormField label="E-mail de remetente">
              <input className="input font-mono text-[12px]" defaultValue="alertas@suaempresa.com.br" />
            </FormField>
            <FormField label="Texto de rodapé">
              <input className="input" defaultValue="© Sua Empresa · 2026 · Powered by DashM" />
            </FormField>
          </div>
        </div>
      </div>

      <div className="space-y-5">
        <div className="panel p-5">
          <SectionHead title="Preview" icon="eye" />
          <div className="rounded-xl border border-[var(--border)] bg-[var(--bg)] p-4 space-y-3">
            <BrandMark />
            <div className="flex gap-2 mt-3">
              {palettes[palette].colors.map((c, i) => (
                <div key={i} className="flex-1 h-12 rounded-lg" style={{ background: c, boxShadow: `0 0 16px ${c}` }} />
              ))}
            </div>
            <div className="p-3 rounded-lg bg-[var(--panel)] border border-[var(--border)]">
              <div className="text-[10px] uppercase tracking-wider text-[var(--fg-muted)]">Faturamento</div>
              <div className="num text-[20px] font-semibold mt-0.5">R$ 1,4M</div>
              <Delta value={12.4} />
            </div>
            <button className="w-full px-3 py-2 rounded-lg font-medium text-[12px]" style={{ background: palettes[palette].colors[0], color: "#ffffff", boxShadow: `0 0 16px ${palettes[palette].colors[0]}` }}>
              Botão primário
            </button>
          </div>
        </div>

        <div className="panel p-5">
          <div className="flex items-center gap-2 mb-3">
            <Icon name="rocket" className="w-4 h-4 text-[var(--accent)]" />
            <h3 className="font-semibold text-[14px]">Publicar mudanças</h3>
          </div>
          <p className="text-[12px] text-[var(--fg-muted)]">As mudanças são propagadas em até 2 minutos para todos os usuários do seu tenant. Você pode reverter a qualquer momento.</p>
          <div className="grid grid-cols-2 gap-2 mt-4">
            <Btn variant="ghost">Reverter</Btn>
            <Btn variant="primary" icon="check">Publicar</Btn>
          </div>
        </div>
      </div>
    </div>
  );
}

function UsuariosTab() {
  const users = Array.from({ length: 10 }, (_, i) => ({
    nome: `Operador ${String.fromCharCode(65 + i)}`,
    email: `operador.${String.fromCharCode(97 + i)}@demo.com`,
    role: ["Owner", "Admin", "Gerente", "Operador", "Analista", "Operador", "Gerente", "Analista", "Operador", "Operador"][i],
    filial: i === 0 || i === 1 ? "Todas" : PH.stores[i % PH.stores.length],
    status: ["ativo", "ativo", "ativo", "ativo", "convite", "ativo", "ativo", "suspenso", "ativo", "ativo"][i],
    last: ["1 min", "5 min", "1h", "2h", "—", "30 min", "4h", "12d", "20 min", "15 min"][i],
  }));

  return (
    <div className="space-y-5">
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
        <KPI label="Total de usuários" value={42} icon="users" compact format="int" />
        <KPI label="Ativos (30d)" value={38} icon="user-check" delta={4.6} compact format="int" />
        <KPI label="Convites pendentes" value={3} icon="mail" compact format="int" />
        <KPI label="MFA habilitado" value="86%" icon="shield-check" delta={11.2} compact />
      </div>

      <div className="panel overflow-hidden">
        <div className="px-5 py-3.5 flex items-center justify-between border-b border-[var(--border)]">
          <div className="flex items-center gap-2 flex-1 max-w-[320px]">
            <Icon name="search" className="w-3.5 h-3.5 text-[var(--fg-faint)]" />
            <input placeholder="Buscar usuário…" className="bg-transparent text-[12.5px] flex-1 focus:outline-none placeholder:text-[var(--fg-faint)]" />
          </div>
          <Btn variant="primary" icon="user-plus">Convidar usuário</Btn>
        </div>
        <table className="dm-table">
          <thead>
            <tr><th>Usuário</th><th>Papel</th><th>Escopo</th><th>Última sessão</th><th>Status</th><th></th></tr>
          </thead>
          <tbody>
            {users.map((u, i) => (
              <tr key={i}>
                <td>
                  <div className="flex items-center gap-2.5">
                    <div className="w-8 h-8 rounded-full bg-gradient-to-br from-[var(--accent)] to-[var(--accent-2)] flex items-center justify-center text-[11px] font-semibold text-[#ffffff]">{u.nome.split(" ")[1][0]}</div>
                    <div>
                      <div className="text-[12.5px] font-medium">{u.nome}</div>
                      <div className="text-[10px] text-[var(--fg-faint)] font-mono">{u.email}</div>
                    </div>
                  </div>
                </td>
                <td>
                  <span className={`badge ${u.role === "Owner" ? "badge-accent" : u.role === "Admin" ? "badge-violet" : ""}`}>{u.role}</span>
                </td>
                <td><span className="badge">{u.filial}</span></td>
                <td className="text-[11px] text-[var(--fg-muted)] num font-mono">{u.last}</td>
                <td>
                  <span className={`badge ${u.status === "ativo" ? "badge-pos" : u.status === "convite" ? "badge-warn" : "badge-neg"}`}>
                    {u.status}
                  </span>
                </td>
                <td><Icon name="more-horizontal" className="w-4 h-4 text-[var(--fg-faint)]" /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function SegurancaTab() {
  return (
    <div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
      <div className="panel p-5">
        <SectionHead title="Autenticação" subtitle="Políticas de acesso e MFA" icon="shield-check" />
        <div className="space-y-3">
          {[
            { t: "Multi-Factor Authentication (MFA)", d: "Exigir TOTP para todos os papéis privilegiados.", on: true },
            { t: "SSO · SAML/OIDC", d: "Login via provedor corporativo.", on: false, badge: "Enterprise" },
            { t: "Brute-force throttle", d: "Bloqueia após 10 tentativas em 15 min.", on: true },
            { t: "Sessão inativa", d: "Logout automático após 30 min.", on: true },
            { t: "IP allowlist", d: "Restringir acesso a IPs corporativos.", on: false },
            { t: "Auditoria completa", d: "Log de todos os eventos sensíveis.", on: true },
          ].map((s) => (
            <div key={s.t} className="flex items-center gap-3 p-3 rounded-lg bg-[var(--panel-2)] border border-[var(--border-soft)]">
              <div className="flex-1">
                <div className="flex items-center gap-2">
                  <span className="text-[12.5px] font-medium">{s.t}</span>
                  {s.badge && <span className="badge badge-violet">{s.badge}</span>}
                </div>
                <div className="text-[11px] text-[var(--fg-muted)] mt-0.5">{s.d}</div>
              </div>
              <Toggle on={s.on} />
            </div>
          ))}
        </div>
      </div>

      <div className="panel p-5">
        <SectionHead title="Atividade recente" subtitle="Eventos de segurança · últimas 24h" icon="activity" />
        <div className="space-y-2">
          {[
            { ev: "Login bem-sucedido", who: "operador.a", when: "2 min", ip: "187.32.x.x" },
            { ev: "MFA ativado", who: "operador.b", when: "1h", ip: "189.4.x.x" },
            { ev: "Falha de login (3×)", who: "—", when: "2h", ip: "45.32.x.x", neg: true },
            { ev: "API key rotacionada", who: "admin", when: "4h", ip: "—" },
            { ev: "Permissão alterada", who: "owner", when: "6h", ip: "—" },
            { ev: "Login bem-sucedido", who: "operador.c", when: "8h", ip: "189.4.x.x" },
          ].map((e, i) => (
            <div key={i} className="flex items-center gap-3 px-3 py-2 rounded-lg hover:bg-[var(--panel-2)]">
              <div className={`w-1.5 h-1.5 rounded-full ${e.neg ? "bg-[var(--neg)]" : "bg-[var(--pos)]"}`} />
              <div className="flex-1 text-[12px]">{e.ev} <span className="text-[var(--fg-muted)]">· {e.who}</span></div>
              <div className="text-[10px] font-mono text-[var(--fg-faint)]">{e.ip}</div>
              <div className="text-[10px] text-[var(--fg-faint)] w-12 text-right">{e.when}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function BillingTab() {
  return (
    <div className="space-y-5">
      <div className="panel-hi p-6 relative overflow-hidden">
        <div className="absolute -top-12 -right-12 w-72 h-72 rounded-full bg-[var(--accent-glow)] blur-3xl pointer-events-none" />
        <div className="relative flex flex-wrap items-end justify-between gap-4">
          <div>
            <div className="flex items-center gap-2 mb-1.5">
              <span className="neon-dot" />
              <span className="text-[10px] uppercase tracking-[0.18em] text-[var(--accent)] font-semibold">Plano atual</span>
            </div>
            <h2 className="text-[28px] font-semibold tracking-tight flex items-center gap-3">Pro <span className="badge badge-accent">anual</span></h2>
            <p className="text-[12.5px] text-[var(--fg-muted)] mt-1">Próxima cobrança em 12/07 · R$ 2.790,00</p>
          </div>
          <div className="flex items-center gap-3">
            <Btn>Histórico</Btn>
            <Btn variant="primary" icon="arrow-up-right">Mudar plano</Btn>
          </div>
        </div>
        <div className="mt-5 grid grid-cols-2 md:grid-cols-4 gap-3 relative">
          <div className="p-3 rounded-lg bg-[var(--panel)] border border-[var(--border)]">
            <div className="text-[10px] uppercase tracking-wider text-[var(--fg-muted)]">Filiais</div>
            <div className="num text-[18px] font-semibold mt-0.5">12 / ∞</div>
          </div>
          <div className="p-3 rounded-lg bg-[var(--panel)] border border-[var(--border)]">
            <div className="text-[10px] uppercase tracking-wider text-[var(--fg-muted)]">Usuários</div>
            <div className="num text-[18px] font-semibold mt-0.5">42 / 50</div>
            <Progress value={42} max={50} height={4} color="var(--warn)" />
          </div>
          <div className="p-3 rounded-lg bg-[var(--panel)] border border-[var(--border)]">
            <div className="text-[10px] uppercase tracking-wider text-[var(--fg-muted)]">Consultas BQ</div>
            <div className="num text-[18px] font-semibold mt-0.5">324 / 500 GB</div>
            <Progress value={324} max={500} height={4} color="var(--accent)" />
          </div>
          <div className="p-3 rounded-lg bg-[var(--panel)] border border-[var(--border)]">
            <div className="text-[10px] uppercase tracking-wider text-[var(--fg-muted)]">Add-ons ativos</div>
            <div className="num text-[18px] font-semibold mt-0.5">3</div>
          </div>
        </div>
      </div>

      <div className="panel overflow-hidden">
        <div className="px-5 py-4 border-b border-[var(--border)] flex items-center justify-between">
          <h3 className="font-semibold text-[14px]">Faturas recentes</h3>
          <Btn variant="ghost" icon="download">Exportar</Btn>
        </div>
        <table className="dm-table">
          <thead>
            <tr><th>Fatura</th><th>Data</th><th>Plano</th><th className="text-right">Valor</th><th>Status</th><th></th></tr>
          </thead>
          <tbody>
            {[
              { n: "INV-2026-0612", d: "12/06/2026", p: "Pro · anual", v: 2790, s: "rascunho", c: "warn" },
              { n: "INV-2026-0512", d: "12/05/2026", p: "Pro · anual", v: 2790, s: "pago", c: "pos" },
              { n: "INV-2026-0412", d: "12/04/2026", p: "Pro · anual", v: 2790, s: "pago", c: "pos" },
              { n: "INV-2026-0312", d: "12/03/2026", p: "Pro · anual", v: 2790, s: "pago", c: "pos" },
              { n: "INV-2026-0212", d: "12/02/2026", p: "Pro · anual", v: 2790, s: "pago", c: "pos" },
            ].map((i, k) => (
              <tr key={k}>
                <td className="font-mono text-[11px]">{i.n}</td>
                <td className="text-[12px] num font-mono">{i.d}</td>
                <td className="text-[12px]">{i.p}</td>
                <td className="text-right num font-mono font-semibold">{fmt.money(i.v)}</td>
                <td><span className={`badge badge-${i.c}`}>{i.s}</span></td>
                <td><Icon name="download" className="w-4 h-4 text-[var(--fg-faint)] hover:text-[var(--fg)] cursor-pointer" /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function Toggle({ on, onChange }) {
  const [v, setV] = useState(on);
  return (
    <button
      onClick={() => { setV(!v); onChange && onChange(!v); }}
      className={`relative w-10 h-6 rounded-full transition-colors ${v ? "bg-[var(--accent)]" : "bg-[var(--border)]"}`}
      style={v ? { boxShadow: "0 0 12px var(--accent-glow)" } : {}}
    >
      <span className={`absolute top-0.5 w-5 h-5 rounded-full bg-white transition-all ${v ? "left-[18px]" : "left-0.5"}`} />
    </button>
  );
}

// ============================================================
// ADMIN — driven by parent (sidebar controls active tab)
// ============================================================
function AdminScreen({ adminTab = "plano", onAdminTab }) {
  const tab = adminTab;
  const setTab = onAdminTab || (() => {});
  const titleMap = {
    plano: "Plano & Cobrança", integracoes: "Integrações", branding: "Branding",
    usuarios: "Usuários & permissões", seguranca: "Segurança", planosCatalog: "Catálogo de planos",
    acessos: "Dashboard de acessos",
  };
  const descMap = {
    plano: "Plano atual, faturas, uso e cobrança.",
    integracoes: "Conector Mitryus, marketplaces, BI e webhooks.",
    branding: "Identidade visual, logo, paleta e domínio próprio.",
    usuarios: "Gerencie quem acessa, com qual papel e em qual escopo.",
    seguranca: "MFA, SSO, throttle, IP allowlist e auditoria.",
    planosCatalog: "Planos fixos, simulador personalizado e add-ons.",
    acessos: "Mapa de calor de uso, total de acessos e usuários ativos.",
  };

  return (
    <div className="space-y-6">
      {/* Tab header (no inline tab bar anymore — sidebar drives it) */}
      <div className="panel p-5 relative overflow-hidden">
        <div className="absolute -top-12 right-10 w-64 h-64 rounded-full bg-[var(--accent-glow)] blur-3xl pointer-events-none opacity-50" />
        <div className="relative flex items-end justify-between flex-wrap gap-3">
          <div>
            <div className="flex items-center gap-2 mb-1.5">
              <span className="neon-dot" />
              <span className="text-[10px] uppercase tracking-[0.18em] text-[var(--accent)] font-semibold">Painel administrativo</span>
              <span className="badge">Tenant Demo · Owner</span>
            </div>
            <h2 className="text-[22px] font-semibold tracking-tight">{titleMap[tab]}</h2>
            <p className="text-[12.5px] text-[var(--fg-muted)] mt-1 max-w-2xl">{descMap[tab]}</p>
          </div>
          <div className="flex items-center gap-2">
            <Btn icon="book-open">Documentação</Btn>
            <Btn icon="life-buoy">Suporte</Btn>
          </div>
        </div>
      </div>

      {tab === "plano"         && <BillingTab />}
      {tab === "acessos"       && <AcessosTab />}
      {tab === "integracoes"   && <IntegracoesTab />}
      {tab === "branding"      && <BrandingTab />}
      {tab === "usuarios"      && <UsuariosTab />}
      {tab === "seguranca"     && <SegurancaTab />}
      {tab === "planosCatalog" && <PlanosScreen />}
    </div>
  );
}

Object.assign(window, { PlanosScreen, ConfigScreen, AdminScreen, Toggle, SimuladorPlano, AcessosTab });

// ============================================================
// ACESSOS — usage dashboard with heatmap (hour × weekday)
// ============================================================
function AcessosTab() {
  const [range, setRange] = useState("30d");
  const RANGES = [
    { id: "7d",  label: "7 dias" },
    { id: "30d", label: "30 dias" },
    { id: "90d", label: "90 dias" },
    { id: "ytd", label: "YTD" },
    { id: "custom", label: "Personalizado" },
  ];

  // Mock data
  const weekdays = ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb"];
  // Heatmap: 7 weekdays × 24 hours, value = accesses count
  const heatmap = Array.from({ length: 7 }, (_, d) =>
    Array.from({ length: 24 }, (_, h) => {
      const isWeekend = d === 0 || d === 6;
      const isBusinessHour = h >= 8 && h <= 20;
      const isPeak = h >= 10 && h <= 12 || h >= 14 && h <= 17;
      let base = 0;
      if (isBusinessHour) base = isPeak ? 75 : 35;
      if (isWeekend) base = isBusinessHour ? base * 0.35 : 4;
      if (h < 6 || h > 22) base = Math.max(0, base * 0.1);
      // Add deterministic variance
      const noise = (Math.sin(d * 1.3 + h * 0.7) * 12 + Math.cos(h * 0.4) * 8);
      return Math.max(0, Math.round(base + noise));
    })
  );
  const maxVal = Math.max(...heatmap.flat());

  // Daily access trend (30d)
  const dailyTrend = Array.from({ length: 30 }, (_, i) => {
    const dow = (new Date().getDay() - 30 + i + 7 * 5) % 7;
    const weekend = dow === 0 || dow === 6;
    return weekend ? 80 + Math.sin(i) * 18 : 240 + Math.sin(i * 0.8) * 60 + Math.cos(i * 0.3) * 30;
  }).map((v) => Math.max(0, Math.round(v)));

  // Top users by accesses
  const topUsers = [
    { nome: "Operador A", role: "Owner",   acessos: 412, sessoes: 184, last: "2 min" },
    { nome: "Operador C", role: "Admin",   acessos: 326, sessoes: 142, last: "8 min" },
    { nome: "Operador B", role: "Admin",   acessos: 298, sessoes: 128, last: "1h" },
    { nome: "Operador D", role: "Gerente", acessos: 218, sessoes: 96,  last: "3h" },
    { nome: "Operador F", role: "Gerente", acessos: 192, sessoes: 88,  last: "15 min" },
    { nome: "Operador G", role: "Analista",acessos: 168, sessoes: 72,  last: "2h" },
    { nome: "Operador E", role: "Operador",acessos: 142, sessoes: 58,  last: "30 min" },
  ];

  // Top accessed screens
  const topScreens = [
    { tela: "Home",                acessos: 1842, pct: 22 },
    { tela: "Visão Geral",         acessos: 1245, pct: 15 },
    { tela: "Análise de Produtos", acessos: 982,  pct: 12 },
    { tela: "Fechamento do Dia",   acessos: 867,  pct: 10 },
    { tela: "Carteira de Pedidos", acessos: 642,  pct: 8 },
    { tela: "Campanhas",           acessos: 481,  pct: 6 },
    { tela: "Alertas Reposição",   acessos: 412,  pct: 5 },
    { tela: "Ruptura & Cobertura", acessos: 386,  pct: 5 },
  ];

  // Devices breakdown
  const devices = [
    { tipo: "Desktop", pct: 64, count: 5421, icon: "monitor", color: "var(--accent)" },
    { tipo: "Mobile",  pct: 28, count: 2374, icon: "smartphone", color: "var(--accent-2)" },
    { tipo: "Tablet",  pct: 8,  count: 678, icon: "tablet", color: "var(--pink)" },
  ];

  const totalAcessos = 8473;
  const usuariosAtivos = 38;
  const sessionMedia = 14.2;
  const adoption = 90;

  const heatColor = (v) => {
    const intensity = v / maxVal;
    if (intensity < 0.1) return "var(--panel-2)";
    if (intensity < 0.25) return "color-mix(in oklch, var(--accent) 12%, var(--panel-2))";
    if (intensity < 0.50) return "color-mix(in oklch, var(--accent) 28%, var(--panel-2))";
    if (intensity < 0.75) return "color-mix(in oklch, var(--accent) 50%, var(--panel-2))";
    return "color-mix(in oklch, var(--accent) 75%, var(--panel-2))";
  };

  return (
    <div className="space-y-5">
      {/* Period selector */}
      <div className="panel p-3 flex items-center gap-2 flex-wrap">
        <Icon name="calendar-range" className="w-4 h-4 text-[var(--fg-muted)] ml-1" />
        <div className="inline-flex p-0.5 rounded-lg border border-[var(--border)] bg-[var(--panel-2)] gap-0.5">
          {RANGES.map((r) => (
            <button
              key={r.id}
              onClick={() => setRange(r.id)}
              className={`px-3 py-1 text-[11.5px] font-medium rounded-md transition-all ${range === r.id ? "bg-[var(--panel-hi)] text-[var(--fg)] shadow-[var(--shadow-sm)]" : "text-[var(--fg-muted)] hover:text-[var(--fg)]"}`}
            >
              {r.label}
            </button>
          ))}
        </div>
        {range === "custom" && (
          <div className="flex items-center gap-2 ml-2">
            <input type="date" defaultValue="2026-05-01" className="input py-1.5 text-[11.5px] w-[140px]" />
            <span className="text-[var(--fg-faint)]">→</span>
            <input type="date" defaultValue="2026-05-26" className="input py-1.5 text-[11.5px] w-[140px]" />
          </div>
        )}
        <div className="flex-1" />
        <Btn icon="download">Exportar</Btn>
      </div>

      {/* KPI strip */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
        <KPI label="Total de acessos"    icon="activity"   value={totalAcessos} delta={18.4} compact format="int" accent />
        <KPI label="Usuários ativos"     icon="user-check" value={usuariosAtivos} delta={6.2} compact format="int" />
        <KPI label="Sessão média"        icon="clock"      value="14m 12s" delta={4.8} compact />
        <KPI label="Adoção do plano"     icon="trending-up" value="90%" delta={11.4} compact info={{ title: "Adoção", desc: "Usuários ativos ÷ total de licenças do tenant." }} />
      </div>

      {/* Heatmap — hour × weekday */}
      <div className="panel p-5">
        <div className="flex items-center justify-between mb-4 flex-wrap gap-3">
          <div>
            <h3 className="font-semibold text-[15px] flex items-center gap-2"><Icon name="layout-grid" className="w-4 h-4 text-[var(--accent)]" /> Mapa de calor · hora × dia da semana</h3>
            <p className="text-[11px] text-[var(--fg-muted)] mt-0.5">Distribuição dos acessos · pico de uso em dias úteis 10–17h</p>
          </div>
          <div className="flex items-center gap-2 text-[10.5px] text-[var(--fg-muted)]">
            <span>menos</span>
            <div className="flex gap-0.5">
              {[0, 0.2, 0.4, 0.6, 0.8].map((i, idx) => (
                <div key={idx} className="w-4 h-4 rounded-sm border border-[var(--border-soft)]" style={{ background: heatColor(i * maxVal) }} />
              ))}
            </div>
            <span>mais</span>
          </div>
        </div>

        <div className="overflow-x-auto">
          <div className="inline-block min-w-full">
            {/* Hour labels */}
            <div className="flex gap-0.5 pl-12 mb-1">
              {Array.from({ length: 24 }, (_, h) => (
                <div key={h} className="w-7 text-[8.5px] font-mono text-[var(--fg-faint)] text-center">{h % 3 === 0 ? `${h}h` : ""}</div>
              ))}
            </div>
            {/* Rows */}
            {heatmap.map((row, d) => (
              <div key={d} className="flex gap-0.5 items-center mb-0.5">
                <div className="w-10 shrink-0 text-[10px] font-semibold text-[var(--fg-muted)] uppercase">{weekdays[d]}</div>
                <div className="flex gap-0.5">
                  {row.map((v, h) => (
                    <Tooltip
                      key={h}
                      width={200}
                      content={
                        <div>
                          <div className="font-semibold text-[12px] mb-1">{weekdays[d]} · {h.toString().padStart(2, "0")}h</div>
                          <div className="text-[var(--fg-muted)]">
                            <div className="num font-mono text-[14px] font-semibold text-[var(--fg)]">{v}</div>
                            acessos neste horário
                          </div>
                        </div>
                      }
                    >
                      <div
                        className="w-7 h-7 rounded-sm border border-[var(--border-soft)] cursor-help transition-transform hover:scale-110"
                        style={{ background: heatColor(v) }}
                      />
                    </Tooltip>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="mt-4 pt-4 border-t border-[var(--border)] grid grid-cols-1 md:grid-cols-3 gap-3 text-[11.5px]">
          <div className="flex items-center gap-2">
            <Icon name="trending-up" className="w-3.5 h-3.5 text-[var(--pos)]" />
            <span><span className="font-semibold">Quarta-feira</span> é o dia mais ativo · <span className="num font-mono">1.142</span> acessos</span>
          </div>
          <div className="flex items-center gap-2">
            <Icon name="clock" className="w-3.5 h-3.5 text-[var(--accent)]" />
            <span>Pico entre <span className="font-semibold">14h–17h</span> · 38% dos acessos</span>
          </div>
          <div className="flex items-center gap-2">
            <Icon name="moon" className="w-3.5 h-3.5 text-[var(--fg-muted)]" />
            <span>Apenas <span className="num font-mono">4%</span> de uso fora do horário comercial</span>
          </div>
        </div>
      </div>

      {/* Daily trend + Devices side by side */}
      <div className="grid grid-cols-1 lg:grid-cols-[1.6fr_1fr] gap-5">
        <div className="panel p-5 chart-bg">
          <div className="flex items-center justify-between mb-3">
            <div>
              <h3 className="font-semibold text-[14px] flex items-center gap-2"><Icon name="line-chart" className="w-4 h-4 text-[var(--accent)]" /> Tendência diária</h3>
              <p className="text-[11px] text-[var(--fg-muted)] mt-0.5">Acessos por dia · últimos 30 dias</p>
            </div>
            <div className="flex items-center gap-3 text-[11px]">
              <Delta value={18.4} />
              <span className="text-[var(--fg-muted)]">vs. período anterior</span>
            </div>
          </div>
          <LineChart
            labels={dailyTrend.map((_, i) => i % 5 === 0 ? `D-${30 - i}` : "")}
            series={[{ name: "Acessos", data: dailyTrend, color: "var(--accent)" }]}
            height={200}
            formatY={(v) => fmt.int(v)}
          />
        </div>

        <div className="panel p-5">
          <h3 className="font-semibold text-[14px] flex items-center gap-2 mb-3"><Icon name="laptop" className="w-4 h-4 text-[var(--fg-muted)]" /> Dispositivos</h3>
          <div className="flex h-3 rounded-full overflow-hidden border border-[var(--border)] mb-4">
            {devices.map((d) => (
              <div key={d.tipo} style={{ width: `${d.pct}%`, background: d.color }} title={d.tipo} />
            ))}
          </div>
          <div className="space-y-2">
            {devices.map((d) => (
              <div key={d.tipo} className="flex items-center gap-3">
                <Icon name={d.icon} className="w-4 h-4 text-[var(--fg-muted)]" />
                <div className="flex-1 text-[12.5px] font-medium">{d.tipo}</div>
                <div className="num font-mono text-[11.5px] text-[var(--fg-muted)]">{fmt.int(d.count)}</div>
                <div className="num font-mono text-[12.5px] font-semibold w-10 text-right" style={{ color: d.color }}>{d.pct}%</div>
              </div>
            ))}
          </div>
          <div className="mt-4 pt-3 border-t border-[var(--border-soft)] text-[11px] text-[var(--fg-muted)]">
            <span className="text-[var(--accent)] font-semibold">+12% mobile</span> em relação ao mês anterior — adoção da versão mobile crescendo.
          </div>
        </div>
      </div>

      {/* Top users + Top screens */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-5">
        <div className="panel overflow-hidden">
          <div className="px-5 py-3.5 border-b border-[var(--border)] flex items-center justify-between">
            <h3 className="font-semibold text-[14px] flex items-center gap-2"><Icon name="users" className="w-4 h-4 text-[var(--fg-muted)]" /> Usuários mais ativos</h3>
            <Btn variant="ghost" icon="external-link">Ver todos</Btn>
          </div>
          <table className="dm-table">
            <thead>
              <tr>
                <th>Usuário</th>
                <th>Papel</th>
                <th className="text-right">Acessos</th>
                <th className="text-right">Sessões</th>
                <th className="text-right">Última</th>
              </tr>
            </thead>
            <tbody>
              {topUsers.map((u, i) => (
                <tr key={i}>
                  <td>
                    <div className="flex items-center gap-2">
                      <div className="w-7 h-7 rounded-full bg-gradient-to-br from-[var(--accent)] to-[var(--accent-2)] flex items-center justify-center text-[10px] font-semibold text-white">{u.nome.split(" ")[1][0]}</div>
                      <span className="text-[12.5px] font-medium">{u.nome}</span>
                    </div>
                  </td>
                  <td><span className={`badge ${u.role === "Owner" ? "badge-accent" : u.role === "Admin" ? "badge-violet" : ""}`}>{u.role}</span></td>
                  <td className="text-right num font-mono font-semibold">{u.acessos}</td>
                  <td className="text-right num font-mono">{u.sessoes}</td>
                  <td className="text-right num font-mono text-[11px] text-[var(--fg-muted)]">{u.last}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="panel overflow-hidden">
          <div className="px-5 py-3.5 border-b border-[var(--border)] flex items-center justify-between">
            <h3 className="font-semibold text-[14px] flex items-center gap-2"><Icon name="layout-dashboard" className="w-4 h-4 text-[var(--fg-muted)]" /> Telas mais acessadas</h3>
            <span className="text-[10px] text-[var(--fg-faint)] uppercase tracking-wider">total {fmt.int(totalAcessos)}</span>
          </div>
          <div className="p-2">
            {topScreens.map((s, i) => (
              <div key={s.tela} className="flex items-center gap-3 px-3 py-2.5">
                <span className="text-[10px] font-mono w-5 text-[var(--fg-faint)]">{(i + 1).toString().padStart(2, "0")}</span>
                <div className="flex-1 min-w-0">
                  <div className="text-[12.5px] font-medium">{s.tela}</div>
                  <div className="mt-1"><Progress value={s.pct} max={25} height={4} color="var(--accent)" /></div>
                </div>
                <div className="text-right shrink-0">
                  <div className="num font-mono text-[12px] font-semibold">{fmt.int(s.acessos)}</div>
                  <div className="num font-mono text-[10px] text-[var(--fg-faint)]">{s.pct}%</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ============================================================
// SIMULADOR DE PLANO — interactive calculator
// ============================================================
function SimuladorPlano() {
  const [lojas, setLojas] = useState(5);
  const [users, setUsers] = useState(15);
  const [freq, setFreq] = useState("hora");          // diaria | hora | 15min | streaming
  const [billing, setBilling] = useState("anual");   // mensal | anual
  const [addons, setAddons] = useState({ consultoria: true, ecommerce: false, ssoSaml: false, treinamento: false });
  const [modules, setModules] = useState({ forecast: true, ruptura: true, otb: true, mobile: true, abc: true, calendar: true, campanhas: false });
  const toast = useToast();

  // Pricing rules
  const BASE = 390;              // platform base
  const PER_LOJA = 290;          // each loja
  const PER_5_USERS = 75;        // each 5 users above 5 included
  const FREQ_MULT = { diaria: 0, hora: 80, "15min": 220, streaming: 480 };
  const MODULE_PRICE = {
    forecast: 320, ruptura: 280, otb: 240, mobile: 180,
    abc: 120, calendar: 90, campanhas: 220,
  };
  const ADDONS = [
    { id: "consultoria", nome: "Consultoria estratégica",    desc: "Análise mensal com recomendações de negócio", price: 1200, kind: "mensal", icon: "compass" },
    { id: "ecommerce",   nome: "Integração com e-commerce",  desc: "Sync de pedidos online (Shopify, VTEX, Tiny…)", price: 200, setup: 1500, kind: "mensal", icon: "globe" },
    { id: "ssoSaml",     nome: "SSO Enterprise (SAML/OIDC)", desc: "Login corporativo unificado",                  price: 390, kind: "mensal", icon: "shield-check" },
    { id: "treinamento", nome: "Treinamento presencial",     desc: "Sessão de 4h em Ponta Grossa",                 price: 800, kind: "one-time", icon: "graduation-cap" },
  ];

  // Calculation
  const lojaCost  = lojas * PER_LOJA;
  const userBaseIncluded = 5;
  const extraUsers = Math.max(0, users - userBaseIncluded);
  const userCost  = Math.ceil(extraUsers / 5) * PER_5_USERS;
  const freqCost  = FREQ_MULT[freq];
  const moduleIds = Object.keys(modules).filter((k) => modules[k]);
  const moduleCost = moduleIds.reduce((acc, k) => acc + MODULE_PRICE[k], 0);
  const subtotal = BASE + lojaCost + userCost + freqCost + moduleCost;
  const addonsMensal = ADDONS.filter((a) => addons[a.id] && a.kind === "mensal").reduce((acc, a) => acc + a.price, 0);
  const addonsOneTime = ADDONS.filter((a) => addons[a.id] && a.kind === "one-time").reduce((acc, a) => acc + a.price, 0);
  const addonsSetup = ADDONS.filter((a) => addons[a.id] && a.setup).reduce((acc, a) => acc + a.setup, 0);

  const totalMensal = subtotal + addonsMensal;
  const totalAnual = totalMensal * 0.80; // 20% off

  const finalMonth = billing === "anual" ? totalAnual : totalMensal;

  // Suggested plan match
  const suggested = lojas <= 1 && users <= 5 ? "Essencial"
                  : lojas <= 3 && users <= 15 ? "Profissional"
                  : lojas <= 6 && users <= 30 ? "Avançado"
                  : "Enterprise";

  const toggleAddon = (id) => setAddons((a) => ({ ...a, [id]: !a[id] }));
  const toggleModule = (id) => setModules((m) => ({ ...m, [id]: !m[id] }));

  return (
    <div className="space-y-6">
      <div className="grid grid-cols-1 lg:grid-cols-[1fr_360px] gap-5">
        {/* LEFT — controls */}
        <div className="space-y-5">
          {/* Lojas + Usuários */}
          <div className="panel p-5">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
              <CounterControl
                label="Quantas lojas?"
                value={lojas}
                onChange={setLojas}
                min={1} max={20}
                hint={`R$ ${PER_LOJA}/mês cada loja`}
                icon="store"
              />
              <CounterControl
                label="Quantos usuários?"
                value={users}
                onChange={setUsers}
                min={1} max={100}
                hint={`Primeiros 5 inclusos · R$ ${PER_5_USERS}/mês a cada 5 adicionais`}
                icon="users"
                markers={[1, 5, 15, 30, 100]}
              />
            </div>
          </div>

          {/* Frequência de atualização */}
          <div className="panel p-5">
            <div className="flex items-center justify-between mb-3">
              <div>
                <h3 className="font-semibold text-[14px] flex items-center gap-2"><Icon name="zap" className="w-4 h-4 text-[var(--accent)]" /> Frequência de atualização</h3>
                <p className="text-[11px] text-[var(--fg-muted)] mt-0.5">Quanto mais rápido, mais perto do tempo real — também impacta o preço</p>
              </div>
            </div>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-2">
              {[
                { id: "diaria",    label: "Diária",     desc: "uma vez por dia",       extra: 0 },
                { id: "hora",      label: "Horária",    desc: "60× por dia",            extra: FREQ_MULT.hora },
                { id: "15min",     label: "15 min",     desc: "operação ao vivo",       extra: FREQ_MULT["15min"] },
                { id: "streaming", label: "Sub-minuto", desc: "stream Mitryus direto",  extra: FREQ_MULT.streaming },
              ].map((f) => (
                <button
                  key={f.id}
                  onClick={() => setFreq(f.id)}
                  className={`p-3 rounded-xl border text-left transition-colors ${freq === f.id ? "border-[var(--accent)] bg-[var(--accent-soft)]" : "border-[var(--border)] bg-[var(--panel-2)] hover:border-[var(--fg-faint)]"}`}
                >
                  <div className="text-[12.5px] font-medium">{f.label}</div>
                  <div className="text-[10px] text-[var(--fg-muted)] mt-0.5">{f.desc}</div>
                  <div className="text-[10px] text-[var(--accent)] font-mono mt-1.5">{f.extra === 0 ? "incluso" : `+ R$ ${f.extra}/mês`}</div>
                </button>
              ))}
            </div>
          </div>

          {/* Módulos */}
          <div className="panel p-5">
            <div className="flex items-center justify-between mb-3">
              <div>
                <h3 className="font-semibold text-[14px] flex items-center gap-2"><Icon name="layers" className="w-4 h-4 text-[var(--accent)]" /> Módulos · {moduleIds.length} ativos</h3>
                <p className="text-[11px] text-[var(--fg-muted)] mt-0.5">Marque o que sua operação precisa hoje · pode ativar/desativar depois</p>
              </div>
              <span className="num font-mono text-[12px] text-[var(--accent)] font-semibold">+ R$ {moduleCost}/mês</span>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2.5">
              {[
                { id: "forecast",  nome: "Previsão de Vendas",  desc: "Forecast 4–12 semanas",        icon: "line-chart" },
                { id: "ruptura",   nome: "Ruptura & Cobertura", desc: "Heatmap por filial",            icon: "shield-alert" },
                { id: "otb",       nome: "Open to Buy (OTB)",   desc: "Planejamento de compras",       icon: "shopping-cart" },
                { id: "mobile",    nome: "Versão mobile",       desc: "App responsivo + push",         icon: "smartphone" },
                { id: "abc",       nome: "Curva ABC",            desc: "Pareto de receita",             icon: "layers" },
                { id: "calendar",  nome: "Calendário de meta",  desc: "Heatmap diário de aderência",   icon: "calendar-days" },
                { id: "campanhas", nome: "Campanhas",            desc: "Tracking de execução",          icon: "megaphone" },
              ].map((m) => {
                const on = modules[m.id];
                return (
                  <button
                    key={m.id}
                    onClick={() => toggleModule(m.id)}
                    className={`p-3 rounded-xl border text-left transition-colors flex items-start gap-2.5 ${on ? "border-[var(--accent)] bg-[var(--accent-soft)]" : "border-[var(--border)] bg-[var(--panel-2)] hover:border-[var(--fg-faint)]"}`}
                  >
                    <div className={`w-8 h-8 rounded-lg flex items-center justify-center shrink-0 ${on ? "bg-[var(--accent)] text-[#00282d]" : "bg-[var(--panel)] text-[var(--fg-muted)] border border-[var(--border)]"}`}>
                      <Icon name={on ? "check" : m.icon} className="w-4 h-4" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="text-[12.5px] font-medium">{m.nome}</div>
                      <div className="text-[10px] text-[var(--fg-muted)]">{m.desc}</div>
                      <div className="text-[10px] font-mono mt-1" style={{ color: on ? "var(--accent)" : "var(--fg-faint)" }}>R$ {MODULE_PRICE[m.id]}/mês</div>
                    </div>
                  </button>
                );
              })}
            </div>
          </div>

          {/* Add-ons */}
          <div className="panel p-5">
            <div className="flex items-center justify-between mb-3">
              <div>
                <h3 className="font-semibold text-[14px] flex items-center gap-2"><Icon name="puzzle" className="w-4 h-4 text-[var(--accent)]" /> Complementos opcionais</h3>
                <p className="text-[11px] text-[var(--fg-muted)] mt-0.5">{ADDONS.filter(a => addons[a.id]).length} ativos</p>
              </div>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-2.5">
              {ADDONS.map((a) => {
                const on = addons[a.id];
                return (
                  <button
                    key={a.id}
                    onClick={() => toggleAddon(a.id)}
                    className={`p-3 rounded-xl border text-left transition-colors ${on ? "border-[var(--accent)] bg-[var(--accent-soft)]" : "border-[var(--border)] bg-[var(--panel-2)] hover:border-[var(--fg-faint)]"}`}
                  >
                    <div className="flex items-center justify-between mb-1">
                      <div className="flex items-center gap-2">
                        <Icon name={a.icon} className={`w-3.5 h-3.5 ${on ? "text-[var(--accent)]" : "text-[var(--fg-muted)]"}`} />
                        <span className="text-[12.5px] font-medium">{a.nome}</span>
                      </div>
                      <div className={`w-5 h-5 rounded border flex items-center justify-center shrink-0 ${on ? "bg-[var(--accent)] border-[var(--accent)]" : "border-[var(--border)] bg-[var(--panel)]"}`}>
                        {on && <Icon name="check" className="w-3 h-3 text-[#00282d]" />}
                      </div>
                    </div>
                    <div className="text-[10.5px] text-[var(--fg-muted)] mb-1.5 leading-snug">{a.desc}</div>
                    <div className="text-[10.5px] font-mono text-[var(--accent)] font-semibold">
                      R$ {a.price}{a.kind === "mensal" ? "/mês" : " (one-time)"}
                      {a.setup && <span className="text-[var(--fg-faint)] font-normal ml-1">+ setup R$ {a.setup}</span>}
                    </div>
                  </button>
                );
              })}
            </div>
          </div>
        </div>

        {/* RIGHT — sticky summary */}
        <div className="space-y-4">
          <div className="sticky top-4 space-y-3">
            <div className="panel-hi p-5 relative overflow-hidden">
              <div className="absolute -top-12 -right-12 w-48 h-48 rounded-full bg-[var(--accent-glow)] blur-3xl pointer-events-none" />
              <div className="relative">
                <div className="text-[10px] uppercase tracking-[0.18em] text-[var(--accent)] font-semibold mb-1">Plano recomendado</div>
                <div className="text-[20px] font-semibold tracking-tight">{suggested}</div>

                {/* Billing toggle */}
                <div className="mt-3 inline-flex p-0.5 rounded-lg border border-[var(--border)] bg-[var(--panel-2)] gap-0.5">
                  <button onClick={() => setBilling("mensal")} className={`px-2.5 py-1 rounded-md text-[11px] font-medium transition-all ${billing === "mensal" ? "bg-[var(--panel-hi)] text-[var(--fg)] shadow-[var(--shadow-sm)]" : "text-[var(--fg-muted)]"}`}>Mensal</button>
                  <button onClick={() => setBilling("anual")} className={`px-2.5 py-1 rounded-md text-[11px] font-medium transition-all flex items-center gap-1 ${billing === "anual" ? "bg-[var(--panel-hi)] text-[var(--fg)] shadow-[var(--shadow-sm)]" : "text-[var(--fg-muted)]"}`}>
                    Anual <span className="text-[var(--accent)] font-mono">-20%</span>
                  </button>
                </div>

                <div className="mt-4 flex items-baseline gap-1.5">
                  <span className="text-[14px] text-[var(--fg-muted)]">R$</span>
                  <span className="num text-[36px] font-semibold tracking-tight leading-none">{new Intl.NumberFormat("pt-BR", { maximumFractionDigits: 0 }).format(Math.round(finalMonth))}</span>
                  <span className="text-[12px] text-[var(--fg-muted)]">/ mês</span>
                </div>
                {billing === "anual" && (
                  <div className="text-[10.5px] text-[var(--fg-faint)] mt-1">
                    cobrado anualmente · economiza <span className="text-[var(--accent)] font-semibold num">R$ {new Intl.NumberFormat("pt-BR").format(Math.round((totalMensal - totalAnual) * 12))}/ano</span>
                  </div>
                )}
                {addonsOneTime > 0 && (
                  <div className="text-[10.5px] text-[var(--fg-faint)] mt-1">
                    + R$ {new Intl.NumberFormat("pt-BR").format(addonsOneTime + addonsSetup)} one-time
                  </div>
                )}

                <button
                  onClick={() => toast.push({ kind: "success", title: "Proposta enviada", desc: "Nosso time vai entrar em contato em até 1 dia útil." })}
                  className="btn btn-primary w-full justify-center mt-4"
                >
                  <Icon name="send" className="w-4 h-4" />
                  Enviar proposta personalizada
                </button>
                <button className="btn btn-ghost w-full justify-center mt-2 text-[11.5px]">
                  <Icon name="file-text" className="w-3.5 h-3.5" />
                  Baixar PDF do orçamento
                </button>
              </div>
            </div>

            {/* Breakdown */}
            <div className="panel p-4">
              <div className="text-[10.5px] uppercase tracking-wider text-[var(--fg-muted)] font-semibold mb-2.5">Composição</div>
              <div className="space-y-1.5 text-[11.5px]">
                <BkRow label="Base da plataforma" value={BASE} />
                <BkRow label={`${lojas} loja${lojas > 1 ? "s" : ""} × R$ ${PER_LOJA}`} value={lojaCost} />
                {userCost > 0 && <BkRow label={`+ ${extraUsers} usuários adicionais`} value={userCost} />}
                {freqCost > 0 && <BkRow label={`Frequência ${freq}`} value={freqCost} />}
                {moduleIds.length > 0 && <BkRow label={`${moduleIds.length} módulos ativos`} value={moduleCost} />}
                {addonsMensal > 0 && <BkRow label="Add-ons (mensal)" value={addonsMensal} />}
                <div className="border-t border-[var(--border)] pt-2 mt-2">
                  <BkRow label="Subtotal mensal" value={totalMensal} strong />
                  {billing === "anual" && <BkRow label="Desconto anual (-20%)" value={totalMensal - totalAnual} neg />}
                  <BkRow label="Total cobrado/mês" value={finalMonth} highlight />
                </div>
              </div>
            </div>

            <div className="panel p-4">
              <div className="flex items-center gap-2 mb-1.5">
                <Icon name="check-circle-2" className="w-3.5 h-3.5 text-[var(--pos)]" />
                <span className="text-[11.5px] font-semibold">Setup, treinamento e onboarding inclusos</span>
              </div>
              <div className="text-[10.5px] text-[var(--fg-muted)] leading-snug">
                Tudo o que você precisa pra começar já está no preço — sem boleto extra de implantação.
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function CounterControl({ label, value, onChange, min, max, hint, icon, markers }) {
  return (
    <div>
      <div className="flex items-center justify-between mb-2">
        <div className="text-[10.5px] uppercase tracking-wider font-semibold text-[var(--fg-muted)] flex items-center gap-1.5">
          {icon && <Icon name={icon} className="w-3 h-3" />} {label}
        </div>
      </div>
      <div className="flex items-center gap-3">
        <button onClick={() => onChange(Math.max(min, value - 1))} className="w-10 h-10 rounded-lg border border-[var(--border)] bg-[var(--panel-2)] hover:bg-[var(--panel-hi)] flex items-center justify-center text-[var(--fg-muted)] hover:text-[var(--fg)]">
          <Icon name="minus" className="w-4 h-4" />
        </button>
        <input
          type="number"
          min={min} max={max}
          value={value}
          onChange={(e) => onChange(Math.max(min, Math.min(max, +e.target.value || min)))}
          className="flex-1 text-center text-[28px] font-semibold tracking-tight num bg-transparent border-0 focus:outline-none"
        />
        <button onClick={() => onChange(Math.min(max, value + 1))} className="w-10 h-10 rounded-lg border border-[var(--border)] bg-[var(--panel-2)] hover:bg-[var(--panel-hi)] flex items-center justify-center text-[var(--fg-muted)] hover:text-[var(--fg)]">
          <Icon name="plus" className="w-4 h-4" />
        </button>
      </div>
      <input
        type="range"
        min={min} max={max}
        value={value}
        onChange={(e) => onChange(+e.target.value)}
        className="neon w-full mt-3"
      />
      {markers && (
        <div className="flex justify-between text-[9px] text-[var(--fg-faint)] font-mono mt-1.5 px-1">
          {markers.map((m) => <span key={m}>{m}</span>)}
        </div>
      )}
      {hint && <div className="text-[10px] text-[var(--fg-faint)] mt-1.5">{hint}</div>}
    </div>
  );
}

function BkRow({ label, value, strong, highlight, neg }) {
  return (
    <div className={`flex justify-between gap-3 ${strong ? "font-semibold" : ""} ${highlight ? "text-[14px] mt-1" : ""}`}>
      <span className={highlight ? "" : "text-[var(--fg-muted)]"}>{label}</span>
      <span className={`num font-mono ${highlight ? "text-[var(--accent)] font-semibold" : neg ? "text-[var(--pos)]" : ""}`}>
        {neg ? "−" : ""}R$ {new Intl.NumberFormat("pt-BR", { maximumFractionDigits: 0 }).format(Math.round(value))}
      </span>
    </div>
  );
}
