/* PSQ WhatsApp delivery: native Salla telephone field, conditional on Yes. */
(() => {
  'use strict';
  const title = 'رقم الواتساب لاستلام الطلب';
  const question = 'هل تريد استخدام رقم جوال مختلف عن المستعمل في سلة؟';
  const mounted = new WeakMap();
  const states = new Set();
  let replay = false, queued = false;

  function write(input, value) {
    if (input.value === value) return;
    input.value = value;
    input.dispatchEvent(new Event('input', { bubbles: true }));
    input.dispatchEvent(new Event('change', { bubbles: true }));
  }
  function telephone(container, target, note = false) {
    const phone = document.createElement('salla-tel-input');
    phone.setAttribute('name', 'psq_delivery_' + (target.id || 'nitro'));
    phone.setAttribute('country-code', 'SA');
    container.append(phone);
    const error = document.createElement('p');
    error.className = 'psq-phone-error'; error.hidden = true;
    error.textContent = 'أدخل رقم واتساب صحيحًا.';
    container.append(error);
    let version = 0;
    const state = { phone, target, error, container, note, sync: async () => {
      const current = ++version;
      await customElements.whenDefined('salla-tel-input');
      const values = await phone.getValues();
      if (current !== version || !target.isConnected) return;
      const digits = String(values[phone.getAttribute('name')] || '').replace(/\D/g, '');
      const dial = String(values.countryKey || '').replace(/\D/g, '');
      write(target, digits && dial ? (note ? 'رقم الواتساب للتسليم: ' : '') + '+' + dial + digits : '');
    }};
    phone.addEventListener('phoneEntered', () => {
      error.hidden = true;
      state.sync().catch(() => { write(target, ''); });
    });
    states.add(state);
    return state;
  }
  function nativeOptions() {
    document.querySelectorAll('select[name^="options["]').forEach(select => {
      const label = document.querySelector('label[for="' + select.id + '"]');
      if (label && label.textContent.includes('هل تريد استخدام رقم جوال مختلف')) {
        const small = label.querySelector('small'); if (small && small.textContent) small.textContent = '';
        if (select.options[0] && !select.options[0].value && select.options[0].textContent !== 'اختر نعم أو لا') select.options[0].textContent = 'اختر نعم أو لا';
      }
    });
    document.querySelectorAll('input[name^="options["]').forEach(input => {
      if (mounted.has(input)) return;
      const label = document.querySelector('label[for="' + input.id + '"]');
      if (!label || !label.textContent.includes(title)) return;
      const card = input.closest('.s-product-options-option');
      if (!card || input.disabled || !card.getClientRects().length) return;
      const small = label.querySelector('small');
      if (small) small.textContent = 'اختر مفتاح دولتك وأدخل رقم الواتساب.';
      card.classList.add('psq-phone-card');
      const host = document.createElement('div'); host.className = 'psq-phone-host';
      input.after(host);
      const state = telephone(host, input);
      input.classList.add('psq-phone-native'); input.tabIndex = -1;
      mounted.set(input, state);
    });
    for (const state of states) {
      if (!state.target.isConnected) { states.delete(state); continue; }
    }
  }
  function nitro() {
    if (!/\/p1530745209\/?$/.test(location.pathname) || document.getElementById('psq-nitro-whatsapp')) return;
    const form = document.querySelector('form[data-testid="store-product-form"]');
    const target = form && form.querySelector('textarea[name="notes"]');
    if (!target) return;
    const box = document.createElement('section'); box.id = 'psq-nitro-whatsapp'; box.dir = 'rtl';
    const group = document.createElement('fieldset'); group.className = 'psq-phone-choice';
    const legend = document.createElement('legend'); legend.textContent = question; group.append(legend);
    ['نعم', 'لا'].forEach((text, i) => {
      const label = document.createElement('label');
      const radio = document.createElement('input'); radio.type = 'radio';
      radio.name = 'psq-use-other'; radio.value = i === 0 ? 'yes' : 'no'; radio.required = true;
      label.append(radio, ' ' + text); group.append(label);
    });
    const card = document.createElement('div'); card.className = 'psq-phone-card'; card.hidden = true;
    const h = document.createElement('h3'); h.textContent = title + ' *';
    const p = document.createElement('p'); p.textContent = 'اختر مفتاح دولتك وأدخل رقم الواتساب.';
    card.append(h, p); box.append(group, card); form.before(box);
    const state = telephone(card, target, true); state.group = group;
    const noteSection = target.closest('section'); if (noteSection) noteSection.hidden = true;
    group.addEventListener('change', () => {
      const selected = group.querySelector('input:checked');
      card.hidden = selected?.value !== 'yes';
      state.error.hidden = true;
      if (selected?.value === 'no') write(target, 'التواصل عبر رقم الجوال المسجل في سلة');
      else state.sync().catch(() => write(target, ''));
    });
  }
  async function validate(scope) {
    for (const state of states) {
      if (!state.target.isConnected || (scope && !scope.contains(state.target))) continue;
      if (state.note) {
        const selected = state.group.querySelector('input:checked');
        if (!selected) { state.group.querySelector('input').reportValidity(); return false; }
        if (selected.value === 'no') continue;
      } else if (state.target.disabled || !state.container.getClientRects().length) continue;
      try {
        await customElements.whenDefined('salla-tel-input');
        const valid = await state.phone.isValid();
        await state.sync(); state.error.hidden = valid === true;
        if (valid !== true) { state.container.scrollIntoView({ block: 'center', behavior: 'smooth' }); return false; }
      } catch (_) { state.error.hidden = false; return false; }
    }
    return true;
  }
  document.addEventListener('click', async event => {
    if (replay) return;
    const path = event.composedPath();
    const buy = path.find(node => node instanceof Element && node.matches('salla-add-product-button,salla-quick-buy'));
    if (!buy || buy.getAttribute('product-status') === 'out' || !states.size) return;
    const form = buy.closest('form') || document.querySelector('form[data-testid="store-product-form"]');
    if (!form) return;
    event.preventDefault(); event.stopImmediatePropagation();
    if (!await validate(form)) return;
    const button = path.find(node => node instanceof HTMLButtonElement) || buy;
    replay = true; try { button.click(); } finally { replay = false; }
  }, true);
  document.addEventListener('submit', async event => {
    if (replay || !states.size || !(event.target instanceof HTMLFormElement)) return;
    const form = event.target;
    if (![...states].some(s => form.contains(s.target))) return;
    event.preventDefault(); event.stopImmediatePropagation();
    if (!await validate(form)) return;
    replay = true; try { form.requestSubmit(event.submitter || undefined); } finally { replay = false; }
  }, true);
  function mount() { nativeOptions(); nitro(); }
  function start() {
    const style = document.createElement('style');
    style.textContent = '.psq-phone-card{margin:18px 0!important;padding:18px!important;background:var(--psq-paper,#f5f1e7);border:1px solid var(--psq-navy,#071e37);color:var(--psq-navy,#071e37)}.psq-phone-card h3,.psq-phone-card .s-product-options-option-label b{font-size:17px!important;font-weight:800;line-height:1.6}.psq-phone-card p,.psq-phone-card small{font-size:12px!important;line-height:1.8;margin:4px 0 12px!important}.psq-phone-host salla-tel-input,.psq-phone-card salla-tel-input{display:block;direction:ltr;text-align:left}.psq-phone-native{position:absolute!important;width:1px!important;height:1px!important;opacity:0!important;pointer-events:none!important;padding:0!important}.psq-phone-card .psq-phone-error{color:#a4262c!important;margin-top:8px!important}.psq-phone-card [hidden],.psq-phone-card[hidden]{display:none!important}.psq-phone-choice{border:0;padding:0;margin:20px 0}.psq-phone-choice legend{font-weight:800;margin-bottom:10px}.psq-phone-choice label{display:inline-flex;align-items:center;gap:6px;margin-inline-end:24px;cursor:pointer}';
    document.head.append(style); mount();
    new MutationObserver(() => { if (queued) return; queued = true; requestAnimationFrame(() => { queued = false; mount(); }); }).observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['disabled'] });
  }
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start, { once: true });
  else start();
})();