/* ============================================================
   LF CONCEITO — dados base da loja
   Fallback quando Supabase não está disponível
   ============================================================ */

const CATEGORIES = [
  { slug: "tenis",      name: "Tênis",      subs: ["Masculino", "Feminino", "Lançamentos"] },
  { slug: "camisetas",  name: "Camisetas",  subs: ["Oversize", "Malha", "Polo"] },
  { slug: "calcas",     name: "Calças",     subs: ["Jeans", "Cargo", "Jogger"] },
  { slug: "conjuntos",  name: "Conjuntos",  subs: ["Moletom", "Verão"] },
  { slug: "bermudas",   name: "Bermudas",   subs: ["Jeans", "Tactel"] },
  { slug: "moletom",    name: "Moletom",    subs: ["Capuz", "Careca"] },
  { slug: "jaquetas",   name: "Jaquetas",   subs: ["Couro", "Corta-vento"] },
  { slug: "acessorios", name: "Acessórios", subs: ["Bonés", "Meias", "Óculos", "Relógio"] },
  { slug: "perfumes",   name: "Perfumes",   subs: ["Masculino", "Feminino", "Unissex"] },
];

function P(o){
  return Object.assign({
    compareAt: 0, tag: "", colors: ["Preto"], featured: false,
    sizes: ["P","M","G","GG"], stock: 8, active: true,
  }, o);
}

const PRODUCTS = []; // fallback vazio — Supabase sempre carrega os dados reais

const STATUSES = ["Pendente","Pago","Enviado","Entregue","Cancelado"];

/* ============================================================
   INICIALIZAÇÃO — Supabase primeiro, dados locais como fallback
   ============================================================ */
async function initStore() {
  if (!window._sb) {
    console.warn("Supabase indisponível — usando dados locais");
    window.STORE_READY = true;
    window.dispatchEvent(new Event("store-ready"));
    return;
  }

  // Esperar window.DB estar disponível (Babel processa scripts de forma assíncrona)
  let attempts = 0;
  while (!window.DB && attempts < 20) {
    await new Promise(r => setTimeout(r, 100));
    attempts++;
  }

  if (!window.DB) {
    console.warn("window.DB não disponível após aguardar");
    window.STORE_READY = true;
    window.dispatchEvent(new Event("store-ready"));
    return;
  }

  try {
    const fetchAll = window.DB.fetchAllProducts || window.DB.fetchProducts;
    const [prods, cats] = await Promise.all([
      fetchAll(),
      window.DB.fetchCategories(),
    ]);
    window.PRODUCTS_LIVE = prods || [];
    window.CATEGORIES_LIVE = cats && cats.length > 0 ? cats : null;
  } catch(e) {
    console.warn("Supabase init error:", e.message);
  }

  window.STORE_READY = true;
  window.dispatchEvent(new Event("store-ready"));
}

if (document.readyState === "loading") {
  document.addEventListener("DOMContentLoaded", initStore);
} else {
  initStore();
}
