(function(){
  'use strict';
  var selectors = [
    'input[data-ua-subscriber-search]',
    '.ad-search input[name="q"]'
  ];
  var stream = null, timer = 0, activeInput = null, dialog = null, video = null, statusNode = null;

  function extractId(raw){
    var value = String(raw || '').trim();
    if (/^\d+$/.test(value)) return value.replace(/^0+(?=\d)/, '');
    var match = value.match(/(?:subscriber[_\s-]*id|\bid)\s*[:=#\/-]\s*(\d+)/i);
    if (!match) match = value.match(/[?&](?:subscriber_id|id)=(\d+)/i);
    if (!match) match = value.match(/#(\d+)\b/);
    return match ? match[1].replace(/^0+(?=\d)/, '') : '';
  }

  function stop(){
    if (timer) { clearTimeout(timer); timer = 0; }
    if (stream) stream.getTracks().forEach(function(track){ track.stop(); });
    stream = null;
    if (video) { video.pause(); video.srcObject = null; }
  }

  function close(){
    stop();
    if (dialog && dialog.open) dialog.close();
  }

  function ensureDialog(){
    if (dialog) return dialog;
    dialog = document.createElement('dialog');
    dialog.className = 'ua-subscriber-scan-dialog';
    dialog.innerHTML = '<header class="ua-subscriber-scan-head"><i class="fa fa-barcode" aria-hidden="true"></i><strong>قراءة باركود رقم المشترك</strong><button type="button" aria-label="إغلاق">×</button></header><div class="ua-subscriber-scan-body"><div class="ua-subscriber-scan-video"><video playsinline muted></video><span class="ua-subscriber-scan-guide" aria-hidden="true"></span></div><p class="ua-subscriber-scan-status">وجّه الكاميرا نحو باركود ID المشترك.</p></div>';
    document.body.appendChild(dialog);
    video = dialog.querySelector('video');
    statusNode = dialog.querySelector('.ua-subscriber-scan-status');
    dialog.querySelector('button').addEventListener('click', close);
    dialog.addEventListener('cancel', function(event){ event.preventDefault(); close(); });
    dialog.addEventListener('close', stop);
    return dialog;
  }

  function submitId(id){
    if (!activeInput || !id) return;
    activeInput.value = id;
    activeInput.dispatchEvent(new Event('input', {bubbles:true}));
    activeInput.dispatchEvent(new Event('change', {bubbles:true}));
    var form = activeInput.form;
    close();
    if (form) {
      window.setTimeout(function(){
        if (typeof form.requestSubmit === 'function') form.requestSubmit();
        else form.submit();
      }, 80);
    }
  }

  async function scan(input){
    activeInput = input;
    if (!('BarcodeDetector' in window) || !navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
      input.focus();
      if (typeof window.uaToast === 'function') window.uaToast('قارئ الكاميرا غير متاح. مرّر الباركود بقارئ USB داخل الحقل ثم اضغط Enter.', 'info');
      return;
    }
    ensureDialog().showModal();
    statusNode.classList.remove('is-error');
    statusNode.textContent = 'جارٍ تشغيل الكاميرا…';
    try {
      var formats = ['code_128','code_39','codabar','ean_13','ean_8','qr_code'];
      var supported = typeof BarcodeDetector.getSupportedFormats === 'function' ? await BarcodeDetector.getSupportedFormats() : formats;
      formats = formats.filter(function(format){ return supported.indexOf(format) !== -1; });
      var detector = new BarcodeDetector(formats.length ? {formats:formats} : undefined);
      stream = await navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:'environment'}},audio:false});
      video.srcObject = stream;
      await video.play();
      statusNode.textContent = 'وجّه الكاميرا نحو باركود ID المشترك.';
      var detect = async function(){
        if (!stream || !dialog.open) return;
        try {
          var codes = await detector.detect(video);
          for (var i=0;i<codes.length;i++) {
            var id = extractId(codes[i].rawValue);
            if (id) { submitId(id); return; }
          }
        } catch(e) {}
        timer = window.setTimeout(detect, 220);
      };
      detect();
    } catch(error) {
      stop();
      statusNode.classList.add('is-error');
      statusNode.textContent = 'تعذر تشغيل الكاميرا. اسمح بالوصول إليها أو استخدم قارئ USB داخل مربع البحث.';
    }
  }

  function enhance(input){
    if (!input || input.dataset.uaSubscriberScanReady === '1' || input.readOnly || input.disabled) return;
    if (input.matches('.ad-search input[name="q"]') && !/\bID\b/i.test(input.placeholder || '')) {
      input.placeholder = 'ID أو الاسم أو المستخدم أو الهاتف';
    }
    input.dataset.uaSubscriberScanReady = '1';
    var oldParent = input.parentElement;
    var box = document.createElement('span');
    box.className = 'ua-subscriber-search-box';
    if (oldParent && oldParent.querySelector(':scope > .search-icon-btn')) box.classList.add('has-external-search');
    input.before(box);
    box.appendChild(input);
    var button = document.createElement('button');
    button.type = 'button';
    button.className = 'ua-subscriber-id-scan';
    button.title = 'قراءة باركود ID المشترك';
    button.setAttribute('aria-label', 'قراءة باركود رقم المشترك');
    button.innerHTML = '<i class="fa fa-barcode" aria-hidden="true"></i>';
    button.addEventListener('click', function(){ scan(input); });
    box.appendChild(button);
  }

  function boot(){
    document.querySelectorAll(selectors.join(',')).forEach(enhance);
  }
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot);
  else boot();
  new MutationObserver(boot).observe(document.documentElement, {childList:true,subtree:true});
})();
