/* global React */
// Per-service content loader.
//
// This file used to define a static SERVICE_PAGES dictionary inline. It now
// loads the entry for the current service from the CMS database via
// /api/public/content?type=services&slug=... so admin edits in /admin.html
// flow through to the public site without a redeploy.
//
// Public surface (unchanged): window.SERVICE_PAGES[slug] is populated once
// the fetch resolves. Components.jsx reads it via getServiceData() and a new
// useServiceData() hook re-renders when the load completes (via a custom
// event on window).
//
// Backup of the original static data: service-pages.legacy.jsx.bak

(function () {
  if (typeof window === 'undefined') return;
  window.SERVICE_PAGES = window.SERVICE_PAGES || {};

  const slug = window.SERVICE_SLUG;
  if (!slug) return;

  const previewMode = (location.search || '').includes('preview=1');
  const url = '/api/public/content?type=services&slug=' + encodeURIComponent(slug)
              + (previewMode ? '&preview=1' : '');

  fetch(url, { credentials: 'include' })
    .then((r) => r.json())
    .then(({ item }) => {
      if (!item) return;
      // Reshape flat DB row → nested SERVICE_PAGES entry expected by components.
      window.SERVICE_PAGES[slug] = {
        tag: (item.discipline_slug || '').toUpperCase(),
        expert: item.expert_slug || '',
        illustration: item.illustration_url || item.hero_image_url || '',
        illustrationScale: item.illustration_scale != null ? Number(item.illustration_scale) : 1,
        hero: { title: item.hero_title || '', lead: item.hero_subtitle || '' },
        wstep: item.wstep && Object.keys(item.wstep).length
          ? item.wstep
          : { label: '', headline: '', body: '' },
        zalety: item.zalety && Object.keys(item.zalety).length
          ? item.zalety
          : { label: '', items: [] },
        coObejmuje: item.co_obejmuje && Object.keys(item.co_obejmuje).length
          ? item.co_obejmuje
          : { headline: '', body: '', sections: [] },
        jakPomoze: item.jak_pomoze && Object.keys(item.jak_pomoze).length
          ? item.jak_pomoze
          : { headline: '', items: [] },
        duration_label: item.duration_label || '',
        faqs: Array.isArray(item.faqs) ? item.faqs : []
      };
      try { window.dispatchEvent(new CustomEvent('luna-service-loaded', { detail: { slug } })); } catch (_) {}
    })
    .catch((err) => { console.error('[service-pages] load failed', err); });
})();
