
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>NT INDICA | Área do Cliente</title>
    
    <meta name="theme-color" content="#f8fafc"> <link rel="manifest" href="manifest.json">
    <link rel="apple-touch-icon" href="imagem/logo.png">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default"> <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    
    <style>
    .modal-overlay { 
    display: none; 
    opacity: 0; 
    transition: opacity 0.3s ease; 
}
.modal-overlay.active { 
    display: flex; 
    opacity: 1; 
}
    /* --- NOVO: CONTROLES DE QUANTIDADE --- */
        .qty-controls { display: flex; align-items: center; gap: 8px; background: #f1f5f9; padding: 4px; border-radius: 8px; }
        .btn-qty { 
            width: 26px; height: 26px; border-radius: 6px; border: none; 
            background: white; color: var(--text-main); font-weight: 800; font-size: 1rem;
            cursor: pointer; display: flex; align-items: center; justify-content: center; 
            box-shadow: 0 1px 2px rgba(0,0,0,0.05); transition: 0.2s;
        }
        .btn-qty:active { transform: scale(0.9); }
        .qty-text { font-weight: 700; font-size: 0.9rem; min-width: 20px; text-align: center; }
        :root {
            --primary: #6366f1;
            --primary-dark: #4f46e5;
            --primary-light: #e0e7ff;
            --secondary: #10b981;
            --bg-body: #f8fafc;
            --bg-surface: #ffffff;
            --text-main: #0f172a;
            --text-muted: #64748b;
            --border: #e2e8f0;
            --gradient-card: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%);
            --shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.05);
            --shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
            --radius-lg: 24px;
            --radius-md: 16px;
            --radius-sm: 12px;
        }

        * { margin: 0; padding: 0; box-sizing: border-box; -webkit-tap-highlight-color: transparent; outline: none; }
        html { background-color: var(--bg-body); }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: var(--bg-body); color: var(--text-main); min-height: 100vh; padding-bottom: 40px; overscroll-behavior-y: none; }
        .container { max-width: 600px; margin: 0 auto; padding: 0 20px; }

        /* Header */
        .app-header { display: flex; align-items: center; justify-content: space-between; padding: 24px 0; margin-bottom: 10px; background-color: var(--bg-body); position: sticky; top: 0; z-index: 10; }
        .brand-area { display: flex; align-items: center; gap: 12px; }
        .brand-logo { width: 42px; height: 42px; border-radius: 12px; object-fit: cover; box-shadow: var(--shadow-sm); background: white; padding: 4px; }
        .brand-name { font-weight: 700; font-size: 1.1rem; color: var(--text-main); line-height: 1.2; }
        .user-status { font-size: 0.75rem; font-weight: 600; padding: 6px 12px; border-radius: 99px; display: inline-flex; align-items: center; gap: 6px; }
        .status-active { background: #dcfce7; color: #166534; }
        .status-visitor { background: #eff6ff; color: #1e40af; }
        .install-pwa-btn { display: none; font-size: 0.7rem; font-weight: 700; color: var(--primary); margin-top: 5px; cursor: pointer; text-align: center; transition: 0.2s; opacity: 0.9; }
        .install-pwa-btn:active { transform: scale(0.95); opacity: 1; }

        .welcome-block { margin-bottom: 24px; }
        .welcome-block h1 { font-size: 1.5rem; font-weight: 800; letter-spacing: -0.02em; }
        .welcome-block p { color: var(--text-muted); font-size: 0.95rem; }

        /* NOVAS ABAS DE NAVEGAÇÃO */
        .nav-tabs-menu { display: flex; gap: 12px; margin-bottom: 24px; }
        .nav-item { flex: 1; background: white; padding: 14px; border-radius: 16px; text-align: center; font-weight: 700; color: var(--text-muted); cursor: pointer; box-shadow: var(--shadow-sm); transition: 0.2s; border: 1px solid transparent; display: flex; align-items: center; justify-content: center; gap: 8px; font-size: 0.95rem; }
        .nav-item:active { transform: scale(0.98); }
        .nav-item.active { color: var(--primary); border-color: #e0e7ff; background: white; box-shadow: var(--shadow-md); }
        .nav-item i { font-size: 1rem; }

        /* Wallet Card */
        .wallet-card { background: var(--gradient-card); border-radius: var(--radius-lg); padding: 28px; color: white; box-shadow: 0 20px 25px -5px rgba(79, 70, 229, 0.3); position: relative; overflow: hidden; margin-bottom: 24px; }
        .wallet-card::before { content: ''; position: absolute; top: -50%; left: -50%; width: 200%; height: 200%; background: radial-gradient(circle, rgba(255,255,255,0.15) 0%, rgba(255,255,255,0) 70%); pointer-events: none; }
        .wallet-label { font-size: 0.85rem; opacity: 0.9; font-weight: 500; margin-bottom: 8px; display: flex; align-items: center; gap: 8px; }
        .wallet-value { font-size: 2.5rem; font-weight: 800; letter-spacing: -0.05em; margin-bottom: 24px; }
        .wallet-actions { display: flex; gap: 12px; }
        .action-btn { background: rgba(255, 255, 255, 0.2); backdrop-filter: blur(8px); border: 1px solid rgba(255, 255, 255, 0.3); color: white; padding: 12px 20px; border-radius: 12px; font-weight: 600; font-size: 0.9rem; cursor: pointer; transition: 0.2s; flex: 1; display: flex; align-items: center; justify-content: center; gap: 8px; }
        .action-btn:hover { background: rgba(255, 255, 255, 0.3); }
        .action-btn.disabled { opacity: 0.5; cursor: not-allowed; }

        /* Info & Transactions */
        .info-card { background: var(--bg-surface); border-radius: var(--radius-md); padding: 24px; box-shadow: var(--shadow-sm); border: 1px solid var(--border); margin-bottom: 24px; }
        .card-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; }
        .card-title { font-weight: 700; color: var(--text-main); font-size: 1.1rem; display: flex; align-items: center; gap: 8px; }
        .count-badge { background: #fef3c7; color: #b45309; padding: 4px 12px; border-radius: 20px; font-weight: 800; font-size: 0.9rem; }
        .link-copy-wrapper { background: var(--bg-body); border: 1px solid var(--border); border-radius: 14px; display: flex; align-items: center; padding: 4px; position: relative; }
        .link-input { border: none; background: transparent; flex: 1; padding: 12px 16px; font-family: monospace; color: var(--text-muted); font-size: 0.9rem; width: 100%; }
        .btn-copy { background: white; border: 1px solid var(--border); width: 40px; height: 40px; border-radius: 10px; display: flex; align-items: center; justify-content: center; color: var(--primary); cursor: pointer; box-shadow: var(--shadow-sm); transition: 0.2s; }
        
        .list-header { font-weight: 700; font-size: 1rem; margin-bottom: 12px; color: var(--text-main); padding: 0 4px; }
        .transaction-list { display: flex; flex-direction: column; gap: 12px; }
        .trans-item { background: var(--bg-surface); padding: 16px; border-radius: var(--radius-md); display: flex; align-items: center; justify-content: space-between; box-shadow: var(--shadow-sm); border: 1px solid transparent; transition: 0.2s; }
        .trans-icon { width: 40px; height: 40px; border-radius: 12px; background: var(--bg-body); display: flex; align-items: center; justify-content: center; color: var(--primary); font-size: 1.1rem; margin-right: 14px; }
        .trans-info { flex: 1; }
        .trans-title { font-weight: 600; font-size: 0.95rem; color: var(--text-main); margin-bottom: 2px; }
        .trans-date { font-size: 0.75rem; color: var(--text-muted); }
        .trans-meta { text-align: right; }
        .trans-amount { font-weight: 700; font-size: 0.95rem; color: var(--text-main); margin-bottom: 2px; }
        .trans-status { font-size: 0.7rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; }
        .st-aprovado { color: var(--secondary); }
        .st-negado { color: #ef4444; }
        .st-pendente { color: #f59e0b; }

        /* Catalog / Products */
        .hero-banner { text-align: center; margin: 20px 0 30px; }
        .hero-title { font-size: 1.5rem; font-weight: 800; color: var(--text-main); margin-bottom: 8px; }
        .hero-subtitle { color: var(--text-muted); line-height: 1.6; max-width: 480px; margin: 0 auto; }
        .category-filter { display: flex; gap: 10px; overflow-x: auto; padding-bottom: 16px; margin-bottom: 8px; scrollbar-width: none; }
        .category-filter::-webkit-scrollbar { display: none; }
        .filter-pill { background: white; border: 1px solid var(--border); padding: 8px 18px; border-radius: 99px; font-size: 0.85rem; font-weight: 600; color: var(--text-muted); white-space: nowrap; cursor: pointer; transition: 0.2s; }
        .filter-pill.active { background: var(--text-main); color: white; border-color: var(--text-main); }
        .products-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 20px; }
        .prod-card { background: white; border-radius: var(--radius-md); overflow: hidden; box-shadow: var(--shadow-sm); border: 1px solid var(--border); transition: 0.3s; display: flex; flex-direction: column; }
        .prod-img { width: 100%; aspect-ratio: 16/9; object-fit: cover; background: #f1f5f9; }
        .prod-content { padding: 16px; flex: 1; display: flex; flex-direction: column; }
        .prod-tag { font-size: 0.7rem; color: var(--primary); font-weight: 700; text-transform: uppercase; margin-bottom: 4px; }
        .prod-name { font-weight: 700; font-size: 1rem; margin-bottom: 8px; color: var(--text-main); }
        .prod-desc { font-size: 0.85rem; color: var(--text-muted); line-height: 1.5; margin-bottom: 16px; flex: 1; }
        .prod-footer { display: flex; align-items: center; justify-content: space-between; border-top: 1px solid #f1f5f9; padding-top: 16px; }
        .prod-price { font-weight: 800; font-size: 1.1rem; color: var(--text-main); }
        .btn-buy { background: var(--text-main); color: white; text-decoration: none; padding: 8px 16px; border-radius: 8px; font-size: 0.85rem; font-weight: 600; display: flex; align-items: center; gap: 6px; transition: 0.2s; }
        .blocked-state { background: white; border-radius: var(--radius-md); padding: 40px 20px; text-align: center; border: 2px dashed var(--border); }
        .blocked-icon { font-size: 3rem; color: #f59e0b; margin-bottom: 16px; opacity: 0.8; }
        .btn-whatsapp-outline { display: inline-flex; align-items: center; gap: 8px; color: #10b981; font-weight: 600; margin-top: 16px; text-decoration: none; padding: 10px 24px; border: 2px solid #10b981; border-radius: 99px; }

        .app-footer { text-align: center; margin-top: 40px; }
        .btn-logout { color: #ef4444; font-weight: 600; font-size: 0.9rem; text-decoration: none; display: inline-flex; align-items: center; gap: 8px; padding: 10px 20px; background: #fef2f2; border-radius: 99px; transition: 0.2s; }

        /* Modal & Forms */
        .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(15, 23, 42, 0.7); backdrop-filter: blur(5px); z-index: 100; display: none; align-items: center; justify-content: center; opacity: 0; transition: opacity 0.3s; }
        .modal-overlay.active { opacity: 1; }
        .modal-card { background: white; width: 90%; max-width: 450px; border-radius: 24px; padding: 24px; position: relative; transform: translateY(20px); transition: transform 0.3s; max-height: 90vh; overflow-y: auto; }
        .modal-overlay.active .modal-card { transform: translateY(0); }
        .close-btn { position: absolute; top: 20px; right: 20px; font-size: 1.5rem; color: var(--text-muted); cursor: pointer; }
        .modal-title { text-align: center; font-size: 1.25rem; font-weight: 700; margin-bottom: 24px; }
        .toggle-switch { background: #f1f5f9; padding: 4px; border-radius: 12px; display: flex; margin-bottom: 24px; }
        .toggle-opt { flex: 1; text-align: center; padding: 10px; border-radius: 8px; font-weight: 600; font-size: 0.9rem; color: var(--text-muted); cursor: pointer; transition: 0.2s; display: flex; align-items: center; justify-content: center; gap: 6px; }
        .toggle-opt.active { background: white; color: var(--primary); box-shadow: var(--shadow-sm); }
        .input-group label { display: block; font-size: 0.85rem; font-weight: 600; color: var(--text-muted); margin-bottom: 6px; margin-top: 16px; }
        .input-field { width: 100%; padding: 12px 16px; border: 1px solid var(--border); border-radius: 12px; font-family: inherit; font-size: 1rem; transition: 0.2s; }
        .input-field:focus { border-color: var(--primary); box-shadow: 0 0 0 4px var(--primary-light); }
        .input-money { font-size: 1.5rem; font-weight: 700; color: var(--text-main); background: #f8fafc; text-align: center; }
        .btn-submit { width: 100%; margin-top: 24px; padding: 14px; border-radius: 14px; border: none; background: var(--text-main); color: white; font-weight: 700; font-size: 1rem; cursor: pointer; transition: 0.2s; }
        .btn-submit:disabled { background: #cbd5e1; cursor: not-allowed; }

        @media (max-width: 480px) {
            .wallet-value { font-size: 2rem; }
            .products-grid { grid-template-columns: 1fr; }
        }
        
        /* --- ESTILOS DO CARRINHO (ADICIONAR) --- */
        .btn-add-cart { 
            background: var(--text-main); color: white; border: none; 
            padding: 10px 16px; border-radius: 12px; font-size: 0.85rem; 
            font-weight: 600; display: flex; align-items: center; gap: 6px; 
            cursor: pointer; transition: 0.2s; text-decoration: none;
        }
        .btn-add-cart:active { transform: scale(0.95); }

        .fab-cart {
            position: fixed; bottom: 20px; right: 20px;
            background: var(--secondary); color: white;
            width: 60px; height: 60px; border-radius: 50%;
            display: none; align-items: center; justify-content: center;
            box-shadow: 0 10px 15px -3px rgba(0,0,0,0.3);
            z-index: 90; cursor: pointer; transition: transform 0.2s;
        }
        .fab-cart:active { transform: scale(0.9); }
        
        .cart-badge {
            position: absolute; top: -5px; right: -5px;
            background: #ef4444; color: white;
            font-size: 0.75rem; font-weight: 700;
            width: 24px; height: 24px; border-radius: 50%;
            display: flex; align-items: center; justify-content: center;
            border: 2px solid white;
        }

        .cart-item-row { display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid var(--border); padding: 12px 0; }
        .cart-item-info { flex: 1; padding-right: 10px; text-align: left; }
        .btn-remove-item { color: #ef4444; background: #fef2f2; border: none; width: 32px; height: 32px; border-radius: 8px; cursor: pointer; display: flex; align-items: center; justify-content: center; }
        .btn-checkout { width: 100%; margin-top: 15px; padding: 14px; border-radius: 14px; border: none; background: #25D366; color: white; font-weight: 800; font-size: 1rem; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 8px; }
    </style>
</head>
<body>

<div class="container">

    <header class="app-header">
        <div class="brand-area">
                            <img src="https://sapienciacontabil.com.br/wp-content/uploads/2022/04/sua-logo-aqui-2.png" class="brand-logo" alt="Logo">
                        <div class="brand-name">NT INDICA</div>
        </div>
        <div style="text-align: center;">
                            <div class="user-status status-visitor"><i class="fas fa-user-clock"></i> Visitante</div>
                        
            <div id="installBtn" class="install-pwa-btn" onclick="installPWA()">
                📲 Instalar App
            </div>
        </div>
    </header>

    <div class="welcome-block">
            <h1>Seja Bem-vindo(a)! 👋</h1>
        <p>Conheça nosso catálogo e faça seu pedido abaixo.</p>

    </div>

        <div id="conteudo-inicio" style="display: none;">
        
            </div>
    <div id="conteudo-catalogo" style="display: block;">
        
        <div class="hero-banner">
            <h2 class="hero-title"></h2>
            <p class="hero-subtitle"></p>
        </div>

                    <div class="blocked-state">
                <div class="blocked-icon"><i class="fas fa-rocket"></i></div>
                <h3>Em breve novidades!</h3>
                <p style="color: var(--text-muted); margin-bottom: 20px;">Estamos preparando ofertas exclusivas para você.</p>
                <a href="https://wa.me/5581000000000?text=Ol%C3%A1%21+Me+cadastrei+no+sistema+%28indicado+por+Nossa+Equipe%29.+Quero+liberar+meu+acesso." target="_blank" class="btn-whatsapp-outline">
                    <i class="fab fa-whatsapp"></i> Falar no Suporte
                </a>
            </div>
        
    </div>
    
</div>

<div id="modalSaque" class="modal-overlay">
    <div class="modal-card">
        <span class="close-btn" onclick="fecharModalSaque()">&times;</span>
        <div class="modal-title">Solicitar Resgate</div>
        
        <form method="POST">
            <div class="toggle-switch">
                <div class="toggle-opt active" onclick="mudarTipoResgate('servico')" id="opt_servico">
                    <i class="fas fa-gift"></i> Serviços
                </div>
                
                            </div>
            
            <input type="hidden" name="tipo_resgate" id="tipo_resgate" value="servico">

            <div id="area_servico">
                <div class="input-group">
                    <label>Escolha o prêmio</label>
                    <select name="servico_resgate" id="servico_resgate" onchange="calcServ()" class="input-field">
    <option value="">Selecione...</option>
    </select>
                </div>
                
                <div class="input-group">
                    <label>Valor do Item</label>
                    <input type="text" id="display_valor_servico" readonly class="input-field input-money" value="R$ 0,00">
                </div>
            </div>

            <div id="area_pix" style="display:none;">
                <div class="input-group">
                    <label>Valor a Sacar (Mín R$ 20,00)</label>
                    <input type="text" name="valor_pix" id="valor_pix" class="input-field input-money" placeholder="0,00" onkeyup="calcPix()">
                </div>

                <div class="input-group">
                    <label>Chave Pix</label>
                    <input type="text" name="chave_pix" id="chave_pix" class="input-field" placeholder="CPF, Email ou Telefone">
                </div>
                
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                    <div class="input-group">
                        <label>Tipo Chave</label>
                        <select name="tipo_chave_pix" class="input-field">
                            <option value="cpf">CPF</option>
                            <option value="email">E-mail</option>
                            <option value="telefone">Celular</option>
                            <option value="aleatoria">Aleatória</option>
                        </select>
                    </div>
                    <div class="input-group">
                        <label>Titular</label>
                        <input type="text" name="nome_titular_pix" class="input-field" placeholder="Nome">
                    </div>
                </div>
                <input type="hidden" name="zap_comprovante" value="">
            </div>

            <div class="input-group">
                <label>Observação (Opcional)</label>
                <textarea name="detalhes" class="input-field" rows="2"></textarea>
            </div>

            <button type="submit" name="solicitar_resgate" id="btn_submit_resgate" class="btn-submit" disabled>
                Selecione uma opção
            </button>
        </form>
    </div>
</div>

<script>
  // 1. VARIÁVEIS GLOBAIS
  const saldo = 0;
  const limitePix = 20;
  let carrinho = [];
  const clienteID = "0";
  const clienteNome = "Seja Bem-vindo(a)";
  const whatsappAdmin = "5581000000000";

  // 2. FUNÇÕES DE INTERFACE (MODAIS E ABAS) - REATIVADAS
  function abrirModalSaque() { 
      document.getElementById('modalSaque').style.display = 'flex'; 
      setTimeout(()=>document.getElementById('modalSaque').classList.add('active'), 10); 
  }
  function fecharModalSaque() { 
      document.getElementById('modalSaque').classList.remove('active'); 
      setTimeout(()=>document.getElementById('modalSaque').style.display='none', 300); 
  }

  function copiarLink() {
      const inputLink = document.getElementById("meuLink");
      inputLink.select();
      inputLink.setSelectionRange(0, 99999); // Para mobile
      navigator.clipboard.writeText(inputLink.value).then(() => {
          alert("Link de convite copiado com sucesso!");
          const btn = document.getElementById("btnCopiar");
          btn.innerHTML = '<i class="fas fa-check"></i>';
          setTimeout(() => { btn.innerHTML = '<i class="far fa-copy"></i>'; }, 2000);
      });
  }

  function alternarAba(aba) {
      document.getElementById('tab-btn-inicio').classList.toggle('active', aba === 'inicio');
      document.getElementById('tab-btn-catalogo').classList.toggle('active', aba === 'catalogo');
      document.getElementById('conteudo-inicio').style.display = (aba === 'inicio' ? 'block' : 'none');
      document.getElementById('conteudo-catalogo').style.display = (aba === 'catalogo' ? 'block' : 'none');
  }

  // 3. LÓGICA DE CÁLCULO DE RESGATE
  function mudarTipoResgate(tipo) {
      document.getElementById('tipo_resgate').value = tipo;
      document.getElementById('opt_servico').classList.toggle('active', tipo === 'servico');
      const optPix = document.getElementById('opt_pix');
      if(optPix) optPix.classList.toggle('active', tipo === 'pix');

      document.getElementById('area_servico').style.display = (tipo === 'servico' ? 'block' : 'none');
      const areaPix = document.getElementById('area_pix');
      if(areaPix) areaPix.style.display = (tipo === 'pix' ? 'block' : 'none');
      
      validarBotaoResgate();
  }

  function calcServ() {
      const sel = document.getElementById('servico_resgate');
      const val = parseFloat(sel.options[sel.selectedIndex].getAttribute('data-val') || 0);
      document.getElementById('display_valor_servico').value = "R$ " + val.toLocaleString('pt-BR', {minimumFractionDigits:2});
      validarBotaoResgate();
  }

  function calcPix() { validarBotaoResgate(); }

  function validarBotaoResgate() {
      const tipo = document.getElementById('tipo_resgate').value;
      const btn = document.getElementById('btn_submit_resgate');
      let podeLiberar = false;
      let mensagem = "";
      let corBotao = "var(--text-main)"; // Cor padrão (Preto/Azul escuro)

      if (tipo === 'servico') {
          const sel = document.getElementById('servico_resgate');
          const val = parseFloat(sel.options[sel.selectedIndex].getAttribute('data-val') || 0);
          
          if (val > saldo) {
              mensagem = "Saldo Insuficiente";
              corBotao = "#ef4444"; // VERMELHO vivo
          } else if (val > 0) {
              podeLiberar = true;
              mensagem = "Confirmar Troca";
              corBotao = "#22c55e"; // VERDE (Sucesso)
          } else {
              mensagem = "Selecione um prêmio";
          }
      } else {
          const valInput = document.getElementById('valor_pix').value.replace(',','.');
          const val = parseFloat(valInput || 0);
          
          if (val > saldo) {
              mensagem = "Saldo Insuficiente";
              corBotao = "#ef4444"; // VERMELHO vivo
          } else if (val > 0 && val < limitePix) {
              mensagem = "Mínimo R$ " + limitePix.toFixed(2).replace('.',',');
              corBotao = "#f59e0b"; // LARANJA (Aviso)
          } else if (val >= limitePix && val <= saldo) {
              podeLiberar = true;
              mensagem = "Solicitar PIX AGORA";
              corBotao = "#6366f1"; // AZUL/ROXO (Destaque)
          } else {
              mensagem = "Digite o valor";
          }
      }

      // Aplica as mudanças no botão
      btn.innerText = mensagem;
      btn.disabled = !podeLiberar;
      
      // Força a cor mesmo se estiver desativado
      btn.style.backgroundColor = corBotao;
      btn.style.opacity = podeLiberar ? "1" : "0.8";
      btn.style.color = "white"; // Garante que o texto fique branco
  }

  // 4. FUNÇÕES DO CARRINHO (MANTIDAS)
  function adicionarAoCarrinho(id, nome, preco) {
      let itemExistente = carrinho.find(item => item.id === id);
      if (itemExistente) { itemExistente.qtd++; } 
      else { carrinho.push({ id: id, nome: nome, preco: preco, qtd: 1 }); }
      atualizarUI();
      const fab = document.getElementById('fabCart');
      if(fab) {
          fab.style.display = 'flex';
          fab.style.transform = "scale(1.2)";
          setTimeout(() => fab.style.transform = "scale(1)", 200);
      }
  }

  function atualizarUI() {
      const fab = document.getElementById('fabCart');
      const badge = document.getElementById('cartCount');
      let totalItens = carrinho.reduce((acc, item) => acc + item.qtd, 0);
      if(badge) badge.innerText = totalItens;
      if(fab) fab.style.display = (carrinho.length > 0) ? 'flex' : 'none';
  }

  function renderizarCarrinho() {
      const container = document.getElementById('listaItensCarrinho');
      const totalEl = document.getElementById('valorTotalCarrinho');
      if(!container) return;
      container.innerHTML = '';
      let total = 0;
      if(carrinho.length === 0) {
          container.innerHTML = '<div style="text-align:center; color:#999; padding:20px;">Carrinho vazio</div>';
      } else {
          carrinho.forEach((item, index) => {
              let subtotal = item.preco * item.qtd;
              total += subtotal;
              container.innerHTML += `
                  <div class="cart-item-row">
                      <div class="cart-item-info">
                          <div style="font-weight:700; font-size:0.9rem;">${item.nome}</div>
                          <div style="color:#64748b; font-size:0.8rem;">R$ ${item.preco.toFixed(2)} un.</div>
                      </div>
                      <div class="qty-controls">
                          <button class="btn-qty" onclick="alterarQtd(${index}, -1)">-</button>
                          <span class="qty-text">${item.qtd}</span>
                          <button class="btn-qty" onclick="alterarQtd(${index}, 1)">+</button>
                      </div>
                  </div>`;
          });
      }
      totalEl.innerText = 'R$ ' + total.toLocaleString('pt-BR', {minimumFractionDigits: 2});
  }

  function alterarQtd(index, delta) {
      if (carrinho[index]) {
          carrinho[index].qtd += delta;
          if (carrinho[index].qtd <= 0) {
              carrinho.splice(index, 1);
              if(carrinho.length === 0) fecharCarrinho();
          }
          atualizarUI();
          renderizarCarrinho();
      }
  }

  function abrirCarrinho() { renderizarCarrinho(); document.getElementById('modalCarrinho').style.display = 'flex'; setTimeout(()=>document.getElementById('modalCarrinho').classList.add('active'), 10); }
  function fecharCarrinho() { document.getElementById('modalCarrinho').classList.remove('active'); setTimeout(()=>document.getElementById('modalCarrinho').style.display='none', 300); }

  // 5. O MAESTRO (CADASTRO + PEDIDO)
  document.addEventListener('DOMContentLoaded', function() {
      const form = document.getElementById('formCadastroRapido');
      if (form) {
          form.addEventListener('submit', function(e) {
              e.preventDefault();
              const btn = this.querySelector('button');
              const textoOriginal = btn.innerHTML;
              btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processando...';
              btn.disabled = true;

              const formData = new FormData(this);

              fetch('processar_cadastro_rapido.php', { method: 'POST', body: formData })
              .then(r => r.json())
              .then(data => {
                  if(data.sucesso) {
                      let itensTxt = carrinho.map(i => `${i.qtd}x ${i.nome}`).join(' | ');
                      let totalP = carrinho.reduce((acc, i) => acc + (i.preco * i.qtd), 0);
                      const dadosPed = new FormData();
                      dadosPed.append('id_usuario', data.id);
                      dadosPed.append('itens', itensTxt);
                      dadosPed.append('valor_total', totalP);

                      return fetch('processar_pedidos.php', { method: 'POST', body: dadosPed })
                      .then(() => { return { nome: data.nome, id: data.id }; });
                  } else { throw new Error(data.erro); }
              })
              .then(res => {
                  enviarPedidoWhatsApp(res.nome, res.id);
                  alert("Sucesso! Cadastro e pedido registrados.");
                  location.reload();
              })
              .catch(err => {
                  alert("Atenção: " + err.message);
                  btn.innerHTML = textoOriginal;
                  btn.disabled = false;
              });
          });
      }
  });

  function enviarPedidoWhatsApp(nome, id) {
      let msg = `Ola! Sou o cliente *${nome}* (ID: ${id}).\nItens:\n`;
      let total = 0;
      carrinho.forEach((item) => {
          let subtotal = item.preco * item.qtd;
          msg += `✅ ${item.qtd}x - ${item.nome} (R$ ${subtotal.toFixed(2)})\n`;
          total += subtotal;
      });
      msg += `\n💰 *Total Geral: R$ ${total.toLocaleString('pt-BR', {minimumFractionDigits: 2})}*`;
      window.open(`https://wa.me/${whatsappAdmin}?text=${encodeURIComponent(msg)}`, '_blank');
  }

  function finalizarPedidoZap() {
      if(carrinho.length === 0) return alert("Carrinho vazio!");
      const estaLogado = false;
      if(!estaLogado) { fecharCarrinho(); abrirCadastroRapido(); } 
      else {
          const fd = new FormData();
          fd.append('id_usuario', clienteID);
          fd.append('itens', carrinho.map(i => `${i.qtd}x ${i.nome}`).join(' | '));
          fd.append('valor_total', carrinho.reduce((acc, i) => acc + (i.preco * i.qtd), 0));
          fetch('processar_pedidos.php', { method: 'POST', body: fd })
          .then(() => {
              enviarPedidoWhatsApp(clienteNome, clienteID);
              location.reload();
          });
      }
  }

  function filtrarCategoria(categoria, btnElement) {
      document.querySelectorAll('.filter-pill').forEach(btn => btn.classList.remove('active'));
      btnElement.classList.add('active');
      document.querySelectorAll('.prod-card').forEach(card => {
          card.style.display = (categoria === 'all' || card.getAttribute('data-category') === categoria) ? 'flex' : 'none';
      });
  }
  function abrirCadastroRapido() { document.getElementById('modalCadastroRapido').style.display = 'flex'; setTimeout(()=>document.getElementById('modalCadastroRapido').classList.add('active'), 10); }
  function fecharCadastroRapido() { document.getElementById('modalCadastroRapido').classList.remove('active'); setTimeout(()=>document.getElementById('modalCadastroRapido').style.display='none', 300); }
</script>
<div class="fab-cart" id="fabCart" onclick="abrirCarrinho()">
    <i class="fas fa-shopping-cart" style="font-size: 1.4rem;"></i>
    <div class="cart-badge" id="cartCount">0</div>
</div>

<div id="modalCarrinho" class="modal-overlay">
    <div class="modal-card">
        <span class="close-btn" onclick="fecharCarrinho()">&times;</span>
        <div class="modal-title"><i class="fas fa-shopping-cart"></i> Seu Carrinho</div>

        <div id="listaItensCarrinho" style="margin-bottom: 20px; max-height: 300px; overflow-y: auto;">
            </div>

        <div style="display: flex; justify-content: space-between; font-weight: 800; font-size: 1.1rem; border-top: 1px solid #e2e8f0; padding-top: 15px;">
            <span>Total:</span>
            <span id="valorTotalCarrinho">R$ 0,00</span>
        </div>

        <button class="btn-checkout" onclick="finalizarPedidoZap()">
            <i class="fab fa-whatsapp"></i> Enviar Pedido
        </button>
    </div>
</div><div id="modalCadastroRapido" class="modal-overlay">
    <div class="modal-card">
        <span class="close-btn" onclick="fecharCadastroRapido()">&times;</span>
        <div class="modal-title">Finalizar Pedido</div>
        <p style="text-align:center; color:#64748b; font-size:0.85rem; margin-bottom:20px;">
            Informe seus dados abaixo para concluirmos seu pedido via WhatsApp.
        </p>
        
        <form id="formCadastroRapido">
            <input type="hidden" name="id_indicacao" value="0">
            <input type="hidden" name="acao" value="cadastro_rapido">

            <div class="input-group">
                <label>Nome Completo</label>
                <input type="text" name="nome" class="input-field" placeholder="Seu nome" required>
            </div>
            <div class="input-group">
                <label>WhatsApp</label>
                <input type="text" name="whatsapp" class="input-field" placeholder="(00) 00000-0000" required>
            </div>
            <div class="input-group">
                <label>E-mail</label>
                <input type="email" name="email" class="input-field" placeholder="seu@email.com" required>
            </div>
            <div class="input-group">
                <label>Crie uma Senha</label>
                <input type="password" name="senha" class="input-field" placeholder="******" required>
            </div>

            <button type="submit" class="btn-checkout" style="background:#4f46e5; margin-top:20px;">
                CADASTRAR E ENVIAR PEDIDO <i class="fas fa-paper-plane"></i>
            </button>
        </form>
    </div>
</div>
</body>
</html>