// catalog.jsx — Supabase'den ürün kataloğu çekme + statik içeriğe (migration
// henüz çalıştırılmamışsa) zarif geri düşüş (fallback).

function parsePriceString(price) {
  const n = parseInt(String(price).replace(/[^\d]/g, ""), 10);
  return isNaN(n) ? 0 : n;
}

function formatPriceTRY(priceKurus) {
  return "₺" + Math.round(priceKurus / 100).toLocaleString("tr-TR");
}

function mapRow(row, lang) {
  const t = (row.product_translations || []).find((x) => x.lang === lang) || {};
  const gallery = (t.gallery && t.gallery.length) ? t.gallery : [{ label: t.label || row.slug, tone: row.tone }];
  return {
    id: row.id,
    slug: row.slug,
    price: formatPriceTRY(row.price_kurus),
    priceKurus: row.price_kurus,
    stock: row.stock,
    tone: row.tone,
    imagePath: row.image_path || null,
    name: t.name || row.slug,
    meta: t.meta || "",
    cat: t.cat || "",
    label: t.label || row.slug,
    tagline: t.tagline || "",
    desc: t.desc || [],
    ingredients: t.ingredients || [],
    usage: t.usage || [],
    storage: t.storage || "",
    highlights: t.highlights || [],
    specs: t.specs || [],
    gallery,
  };
}

// content.jsx / product.jsx'teki statik verinin aynı şekle dönüştürülmüş hali —
// Supabase migration'ları henüz çalıştırılmadıysa veya sorgu başarısız olursa
// site boş kalmasın diye kullanılır.
function staticFallbackCatalog(lang) {
  const items = window.CONTENT[lang].products.items;
  return items.map((it) => {
    const det = (window.DETAILS[it.slug] || window.DETAILS["gul-mayasi-100ml"])[lang];
    return {
      id: it.slug,
      slug: it.slug,
      price: it.price,
      priceKurus: parsePriceString(it.price) * 100,
      stock: 999,
      tone: it.tone,
      imagePath: it.image || null,
      name: it.name,
      meta: it.meta,
      cat: it.cat,
      label: it.label,
      tagline: det.tagline,
      desc: det.desc,
      ingredients: det.ingredients,
      usage: det.usage,
      storage: det.storage,
      highlights: det.highlights,
      specs: det.specs,
      gallery: det.gallery,
    };
  });
}

let rawCatalogPromise = null;
function loadRawCatalog() {
  try {
    return window.sb
      .from("products")
      .select("*, product_translations(*)")
      .eq("active", true)
      .order("sort_order")
      .then(({ data, error }) => {
        if (error || !data || !data.length) throw error || new Error("empty catalog");
        return data;
      });
  } catch (err) {
    return Promise.resolve(null);
  }
}

function fetchCatalog(lang) {
  if (!rawCatalogPromise) {
    rawCatalogPromise = loadRawCatalog().catch((err) => {
      console.warn("Elfinrose: Supabase ürün verisi alınamadı, statik içerik gösteriliyor.", err);
      return null;
    });
  }
  return rawCatalogPromise.then((rows) => (rows ? rows.map((r) => mapRow(r, lang)) : staticFallbackCatalog(lang)));
}

function productImageUrl(imagePath) {
  if (!imagePath) return null;
  // "img/..." ile başlayan yollar sitenin kendi statik görselleridir;
  // Supabase Storage yerine doğrudan servis edilir.
  if (imagePath.startsWith("img/") || imagePath.startsWith("/img/")) return "/" + imagePath.replace(/^\//, "");
  if (!window.sb) return null;
  return window.sb.storage.from("product-photos").getPublicUrl(imagePath).data.publicUrl;
}

Object.assign(window, { fetchCatalog, productImageUrl, formatPriceTRY, parsePriceString });
