// data.jsx — loads bilingual content + products from /api/data.php
// Falls back to defaults if API is unreachable, so the page always renders.

const I18N_DEFAULTS = {
  ar: {
    dir: "rtl",
    nav: { home: "الرئيسية", shop: "المتجر", about: "من نحن", contact: "تواصل معنا", search: "بحث", wishlist: "المفضلة", menu: "القائمة" },
    announce: ["شحن مجاني للطلبات فوق ٧٥٬٠٠٠ د.ع"],
    hero: { eyebrow: "مجموعة ربيع ٢٠٢٦", title: "الأناقة\nبتفاصيل ناعمة", sub: "قطع مختارة بعناية لتعكس أنوثتك بكل بساطة.", cta: "اكتشفي المجموعة", ctaAlt: "العروض" },
    sections: { newest: "أحدث الموديلات", newestSub: "وصل حديثاً", bestsellers: "الأكثر مبيعاً", bestsellersSub: "اختيارات بناتنا", shopBy: "تسوقي حسب الفئة", lookbook: "من إنستغرام", lookbookSub: "@hallo.banat", newsletter: "انضمي إلى عائلتنا", newsletterSub: "احصلي على ١٠٪ خصم على أول طلب", newsletterPh: "بريدك الإلكتروني", subscribe: "اشتراك", viewAll: "عرض الكل", featured: "بنر مميز" },
    product: { addToCart: "اطلبي عبر واتساب", buyNow: "اشتري الآن", size: "المقاس", color: "اللون", desc: "الوصف", details: "تفاصيل المنتج", shipping: "الشحن والإرجاع", similar: "قد يعجبك أيضاً", addedWish: "أضيفت للمفضلة", sizeGuide: "دليل المقاسات", sku: "الرمز", price: "السعر" },
    shop: { title: "المتجر", sub: "كل القطع — مرتبة حسب الأحدث", filter: "تصفية", sort: "ترتيب", categories: "الفئات", all: "الكل", results: "منتج", sortNew: "الأحدث", sortPriceLow: "السعر: من الأقل", sortPriceHigh: "السعر: من الأعلى", sortPopular: "الأكثر شعبية", empty: "لا توجد منتجات في هذه الفئة", clear: "مسح الفلاتر" },
    about: { eyebrow: "قصتنا", title: "أناقة بسيطة\nبروح أنثوية", p1: "هلو بنات ولدت من شغف بالأزياء التي تحتفي بالأنوثة دون مبالغة.", p2: "نؤمن بأن الأناقة الحقيقية في البساطة.", values: [{t:"أنثوي",d:"تفاصيل ناعمة"},{t:"محتشم",d:"تصاميم راقية"},{t:"عصري",d:"ستايل عصري"}], visionTitle: "رؤيتنا", vision: "أن نكون الوجهة الأولى لكل بنت تبحث عن قطعة بسيطة، أنيقة، ومحتشمة." },
    contact: { title: "تواصلي معنا", sub: "نسعد بخدمتك في أي وقت", whatsapp: "واتساب", whatsappDesc: "تواصل مباشر", whatsappCta: "افتحي محادثة", ig: "إنستغرام", igDesc: "تابعي جديدنا", igCta: "زيارة الحساب", email: "البريد الإلكتروني", emailDesc: "للاستفسارات", hoursTitle: "ساعات العمل", hours: ["السبت — الخميس: ١٠:٠٠ ص — ١٠:٠٠ م"] },
    footer: { tagline: "أزياء نسائية أنيقة ومحتشمة", shop: "تسوقي", help: "المساعدة", follow: "تابعينا", rights: "جميع الحقوق محفوظة © هلو بنات ٢٠٢٦", links: { size: "دليل المقاسات", shipping: "الشحن", returns: "الإرجاع", faq: "الأسئلة الشائعة" } },
  },
  en: {
    dir: "ltr",
    nav: { home: "Home", shop: "Shop", about: "About", contact: "Contact", search: "Search", wishlist: "Wishlist", menu: "Menu" },
    announce: ["Free shipping on orders over 75,000 IQD"],
    hero: { eyebrow: "Spring 2026 Collection", title: "Elegance\nin soft details", sub: "Carefully curated pieces that reflect your femininity, simply.", cta: "Discover collection", ctaAlt: "Sale" },
    sections: { newest: "Newest arrivals", newestSub: "Just landed", bestsellers: "Bestsellers", bestsellersSub: "Loved by our girls", shopBy: "Shop by category", lookbook: "From Instagram", lookbookSub: "@hallo.banat", newsletter: "Join our family", newsletterSub: "Get 10% off your first order", newsletterPh: "Your email", subscribe: "Subscribe", viewAll: "View all", featured: "Featured banner" },
    product: { addToCart: "Order via WhatsApp", buyNow: "Buy now", size: "Size", color: "Color", desc: "Description", details: "Product details", shipping: "Shipping & returns", similar: "You may also like", addedWish: "Added to wishlist", sizeGuide: "Size guide", sku: "SKU", price: "Price" },
    shop: { title: "Shop", sub: "All pieces — sorted by newest", filter: "Filter", sort: "Sort", categories: "Categories", all: "All", results: "items", sortNew: "Newest", sortPriceLow: "Price: low to high", sortPriceHigh: "Price: high to low", sortPopular: "Most popular", empty: "No products in this category", clear: "Clear filters" },
    about: { eyebrow: "Our story", title: "Simple elegance\nwith a feminine soul", p1: "Hillo Banat was born from a passion for fashion that celebrates femininity without excess.", p2: "We believe true elegance lies in simplicity.", values: [{t:"Feminine",d:"Soft details"},{t:"Modest",d:"Refined designs"},{t:"Modern",d:"Modern style"}], visionTitle: "Our vision", vision: "To be the first destination for every girl looking for a simple, elegant, modest piece." },
    contact: { title: "Get in touch", sub: "We're happy to help anytime", whatsapp: "WhatsApp", whatsappDesc: "Direct chat", whatsappCta: "Open chat", ig: "Instagram", igDesc: "Follow our daily updates", igCta: "Visit profile", email: "Email", emailDesc: "For inquiries", hoursTitle: "Working hours", hours: ["Sat — Thu: 10:00 AM — 10:00 PM"] },
    footer: { tagline: "Elegant & modest women's fashion", shop: "Shop", help: "Help", follow: "Follow", rights: "All rights reserved © Hillo Banat 2026", links: { size: "Size guide", shipping: "Shipping", returns: "Returns", faq: "FAQ" } },
  },
};

