// data.jsx — boot-time loader. Replaces the previous PRNG-driven mock.
// On `loadDashboardData()` we fetch /api/dashboard and populate the window
// globals every other JSX file expects. If the API is down or returns
// garbage, the loader rejects — index boot renders a BootError component.
//
// Globals populated:
//   window.CATEGORIES     [{id, label}]   only categories with >=1 item
//   window.CONDITIONS     [{id, label, desc, priceMult}]   4 grades (A+ A B C)
//   window.MODELS         [{id, cat, brand, name, ..., variants, axisOptions, defaultVariantId}]
//   window.VARIANTS       flat list of priced variants
//   window.MODELS_BY_ID, window.VARIANT_BY_ID
//   window.ALPHA_DATA_SOURCE  'api'

(function () {
  function applyDashboardData(payload) {
    if (!payload || !Array.isArray(payload.models) || !Array.isArray(payload.variants)) {
      throw new Error('Invalid dashboard payload');
    }
    window.CATEGORIES = payload.categories || [];
    window.CONDITIONS = payload.conditions || [];
    window.MODELS = payload.models;
    window.VARIANTS = payload.variants;
    window.MODELS_BY_ID = Object.fromEntries(window.MODELS.map(m => [m.id, m]));
    window.VARIANT_BY_ID = Object.fromEntries(window.VARIANTS.map(v => [v.id, v]));
  }

  window.loadDashboardData = async function loadDashboardData() {
    const response = await fetch('/api/dashboard', { cache: 'no-store', credentials: 'include' });
    if (!response.ok) throw new Error(`API /api/dashboard returned ${response.status}`);
    const payload = await response.json();
    applyDashboardData(payload);
    window.ALPHA_DATA_SOURCE = 'api';
  };

  // Auth probe: returns the current user dict or null.
  window.fetchCurrentUser = async function fetchCurrentUser() {
    const response = await fetch('/api/v2/auth/me', { credentials: 'include' });
    if (!response.ok) return null;
    const body = await response.json();
    return body && body.user ? body.user : null;
  };

  window.logoutCurrentUser = async function logoutCurrentUser() {
    await fetch('/api/v2/auth/logout', { method: 'POST', credentials: 'include' });
    window.location.href = '/login.html';
  };
})();
