/* عذبة — تحسينات المتجر وحاسبة المقاس */
(function () {
  'use strict';

  var SIZES = [
    [140, 150, '48'],
    [150, 156, '52'],
    [156, 161, '54'],
    [161, 166, '56'],
    [166, 172, '58'],
    [172, 196, '60']
  ];
  var MIN = 140, MAX = 195;
  var CSS = '.azf-box{margin:16px 0;padding:16px;border:1px solid rgba(0,0,0,.10);border-radius:14px;background:rgba(0,0,0,.02);direction:rtl;text-align:right}'
    + '.azf-box *{box-sizing:border-box}'
    + '.azf-t{font-weight:700;margin:0 0 4px;font-size:15px}'
    + '.azf-s{margin:0 0 12px;font-size:13px;opacity:.7}'
    + '.azf-row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}'
    + '.azf-box input{flex:1 1 140px;min-width:120px;padding:11px 14px;border:1px solid rgba(0,0,0,.18);border-radius:10px;font-size:15px;background:#fff;color:#111;text-align:right}'
    + '.azf-box input:focus{outline:none;border-color:currentColor}'
    + '.azf-unit{font-size:13px;opacity:.6}'
    + '.azf-out{margin-top:12px;font-size:15px;line-height:1.8;min-height:24px}'
    + '.azf-size{display:inline-block;font-weight:800;font-size:20px;padding:2px 12px;border-radius:8px;background:rgba(0,0,0,.06)}'
    + '.azf-warn{font-size:14px;opacity:.8}';

  function isProductPage() {
    return /\/p\d+(?:[\/?#]|$)/.test(location.pathname);
  }

  function injectCss() {
    if (document.getElementById('azf-style')) return;
    var style = document.createElement('style');
    style.id = 'azf-style';
    style.textContent = CSS;
    document.head.appendChild(style);
  }

  function calc(height) {
    for (var i = 0; i < SIZES.length; i++) {
      if (height >= SIZES[i][0] && height < SIZES[i][1]) return SIZES[i][2];
    }
    return null;
  }

  function render(input, output) {
    var raw = (input.value || '').trim();
    if (raw === '') { output.innerHTML = ''; return; }
    var height = parseFloat(raw);
    if (isNaN(height)) { output.innerHTML = ''; return; }
    if (height < MIN || height > MAX) {
      output.innerHTML = '<span class="azf-warn">تواصلي معنا واتساب ونساعدك تختارين مقاسك</span>';
      return;
    }
    var size = calc(height);
    output.innerHTML = size
      ? 'مقاسك المناسب: <span class="azf-size">' + size + '</span>'
      : '<span class="azf-warn">تواصلي معنا واتساب ونساعدك تختارين مقاسك</span>';
  }

  function buildBox() {
    var box = document.createElement('div');
    box.className = 'azf-box';
    box.id = 'azf-box';
    box.innerHTML = '<p class="azf-t">حاسبة المقاس الفورية</p>'
      + '<p class="azf-s">اكتبي طولك بالسنتيمتر ونطلع لك المقاس المناسب فورا.</p>'
      + '<div class="azf-row"><input id="azfH" type="number" inputmode="numeric" min="140" max="195" autocomplete="off" tabindex="-1" placeholder="مثال: 165" aria-label="طولك بالسنتيمتر"><span class="azf-unit">سم</span></div>'
      + '<div class="azf-out" id="azfOut"></div>';
    var input = box.querySelector('#azfH');
    var output = box.querySelector('#azfOut');
    input.addEventListener('input', function () { render(input, output); });
    input.addEventListener('change', function () { render(input, output); });
    return box;
  }

  function mountCalculator() {
    if (!isProductPage()) return;
    var holder = document.querySelector('.sticky-product-bar');
    if (!holder || !holder.parentNode) return;
    injectCss();
    var box = document.getElementById('azf-box') || buildBox();
    if (holder.nextElementSibling !== box) holder.parentNode.insertBefore(box, holder.nextSibling);
    var input = box.querySelector('#azfH');
    if (input) {
      input.setAttribute('autocomplete', 'off');
      input.setAttribute('tabindex', '-1');
      input.removeAttribute('autofocus');
    }
  }

  function updateHomeTrust() {
    if (location.pathname !== '/' && location.pathname !== '') return;
    var headings = document.querySelectorAll('h2');
    for (var i = 0; i < headings.length; i++) {
      var heading = headings[i];
      var title = (heading.textContent || '').trim();
      if (title === 'توصيل سريع ومجاني') {
        heading.textContent = 'تفصيل حسب الطلب وشحن مجاني';
        if (heading.nextElementSibling) heading.nextElementSibling.textContent = 'نُفصّل عبايتكِ على مقاسكِ بعناية، ثم تُشحن لكِ مجانًا لجميع مدن المملكة.';
      }
      if (title === 'دعم فني على مدار الساعة') {
        heading.textContent = 'دعم عبر واتساب';
        if (heading.nextElementSibling) heading.nextElementSibling.textContent = 'يسعدنا الرد على استفساراتكِ ومساعدتكِ قبل وبعد الطلب.';
      }
    }
  }

  var autoTopAllowed = true;
  var guardedProductPath = '';
  var topGuardTimer = null;

  function stopAutoTop() {
    autoTopAllowed = false;
    if (topGuardTimer) clearInterval(topGuardTimer);
  }

  function openProductAtTop() {
    if (!autoTopAllowed || !isProductPage()) return;
    if ('scrollRestoration' in history) history.scrollRestoration = 'manual';
    var input = document.getElementById('azfH');
    if (input && document.activeElement === input) input.blur();
    document.documentElement.scrollTop = 0;
    document.body.scrollTop = 0;
    window.scrollTo(0, 0);
  }

  function startProductTopGuard() {
    if (!isProductPage()) return;
    if (guardedProductPath === location.pathname && topGuardTimer) return;
    guardedProductPath = location.pathname;
    autoTopAllowed = true;
    if (topGuardTimer) clearInterval(topGuardTimer);
    openProductAtTop();
    var startedAt = Date.now();
    topGuardTimer = setInterval(function () {
      openProductAtTop();
      if (!autoTopAllowed || Date.now() - startedAt >= 5000) {
        clearInterval(topGuardTimer);
        topGuardTimer = null;
      }
    }, 120);
  }

  function updatePromotionText() {
    var links = document.querySelectorAll('a[aria-label="Promotion Text"]');
    for (var i = 0; i < links.length; i++) {
      links[i].textContent = 'الشحن مجاني على جميع العبايات';
    }
  }

  function resumeRahafAtTop() {
    if (!/\/p1542860484(?:[\/?#]|$)/.test(location.pathname)) return;
    guardedProductPath = '';
    autoTopAllowed = true;
    if (topGuardTimer) {
      clearInterval(topGuardTimer);
      topGuardTimer = null;
    }
    setTimeout(startProductTopGuard, 0);
  }

  function reorderFooterLinks() {
    var columns = document.querySelectorAll('[data-selia="footer-links-column"]');
    var desired = ['من نحن', 'الأسئلة الشائعة', 'سياسة الطلب', 'سياسة الاستبدال والاسترجاع', 'تعليمات الغسيل والكوي'];
    for (var i = 0; i < columns.length; i++) {
      var heading = columns[i].querySelector('h3');
      if (!heading || (heading.textContent || '').trim() !== 'روابط مهمة') continue;
      var list = columns[i].querySelector('ul');
      if (!list) return;
      var items = Array.prototype.slice.call(list.children);
      var current = items.map(function (item) { return (item.textContent || '').trim(); });
      if (current.join('|') === desired.join('|')) return;
      for (var j = 0; j < desired.length; j++) {
        for (var k = 0; k < items.length; k++) {
          if ((items[k].textContent || '').trim() === desired[j]) list.appendChild(items[k]);
        }
      }
      return;
    }
  }

  function init() {
    mountCalculator();
    updateHomeTrust();
    updatePromotionText();
    reorderFooterLinks();
    startProductTopGuard();
  }

  ['touchstart', 'pointerdown', 'wheel', 'keydown'].forEach(function (eventName) {
    window.addEventListener(eventName, stopAutoTop, { once: true, passive: true });
  });

  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);
  else init();

  var tries = 0;
  var timer = setInterval(function () {
    init();
    tries += 1;
    if (tries >= 30) clearInterval(timer);
  }, 500);

  var observerTimer = null;
  new MutationObserver(function () {
    clearTimeout(observerTimer);
    observerTimer = setTimeout(init, 80);
  }).observe(document.documentElement, { childList: true, subtree: true });

  window.addEventListener('pageshow', function () {
    guardedProductPath = '';
    requestAnimationFrame(startProductTopGuard);
  });
  window.addEventListener('popstate', function () {
    guardedProductPath = '';
    setTimeout(init, 0);
  });
  document.addEventListener('visibilitychange', function () {
    if (!document.hidden) resumeRahafAtTop();
  });
  window.addEventListener('focus', resumeRahafAtTop);
})();