// Parse the e-shop's allowed delivery countries from /admin/countries/.
//
// That admin page is an Inertia.js view: the server renders the full props into
// a `<div id="app" data-page="{json}">` attribute (HTML-entity-escaped), so we
// can read it from the raw fetched HTML without running the SPA. The relevant
// slice is component === 'CountriesListing' → props.data.countries = the enabled
// delivery countries, each { id, name, ... } (NO iso — `code` there is the
// currency). We map id → ISO via the global Shoptet country codebook so the
// result is the { iso, id } shape BC stores + routes on.
(function (root) {
  var countryIds = (typeof module !== 'undefined' && module.exports)
    ? require('./shoptet-country-ids.js')
    : (root.NP && root.NP.shoptetCountryIds);

  function htmlUnescape(s) {
    return String(s)
      .replace(/&quot;/g, '"').replace(/&#34;/g, '"')
      .replace(/&#39;/g, "'").replace(/&apos;/g, "'")
      .replace(/&lt;/g, '<').replace(/&gt;/g, '>')
      .replace(/&amp;/g, '&');
  }

  // Extract the Inertia data-page JSON object from a raw HTML string.
  function extractInertiaPage(html) {
    var m = /data-page="([^"]*)"/.exec(String(html || ''));
    if (!m) return null;
    try { return JSON.parse(htmlUnescape(m[1])); }
    catch (e) { return null; }
  }

  // Map a parsed Inertia page object → { countries: [{iso,id}], unmapped: [Name] }.
  // `unmapped` lists enabled countries whose Shoptet id isn't in the codebook map
  // (so onboarding can surface "extend the map" instead of silently dropping a
  // country the operator can ship to).
  function mapPage(page) {
    var out = { countries: [], unmapped: [] };
    if (!page || page.component !== 'CountriesListing') return out;
    var rows = (page.props && page.props.data && page.props.data.countries) || [];
    var resolve = (countryIds && countryIds.isoForCountryId) || function () { return null; };
    for (var i = 0; i < rows.length; i++) {
      var r = rows[i] || {};
      if (r.id == null) continue;
      var iso = resolve(r.id);
      if (iso) out.countries.push({ iso: iso, id: r.id });
      else out.unmapped.push(r.name || String(r.id));
    }
    return out;
  }

  // From a raw HTML string (e.g. a server fetch of /admin/countries/).
  function parseDeliveryCountries(html) {
    return mapPage(extractInertiaPage(html));
  }

  // From the LIVE DOM's `#app` data-page attribute value. getAttribute returns
  // the entity-DECODED string, so JSON.parse works directly; fall back to
  // entity-unescape for a raw (still-escaped) attribute value. This path is the
  // reliable one in BC — a same-origin fetch of the admin SPA route can return
  // the app shell WITHOUT the server-rendered props, whereas the loaded page's
  // #app always carries the current CountriesListing props.
  function parseDeliveryCountriesFromDataPage(dataPage) {
    var s = String(dataPage || '');
    if (!s) return { countries: [], unmapped: [] };
    var page = null;
    try { page = JSON.parse(s); }
    catch (e) { try { page = JSON.parse(htmlUnescape(s)); } catch (e2) { page = null; } }
    return mapPage(page);
  }

  var api = {
    htmlUnescape: htmlUnescape,
    extractInertiaPage: extractInertiaPage,
    parseDeliveryCountries: parseDeliveryCountries,
    parseDeliveryCountriesFromDataPage: parseDeliveryCountriesFromDataPage
  };
  if (typeof module !== 'undefined' && module.exports) module.exports = api;
  else { root.NP = root.NP || {}; root.NP.shoptetDeliveryCountries = api; }
})(typeof self !== 'undefined' ? self : this);