// Initial empty placeholders — replaced by API data
window.I18N = JSON.parse(JSON.stringify(I18N_DEFAULTS));
window.CATEGORIES = [];
window.PRODUCTS = [];
window.LOOKBOOK = [];
window.IMG = { hero1: '', hero2: '', hero3: '', p: [] };
window.SITE_SETTINGS = {};
window.BANNERS = {};
window.CONTENT = {};

// Loader (called from app.jsx on mount)
window.loadSiteData = async function() {
  try {
    const r = await fetch('/api/data.php');
    if (!r.ok) throw new Error('API fail');
    const d = await r.json();

    window.SITE_SETTINGS = d.settings || {};
    window.BANNERS = d.banners || {};
    window.CONTENT = d.content || {};

    // Categories — keep API shape compatible with frontend ({id: slug, ar, en, img})
    window.CATEGORIES = (d.categories || []).map(c => ({
      id: c.slug,
      ar: c.name_ar,
      en: c.name_en,
      img: c.image || '',
    }));

    // Products
    window.PRODUCTS = d.products || [];

    // Lookbook
    window.LOOKBOOK = (d.lookbook || []).map(l => l.image);

    // Hero images from banners
    const heroImg = d.banners?.hero?.image || '';
    const featImg = d.banners?.featured?.image || '';
    window.IMG = {
      hero1: heroImg || (window.PRODUCTS[0]?.cover ?? ''),
      hero2: window.PRODUCTS[1]?.cover ?? heroImg,
      hero3: featImg || heroImg,
      p: window.PRODUCTS.map(p => p.cover).filter(Boolean),
    };

    // Announcements → I18N
    const anns = d.announcements || [];
    if (anns.length) {
      window.I18N.ar.announce = anns.map(a => a.text_ar).filter(Boolean);
      window.I18N.en.announce = anns.map(a => a.text_en).filter(Boolean);
    }

    // Content overrides
    const c = d.content || {};
    const apply = (lang) => {
      const t = window.I18N[lang]; const k = lang === 'ar' ? 'ar' : 'en';
      if (c.hero_eyebrow?.[k]) t.hero.eyebrow = c.hero_eyebrow[k];
      if (c.hero_title?.[k]) t.hero.title = c.hero_title[k];
      if (c.hero_sub?.[k]) t.hero.sub = c.hero_sub[k];
      if (c.hero_cta?.[k]) t.hero.cta = c.hero_cta[k];
      if (c.about_p1?.[k]) t.about.p1 = c.about_p1[k];
      if (c.about_p2?.[k]) t.about.p2 = c.about_p2[k];
      if (c.about_vision?.[k]) t.about.vision = c.about_vision[k];
      if (c.footer_tagline?.[k]) t.footer.tagline = c.footer_tagline[k];
    };
    apply('ar'); apply('en');

    // Hours
    if (d.settings?.hours_ar) window.I18N.ar.contact.hours = d.settings.hours_ar.split('\n').filter(Boolean);
    if (d.settings?.hours_en) window.I18N.en.contact.hours = d.settings.hours_en.split('\n').filter(Boolean);

    // Currency / WhatsApp number → expose globally
    window.WA_NUMBER = (d.settings?.whatsapp_number || '9647700000000').replace(/[^0-9]/g, '');
    window.IG_HANDLE = d.settings?.instagram_handle || 'hallo.banat';

    // CSS color overrides
    const root = document.documentElement.style;
    if (d.settings?.color_ink) root.setProperty('--ink', d.settings.color_ink);
    if (d.settings?.color_bone) root.setProperty('--bone', d.settings.color_bone);
    if (d.settings?.color_cream) root.setProperty('--cream', d.settings.color_cream);
    if (d.settings?.color_beige) root.setProperty('--beige', d.settings.color_beige);

    return d;
  } catch (e) {
    console.error('Site data load failed', e);
    return null;
  }
};
