// data.jsx — loads product catalog, reviews, FAQ, blog from API

let PRODUCTS = [];
let REVIEWS_BY_BRAND = {};
let FAQ = [];
let BLOG_POSTS = [];
let CATEGORIES = [];

function mapProduct(p) {
  const stockMap = { in_stock: 'in', low_stock: 'low', out_of_stock: 'out' };
  let tag = null, tagLabel = null;
  if (p.is_featured) { tag = 'best'; tagLabel = 'Top Seller'; }
  else if (p.is_sale) { tag = 'sale'; tagLabel = 'Sale'; }
  else if (p.is_new) { tag = 'new'; tagLabel = 'New ✱'; }
  else if (p.stock_status === 'low_stock') { tag = 'low'; tagLabel = 'Low Stock'; }
  else if (p.stock_status === 'out_of_stock') { tag = 'out'; tagLabel = 'Restocks Friday'; }

  return {
    id: p.id,
    sku: p.sku,
    name: p.name,
    brand: p.brand_name,
    brand_slug: p.brand_slug,
    slug: p.slug,
    blend: p.blend.replace('_', ' ').replace(/\b\w/g, c => c.toUpperCase()),
    strength: p.strength,
    price: parseFloat(p.price),
    packPrice: p.pack_price != null ? parseFloat(p.pack_price) : parseFloat(p.price) / (p.packs_per_carton || 10),
    count: p.total_sticks || (p.sticks_per_pack || 20) * (p.packs_per_carton || 10),
    packs: p.packs_per_carton || 10,
    perPack: p.sticks_per_pack || 20,
    size: (p.format || 'Carton') + ' · ' + (p.size || 'King'),
    tar: p.tar_mg + 'mg',
    nicotine: p.nicotine_mg + 'mg',
    stock: stockMap[p.stock_status] || 'in',
    tag, tagLabel,
    oldPrice: p.compare_at_price ? parseFloat(p.compare_at_price) : null,
    blurb: p.blurb || p.short_desc || '',
    image_url: p.image_url || null,
    category: p.category_slug || null,
    categoryName: p.category_name || null,
  };
}

async function loadData() {
  try {
    const [prodRes, faqRes, blogRes, reviewRes, catRes] = await Promise.all([
      api.get('/products?limit=100'),
      api.get('/faq'),
      api.get('/blog?limit=20'),
      api.get('/reviews?limit=100'),
      api.get('/categories').catch(() => ({ categories: [] })),
    ]);

    PRODUCTS = (prodRes.products || []).map(mapProduct);

    // Product-type categories (Cigarettes, Nicotine Pouches, …) for the nav.
    // Only surface categories that actually have products so the menu stays clean.
    CATEGORIES = (catRes.categories || []).filter(c => Number(c.product_count) > 0);

    FAQ = (faqRes.items || []).map(f => ({ q: f.question, a: f.answer, id: f.id }));

    const months = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'];
    BLOG_POSTS = (blogRes.posts || []).map(p => {
      const d = p.published_at ? new Date(p.published_at) : new Date();
      const date = `${months[d.getMonth()]} ${String(d.getDate()).padStart(2,'0')} · ${d.getFullYear()}`;
      return {
        slug: p.slug,
        title: p.title,
        deck: p.deck,
        body: typeof p.body === 'string' ? JSON.parse(p.body) : p.body,
        thumbKind: p.thumbnail_kind || 'price',
        cat: p.category_name || 'Field notes',
        catColor: p.category_color || 'acid',
        categorySlug: p.category_slug,
        author: p.author_name || 'Mad Smokes',
        authorRole: p.author_role || 'Editorial',
        readTime: p.read_time_min ? `${p.read_time_min} min read` : '5 min read',
        date,
        publishedAt: p.published_at,
        tags: p.tags || [],
      };
    });

    // Build reviews grouped by brand
    const byBrand = {};
    for (const r of (reviewRes.reviews || [])) {
      const brand = r.brand_name;
      if (!byBrand[brand]) byBrand[brand] = [];
      const months = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'];
      const d = new Date(r.created_at);
      const when = months[d.getMonth()] + ' ' + d.getFullYear();
      byBrand[brand].push({
        who: r.author_name,
        when,
        stars: r.rating,
        title: r.title,
        body: r.body,
      });
    }
    REVIEWS_BY_BRAND = byBrand;
  } catch (err) {
    console.warn('Data load from API failed, using empty defaults:', err.message);
  }

  window.PRODUCTS = PRODUCTS;
  window.REVIEWS_BY_BRAND = REVIEWS_BY_BRAND;
  window.FAQ = FAQ;
  window.BLOG_POSTS = BLOG_POSTS;
  window.CATEGORIES = CATEGORIES;
}

window.PRODUCTS = PRODUCTS;
window.REVIEWS_BY_BRAND = REVIEWS_BY_BRAND;
window.FAQ = FAQ;
window.BLOG_POSTS = BLOG_POSTS;
window.CATEGORIES = CATEGORIES;
window.loadData = loadData;
