// ============================================================
// FIRM OFFERS — shared data layer for Apex / Tradeify promo
// ------------------------------------------------------------
// Single source of truth, loaded from Supabase (table firm_offers
// + firm_promo). Falls back to hardcoded data if the DB is empty
// or unreachable, so the site never breaks.
//
// Consumed by:
//   • page-shop.jsx        → upload catalog + coin estimate
//   • page-propfirms.jsx   → challenges list + discount label
//   • page-admin.jsx       → Apex Promo / Tradeify Promo editors
//
// Canonical shape returned by fetchFirmOffers():
//   {
//     apex:     { discountLabel, accounts: [{ accountType, size, price, originalPrice, sortOrder, active }] },
//     tradeify: { discountLabel, accounts: [...] },
//   }
// ============================================================

const FIRM_OFFERS_FALLBACK = {
  apex: {
    discountLabel: 'până la 80% OFF',
    accounts: [
      { accountType: 'EOD',      size: '25K',  price: 34.90, originalPrice: 349.00, sortOrder: 1, active: true },
      { accountType: 'EOD',      size: '50K',  price: 39.90, originalPrice: 399.00, sortOrder: 2, active: true },
      { accountType: 'EOD',      size: '100K', price: 59.90, originalPrice: 599.00, sortOrder: 3, active: true },
      { accountType: 'EOD',      size: '150K', price: 89.90, originalPrice: 899.00, sortOrder: 4, active: true },
      { accountType: 'Intraday', size: '25K',  price: 24.90, originalPrice: 249.00, sortOrder: 5, active: true },
      { accountType: 'Intraday', size: '50K',  price: 29.90, originalPrice: 299.00, sortOrder: 6, active: true },
      { accountType: 'Intraday', size: '100K', price: 44.90, originalPrice: 449.00, sortOrder: 7, active: true },
      { accountType: 'Intraday', size: '150K', price: 69.90, originalPrice: 699.00, sortOrder: 8, active: true },
      // No Activation Fee variants (prețuri promo, fără preț original)
      { accountType: 'EOD (No Activation Fee)', size: '25K',  price: 89.00,  originalPrice: null, sortOrder: 9,  active: true },
      { accountType: 'EOD (No Activation Fee)', size: '50K',  price: 109.00, originalPrice: null, sortOrder: 10, active: true },
      { accountType: 'EOD (No Activation Fee)', size: '100K', price: 139.00, originalPrice: null, sortOrder: 11, active: true },
      { accountType: 'EOD (No Activation Fee)', size: '150K', price: 229.00, originalPrice: null, sortOrder: 12, active: true },
      { accountType: 'Intraday (No Activation Fee)', size: '25K',  price: 69.00,  originalPrice: null, sortOrder: 13, active: true },
      { accountType: 'Intraday (No Activation Fee)', size: '50K',  price: 79.00,  originalPrice: null, sortOrder: 14, active: true },
      { accountType: 'Intraday (No Activation Fee)', size: '100K', price: 109.00, originalPrice: null, sortOrder: 15, active: true },
      { accountType: 'Intraday (No Activation Fee)', size: '150K', price: 169.00, originalPrice: null, sortOrder: 16, active: true },
    ],
  },
  tradeify: {
    discountLabel: '40% OFF',
    accounts: [
      { accountType: 'Growth Plan',      size: '25K',  price: 59.40,  originalPrice: 99.00,  sortOrder: 1,  active: true },
      { accountType: 'Growth Plan',      size: '50K',  price: 99.00,  originalPrice: 165.00, sortOrder: 20, active: true },
      { accountType: 'Growth Plan',      size: '100K', price: 159.00, originalPrice: 265.00, sortOrder: 21, active: true },
      { accountType: 'Growth Plan',      size: '150K', price: 221.40, originalPrice: 369.00, sortOrder: 22, active: true },
      { accountType: 'Select Daily',     size: '25K',  price: 65.40,  originalPrice: 109.00, sortOrder: 2,  active: true },
      { accountType: 'Select Daily',     size: '50K',  price: 99.00,  originalPrice: 165.00, sortOrder: 3,  active: true },
      { accountType: 'Select Daily',     size: '100K', price: 159.00, originalPrice: 265.00, sortOrder: 4,  active: true },
      { accountType: 'Select Daily',     size: '150K', price: 221.40, originalPrice: 369.00, sortOrder: 5,  active: true },
      { accountType: 'Select Flex',      size: '25K',  price: 65.40,  originalPrice: 109.00, sortOrder: 6,  active: true },
      { accountType: 'Select Flex',      size: '50K',  price: 99.00,  originalPrice: 165.00, sortOrder: 7,  active: true },
      { accountType: 'Select Flex',      size: '100K', price: 159.00, originalPrice: 265.00, sortOrder: 8,  active: true },
      { accountType: 'Select Flex',      size: '150K', price: 221.40, originalPrice: 369.00, sortOrder: 9,  active: true },
      { accountType: 'Lightning Funded', size: '25K',  price: 203.40, originalPrice: 339.00, sortOrder: 10, active: true },
      { accountType: 'Lightning Funded', size: '50K',  price: 281.40, originalPrice: 469.00, sortOrder: 11, active: true },
      { accountType: 'Lightning Funded', size: '100K', price: 413.40, originalPrice: 689.00, sortOrder: 12, active: true },
      { accountType: 'Lightning Funded', size: '150K', price: 477.60, originalPrice: 796.00, sortOrder: 13, active: true },
    ],
  },
};

