// Scan Shoptet shipping methods page for Nova Post entries.
//
// URL + per-row link path differ across admin locales:
//   - SK / EN: /admin/billing-and-shipping/ → rows link to /admin/shipping-detail/?id=N
//   - CZ:      /admin/zpusoby-dopravy/      → rows link to /admin/doprava-detail/?id=N
//
// We scope the search to the formShippingMethods form (a stable data-testid
// across locales) and accept any link with `?id=N` inside it — which is the
// row's editor link regardless of how Shoptet localized the path.
(function (root) {
  function detectShippingIdsInDom() {
    var scope = document.querySelector('[data-testid="formShippingMethods"]')
      || document.querySelector('table.checkbox-table')
      || document;
    var links = scope.querySelectorAll('a[href*="?id="]');
    var found = { branch: null, address: null };

    for (var i = 0; i < links.length; i++) {
      var text = links[i].textContent.trim().toLowerCase();
      var href = links[i].getAttribute('href') || '';
      var idMatch = href.match(/[?&]id=(\d+)/);
      if (!idMatch) continue;
      var id = idMatch[1];

      if (text.indexOf('nova post') === -1) continue;

      if (text.indexOf('branch') !== -1 || text.indexOf('pobočk') !== -1
          || text.indexOf('pobock') !== -1 || text.indexOf('výdajn') !== -1) {
        found.branch = { id: id, name: links[i].textContent.trim() };
      } else if (text.indexOf('address') !== -1 || text.indexOf('adres') !== -1) {
        found.address = { id: id, name: links[i].textContent.trim() };
      } else if (!found.branch) {
        // First Nova Post entry without qualifier → assume branch.
        found.branch = { id: id, name: links[i].textContent.trim() };
      }
    }
    return found;
  }

  var DETECT_SHIPPING_IDS_SRC = '(' + detectShippingIdsInDom.toString() + ')()';

  var api = {
    detectShippingIdsInDom: detectShippingIdsInDom,
    DETECT_SHIPPING_IDS_SRC: DETECT_SHIPPING_IDS_SRC
  };
  if (typeof module !== 'undefined' && module.exports) module.exports = api;
  else { root.NP = root.NP || {}; root.NP.shoptetShippingIds = api; }
})(typeof self !== 'undefined' ? self : this);
