(function () {
  'use strict';

  var route = window.UA_OUTPUT_ROUTE || null;
  if (!route || window.__uaOutputRouterReady) return;
  window.__uaOutputRouterReady = true;

  var nativePrint = typeof window.print === 'function' ? window.print.bind(window) : function () {};
  var printing = false;
  var silent = window.UA_OUTPUT_SILENT === true;

  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)) {
      if (window.crypto && typeof window.crypto.randomUUID === 'function') {
        value = window.crypto.randomUUID().toLowerCase();
      } else {
        value = 'device-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 12);
      }
      try { localStorage.setItem(key, value); } catch (error) {}
    }
    return value;
  }

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

  route.scopeKey = activeScope();

  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 printableHtml() {
    var clone = document.documentElement.cloneNode(true);
    clone.querySelectorAll('script, .ua-print-toolbar, .bar.ua-print-toolbar, [data-no-print]').forEach(function (node) {
      node.remove();
    });
    return '<!doctype html>\n' + clone.outerHTML;
  }

  function showOutputToast(message, kind) {
    var toast = document.createElement('div');
    toast.setAttribute('role', 'status');
    toast.textContent = message;
    toast.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(toast);
    window.setTimeout(function () { if (toast.parentNode) toast.parentNode.removeChild(toast); }, 6500);
  }

  async function resolveDeviceRoute() {
    if (!route.deviceScoped || !route.configUrl) return route;
    var url = new URL(route.configUrl, location.href);
    url.searchParams.set('command_key', route.commandKey || '');
    url.searchParams.set('scope_key', route.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));
    Object.keys(result.route).forEach(function (key) { route[key] = result.route[key]; });
    return route;
  }

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

  async function routedPrint() {
    if (printing) return;
    if ((!route.enabled || !route.deviceName) && !route.deviceScoped) {
      log('dialog', 'لم يحدد جهاز ثابت؛ تم فتح مربع الطباعة.');
      if (!silent) nativePrint();
      return;
    }

    printing = true;
    try {
      if (!route.proxyUrl) await resolveDeviceRoute();
      if ((!route.enabled || !route.deviceName) && !route.proxyUrl) {
        log('dialog', 'لم يحدد جهاز ثابت لهذا الكمبيوتر؛ تم فتح مربع الطباعة.');
        if (!silent) nativePrint();
        return;
      }
      // The application proxy owns authorization and can route the job to any
      // approved printer node. Browsers and Android never need direct LAN access.
      var useDirectAgent = !route.proxyUrl;
      var endpoint = route.proxyUrl || (agentBase(route.agentHost) + '/print');
      var headers = {'Content-Type': 'application/json'};
      if (!useDirectAgent && route.proxyUrl && route.csrfToken) headers['X-UA-CSRF'] = route.csrfToken;
      if ((useDirectAgent || !route.proxyUrl) && route.agentToken) headers['X-UA-Output-Token'] = route.agentToken;
      var response = await fetch(endpoint, {
        method: 'POST',
        mode: useDirectAgent || !route.proxyUrl ? 'cors' : 'same-origin',
        credentials: useDirectAgent || !route.proxyUrl ? 'omit' : 'same-origin',
        cache: 'no-store',
        headers: headers,
        body: JSON.stringify({
          command_key: route.commandKey,
          printer: route.deviceName,
          copies: Math.max(1, parseInt(route.copies || 1, 10)),
          paper: route.paperSize || '',
          title: document.title || route.commandKey,
          command_key: route.commandKey,
          scope_key: route.scopeKey || '',
          action: 'print',
          source_url: location.href,
          html: printableHtml()
        })
      });
      var result = await response.json().catch(function () { return {}; });
      if (!response.ok || result.ok === false) throw new Error(result.error || ('HTTP ' + response.status));
      var routedPrinter = String(result.printer || route.deviceName || '');
      log('sent', 'تم إرسال المهمة إلى ' + routedPrinter);
      window.dispatchEvent(new CustomEvent('ua:output-sent', {detail: {route: route, result: result}}));
    } catch (error) {
      log('fallback', String(error && error.message ? error.message : error));
      if (!silent) {
        showOutputToast('تعذر تنفيذ مسار الطباعة المحفوظ لهذا الجهاز. سيتم فتح مربع طباعة ويندوز لإكمال العملية يدوياً.', 'error');
        nativePrint();
      }
    } finally {
      printing = false;
    }
  }

  window.uaPrintWithRoute = routedPrint;
  window.print = routedPrint;
})();
