(function () {
  'use strict';

  const form = document.querySelector('[data-bulk-export-form]');
  if (!form || typeof window.fetch !== 'function') return;

  const progress = form.querySelector('[data-export-progress]');
  const progressBar = progress && progress.querySelector('[data-progress-bar]');
  const progressPercent = progress && progress.querySelector('[data-progress-percent]');
  const progressCount = progress && progress.querySelector('[data-progress-count]');
  const progressState = progress && progress.querySelector('[data-progress-state]');
  const progressIcon = progress && progress.querySelector('[data-progress-icon]');
  const submitButtons = Array.from(form.querySelectorAll('[data-export-format]'));
  const exportControls = Array.from(form.querySelectorAll('[data-export-lock]'));
  const originalLabels = new Map(submitButtons.map(function (button) {
    const label = button.querySelector('span');
    return [button, label ? label.textContent : ''];
  }));
  const csrf = form.querySelector('input[name="ua_csrf"]');
  let running = false;

  function setButtonsDisabled(disabled) {
    exportControls.forEach(function (control) { control.disabled = disabled; });
  }

  function setButtonLabel(button, label) {
    const node = button && button.querySelector('span');
    if (node) node.textContent = label;
  }

  function restoreButtonLabels() {
    submitButtons.forEach(function (button) {
      setButtonLabel(button, originalLabels.get(button) || '');
    });
  }

  function notify(message, type) {
    if (typeof window.uaToast === 'function') {
      window.uaToast(message, type || 'info', 6000);
    }
  }

  function render(state, label) {
    const total = Math.max(0, Number(state.total || 0));
    const processed = Math.min(total, Math.max(0, Number(state.processed || 0)));
    const percent = Math.min(100, Math.max(0, Number(state.percent || 0)));
    if (progress) progress.hidden = false;
    if (progressBar) progressBar.style.width = percent + '%';
    if (progressPercent) progressPercent.textContent = percent + '%';
    if (progressCount) progressCount.textContent = processed + ' من ' + total;
    if (progressState) progressState.textContent = label || 'توليد ملفات العقود';
  }

  async function request(body) {
    const response = await fetch('subscriber_contracts_bulk_api.php', {
      method: 'POST',
      body: body,
      credentials: 'same-origin',
      headers: { 'X-Requested-With': 'XMLHttpRequest' }
    });
    const text = await response.text();
    let payload;
    try {
      payload = JSON.parse(text);
    } catch (_error) {
      throw new Error('تعذر قراءة استجابة خادم التصدير.');
    }
    if (!response.ok || !payload.ok) {
      throw new Error(payload.message || 'تعذرت متابعة مهمة التصدير.');
    }
    return payload;
  }

  function processBody(token) {
    const body = new FormData();
    body.set('action', 'process');
    body.set('token', token);
    if (csrf) body.set('ua_csrf', csrf.value);
    return body;
  }

  form.addEventListener('submit', async function (event) {
    if (running) {
      event.preventDefault();
      return;
    }
    event.preventDefault();
    const submitter = event.submitter && event.submitter.matches('[data-export-format]')
      ? event.submitter
      : submitButtons[0];
    const outputFormat = submitter && submitter.dataset.exportFormat === 'pdf' ? 'pdf' : 'docx';
    const isPdf = outputFormat === 'pdf';
    // Capture the user's choices before locking the controls. Disabled form
    // controls are omitted by FormData, which used to discard page selection.
    const startBody = new FormData(form);
    startBody.set('action', 'start');
    startBody.set('output_format', outputFormat);
    running = true;
    if (progress) progress.classList.remove('is-error', 'is-complete');
    if (progressIcon) progressIcon.className = 'fa fa-cog fa-spin';
    setButtonsDisabled(true);
    setButtonLabel(submitter, isPdf ? 'جاري تجهيز PDF الجماعي' : 'جاري تجهيز عقود Word');
    render({ total: 0, processed: 0, percent: 0 }, 'تحليل القالب وتطبيق الفلتر');

    try {
      let state = await request(startBody);
      render(state, isPdf ? 'تجهيز صفحات PDF الجماعي' : 'توليد ملفات العقود');

      while (state.status === 'running') {
        state = await request(processBody(state.token));
        render(state, state.status === 'complete'
          ? 'اكتمل التصدير'
          : (isPdf ? 'تجهيز صفحات PDF الجماعي' : 'توليد ملفات العقود'));
      }

      if (!state.download_url) throw new Error('اكتمل التوليد دون رابط تنزيل صالح.');
      render({ total: state.total, processed: state.total, percent: 100 }, 'اكتمل التصدير وبدأ التنزيل');
      if (progress) progress.classList.add('is-complete');
      if (progressIcon) progressIcon.className = 'fa fa-check-circle';
      setButtonLabel(submitter, isPdf ? 'اكتمل PDF الجماعي' : 'اكتمل تصدير Word');
      notify(isPdf ? 'تم إنشاء ملف PDF موحّد وبدأ تنزيله بنجاح.' : 'تم توليد عقود Word وبدأ تنزيل الملف بنجاح.', 'success');
      const link = document.createElement('a');
      link.href = state.download_url;
      link.download = '';
      link.hidden = true;
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.setTimeout(function () {
        setButtonsDisabled(false);
        restoreButtonLabels();
      }, 1200);
    } catch (error) {
      const message = error instanceof Error ? error.message : 'تعذرت عملية التصدير.';
      if (progress) progress.classList.add('is-error');
      if (progressIcon) progressIcon.className = 'fa fa-exclamation-triangle';
      if (progressState) progressState.textContent = message;
      notify(message, 'error');
      setButtonsDisabled(false);
      setButtonLabel(submitter, isPdf ? 'إعادة محاولة تصدير PDF' : 'إعادة محاولة تصدير Word');
    } finally {
      running = false;
    }
  });
})();
