(function(){
  function ensureStack(){var s=document.getElementById('uaToastStack')||document.getElementById('uaGlobalToastStack');if(!s){s=document.createElement('div');s.id='uaGlobalToastStack';s.className='ua-feedback-stack ua-toast-stack';document.body.appendChild(s);}else{s.classList.add('ua-feedback-stack');}return s;}
  function toast(message,type,timeout){message=String(message||''); if(!message.trim()) return; type=type||'info'; var st=ensureStack(); var el=document.createElement('div'); el.className='ua-toast ua-toast-'+type; el.textContent=message; st.appendChild(el); requestAnimationFrame(function(){el.classList.add('show')}); setTimeout(function(){el.classList.remove('show'); setTimeout(function(){el.remove()},260);}, timeout||4200);}
  window.UAToast=toast; window.uaToast=toast;


  /* Protection-style program dialogs (alert/confirm skin)
     - Uses the same visual language as the subscribers security password dialog.
     - Keeps native confirm as a fallback for non-click/async legacy flows so logic is not broken. */
  var _uaNativeAlert = window.alert ? window.alert.bind(window) : function(m){};
  var _uaNativeConfirm = window.confirm ? window.confirm.bind(window) : function(){return true;};
  var _uaConfirmApprovedUntil = 0;
  var _uaActiveClickTarget = null;

  function uaEsc(s){
    return String(s == null ? '' : s).replace(/[&<>"']/g,function(c){return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[c];});
  }
  function uaDecodeQuoted(s){
    s = String(s == null ? '' : s);
    try { return JSON.parse('"' + s.replace(/\\/g,'\\\\').replace(/"/g,'\\"').replace(/\n/g,'\\n').replace(/\r/g,'\\r') + '"'); } catch(e) {}
    return s.replace(/\\n/g,'\n').replace(/\\r/g,'\r').replace(/\\'/g,"'").replace(/\\"/g,'"');
  }
  function uaExtractConfirmMessage(code){
    code = String(code || '');
    var m = code.match(/confirm\s*\(\s*(['"`])([\s\S]*?)\1\s*\)/i);
    return m ? uaDecodeQuoted(m[2]) : '';
  }
  function uaDialog(opts){
    opts = opts || {};
    var title = String(opts.title || (opts.kind === 'alert' ? 'تنبيه' : 'تأكيد العملية'));
    var msg = String(opts.message == null ? '' : opts.message);
    var html = opts.html != null ? String(opts.html) : uaEsc(msg).replace(/\n/g,'<br>');
    var kind = String(opts.kind || 'confirm');
    var showCancel = opts.showCancel !== false && kind !== 'alert';
    var confirmText = String(opts.confirmText || (showCancel ? 'موافق' : 'موافق'));
    var cancelText = String(opts.cancelText || 'إلغاء');
    var icon = String(opts.icon || (kind === 'alert' ? 'fa-bell' : (kind === 'danger' ? 'fa-exclamation-triangle' : 'fa-shield')));
    return new Promise(function(resolve){
      function build(){
        var old = document.getElementById('uaGlobalDialogBackdrop');
        if (old) old.remove();
        var b = document.createElement('div');
        b.id = 'uaGlobalDialogBackdrop';
        b.className = 'ua-global-dialog-backdrop ua-global-dialog-' + kind;
        b.setAttribute('role','dialog');
        b.setAttribute('aria-modal','true');
        b.dir = 'rtl';
        b.innerHTML = '<div class="ua-global-dialog-card">'
          + '<div class="ua-global-dialog-icon" aria-hidden="true"><i class="fa '+uaEsc(icon)+'"></i></div>'
          + '<div class="ua-global-dialog-title">'+uaEsc(title)+'</div>'
          + '<div class="ua-global-dialog-message">'+html+'</div>'
          + '<div class="ua-global-dialog-actions">'
          + (showCancel ? '<button type="button" class="ua-global-dialog-btn ua-global-dialog-cancel" data-ua-dialog-cancel>'+uaEsc(cancelText)+'</button>' : '')
          + '<button type="button" class="ua-global-dialog-btn ua-global-dialog-ok" data-ua-dialog-ok>'+uaEsc(confirmText)+'</button>'
          + '</div></div>';
        document.body.appendChild(b);
        document.body.classList.add('ua-global-dialog-open');
        var ok = b.querySelector('[data-ua-dialog-ok]');
        var cancel = b.querySelector('[data-ua-dialog-cancel]');
        var done = function(v){
          try { b.remove(); } catch(e) {}
          document.body.classList.remove('ua-global-dialog-open');
          resolve(!!v);
        };
        if (ok) ok.addEventListener('click',function(){done(true);});
        if (cancel) cancel.addEventListener('click',function(){done(false);});
        b.addEventListener('click',function(ev){ if(ev.target === b && showCancel) done(false); });
        document.addEventListener('keydown',function escHandler(ev){
          if (!document.getElementById('uaGlobalDialogBackdrop')) { document.removeEventListener('keydown',escHandler,true); return; }
          if (ev.key === 'Escape' && showCancel) { ev.preventDefault(); document.removeEventListener('keydown',escHandler,true); done(false); }
          if (ev.key === 'Enter') { ev.preventDefault(); document.removeEventListener('keydown',escHandler,true); done(true); }
        }, true);
        setTimeout(function(){ try{ (ok || cancel || b).focus({preventScroll:true}); }catch(e){} },30);
      }
      if (document.body) build(); else document.addEventListener('DOMContentLoaded',build,{once:true});
    });
  }
  window.uaDialog = uaDialog;
  window.UADialog = uaDialog;
  window.uaConfirm = function(title, message, options){ options = options || {}; options.title = title || options.title; options.message = message == null ? options.message : message; options.kind = options.kind || 'confirm'; options.showCancel = true; return uaDialog(options); };
  window.uaAlert = function(title, message, options){ options = options || {}; options.title = title || options.title || 'تنبيه'; options.message = message == null ? options.message : message; options.kind = options.kind || 'alert'; options.showCancel = false; return uaDialog(options); };

  window.alert = function(message){
    try { uaDialog({title:'تنبيه', message:String(message == null ? '' : message), kind:'alert', showCancel:false, icon:'fa-info'}); } catch(e) { _uaNativeAlert(message); }
  };
  window.confirm = function(message){
    if (_uaConfirmApprovedUntil && Date.now() < _uaConfirmApprovedUntil) return true;
    var target = _uaActiveClickTarget;
    if (target && target.nodeType === 1 && !target.__uaConfirmReplayRunning) {
      try {
        uaDialog({title:'تأكيد العملية', message:String(message == null ? '' : message), kind:'confirm', showCancel:true, icon:'fa-shield'}).then(function(ok){
          if (!ok) return;
          _uaConfirmApprovedUntil = Date.now() + 1200;
          target.__uaConfirmReplayRunning = true;
          try { target.click(); } finally { setTimeout(function(){ try{ target.__uaConfirmReplayRunning = false; }catch(e){} },0); }
        });
        return false;
      } catch(e) {}
    }
    return _uaNativeConfirm(message);
  };

  function uaSubmitWithSubmitter(form, submitter){
    if (!form) return;
    var added = null;
    try {
      if (submitter && submitter.name && !submitter.disabled) {
        added = document.createElement('input');
        added.type = 'hidden';
        added.name = submitter.name;
        added.value = submitter.value || '';
        form.appendChild(added);
      }
      HTMLFormElement.prototype.submit.call(form);
    } finally {
      if (added && added.parentNode) added.parentNode.removeChild(added);
    }
  }
  document.addEventListener('click', function(ev){
    var t = ev.target && ev.target.closest ? ev.target.closest('button,input[type="button"],input[type="submit"],a,[role="button"]') : null;
    _uaActiveClickTarget = t || null;
    setTimeout(function(){ _uaActiveClickTarget = null; },0);
    var el = ev.target && ev.target.closest ? ev.target.closest('[onclick*="confirm("]') : null;
    if (!el) return;
    if (el.getAttribute('data-ua-confirm-approved') === '1') {
      el.removeAttribute('data-ua-confirm-approved');
      _uaConfirmApprovedUntil = Date.now() + 1200;
      return;
    }
    var msg = uaExtractConfirmMessage(el.getAttribute('onclick') || '');
    if (!msg) return;
    ev.preventDefault();
    ev.stopPropagation();
    ev.stopImmediatePropagation();
    uaDialog({title:'تأكيد العملية', message:msg, kind:'confirm', showCancel:true, icon:'fa-shield'}).then(function(ok){
      if (!ok) return;
      el.setAttribute('data-ua-confirm-approved','1');
      _uaConfirmApprovedUntil = Date.now() + 1200;
      if (el.tagName === 'A' && el.getAttribute('href') && el.getAttribute('href') !== '#') {
        el.click();
      } else if ((el.tagName === 'BUTTON' || el.tagName === 'INPUT') && el.form && ((el.type || '').toLowerCase() === 'submit' || !el.type)) {
        uaSubmitWithSubmitter(el.form, el);
      } else {
        el.click();
      }
    });
  }, true);
  document.addEventListener('submit', function(ev){
    var form = ev.target;
    if (!form || !form.getAttribute) return;
    var code = form.getAttribute('onsubmit') || '';
    if (code.indexOf('confirm(') < 0) return;
    if (form.getAttribute('data-ua-confirm-approved') === '1') {
      form.removeAttribute('data-ua-confirm-approved');
      _uaConfirmApprovedUntil = Date.now() + 1200;
      return;
    }
    var msg = uaExtractConfirmMessage(code);
    if (!msg) return;
    ev.preventDefault();
    ev.stopPropagation();
    ev.stopImmediatePropagation();
    var submitter = ev.submitter || document.activeElement;
    uaDialog({title:'تأكيد العملية', message:msg, kind:'confirm', showCancel:true, icon:'fa-shield'}).then(function(ok){
      if (!ok) return;
      form.setAttribute('data-ua-confirm-approved','1');
      _uaConfirmApprovedUntil = Date.now() + 1200;
      uaSubmitWithSubmitter(form, submitter && submitter.form === form ? submitter : null);
    });
  }, true);

  var TASK_KEY='ua_minimized_pages_v2';
  function safeJson(v,d){try{return JSON.parse(v||'')}catch(e){return d}}
  function getTasks(){var a=safeJson(sessionStorage.getItem(TASK_KEY),'[]');return Array.isArray(a)?a:[];}
  function setTasks(a){try{sessionStorage.setItem(TASK_KEY,JSON.stringify((a||[]).slice(0,24)));}catch(e){}}
  function pageTitle(){var h=document.querySelector('h1,h2,.page-title,.content-header h1,.ua-page-title'); return (h&&h.textContent&&h.textContent.trim()) || (document.title||'صفحة').replace(/\s*[-|].*$/,'').trim() || 'صفحة';}
  function pageUrl(){return location.pathname.split('/').pop()+location.search;}
  function groupKey(url){return String(url||'').split('?')[0] || 'صفحة';}
  function addTask(url,title){url=url||pageUrl(); title=title||pageTitle(); var arr=getTasks().filter(function(x){return x&&x.url!==url;}); arr.unshift({url:url,title:title,ts:Date.now()}); setTasks(arr); renderTaskbar();}
  function removeTask(url){setTasks(getTasks().filter(function(x){return x&&x.url!==url;})); renderTaskbar();}
  function removeGroup(key){setTasks(getTasks().filter(function(x){return groupKey(x.url)!==key;})); renderTaskbar();}
  function openTask(t){if(!t||!t.url) return; removeTask(t.url); location.href=t.url;}
  function groupedTasks(){var map={},order=[]; getTasks().forEach(function(t){if(!t||!t.url)return; var k=groupKey(t.url); if(!map[k]){map[k]=[];order.push(k);} map[k].push(t);}); return order.map(function(k){return {key:k,items:map[k]};});}
  function closeTaskMenu(){var m=document.getElementById('uaTaskContextMenu'); if(m) m.remove();}
  function showTaskMenu(group,anchor,x,y){closeTaskMenu(); if(!group||!group.items||!group.items.length) return; var first=group.items[0]; var menu=document.createElement('div'); menu.id='uaTaskContextMenu'; menu.className='ua-task-menu';
    var title=document.createElement('div'); title.className='ua-task-menu-title'; title.textContent=(group.items.length>1?('مجموعة: '+group.items.length+' صفحات'):(first.title||'صفحة')); menu.appendChild(title);
    group.items.slice(0,8).forEach(function(t,idx){var b=document.createElement('button'); b.type='button'; b.innerHTML='<i class="fa fa-window-restore"></i><span>'+ (group.items.length>1?(t.title||('صفحة '+(idx+1))):'تكبير') +'</span>'; b.addEventListener('click',function(){openTask(t);}); menu.appendChild(b);});
    if(group.items.length>8){var more=document.createElement('button'); more.type='button'; more.disabled=true; more.innerHTML='<i class="fa fa-ellipsis-h"></i><span>+'+(group.items.length-8)+' صفحات أخرى</span>'; menu.appendChild(more);}
    var closeOne=document.createElement('button'); closeOne.type='button'; closeOne.className='ua-danger'; closeOne.innerHTML='<i class="fa fa-times"></i><span>'+(group.items.length>1?'إغلاق آخر صفحة':'إغلاق')+'</span>'; closeOne.addEventListener('click',function(){removeTask(first.url); closeTaskMenu();}); menu.appendChild(closeOne);
    if(group.items.length>1){var closeAll=document.createElement('button'); closeAll.type='button'; closeAll.className='ua-danger'; closeAll.innerHTML='<i class="fa fa-times-circle"></i><span>إغلاق المجموعة</span>'; closeAll.addEventListener('click',function(){removeGroup(group.key); closeTaskMenu();}); menu.appendChild(closeAll);}
    document.body.appendChild(menu); var r=menu.getBoundingClientRect(); var left=(x!=null?x:(anchor?anchor.getBoundingClientRect().left:20)); var top=(y!=null?y:(anchor?anchor.getBoundingClientRect().top:20)); left=Math.max(8, Math.min(left, window.innerWidth-r.width-8)); top=Math.max(8, Math.min(top-r.height-8)); menu.style.left=left+'px'; menu.style.top=top+'px'; setTimeout(function(){document.addEventListener('click',closeTaskMenu,{once:true});},0);
  }
  function renderTaskbar(){var bar=document.getElementById('uaTopPageTabs')||document.getElementById('uaFooterTaskbar'); if(!bar) return; var groups=groupedTasks(); bar.innerHTML=''; if(!groups.length){bar.style.display='flex'; return;} bar.style.display='flex'; groups.forEach(function(g){var first=g.items[0]; var chip=document.createElement('span'); chip.className='ua-task-chip'; chip.title=(g.items.length>1?(g.items.length+' صفحات مصغرة'):(first.title||'صفحة')); var open=document.createElement('button'); open.type='button'; open.className='ua-task-open'; open.setAttribute('aria-label',chip.title); open.innerHTML='<i class="fa fa-window-restore"></i><span>'+(first.title||'صفحة')+'</span>'; open.addEventListener('click',function(e){ if(g.items.length===1){openTask(first);} else {showTaskMenu(g,chip,e.clientX,e.clientY);} }); var x=document.createElement('button'); x.type='button'; x.className='ua-task-x'; x.title='إغلاق الصفحة المصغرة'; x.setAttribute('aria-label','إغلاق الصفحة المصغرة'); x.innerHTML='×'; x.addEventListener('click',function(e){e.preventDefault();e.stopPropagation();removeTask(first.url);}); chip.addEventListener('contextmenu',function(e){e.preventDefault();showTaskMenu(g,chip,e.clientX,e.clientY);}); chip.addEventListener('auxclick',function(e){if(e.button===1){e.preventDefault();removeTask(first.url);}}); chip.appendChild(open); chip.appendChild(x); if(g.items.length>1){var c=document.createElement('span'); c.className='ua-task-count'; c.textContent=g.items.length; chip.appendChild(c);} bar.appendChild(chip); });}
  window.uaRenderTaskbar=renderTaskbar;

  function migrateAlerts(){document.querySelectorAll('.alert:not([data-ua-toast-done])').forEach(function(a){var txt=(a.textContent||'').trim(); if(!txt) return; a.setAttribute('data-ua-toast-done','1'); var t=a.classList.contains('alert-success')?'success':(a.classList.contains('alert-danger')?'error':(a.classList.contains('alert-warning')?'warning':'info')); toast(txt,t); a.style.display='none';});}
  function controls(closeHandler,maxHandler,minHandler){var wrap=document.createElement('div');wrap.className='ua-window-controls';
    var c=document.createElement('button');c.type='button';c.className='ua-window-btn ua-window-close';c.title='إغلاق';c.innerHTML='×';c.addEventListener('click',function(e){e.preventDefault(); if(closeHandler) closeHandler(e);});
    var m=document.createElement('button');m.type='button';m.className='ua-window-btn ua-window-max';m.title='تكبير';m.innerHTML='<span class="ua-win11-max-icon" aria-hidden="true"></span>';m.addEventListener('click',function(e){e.preventDefault(); if(maxHandler) maxHandler(e);});
    var n=document.createElement('button');n.type='button';n.className='ua-window-btn ua-window-min';n.title='تصغير';n.innerHTML='<span class="ua-win11-min-icon" aria-hidden="true"></span>';n.addEventListener('click',function(e){e.preventDefault(); if(minHandler) minHandler(e);});
    wrap.appendChild(c);wrap.appendChild(m);wrap.appendChild(n);return wrap;}
  function enhanceModalHeaders(root){(root||document).querySelectorAll('.modal-header:not([data-ua-windowized]), .ua-secure-head:not([data-ua-windowized])').forEach(function(h){var close=h.querySelector('.btn-close,[data-bs-dismiss="modal"],.ua-secure-close'); if(!close) return; h.setAttribute('data-ua-windowized','1'); close.classList.add('ua-hidden-by-window-controls'); var box=h.closest('.modal-content,.ua-secure-modal,.ua-modal,.ua-window'); var ctl=controls(function(){close.click();},function(){if(box) box.classList.toggle('ua-window-maximized');},function(){if(box) box.classList.toggle('ua-window-minimized');}); h.insertBefore(ctl,h.firstChild);});}
  function bindPageChrome(){document.addEventListener('click',function(e){var min=e.target.closest('[data-ua-page-min="1"], .ua-close-strip .ua-window-min'); if(min){e.preventDefault(); e.stopPropagation(); var strip=min.closest('.ua-close-strip'); var url=min.getAttribute('data-ua-page-url') || (strip&&strip.getAttribute('data-ua-page-url')) || pageUrl(); var title=min.getAttribute('data-ua-page-title') || (strip&&strip.getAttribute('data-ua-page-title')) || pageTitle(); addTask(url,title); location.href=min.getAttribute('data-ua-home-url') || 'dashboard.php'; return;} var max=e.target.closest('[data-ua-page-max="1"], .ua-close-strip .ua-window-max'); if(max){e.preventDefault(); e.stopPropagation(); document.body.classList.toggle('ua-page-maximized'); return;} });}
  function init(){ensureStack();renderTaskbar();migrateAlerts();enhanceModalHeaders(document);bindPageChrome(); if(document.documentElement){var mo=new MutationObserver(function(muts){muts.forEach(function(m){m.addedNodes&&m.addedNodes.forEach(function(n){if(n.nodeType===1){migrateAlerts();enhanceModalHeaders(n);}});});}); mo.observe(document.documentElement,{childList:true,subtree:true});} window.addEventListener('storage',renderTaskbar); document.addEventListener('keydown',function(e){if(e.key==='Escape') closeTaskMenu();}); window.addEventListener('resize',closeTaskMenu);}
  if(document.readyState==='loading') document.addEventListener('DOMContentLoaded',init); else init();
})();
