// ============================================
// ستيلارا — ملف التسويق النفسي (نسخة نهائية منقحة)
// ============================================

(function () {
  'use strict';

  var StellaraState = {
    timers: {},
    observers: {},
    stylesInjected: false
  };

  var OFFERS = [
    {
      title: '✨ عرض لفترة محدودة',
      text: 'خصم 20% على طلبك باستخدام الكود',
      code: 'SB20'
    },
    {
      title: '&#127775; عرض حصري لك',
      text: 'خصم 150 ريال عند الشراء بـ 550 ريال',
      code: 'SB2026'
    }
  ];

  var BLOCK_DURATION_SECONDS = 6 * 60 * 60;
  var RETRY_INTERVAL = 350;
  var RETRY_MAX_ATTEMPTS = 25;

  var OFFER_TITLE_ALIGN = 'center';
  var OFFER_TITLE_PADDING_RIGHT = '0px';

  function nextFrame(callback) {
    if (typeof window.requestAnimationFrame === 'function') {
      window.requestAnimationFrame(callback);
    } else {
      setTimeout(callback, 16);
    }
  }

  function injectStylesOnce() {
    if (StellaraState.stylesInjected) return;
    if (document.getElementById('stellara-psychology-styles')) {
      StellaraState.stylesInjected = true;
      return;
    }

    var style = document.createElement('style');
    style.id = 'stellara-psychology-styles';
    style.textContent = [
      '.stellara-card {',
      '  background: linear-gradient(135deg, #1a1a1a, #2d2d2d);',
      '  border: 1px solid #c9a96e;',
      '  border-radius: 10px;',
      '  padding: 9px 14px;',
      '  text-align: center;',
      '  margin: 12px auto;',
      '  font-family: Tajawal, sans-serif;',
      '  direction: rtl;',
      '}',
      '.stellara-offer-title {',
      '  color: #c9a96e;',
      '  font-size: 15px;',
      '  font-weight: 700;',
      '  line-height: 1.4;',
      '  margin: 0 0 3px;',
      '  text-align: ' + OFFER_TITLE_ALIGN + ';',
      '  padding-right: ' + (OFFER_TITLE_ALIGN === 'right' ? OFFER_TITLE_PADDING_RIGHT : '0') + ';',
      '}',
      '.stellara-offer-text {',
      '  color: #fff;',
      '  font-size: 11px;',
      '  line-height: 1.5;',
      '  margin: 0 0 5px;',
      '}',
      '.stellara-offer-timer {',
      '  color: #d97a7a;',
      '  font-size: 11px;',
      '  line-height: 1.4;',
      '  margin: 0 0 6px;',
      '  font-weight: 600;',
      '}',
      '.stellara-code-btn {',
      '  background: #fff;',
      '  color: #1a1a1a;',
      '  font-size: 14px;',
      '  font-weight: 700;',
      '  letter-spacing: 3px;',
      '  padding: 5px 14px;',
      '  border-radius: 6px;',
      '  display: inline-block;',
      '  border: 1.5px dashed #c9a96e;',
      '  cursor: pointer;',
      '  transition: all 0.3s;',
      '  font-family: Tajawal, sans-serif;',
      '  direction: ltr;',
      '  unicode-bidi: isolate;',
      '  user-select: none;',
      '  -webkit-user-select: none;',
      '  -webkit-touch-callout: none;',
      '  -webkit-tap-highlight-color: transparent;',
      '  touch-action: manipulation;',
      '}',
      '.stellara-code-btn:focus { outline: none; }',
      '.stellara-code-btn[disabled] { opacity: 0.85; cursor: default; }',
      '.stellara-offer-note {',
      '  color: #aaa;',
      '  font-size: 11px;',
      '  line-height: 1.4;',
      '  margin: 4px 0 0;',
      '}',
      '.stellara-savings {',
      '  background: rgba(201, 169, 110, 0.08);',
      '  border: 1px solid rgba(201, 169, 110, 0.2);',
      '  border-radius: 8px;',
      '  padding: 6px 12px;',
      '  text-align: center;',
      '  margin: 8px 0 10px;',
      '  font-family: Tajawal, sans-serif;',
      '  direction: rtl;',
      '}',
      '.stellara-savings p { color: #555; font-size: 13px; font-weight: 500; margin: 0; }',
      '.stellara-savings strong { color: #1a1a1a; font-size: 14px; font-weight: 700; }',
      '.stellara-delivery {',
      '  display: flex;',
      '  align-items: center;',
      '  gap: 6px;',
      '  margin: 8px 0;',
      '  font-family: Tajawal, sans-serif;',
      '  font-size: 13px;',
      '  color: #555;',
      '  direction: rtl;',
      '}'
    ].join('\n');

    document.head.appendChild(style);
    StellaraState.stylesInjected = true;
  }

  function isCartPage() {
    return window.location.pathname.indexOf('/cart') !== -1;
  }

  function isHomepage() {
    var path = window.location.pathname;
    return path === '/' || path === '/ar/' || path === '/ar';
  }

  function isProductPage() {
    var path = window.location.pathname;
    return /\/p\d+/.test(path) || path.indexOf('/product') !== -1;
  }

  function clearTimer(key) {
    if (StellaraState.timers[key]) {
      clearInterval(StellaraState.timers[key]);
      delete StellaraState.timers[key];
    }
  }

  function disconnectObserver(key) {
    if (StellaraState.observers[key]) {
      StellaraState.observers[key].disconnect();
      delete StellaraState.observers[key];
    }
  }

  function retryUntilFound(fn, options) {
    var attempts = 0;
    var maxAttempts = (options && options.maxAttempts) || RETRY_MAX_ATTEMPTS;
    var interval = (options && options.interval) || RETRY_INTERVAL;

    function run() {
      attempts += 1;
      var done = false;
      try {
        done = !!fn();
      } catch (err) {
        console.error('[Stellara JS] خطأ:', err);
        done = true;
      }
      if (done) return;
      if (attempts < maxAttempts) setTimeout(run, interval);
    }

    run();
  }

  function formatCountdown(seconds) {
    var h = Math.floor(seconds / 3600);
    var m = Math.floor((seconds % 3600) / 60);
    var s = seconds % 60;
    return (
      (h < 10 ? '0' + h : String(h)) + ':' +
      (m < 10 ? '0' + m : String(m)) + ':' +
      (s < 10 ? '0' + s : String(s))
    );
  }

  function getCurrentOffer() {
    var now = new Date();
    var secondsToday = now.getHours() * 3600 + now.getMinutes() * 60 + now.getSeconds();
    var index = Math.floor(secondsToday / BLOCK_DURATION_SECONDS) % OFFERS.length;
    var secondsLeft = BLOCK_DURATION_SECONDS - (secondsToday % BLOCK_DURATION_SECONDS);
    return { offer: OFFERS[index], secondsLeft: secondsLeft, index: index };
  }

  function parseArabicOrEnglishNumber(text) {
    if (!text) return 0;
    var normalized = String(text)
      .replace(/[٠-٩]/g, function (d) {
        return '٠١٢٣٤٥٦٧٨٩'.indexOf(d);
      })
      .replace(/,/g, '')
      .replace(/[^\d.-]/g, '');
    var value = parseFloat(normalized);
    return isNaN(value) ? 0 : value;
  }

  function formatCurrencyAmount(value) {
    var num = Math.round(value * 100) / 100;
    if (num % 1 === 0) return String(num);
    return num.toFixed(2);
  }

  function setNativeInputValue(input, value) {
    if (!input) return;
    var prototype = window.HTMLInputElement && window.HTMLInputElement.prototype;
    var descriptor = prototype && Object.getOwnPropertyDescriptor(prototype, 'value');
    if (descriptor && typeof descriptor.set === 'function') {
      descriptor.set.call(input, value);
    } else {
      input.value = value;
    }
  }

  function copyTextSync(text) {
    var cleanText = String(text || '').trim();
    if (!cleanText) return false;

    var input = document.createElement('input');
    input.type = 'text';
    input.value = cleanText;
    input.setAttribute('readonly', 'readonly');
    input.setAttribute('aria-hidden', 'true');
    input.setAttribute('autocomplete', 'off');
    input.setAttribute('autocorrect', 'off');
    input.setAttribute('autocapitalize', 'off');
    input.setAttribute('spellcheck', 'false');
    input.style.cssText = [
      'position:fixed',
      'top:0',
      'left:0',
      'width:2em',
      'height:2em',
      'opacity:0.01',
      'pointer-events:none',
      'z-index:-1',
      'font-size:16px',
      'border:0',
      'padding:0',
      'margin:0',
      'background:transparent'
    ].join(';');

    document.body.appendChild(input);

    var success = false;
    try {
      try {
        input.focus({ preventScroll: true });
      } catch (focusErr) {
        input.focus();
      }
      input.select();
      input.setSelectionRange(0, cleanText.length);
      success = document.execCommand('copy');
    } catch (err) {
      success = false;
    }

    input.blur();
    document.body.removeChild(input);
    return !!success;
  }

  function handleCopyClick(button, code) {
    var cleanCode = String(code || '').trim();

    if (isCartPage()) {
      var couponInput = document.querySelector('#coupon-input');
      var applyBtn = document.querySelector('.s-cart-coupons-coupon-button-apply');

      if (couponInput && applyBtn) {
        setNativeInputValue(couponInput, cleanCode);
        couponInput.dispatchEvent(new Event('input', { bubbles: true }));
        couponInput.dispatchEvent(new Event('change', { bubbles: true }));

        nextFrame(function () {
          nextFrame(function () {
            if (!applyBtn.disabled) {
              applyBtn.click();
            }
          });
        });

        button.disabled = true;
        button.textContent = '✓ جاري التطبيق...';
        button.style.letterSpacing = '0px';
        button.style.background = '#c9a96e';
        button.style.color = '#fff';

        setTimeout(function () {
          button.textContent = cleanCode;
          button.style.letterSpacing = '3px';
          button.style.background = '#fff';
          button.style.color = '#1a1a1a';
          button.disabled = false;
        }, 2000);

        return;
      }
    }

    var result = copyTextSync(cleanCode);
    setCopiedVisualState(button, cleanCode, result);
  }

  function setCopiedVisualState(button, originalCode, success) {
    if (!button) return;
    button.disabled = true;
    button.style.letterSpacing = '0px';

    if (success) {
      button.textContent = '✓ تم النسخ';
      button.style.background = '#c9a96e';
      button.style.color = '#fff';
    } else {
      button.textContent = 'انسخي الكود يدويًا';
      button.style.background = '#a94442';
      button.style.color = '#fff';
    }

    setTimeout(function () {
      button.textContent = originalCode;
      button.style.letterSpacing = '3px';
      button.style.background = '#fff';
      button.style.color = '#1a1a1a';
      button.disabled = false;
    }, 2000);
  }

  function createOfferBlock(config) {
    var wrapper = document.createElement('div');
    wrapper.className = 'stellara-card';

    var title = document.createElement('p');
    title.className = 'stellara-offer-title';
    title.innerHTML = config.offer.title;

    var text = document.createElement('p');
    text.className = 'stellara-offer-text';
    text.textContent = config.offer.text;

    var timer = document.createElement('p');
    timer.className = 'stellara-offer-timer';
    var timerSpan = document.createElement('span');
    timerSpan.id = config.countdownId;
    timerSpan.textContent = formatCountdown(config.secondsLeft);
    timer.textContent = 'ينتهي العرض خلال: ';
    timer.appendChild(timerSpan);

    var button = document.createElement('button');
    button.type = 'button';
    button.id = config.buttonId;
    button.className = 'stellara-code-btn';
    var cleanCode = String(config.offer.code || '').trim();
    button.textContent = cleanCode;
    button.setAttribute(
      'aria-label',
      isCartPage() ? 'تطبيق كود الخصم ' + cleanCode : 'نسخ كود الخصم ' + cleanCode
    );

    button.addEventListener('click', function (e) {
      e.preventDefault();
      e.stopPropagation();
      handleCopyClick(button, cleanCode);
    });

    var note = document.createElement('p');
    note.className = 'stellara-offer-note';
    note.textContent = isCartPage()
      ? 'اضغطي على الكود لتطبيق الخصم تلقائياً'
      : 'اضغطي على الكود لنسخه تلقائياً';

    wrapper.appendChild(title);
    wrapper.appendChild(text);
    wrapper.appendChild(timer);
    wrapper.appendChild(button);
    wrapper.appendChild(note);

    return wrapper;
  }

  function renderOfferIntoContainer(container, ids) {
    if (!container) return false;
    var current = getCurrentOffer();
    container.innerHTML = '';
    container.appendChild(createOfferBlock({
      offer: current.offer,
      secondsLeft: current.secondsLeft,
      countdownId: ids.countdownId,
      buttonId: ids.buttonId
    }));
    return true;
  }

  function startOfferCountdown(timerKey, ids, wrapperId) {
    clearTimer(timerKey);
    var lastIndex = getCurrentOffer().index;

    StellaraState.timers[timerKey] = setInterval(function () {
      var current = getCurrentOffer();
      var countdownEl = document.getElementById(ids.countdownId);
      var wrapper = document.getElementById(wrapperId);

      if (!wrapper || !countdownEl) {
        clearTimer(timerKey);
        return;
      }

      if (current.index !== lastIndex) {
        lastIndex = current.index;
        renderOfferIntoContainer(wrapper, ids);
        return;
      }

      countdownEl.textContent = formatCountdown(current.secondsLeft);
    }, 1000);
  }

  function initCartOffer() {
    if (!isCartPage()) return;

    retryUntilFound(function () {
      if (document.getElementById('stellara-offer-cart')) return true;

      var summaryCard = document.querySelector('.shadow-default.bg-white.p-5.rounded-md.mb-5.relative.transition-height');
      if (!summaryCard) return false;

      var wrapper = document.createElement('div');
      wrapper.id = 'stellara-offer-cart';
      summaryCard.insertAdjacentElement('beforebegin', wrapper);

      renderOfferIntoContainer(wrapper, {
        countdownId: 'stellara-countdown-cart',
        buttonId: 'stellara-code-cart'
      });

      startOfferCountdown(
        'cart-offer',
        {
          countdownId: 'stellara-countdown-cart',
          buttonId: 'stellara-code-cart'
        },
        'stellara-offer-cart'
      );

      return true;
    });
  }

  function initHomepageOffer() {
    if (!isHomepage()) return;

    retryUntilFound(function () {
      if (document.getElementById('stellara-offer-home')) return true;

      var placeholder = document.getElementById('stellara-homepage-offer');
      if (!placeholder) return false;

      var wrapper = document.createElement('div');
      wrapper.id = 'stellara-offer-home';
      placeholder.appendChild(wrapper);

      renderOfferIntoContainer(wrapper, {
        countdownId: 'stellara-countdown-home',
        buttonId: 'stellara-code-home'
      });

      startOfferCountdown(
        'home-offer',
        {
          countdownId: 'stellara-countdown-home',
          buttonId: 'stellara-code-home'
        },
        'stellara-offer-home'
      );

      return true;
    });
  }

  function getDiscountTarget() {
    return document.querySelector('#total-discount');
  }

  function getDiscountAmount() {
    var el = document.querySelector('#total-discount b') || getDiscountTarget();
    if (!el) return 0;
    var raw = (el.textContent || '').trim();
    var amount = Math.abs(parseArabicOrEnglishNumber(raw));
    return amount > 0 ? amount : 0;
  }

  function updateSavingsBlock() {
    var amount = getDiscountAmount();
    var existing = document.getElementById('stellara-savings');
    var submitWrap = document.querySelector('.cart-submit-wrap');
    if (!submitWrap) return false;

    if (amount <= 0) {
      if (existing) existing.remove();
      return true;
    }

    var displayText = formatCurrencyAmount(amount) + ' ريال';

    if (!existing) {
      var block = document.createElement('div');
      block.id = 'stellara-savings';
      block.className = 'stellara-savings';
      var p = document.createElement('p');
      p.textContent = '✨ وفرتِ ';
      var strong = document.createElement('strong');
      strong.textContent = displayText;
      p.appendChild(strong);
      p.appendChild(document.createTextNode(' على هذا الطلب'));
      block.appendChild(p);
      submitWrap.insertAdjacentElement('beforebegin', block);
      return true;
    }

    var existingStrong = existing.querySelector('strong');
    if (existingStrong && existingStrong.textContent !== displayText) {
      existingStrong.textContent = displayText;
    }

    return true;
  }

  function initSavings() {
    if (!isCartPage()) return;

    retryUntilFound(function () {
      var target = getDiscountTarget();
      var submitWrap = document.querySelector('.cart-submit-wrap');
      if (!target || !submitWrap) return false;

      updateSavingsBlock();
      disconnectObserver('cart-savings');

      var scheduled = false;
      var observer = new MutationObserver(function () {
        if (!document.contains(target)) {
          disconnectObserver('cart-savings');
          initSavings();
          return;
        }

        if (scheduled) return;
        scheduled = true;

        nextFrame(function () {
          updateSavingsBlock();
          scheduled = false;
        });
      });

      observer.observe(target, {
        childList: true,
        subtree: true,
        characterData: true
      });

      StellaraState.observers['cart-savings'] = observer;
      return true;
    });
  }

  function addWorkingDays(date, days, excludedWeekdays) {
    var result = new Date(date);
    var added = 0;
    var excluded = excludedWeekdays || [5];

    while (added < days) {
      result.setDate(result.getDate() + 1);
      if (excluded.indexOf(result.getDay()) === -1) added += 1;
    }

    return result;
  }

  function formatArabicDate(date) {
    var days = ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'];
    var months = ['يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر'];
    return days[date.getDay()] + ' ' + date.getDate() + ' ' + months[date.getMonth()];
  }

  function findProductPriceAnchor() {
    var selectors = [
      '.flex.whitespace-nowrap.gap-4.items-center',
      '.product-formatted-price',
      '.product-price'
    ];

    for (var i = 0; i < selectors.length; i++) {
      var el = document.querySelector(selectors[i]);
      if (el) return el;
    }

    return null;
  }

  function initDeliveryEstimate() {
    if (!isProductPage()) return;

    retryUntilFound(function () {
      if (document.getElementById('stellara-delivery')) return true;

      var anchor = findProductPriceAnchor();
      if (!anchor) return false;

      var today = new Date();
      var earliest = addWorkingDays(today, 4, [5]);
      var latest = addWorkingDays(today, 6, [5]);

      var delivery = document.createElement('div');
      delivery.id = 'stellara-delivery';
      delivery.className = 'stellara-delivery';

      var span = document.createElement('span');
      var e1 = document.createElement('strong');
      e1.textContent = formatArabicDate(earliest);
      var e2 = document.createElement('strong');
      e2.textContent = formatArabicDate(latest);

      span.textContent = 'التوصيل المتوقع: ';
      span.appendChild(e1);
      span.appendChild(document.createTextNode(' إلى '));
      span.appendChild(e2);

      delivery.textContent = '🚚 ';
      delivery.appendChild(span);

      anchor.insertAdjacentElement('afterend', delivery);
      return true;
    });
  }

  function init() {
    injectStylesOnce();
    initCartOffer();
    initHomepageOffer();
    initSavings();
    initDeliveryEstimate();
  }

  init();
})();