// Live data layer — products, variants, and reviews come from Supabase.

const CATEGORIES = [
  { id: 'all', name: 'All' },
  { id: 'streaming', name: 'Streaming' },
  { id: 'gaming', name: 'Gaming' },
  { id: 'productivity', name: 'Productivity' },
  { id: 'social', name: 'Social' },
  { id: 'boosts', name: 'Boosts' },
];

const CRYPTOS = [
  { id: 'sol', symbol: 'SOL', name: 'Solana', rate: 142.08, network: 'Solana', conf: 1, color: '#9945ff' },
];

// Mutable globals — refreshed from Supabase.
let PRODUCTS = [];
let REVIEWS = [];

async function loadStore() {
  const [pRes, vRes, rRes] = await Promise.all([
    sb.from('products').select('*').order('sort_order', { ascending: true }),
    sb.from('product_variants').select('*').order('sort_order', { ascending: true }),
    sb.from('reviews').select('*').order('created_at', { ascending: false }),
  ]);
  if (pRes.error) throw pRes.error;
  if (vRes.error) throw vRes.error;
  if (rRes.error) throw rRes.error;

  const variantsByProduct = {};
  for (const v of vRes.data) {
    (variantsByProduct[v.product_id] ||= []).push({
      id: v.id, label: v.label, price: Number(v.price), inStock: v.in_stock, badge: v.badge || undefined,
    });
  }
  PRODUCTS = pRes.data.map(p => ({
    id: p.id,
    name: p.name,
    tagline: p.tagline || '',
    category: p.category,
    tile: p.tile || 'tile-cloud',
    glyph: p.glyph || '•',
    glyphColor: p.glyph_color || '#a87bff',
    priceFrom: Number(p.price_from),
    rating: Number(p.rating),
    reviewCount: p.review_count,
    stock: p.stock,
    delivery: p.delivery || '',
    description: p.description || '',
    imageUrl: p.image_url || null,
    reviewsByStar: { 5: p.reviews_5 || 0, 4: p.reviews_4 || 0, 3: p.reviews_3 || 0, 2: p.reviews_2 || 0, 1: p.reviews_1 || 0 },
    variants: variantsByProduct[p.id] || [],
  }));
  REVIEWS = rRes.data.map(r => ({
    id: r.id, product: r.product_id, user: r.username, rating: r.rating, verified: r.verified,
    ago: r.ago || 'recent', text: r.body, variant: r.variant || '', hasMedia: r.has_media,
  }));
  window.PRODUCTS = PRODUCTS;
  window.REVIEWS = REVIEWS;
}

function ProductTile({ product, size = 'md' }) {
  const h = size === 'lg' ? 'h-48' : size === 'sm' ? 'h-20' : 'h-32';
  const fs = size === 'lg' ? 'text-7xl' : size === 'sm' ? 'text-3xl' : 'text-5xl';
  if (product.imageUrl) {
    return (
      <div className={`relative ${h} w-full rounded-xl overflow-hidden hairline`} style={{ background: '#0c0c14' }}>
        <img src={product.imageUrl} alt={product.name} className="absolute inset-0 w-full h-full object-cover" />
        <div className="absolute bottom-2 left-2.5 right-2.5 flex items-center justify-between">
          <div className="text-[10px] mono uppercase tracking-widest text-white/80" style={{ textShadow: '0 1px 2px rgba(0,0,0,0.6)' }}>{product.name}</div>
        </div>
      </div>
    );
  }
  return (
    <div className={`relative ${h} w-full ${product.tile} rounded-xl overflow-hidden hairline flex items-center justify-center`}>
      <div className="absolute inset-0 opacity-40"
        style={{ backgroundImage: 'radial-gradient(circle at 80% 20%, rgba(255,255,255,0.12), transparent 40%)' }} />
      <div className="absolute inset-0 grid-bg opacity-40" />
      <div className={`glyph ${fs}`} style={{ color: product.glyphColor, textShadow: `0 0 40px ${product.glyphColor}55` }}>
        {product.glyph}
      </div>
      <div className="absolute bottom-2 left-2.5 right-2.5 flex items-center justify-between">
        <div className="text-[10px] mono uppercase tracking-widest text-white/50">{product.name}</div>
      </div>
    </div>
  );
}

// Small square thumbnail — image if uploaded, otherwise glyph tile. Used in cart, checkout, history rows.
function ProductThumb({ product, size = 48, rounded = 'rounded-md', glyphClass = 'text-2xl' }) {
  const style = { width: size, height: size };
  if (product.imageUrl) {
    return (
      <div className={`${rounded} hairline overflow-hidden shrink-0 relative`} style={{ ...style, background: '#0c0c14' }}>
        <img src={product.imageUrl} alt={product.name} className="absolute inset-0 w-full h-full object-cover" />
      </div>
    );
  }
  return (
    <div
      className={`${rounded} ${product.tile} hairline flex items-center justify-center glyph ${glyphClass} shrink-0`}
      style={{ ...style, color: product.glyphColor }}
    >
      {product.glyph}
    </div>
  );
}

Object.assign(window, { CATEGORIES, CRYPTOS, ProductTile, ProductThumb, loadStore, PRODUCTS, REVIEWS });
