// Sexy Geek — helpers compartilhados entre páginas (sem bundler: carregado como script Babel-
// standalone em toda página, antes do .jsx da própria página). Namespace global `window.SG`.
window.SG = (function () {
  const TOKEN_KEY = 'sg_token';
  const USER_KEY = 'sg_user';
  const ADMIN_TOKEN_KEY = 'sg_admin_token';
  const ADMIN_KEY = 'sg_admin_user';

  function safeLS(fn, fallback) {
    try { return fn(); } catch { return fallback; }
  }

  function getToken() { return safeLS(() => localStorage.getItem(TOKEN_KEY), null); }
  function setSession(token, user) {
    safeLS(() => { localStorage.setItem(TOKEN_KEY, token); localStorage.setItem(USER_KEY, JSON.stringify(user)); });
  }
  function getUser() { return safeLS(() => JSON.parse(localStorage.getItem(USER_KEY) || 'null'), null); }
  function clearSession() { safeLS(() => { localStorage.removeItem(TOKEN_KEY); localStorage.removeItem(USER_KEY); }); }

  function getAdminToken() { return safeLS(() => localStorage.getItem(ADMIN_TOKEN_KEY), null); }
  function setAdminSession(token, admin) {
    safeLS(() => { localStorage.setItem(ADMIN_TOKEN_KEY, token); localStorage.setItem(ADMIN_KEY, JSON.stringify(admin)); });
  }
  function getAdmin() { return safeLS(() => JSON.parse(localStorage.getItem(ADMIN_KEY) || 'null'), null); }
  function clearAdminSession() { safeLS(() => { localStorage.removeItem(ADMIN_TOKEN_KEY); localStorage.removeItem(ADMIN_KEY); }); }

  // fetch wrapper — `auth:true` manda o Bearer de usuário, `admin:true` manda o de admin.
  async function api(path, { method = 'GET', body, auth = false, admin = false, formData = false } = {}) {
    const headers = {};
    const token = admin ? getAdminToken() : (auth ? getToken() : null);
    if (token) headers['Authorization'] = `Bearer ${token}`;
    let payload = body;
    if (body && !formData) {
      headers['Content-Type'] = 'application/json';
      payload = JSON.stringify(body);
    }
    const res = await fetch(path, { method, headers, body: payload });
    let data = null;
    try { data = await res.json(); } catch { /* resposta vazia */ }
    if (!res.ok) throw new Error((data && data.error) || `Erro ${res.status}`);
    return data;
  }

  function money(cents) {
    return ((cents || 0) / 100).toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
  }

  function fmtDate(iso) {
    if (!iso) return '';
    try { return new Date(iso).toLocaleDateString('pt-BR'); } catch { return ''; }
  }

  function fmtCard(v) { return v.replace(/\D/g, '').slice(0, 16).replace(/(\d{4})(?=\d)/g, '$1 '); }
  function fmtExpiry(v) { const d = v.replace(/\D/g, '').slice(0, 4); return d.length > 2 ? d.slice(0, 2) + '/' + d.slice(2) : d; }
  function fmtPhone(v) { const d = v.replace(/\D/g, '').slice(0, 11); if (d.length <= 2) return d; if (d.length <= 7) return `(${d.slice(0, 2)}) ${d.slice(2)}`; return `(${d.slice(0, 2)}) ${d.slice(2, 7)}-${d.slice(7)}`; }
  function fmtCpf(v) { const d = v.replace(/\D/g, '').slice(0, 11); if (d.length <= 3) return d; if (d.length <= 6) return `${d.slice(0, 3)}.${d.slice(3)}`; if (d.length <= 9) return `${d.slice(0, 3)}.${d.slice(3, 6)}.${d.slice(6)}`; return `${d.slice(0, 3)}.${d.slice(3, 6)}.${d.slice(6, 9)}-${d.slice(9)}`; }
  function validCpf(v) { return v.replace(/\D/g, '').length === 11; }

  // Captura UTM/gclid/gbraid/wbraid na 1ª visita e persiste na sessão do navegador — sobrevive
  // entre landing → checkout sem precisar de query string em cada passo.
  function getAttribution() {
    const stored = safeLS(() => JSON.parse(sessionStorage.getItem('sg_attribution') || 'null'), null);
    if (stored) return stored;
    const params = new URLSearchParams(window.location.search);
    const keys = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term', 'gclid', 'gbraid', 'wbraid'];
    const out = {};
    for (const k of keys) { const v = params.get(k); if (v) out[k] = v; }
    safeLS(() => sessionStorage.setItem('sg_attribution', JSON.stringify(out)));
    return out;
  }

  function navTo(path) { window.location.href = path; }

  return {
    getToken, setSession, getUser, clearSession,
    getAdminToken, setAdminSession, getAdmin, clearAdminSession,
    api, money, fmtDate, fmtCard, fmtExpiry, fmtPhone, fmtCpf, validCpf,
    getAttribution, navTo,
  };
})();