let _firmOffersCache = null;

// Fetch offers from DB, merge over the fallback. Cached after first call.
// Pass { force: true } to bypass cache (used after admin edits).
async function fetchFirmOffers(opts = {}) {
  if (_firmOffersCache && !opts.force) return _firmOffersCache;
  // Default to a deep-ish clone of the fallback
  const result = {
    apex:     { discountLabel: FIRM_OFFERS_FALLBACK.apex.discountLabel,     accounts: [] },
    tradeify: { discountLabel: FIRM_OFFERS_FALLBACK.tradeify.discountLabel, accounts: [] },
  };

  if (!window.sb) {
    _firmOffersCache = {
      apex:     { ...FIRM_OFFERS_FALLBACK.apex },
      tradeify: { ...FIRM_OFFERS_FALLBACK.tradeify },
    };
    return _firmOffersCache;
  }

  try {
    const [offersRes, promoRes] = await Promise.all([
      window.sb.from('firm_offers').select('*').order('sort_order', { ascending: true }),
      window.sb.from('firm_promo').select('*'),
    ]);

    const offers = offersRes.data || [];
    const promos = promoRes.data || [];

    if (offers.length === 0) {
      // DB empty → use full fallback
      _firmOffersCache = {
        apex:     { ...FIRM_OFFERS_FALLBACK.apex },
        tradeify: { ...FIRM_OFFERS_FALLBACK.tradeify },
      };
      return _firmOffersCache;
    }

    for (const firm of ['apex', 'tradeify']) {
      result[firm].accounts = offers
        .filter(o => o.firm === firm)
        .map(o => ({
          id: o.id,
          accountType: o.account_type,
          size: o.size,
          price: Number(o.price),
          originalPrice: o.original_price != null ? Number(o.original_price) : null,
          sortOrder: o.sort_order,
          active: o.active,
        }));
      const promo = promos.find(p => p.firm === firm);
      if (promo && promo.discount_label) result[firm].discountLabel = promo.discount_label;
    }

    _firmOffersCache = result;
    return result;
  } catch (e) {
    console.warn('[firm-offers] fetch failed, using fallback:', e);
    _firmOffersCache = {
      apex:     { ...FIRM_OFFERS_FALLBACK.apex },
      tradeify: { ...FIRM_OFFERS_FALLBACK.tradeify },
    };
    return _firmOffersCache;
  }
}

// Invalidate cache (call after admin edits)
function invalidateFirmOffers() { _firmOffersCache = null; }

// ---- Derived shapes -------------------------------------------------------

// Group a firm's accounts by accountType → shop catalog "types"
function offersToShopTypes(firmOffers) {
  const byType = {};
  const order = [];
  for (const a of (firmOffers.accounts || [])) {
    if (a.active === false) continue;
    if (!byType[a.accountType]) {
      byType[a.accountType] = { id: a.accountType.toLowerCase().replace(/\s+/g, '-'), label: a.accountType, sizes: [] };
      order.push(a.accountType);
    }
    byType[a.accountType].sizes.push({ size: a.size, price: a.price });
  }
  return order.map(t => byType[t]);
}

// Build the propfirms pricingMatrix sections from offers.
// Each account_type becomes its own section (heading + sizes + one price row).
function offersToMatrix(firm, firmOffers) {
  const byType = {};
  const order = [];
  for (const a of (firmOffers.accounts || [])) {
    if (a.active === false) continue;
    if (!byType[a.accountType]) { byType[a.accountType] = []; order.push(a.accountType); }
    byType[a.accountType].push(a);
  }
  return order.map((type) => {
    const accts = byType[type].slice().sort((x, y) => (x.sortOrder || 0) - (y.sortOrder || 0));
    let heading = type;
    if (firm === 'apex') {
      // 'EOD' → 'EOD Trailing Drawdown', keep '(No Activation Fee)' suffix
      heading = type
        .replace('EOD', 'EOD Trailing Drawdown')
        .replace('Intraday', 'Intraday Trailing Drawdown');
    }
    const rowLabel = type.toLowerCase().includes('lightning') ? 'Instant' : 'Evaluation';
    return {
      heading,
      sizes: accts.map(a => a.size),
      rows: [{
        type: rowLabel,
        cells: accts.map(a => ({
          old: a.originalPrice != null ? `$${a.originalPrice.toFixed(2)}` : null,
          current: `$${a.price.toFixed(2)}`,
        })),
      }],
    };
  });
}

// Format a firm's accounts as propfirms "challenges" list
function offersToChallenges(firm, firmOffers) {
  const prefix = firm === 'apex' ? 'Apex ' : '';
  return (firmOffers.accounts || [])
    .filter(a => a.active !== false)
    .map(a => ({
      name: `${prefix}${a.accountType} — ${a.size}`,
      price: `$${a.price.toFixed(2)}`,
      originalPrice: a.originalPrice != null ? `$${a.originalPrice.toFixed(2)}` : null,
    }));
}

Object.assign(window, {
  FIRM_OFFERS_FALLBACK,
  fetchFirmOffers,
  invalidateFirmOffers,
  offersToShopTypes,
  offersToChallenges,
  offersToMatrix,
});
