// Parse Shoptet orders-list table row and order detail page HTML.
(function (root) {
  var C = typeof module !== 'undefined' && module.exports
    ? require('../constants.js')
    : (root.NP && root.NP.constants);

  function parseOrderRow(tr, opts) {
    opts = opts || {};
    var shippingBranchId = opts.shippingBranchId || '';
    var shippingAddressId = opts.shippingAddressId || '';

    var checkbox = tr.querySelector('input[type="checkbox"][name^="orderId"]');
    var codeEl = tr.querySelector('[data-testid="orderCode"]');
    var deliveryEl = tr.querySelector('[data-testid="orderRowDeliveryType"]');
    var detailLink = tr.querySelector('a.table__detailLink');

    if (!checkbox || !codeEl) return null;

    var orderId = checkbox.value;
    var orderCode = codeEl.textContent.trim();
    var deliveryType = deliveryEl ? deliveryEl.textContent.trim() : '';
    var detailUrl = detailLink ? detailLink.getAttribute('href') : '';

    var nameEl = tr.querySelector('[data-testid="tableOrderRow"]');
    var recipientName = nameEl ? nameEl.textContent.trim() : '';

    var isNovaPost = false;
    var npDeliveryType = '';
    for (var i = 0; i < C.NOVA_POST_KEYWORDS.length; i++) {
      if (deliveryType.toLowerCase().indexOf(C.NOVA_POST_KEYWORDS[i]) !== -1) {
        isNovaPost = true;
        break;
      }
    }
    if (!isNovaPost) {
      var shippingIdEl = tr.querySelector('input[name^="shippingId"]') || tr.querySelector('[data-shipping-id]');
      var rowShippingId = shippingIdEl ? (shippingIdEl.value || shippingIdEl.getAttribute('data-shipping-id') || '') : '';
      if (shippingBranchId && rowShippingId === shippingBranchId) {
        isNovaPost = true;
        npDeliveryType = 'branch';
      } else if (shippingAddressId && rowShippingId === shippingAddressId) {
        isNovaPost = true;
        npDeliveryType = 'address';
      }
    }

    return {
      orderId: orderId,
      orderCode: orderCode,
      deliveryType: deliveryType,
      detailUrl: detailUrl,
      isNovaPost: isNovaPost,
      npDeliveryType: npDeliveryType,
      recipientName: recipientName,
      tr: tr
    };
  }

  // Extract shipment-relevant fields from a parsed order detail Document.
  function parseOrderDetail(doc) {
    var result = {
      recipientName: '',
      recipientPhone: '',
      recipientEmail: '',
      recipientAddress: '',
      branchId: '',
      branchName: '',
      remark: '',
      codAmount: 0
    };

    var customerContact = doc.getElementById('customer-contact');
    if (customerContact) {
      var nameLink = customerContact.querySelector('a[href*="zakaznici-detail"]');
      if (nameLink) result.recipientName = nameLink.textContent.trim();
    }
    if (!result.recipientName) {
      var clipName = doc.querySelector('#customer-contact [data-clipboard]');
      if (clipName) result.recipientName = clipName.getAttribute('data-clipboard').trim();
    }

    var phoneEl = doc.querySelector('[data-testid="customerPhone"] a[href^="tel:"]');
    if (phoneEl) result.recipientPhone = phoneEl.getAttribute('href').replace('tel:', '').trim();

    var emailEl = doc.querySelector('[data-testid="customerEmail"] a[href^="mailto:"]');
    if (emailEl) result.recipientEmail = emailEl.getAttribute('href').replace('mailto:', '').trim();

    var shippingTd = doc.getElementById('shipping-address');
    if (shippingTd) {
      var sameAs = shippingTd.querySelector('[data-testid="textSameShippingAddress"]');
      if (sameAs) {
        var billingClip = doc.querySelector('#billing-address [data-testid="billingAddress"]');
        if (billingClip) result.recipientAddress = billingClip.getAttribute('data-clipboard').trim();
      } else {
        var shippingClip = shippingTd.querySelector('[data-clipboard]');
        if (shippingClip) result.recipientAddress = shippingClip.getAttribute('data-clipboard').trim();
      }
    }
    if (!result.recipientAddress) {
      var billingClip2 = doc.querySelector('[data-testid="billingAddress"]');
      if (billingClip2) result.recipientAddress = billingClip2.getAttribute('data-clipboard').trim();
    }

    var allText = doc.body ? doc.body.textContent : '';
    var branchMatch = allText.match(C.NP_BRANCH_RE);
    if (branchMatch) result.branchId = branchMatch[1];
    var remarkMatch = allText.match(C.NP_REMARK_RE);
    if (remarkMatch) result.branchName = remarkMatch[1].trim();

    if (result.branchId && result.branchName) {
      result.recipientAddress = result.branchName;
    }

    var priceEls = doc.querySelectorAll('td, .order-price');
    for (var k = 0; k < priceEls.length; k++) {
      var txt = priceEls[k].textContent;
      if (txt.indexOf('Dobierkou') !== -1 || txt.indexOf('dobierka') !== -1) {
        var priceMatch = txt.match(/(\d+[.,]\d+)\s*€/);
        if (priceMatch) result.codAmount = parseFloat(priceMatch[1].replace(',', '.'));
      }
    }

    return result;
  }

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