// Product service — Firebase compat wrappers as window globals

const _col = () => window.db.collection('products');

window.fetchFeatured = () =>
  _col()
    .where('featured', '==', true)
    .where('active', '==', true)
    .get()
    .then(snap => snap.docs.map(d => ({ id: d.id, ...d.data() })));

window.fetchTrending = () =>
  _col()
    .where('trending', '==', true)
    .where('active', '==', true)
    .get()
    .then(snap => snap.docs.map(d => ({ id: d.id, ...d.data() })));

window.fetchByCategory = (categoryName) =>
  _col()
    .where('category', '==', categoryName)
    .where('active', '==', true)
    .get()
    .then(snap => snap.docs.map(d => ({ id: d.id, ...d.data() })));

window.fetchOffers = () =>
  _col()
    .where('active', '==', true)
    .get()
    .then(snap =>
      snap.docs
        .map(d => ({ id: d.id, ...d.data() }))
        .filter(p => p.oldPrice && Number(p.oldPrice) > 0)
    );

window.fetchBrands = () =>
  _col()
    .where('active', '==', true)
    .get()
    .then(snap => {
      const brands = new Set();
      snap.docs.forEach(d => { const b = d.data().brand; if (b) brands.add(b); });
      return [...brands].sort();
    });

window.fetchByBrand = (brandName) =>
  _col()
    .where('brand', '==', brandName)
    .where('active', '==', true)
    .get()
    .then(snap => snap.docs.map(d => ({ id: d.id, ...d.data() })));
