// Shared loader: fetches /api/listings once, caches the promise, and enriches
// each listing with fields the gallery + Germany map expect.
(function () {
  let promise = null;

  function fmtSince(iso) {
    if (!iso) return '—';
    const d = new Date(iso);
    if (isNaN(d)) return '—';
    return d.toLocaleDateString('de-DE', { month: 'short', year: 'numeric' });
  }

  const EN_TO_CODE = {
    'Bavaria': 'BY', 'Lower Saxony': 'NI', 'North Rhine-Westphalia': 'NW',
    'Rhineland-Palatinate': 'RP', 'Saxony': 'SN', 'Hesse': 'HE',
    'Thuringia': 'TH', 'Mecklenburg-Western Pomerania': 'MV',
    'Schleswig-Holstein': 'SH', 'Saxony-Anhalt': 'ST', 'Brandenburg': 'BB',
    'Baden-Württemberg': 'BW', 'Berlin': 'BE', 'Hamburg': 'HH',
    'Bremen': 'HB', 'Saarland': 'SL',
  };

  function regionToCode(region) {
    const map = window.BL_NAME_TO_CODE || {};
    if (region && map[region]) return map[region];
    if (region && EN_TO_CODE[region]) return EN_TO_CODE[region];
    return '';
  }

  window.RBListings = {
    load() {
      if (promise) return promise;
      promise = fetch('/api/listings', { credentials: 'same-origin' })
        .then(r => (r.ok ? r.json() : { listings: [] }))
        .then(d => {
          const listings = (d.listings || []).map(l => ({
            ...l,
            bundesland: regionToCode(l.region),
            since: fmtSince(l.onlineSince),
            capacity: l.accommodates,
            tags: l.amenities || [],
          }));
          const counts = {};
          listings.forEach(l => {
            if (l.bundesland) counts[l.bundesland] = (counts[l.bundesland] || 0) + 1;
          });
          const max = Math.max(1, ...Object.values(counts));
          const heat = {};
          Object.keys(counts).forEach(c => { heat[c] = counts[c] / max; });
          return { listings, heat, count: listings.length };
        })
        .catch(() => ({ listings: [], heat: {}, count: 0 }));
      return promise;
    },
  };
})();
