// ============================================================================
// data.jsx — Supabase-backed product catalog
//
// On script load:
//   1. Create Supabase client from window.SUPABASE_CONFIG
//   2. Set window.PRODUCTS = []  (initial, before fetch completes)
//   3. Fetch products + categories from Supabase
//   4. Map rows to the shape the site components expect
//   5. Dispatch "products-loaded" event so App can re-render
// ============================================================================

// ─── Fallback imagery (used until you upload real photos via dashboard) ─────
const FALLBACK_IMG = (id, w = 900) =>
  `https://images.unsplash.com/photo-${id}?auto=format&fit=crop&w=${w}&q=80`;

const FALLBACK_IMAGES = [
  FALLBACK_IMG("1628595351029-c2bf17511435"), // amber vials
  FALLBACK_IMG("1582719188393-bb71ca45dbb9"), // clear vials
  FALLBACK_IMG("1576091160550-2173dba999ef"), // pills white
  FALLBACK_IMG("1614935151651-0bea6508db6b"), // pills minimal
  FALLBACK_IMG("1576086213369-97a306d36557"), // pipette
  FALLBACK_IMG("1581595220892-b0739db3ba8c"), // pipetting research
  FALLBACK_IMG("1554475901-4538ddfbccc2"),    // clean test tubes
  FALLBACK_IMG("1587854692152-cbe660dbde88"), // pharmacy shelves
];

// Backward-compat global (some code still reads window.SHOTS)
window.SHOTS = {
  vialsAmber:   FALLBACK_IMAGES[0],
  vialsClear:   FALLBACK_IMAGES[1],
  pillsWhite:   FALLBACK_IMAGES[2],
  pillsMinimal: FALLBACK_IMAGES[3],
  pipette:     FALLBACK_IMAGES[4],
  pipette2:    FALLBACK_IMAGES[5],
  cleanTubes:  FALLBACK_IMAGES[6],
  pharmacy:    FALLBACK_IMAGES[7],
  labWide:     FALLBACK_IMG("1532187863486-abf9dbad1b69", 1600),
  labWoman:    FALLBACK_IMG("1582719471384-894fbb16e074", 1200),
  molecule:    FALLBACK_IMG("1631549916768-4119b2e5f926", 1200),
  dna:         FALLBACK_IMG("1559757175-7b21bdcd1eee"),
};

// ─── Initialize Supabase client ─────────────────────────────────────────────
const { createClient } = window.supabase;
const SB = createClient(
  window.SUPABASE_CONFIG.url,
  window.SUPABASE_CONFIG.anonKey,
  { auth: { persistSession: false } }
);
window.sb = SB;  // expose for debugging in browser console

// Initial empty array — populated by loadProducts()
window.PRODUCTS = [];
window.PRODUCTS_STATE = "loading";  // "loading" | "ready" | "error"

// ─── Map Supabase row → site product shape ──────────────────────────────────
function mapProduct(row, idx) {
  // product_categories is a join array: [{ categories: { slug, name_en, name_ro } }]
  const cats = (row.product_categories || [])
    .map(pc => pc.categories?.name_en)
    .filter(Boolean);

  // Cheap "badge" logic until you set is_featured on real products
  let badge = null;
  if (row.is_featured) badge = "Featured";
  else if (cats.includes("GLP-1 & Weight")) badge = "Popular";

  return {
    id:           row.id,
    code:         row.sku || row.slug.toUpperCase(),
    slug:         row.slug,
    name:         row.name,
    shortName:    row.name,
    displayName:  row.display_name,
    category:     cats[0] || "Research",
    categories:   cats,
    dose:         row.dosage_mg ? `${row.dosage_mg} mg` : "",
    price:        Number(row.price_ron) || 0,
    currency:     row.currency || "RON",
    badge,
    blurb:        row.short_description ||
                  `${row.name} ${row.dosage_mg ? row.dosage_mg + "mg " : ""}lyophilized peptide for laboratory research.`,
    description:    row.description || null,
    mechanism:      row.mechanism_summary || null,
    researchAreas:  row.research_areas || [],
    scientificName: row.scientific_name || null,
    purity:       row.hplc_purity ? `${row.hplc_purity}%` : "≥99%",
    form:         "Lyophilized powder",
    storage:      "−20°C",
    grade:        "Research",
    sequence:     row.amino_acid_sequence || null,
    cas:          row.cas_number || null,
    formula:      row.molecular_formula || null,
    mw:           row.molecular_weight || null,
    image:        row.primary_image_url || FALLBACK_IMAGES[idx % FALLBACK_IMAGES.length],
    isActive:     row.is_active,
    isFeatured:   row.is_featured,
    stock:        row.stock || 0,
  };
}

// ─── Fetch products from Supabase ───────────────────────────────────────────
async function loadProducts() {
  try {
    const { data, error } = await SB
      .from("products")
      .select(`
        *,
        product_categories (
          categories ( slug, name_en, name_ro )
        )
      `)
      .eq("is_active", true)
      .order("is_featured", { ascending: false })
      .order("created_at", { ascending: true });

    if (error) throw error;

    window.PRODUCTS = (data || []).map(mapProduct);
    window.PRODUCTS_STATE = "ready";
    console.log(`[data] Loaded ${window.PRODUCTS.length} products from Supabase`);
    window.dispatchEvent(new CustomEvent("products-loaded", {
      detail: { count: window.PRODUCTS.length }
    }));
  } catch (e) {
    window.PRODUCTS_STATE = "error";
    window.PRODUCTS_ERROR = e?.message || String(e);
    console.error("[data] Failed to load products from Supabase:", e);
    window.dispatchEvent(new CustomEvent("products-error", { detail: e }));
  }
}

// Kick off the fetch — App will listen for "products-loaded"
loadProducts();
