(() => {
  'use strict';

  const endpoint = 'https://script.google.com/macros/s/AKfycby2iAqcpAogzJoT-EFn86n38aVcctx39dfU2FefIB_MwGK6ueSjoaWa43oJt8B-qafy/exec';
  const hosts = ['wesalmkh.com', 'www.wesalmkh.com'];
  const icons = {
    file: '<path d="M7 3h7l4 4v14H6V3h1zM14 3v5h4M9 13h6M9 17h6"/>',
    download: '<path d="M12 3v12m-5-5 5 5 5-5M5 15v5h14v-5"/>',
    close: '<path d="m6 6 12 12M18 6 6 18"/>'
  };

  function element(tag, className, content) {
    const node = document.createElement(tag);
    if (className) node.className = 'wpd-' + className;
    if (content !== undefined) node.textContent = content;
    return node;
  }

  function icon(name) {
    const holder = element('span', 'icon');
    holder.setAttribute('aria-hidden', 'true');
    holder.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">' + icons[name] + '</svg>';
    return holder;
  }

  function digits(value) {
    return value.replace(/[٠-٩]/g, char => String('٠١٢٣٤٥٦٧٨٩'.indexOf(char)))
      .replace(/[۰-۹]/g, char => String('۰۱۲۳۴۵۶۷۸۹'.indexOf(char)))
      .replace(/[^0-9]/g, '');
  }

  async function lookup(query, signal) {
    const url = new URL(endpoint);
    url.searchParams.set('action', 'lookupProof');
    const response = await fetch(url, {
      method: 'POST',
      headers: {'Content-Type': 'text/plain;charset=UTF-8'},
      body: JSON.stringify({query}),
      credentials: 'omit',
      referrerPolicy: 'no-referrer',
      signal
    });
    if (!response.ok) throw new Error('lookup');
    return response.json();
  }

  function safeDownload(value) {
    try {
      const url = new URL(value);
      return url.origin === 'https://drive.google.com' && url.pathname === '/uc' &&
        url.searchParams.get('export') === 'download' && /^[\w-]+$/.test(url.searchParams.get('id') || '') ? url.href : '';
    } catch (err) { return ''; }
  }

  function resultCard(item) {
    if (!/^\d{5,30}$/.test(item.order) || !Array.isArray(item.files)) return null;
    const card = element('article', 'result');
    const order = element('h3', 'order', 'رقم الطلب ');
    order.append(element('bdi', '', '#' + item.order));
    card.append(order);
    for (const phrase of Array.isArray(item.phrases) ? item.phrases : []) {
      if (typeof phrase === 'string' && phrase.trim()) card.append(element('p', 'phrase', phrase));
    }
    const downloads = element('div', 'downloads');
    item.files.forEach((file, index) => {
      if (!file) return;
      const href = safeDownload(file.downloadUrl);
      if (!href) return;
      const label = item.files.length === 1 ? 'تحميل التوثيق' : 'تحميل ' + (file.type === 'video' ? 'الفيديو ' : 'الصورة ') + (index + 1);
      const link = element('a', 'download');
      link.href = href;
      link.target = '_blank';
      link.rel = 'noopener noreferrer';
      link.setAttribute('aria-label', label + ' للطلب ' + item.order);
      link.append(icon('download'), element('span', '', label));
      downloads.append(link);
    });
    if (!downloads.childElementCount) return null;
    card.append(downloads);
    return card;
  }

  function start() {
    if (!hosts.includes(location.hostname) || document.getElementById('wpd-dialog')) return;
    const trigger = element('button', 'trigger');
    trigger.type = 'button';
    trigger.setAttribute('aria-haspopup', 'dialog');
    trigger.setAttribute('aria-controls', 'wpd-dialog');
    trigger.append(icon('file'), element('span', '', 'توثيق الطلبات'));

    const dialog = element('dialog', 'dialog');
    dialog.id = 'wpd-dialog';
    dialog.dir = 'rtl';
    dialog.setAttribute('aria-labelledby', 'wpd-title');
    const header = element('header', 'header');
    const close = element('button', 'close');
    close.type = 'button';
    close.setAttribute('aria-label', 'إغلاق نافذة التوثيق');
    close.append(icon('close'));
    const title = element('h2', 'title', 'توثيق الطلبات');
    title.id = 'wpd-title';
    header.append(element('span', 'eyebrow', 'وصال'), title,
      element('p', 'intro', 'اعثر على توثيق تنفيذ طلبك وحمّله على جهازك.'), close);

    const body = element('div', 'body');
    const form = element('form', 'form');
    form.noValidate = true;
    const label = element('label', 'label', 'رقم الطلب أو رقم الجوال');
    label.htmlFor = 'wpd-search';
    const input = element('input', 'input');
    input.id = 'wpd-search';
    input.type = 'text';
    input.inputMode = 'tel';
    input.autocomplete = 'off';
    input.dir = 'ltr';
    input.placeholder = '#123456789 / 05XXXXXXXX';
    input.maxLength = 80;
    input.required = true;
    const submit = element('button', 'submit', 'بحث');
    submit.type = 'submit';
    const fields = element('div', 'fields');
    fields.append(input, submit);
    form.append(label, fields);
    const status = element('p', 'status');
    status.setAttribute('role', 'status');
    status.setAttribute('aria-live', 'polite');
    const results = element('div', 'results');
    body.append(form, status, results);
    dialog.append(header, body);
    document.body.append(trigger, dialog);

    const open = () => {
      if (!dialog.open) dialog.showModal();
      input.focus();
    };
    trigger.addEventListener('click', open);
    const openFromLink = () => {
      if (location.hash === '#wisal-proof-section') open();
    };
    window.addEventListener('hashchange', openFromLink);
    openFromLink();
    close.addEventListener('click', () => dialog.close());
    dialog.addEventListener('click', event => {
      if (event.target !== dialog) return;
      const box = dialog.getBoundingClientRect();
      if (event.clientX < box.left || event.clientX > box.right || event.clientY < box.top || event.clientY > box.bottom) dialog.close();
    });

    let pending;
    function reset() {
      if (pending) pending.abort();
      pending = undefined;
      submit.disabled = false;
      input.disabled = false;
      input.removeAttribute('aria-invalid');
      input.value = '';
      status.textContent = '';
      results.replaceChildren();
    }
    dialog.addEventListener('close', reset);
    form.addEventListener('submit', async event => {
      event.preventDefault();
      if (pending) return;
      const query = digits(input.value);
      input.removeAttribute('aria-invalid');
      results.replaceChildren();
      if (query.length < 5 || query.length > 30) {
        input.setAttribute('aria-invalid', 'true');
        status.textContent = 'أدخل رقم الطلب أو رقم الجوال كاملًا.';
        input.focus();
        return;
      }

      const controller = new AbortController();
      pending = controller;
      const timer = setTimeout(() => controller.abort(), 20000);
      submit.disabled = true;
      input.disabled = true;
      status.textContent = 'جاري البحث عن التوثيق…';
      try {
        const data = await lookup(query, controller.signal);
        if (pending !== controller) return;
        if (data.status === 'no_match') {
          status.textContent = 'لا يوجد توثيق جاهز لهذا الرقم. تأكد منه أو جرّب لاحقًا.';
          return;
        }
        if (data.status !== 'ready' || !Array.isArray(data.orders)) throw new Error('lookup');
        const cards = data.orders.filter(Boolean).map(resultCard).filter(Boolean);
        if (!cards.length) throw new Error('empty proof');
        results.append(...cards);
        status.textContent = cards.length === 1 ? 'التوثيق جاهز للتحميل' : 'اختر الطلب الذي تريد تحميل توثيقه';
      } catch (err) {
        if (pending === controller) status.textContent = 'تعذر البحث الآن. حاول مجددًا بعد قليل.';
      } finally {
        clearTimeout(timer);
        if (pending === controller) {
          pending = undefined;
          submit.disabled = false;
          input.disabled = false;
        }
      }
    });
  }

  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start, {once: true});
  else start();
})();