(function () {
  'use strict';

  var config = window.UA_OUTPUT_FILE_ROUTE || null;
  if (!config || window.UAOutputFileRouter) return;

  var busy = false;

  function stableDeviceId() {
    var key = 'ua_output_device_id_v1';
    var value = '';
    try { value = String(localStorage.getItem(key) || '').toLowerCase(); } catch (error) {}
    if (!/^[a-z0-9][a-z0-9_-]{7,63}$/.test(value)) {
      value = window.crypto && typeof window.crypto.randomUUID === 'function'
        ? window.crypto.randomUUID().toLowerCase()
        : 'device-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 12);
      try { localStorage.setItem(key, value); } catch (error) {}
    }
    return value;
  }

  function activeScope() {
    var base = String(config.scopeBase || config.scopeKey || '').replace(/:device:[a-z0-9_-]{8,64}$/i, '');
    return base ? base + ':device:' + stableDeviceId() : '';
  }

  function agentBase(host) {
    var value = String(host || '127.0.0.1').trim();
    if (!/^https?:\/\//i.test(value)) value = 'http://' + value;
    try {
      var url = new URL(value);
      if (!url.port) url.port = '9123';
      return url.origin;
    } catch (error) {
      return 'http://127.0.0.1:9123';
    }
  }

  function toast(message, kind) {
    var node = document.createElement('div');
    node.setAttribute('role', 'status');
    node.textContent = message;
    node.style.cssText = 'position:fixed;left:18px;bottom:18px;z-index:2147483647;width:min(480px,calc(100vw - 36px));padding:13px 16px;border:1px solid ' +
      (kind === 'error' ? 'rgba(255,105,120,.55)' : 'rgba(65,211,163,.5)') +
      ';border-radius:9px;background:' + (kind === 'error' ? 'rgba(91,25,37,.97)' : 'rgba(10,65,51,.97)') +
      ';color:#fff;font:700 13px/1.7 Tahoma,Arial,sans-serif;text-align:right;direction:rtl;box-shadow:0 18px 46px rgba(0,0,0,.42)';
    document.body.appendChild(node);
    window.setTimeout(function () { if (node.parentNode) node.parentNode.removeChild(node); }, 6500);
  }

  async function resolveRoute(scopeKey) {
    var url = new URL(config.configUrl || 'output_route_config.php', location.href);
    url.searchParams.set('command_key', config.commandKey || 'contract_print');
    url.searchParams.set('scope_key', scopeKey);
    var response = await fetch(url.toString(), {cache: 'no-store', credentials: 'same-origin'});
    var result = await response.json().catch(function () { return {}; });
    if (!response.ok || !result.ok || !result.route) throw new Error(result.error || ('HTTP ' + response.status));
    return result.route;
  }

  function responseFilename(response, fallback) {
    var disposition = String(response.headers.get('Content-Disposition') || '');
    var utf = disposition.match(/filename\*=UTF-8''([^;]+)/i);
    if (utf) {
      try { return decodeURIComponent(utf[1].replace(/["']/g, '')); } catch (error) {}
    }
    var plain = disposition.match(/filename="?([^";]+)"?/i);
    return plain ? plain[1] : (fallback || 'contract.docx');
  }

  function downloadBlob(blob, fileName) {
    var url = URL.createObjectURL(blob);
    var link = document.createElement('a');
    link.href = url;
    link.download = fileName || 'contract.docx';
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();
    link.remove();
    window.setTimeout(function () { URL.revokeObjectURL(url); }, 30000);
  }

  function arrayBufferToBase64(buffer) {
    var bytes = new Uint8Array(buffer);
    var chunks = [];
    for (var offset = 0; offset < bytes.length; offset += 0x8000) {
      chunks.push(String.fromCharCode.apply(null, bytes.subarray(offset, offset + 0x8000)));
    }
    return btoa(chunks.join(''));
  }

  function logOutput(scopeKey, status, message, referenceId) {
    if (!config.logUrl) return;
    fetch(config.logUrl, {
      method: 'POST',
      credentials: 'same-origin',
      headers: {'Content-Type': 'application/json', 'X-UA-CSRF': config.csrfToken || ''},
      body: JSON.stringify({
        command_key: config.commandKey || 'contract_print',
        scope_key: scopeKey,
        reference_id: String(referenceId || ''),
        status: status,
        message: String(message || '')
      })
    }).catch(function () {});
  }

  function markPrinted(scopeKey, contractId) {
    if (!contractId || !config.contractLogUrl) return;
    fetch(config.contractLogUrl, {
      method: 'POST',
      credentials: 'same-origin',
      headers: {'Content-Type': 'application/json', 'X-UA-CSRF': config.csrfToken || ''},
      body: JSON.stringify({contract_id: parseInt(contractId, 10), scope_key: scopeKey})
    }).catch(function () {});
  }

  async function printRequest(options) {
    if (busy) return;
    busy = true;
    var fileResponse;
    var blob;
    var fileName = options.fileName || 'contract.docx';
    var scopeKey = activeScope();
    var contractId = options.contractId || '';
    try {
      fileResponse = await fetch(options.url, {
        method: options.method || 'GET',
        body: options.body || undefined,
        credentials: 'same-origin',
        cache: 'no-store'
      });
      if (!fileResponse.ok) throw new Error('contract_file_http_' + fileResponse.status);
      fileName = responseFilename(fileResponse, fileName);
      contractId = fileResponse.headers.get('X-UA-Contract-Id') || contractId;
      blob = await fileResponse.blob();

      var payload = {
        command_key: config.commandKey || 'contract_print',
        scope_key: scopeKey,
        file_name: fileName,
        file_base64: arrayBufferToBase64(await blob.arrayBuffer())
      };
      var headers = {'Content-Type': 'application/json', 'X-UA-CSRF': config.csrfToken || ''};
      var printResponse = await fetch(config.fileProxyUrl || 'output_file_proxy.php', {
        method: 'POST',
        credentials: 'same-origin',
        cache: 'no-store',
        headers: headers,
        body: JSON.stringify(payload)
      });
      var printResult = await printResponse.json().catch(function () { return {}; });
      if (!printResponse.ok || printResult.ok === false) throw new Error(printResult.error || ('print_http_' + printResponse.status));

      logOutput(scopeKey, 'sent', 'تم إرسال العقد عبر مركز الطباعة', contractId);
      markPrinted(scopeKey, contractId);
      toast('تم إرسال العقد إلى الطابعة المحددة بنجاح.', 'success');
    } catch (error) {
      if (blob) downloadBlob(blob, fileName);
      logOutput(scopeKey, 'fallback', String(error && error.message ? error.message : error), contractId);
      toast('تعذر الوصول إلى مسار طباعة العقود؛ تم تنزيل ملف Word لإكمال الطباعة يدوياً.', 'error');
    } finally {
      busy = false;
    }
  }

  window.UAOutputFileRouter = {print: printRequest};

  document.addEventListener('click', function (event) {
    var button = event.target.closest('[data-ua-print-contract]');
    if (!button) return;
    event.preventDefault();
    var formSelector = button.getAttribute('data-form');
    var form = formSelector ? document.querySelector(formSelector) : button.closest('form');
    var formBody = form ? new FormData(form) : undefined;
    if (formBody && button.getAttribute('data-delivery')) {
      formBody.set('delivery', button.getAttribute('data-delivery'));
    }
    printRequest({
      url: button.getAttribute('data-url') || (form ? form.action : location.href),
      method: form ? String(form.method || 'POST').toUpperCase() : 'GET',
      body: formBody,
      fileName: button.getAttribute('data-file-name') || 'contract.docx',
      contractId: button.getAttribute('data-contract-id') || ''
    });
  });
})();
