(function(){
  'use strict';

  function text(value){
    return String(value || '').replace(/\s+/g, ' ').trim();
  }

  function excludedTable(table){
    if (!table || table.dataset.uaAndroidTable === 'off') return true;
    if (table.matches('[role="grid"],.calendar,.calendar-table,.fc-scrollgrid,.ui-datepicker-calendar,.table-calendar')) return true;
    return /calendar|datepicker|schedule-grid|matrix/i.test(String(table.className || ''));
  }

  function prepareTable(table){
    if (!table || excludedTable(table)) return;
    var heads = Array.from(table.querySelectorAll('thead tr:last-child th'));
    if (!heads.length) heads = Array.from(table.querySelectorAll('tr:first-child th'));
    if (heads.length < 3) return;

    var labels = heads.map(function(head){
      return text(head.getAttribute('aria-label') || head.textContent);
    });
    table.classList.add('ua-android-card-table');

    var cards = window.matchMedia('(max-width:720px)').matches;
    var set = function(element, property, value){
      element.style.setProperty(property, value, 'important');
    };
    if (cards) {
      set(table, 'display', 'block');
      set(table, 'width', '100%');
      set(table, 'min-width', '0');
      set(table, 'max-width', '100%');
    }

    Array.from(table.tBodies || []).forEach(function(body){
      if (cards) {
        set(body, 'display', 'grid');
        set(body, 'width', '100%');
        set(body, 'min-width', '0');
        set(body, 'grid-template-columns', 'minmax(0,1fr)');
      }
      Array.from(body.rows || []).forEach(function(row){
        if (cards) {
          set(row, 'display', 'block');
          set(row, 'width', '100%');
          set(row, 'min-width', '0');
          set(row, 'max-width', '100%');
        }
        Array.from(row.cells || []).forEach(function(cell, index){
          if (cell.colSpan > 1) {
            cell.classList.add('ua-android-card-span');
            return;
          }
          var label = labels[index] || text(cell.getAttribute('data-title'));
          if (label) cell.setAttribute('data-ua-android-label', label);
          if (cards) {
            set(cell, 'display', cell.colSpan > 1 ? 'block' : 'grid');
            set(cell, 'width', '100%');
            set(cell, 'min-width', '0');
            set(cell, 'max-width', '100%');
          }
        });
      });
    });
  }

  function prepareTables(root){
    var scope = root && root.querySelectorAll ? root : document;
    if (scope.matches && scope.matches('table')) prepareTable(scope);
    Array.from(scope.querySelectorAll('table')).forEach(prepareTable);
  }

  function prepareLayouts(root){
    if (!window.matchMedia('(max-width:720px)').matches) return;
    var scope = root && root.querySelectorAll ? root : document;
    Array.from(scope.querySelectorAll('[class*="form-grid"],[class*="fields-grid"],[class*="filter-grid"],.settings-grid')).forEach(function(grid){
      if (grid.closest('[data-ua-android-native-layout]')) return;
      grid.style.setProperty('grid-template-columns', 'minmax(0,1fr)', 'important');
      grid.style.setProperty('width', '100%', 'important');
      grid.style.setProperty('min-width', '0', 'important');
      grid.style.setProperty('max-width', '100%', 'important');
      Array.from(grid.children || []).forEach(function(child){
        child.style.setProperty('grid-column', '1 / -1', 'important');
        child.style.setProperty('min-width', '0', 'important');
        child.style.setProperty('max-width', '100%', 'important');
      });
    });
  }

  function closeSubmenu(){
    var panel = document.querySelector('.ua-android-submenu');
    if (panel) panel.remove();
    document.body.classList.remove('ua-android-submenu-open');
  }

  function openSubmenu(button){
    var id = button.getAttribute('data-sb3-group');
    var template = id ? document.getElementById('sb3_tpl_' + id) : null;
    if (!template) return;
    closeSubmenu();

    var panel = document.createElement('section');
    panel.className = 'ua-android-submenu';
    panel.setAttribute('role', 'dialog');
    panel.setAttribute('aria-modal', 'true');
    panel.innerHTML = '<button type="button" class="ua-android-submenu__back" aria-label="العودة إلى القائمة"><i class="fa fa-arrow-right"></i><span>العودة إلى القائمة</span></button><div class="ua-android-submenu__body"></div>';
    panel.querySelector('.ua-android-submenu__body').appendChild(template.content.cloneNode(true));
    panel.querySelector('.ua-android-submenu__back').addEventListener('click', closeSubmenu);
    document.body.appendChild(panel);
    document.body.classList.add('ua-android-submenu-open');
  }

  function mountMenuCloseButton(){
    var sidebar = document.getElementById('uaSb3');
    if (!sidebar || sidebar.querySelector('.ua-android-menu-close')) return;
    var button = document.createElement('button');
    button.type = 'button';
    button.className = 'ua-android-menu-close';
    button.innerHTML = '<i class="fa fa-times" aria-hidden="true"></i><span>إغلاق القائمة</span>';
    button.addEventListener('click', function(){
      closeSubmenu();
      document.body.classList.remove('ua-mobile-sb-open', 'ua-sidebar-open');
    });
    sidebar.insertBefore(button, sidebar.firstChild);
  }

  function mountProtectedLinkFlow(){
    if (document.getElementById('uaAndroidProtectedAuth')) return;

    var protectedPages = {
      'subscribers_view.php': true,
      'subscribers_edit.php': true,
      'subscribers_distribution.php': true,
      'subscribers_history.php': true,
      'subscribers_history_clear.php': true,
      'subscribers_cancel.php': true,
      'subscribers_ppp_toggle.php': true,
      'subscribers_restore.php': true,
      'subscribers_speed_toggle_all.php': true,
      'subscribers_speed_toggle_selected.php': true
    };

    function protectedGo(anchor){
      if (!anchor || anchor.hasAttribute('data-ua-no-password')) return '';
      var href = anchor.getAttribute('data-go') || anchor.getAttribute('href') || '';
      if (!href || href === '#' || /^javascript:/i.test(href)) return '';
      try {
        var url = new URL(href, window.location.href);
        if (url.origin !== window.location.origin) return '';
        var file = (url.pathname.split('/').pop() || '').toLowerCase();
        if (file === 'super_admin_guard.php') {
          return String(url.searchParams.get('go') || '').replace(/^\/+/, '');
        }
        if (!protectedPages[file]) return '';
        ['embed','ua_modal','ua_sub_modal','ua_subscriber_modal','subscriber_modal','modal','popup','iframe','ua_tab'].forEach(function(key){
          url.searchParams.delete(key);
        });
        var query = url.searchParams.toString();
        return file + (query ? '?' + query : '') + (url.hash || '');
      } catch (_error) {
        return '';
      }
    }

    var shell = document.createElement('section');
    shell.id = 'uaAndroidProtectedAuth';
    shell.className = 'ua-android-protected-auth';
    shell.hidden = true;
    shell.setAttribute('role', 'dialog');
    shell.setAttribute('aria-modal', 'true');
    shell.setAttribute('aria-labelledby', 'uaAndroidProtectedTitle');
    shell.innerHTML = '<div class="ua-android-protected-card">' +
      '<div class="ua-android-protected-icon" aria-hidden="true"><i class="fa fa-lock"></i></div>' +
      '<h2 id="uaAndroidProtectedTitle">عملية محمية</h2>' +
      '<p>أدخل كلمة مرور السوبر أدمن للمتابعة.</p>' +
      '<form id="uaAndroidProtectedForm">' +
        '<label for="uaAndroidProtectedPassword">كلمة المرور</label>' +
        '<div class="ua-android-protected-input"><input id="uaAndroidProtectedPassword" type="password" autocomplete="current-password" placeholder="أدخل كلمة المرور"><button type="button" data-ua-protected-eye aria-label="إظهار أو إخفاء كلمة المرور"><i class="fa fa-eye"></i></button></div>' +
        '<div class="ua-android-protected-error" role="alert" aria-live="polite"></div>' +
        '<div class="ua-android-protected-actions"><button type="submit" class="is-confirm">متابعة</button><button type="button" class="is-cancel" data-ua-protected-close>إلغاء</button></div>' +
      '</form>' +
    '</div>';
    document.body.appendChild(shell);

    var form = shell.querySelector('#uaAndroidProtectedForm');
    var input = shell.querySelector('#uaAndroidProtectedPassword');
    var error = shell.querySelector('.ua-android-protected-error');
    var submit = shell.querySelector('.is-confirm');
    var title = shell.querySelector('#uaAndroidProtectedTitle');
    var pendingGo = '';

    function close(){
      shell.hidden = true;
      document.body.classList.remove('ua-android-protected-open');
      input.value = '';
      error.textContent = '';
      pendingGo = '';
    }

    function open(go, label){
      pendingGo = go;
      title.textContent = label || 'عملية محمية';
      input.value = '';
      error.textContent = '';
      shell.hidden = false;
      document.body.classList.add('ua-android-protected-open');
      closeSubmenu();
      document.body.classList.remove('ua-mobile-sb-open', 'ua-sidebar-open');
      setTimeout(function(){ input.focus({preventScroll:true}); }, 60);
    }

    window.uaAndroidRequestProtectedLink = open;
    window.addEventListener('click', function(event){
      if (event.defaultPrevented || event.button > 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
      var anchor = event.target && event.target.closest ? event.target.closest('a[href],a[data-go]') : null;
      if (!anchor || shell.contains(anchor)) return;
      var go = protectedGo(anchor);
      if (!go) return;
      event.preventDefault();
      event.stopPropagation();
      if (event.stopImmediatePropagation) event.stopImmediatePropagation();
      var label = text(anchor.getAttribute('data-title') || anchor.getAttribute('title') || anchor.textContent) || 'عملية محمية';
      open(go, label);
    }, true);

    shell.querySelector('[data-ua-protected-close]').addEventListener('click', close);
    shell.addEventListener('click', function(event){ if (event.target === shell) close(); });
    shell.querySelector('[data-ua-protected-eye]').addEventListener('click', function(){
      var showing = input.type === 'text';
      input.type = showing ? 'password' : 'text';
      this.querySelector('i').className = showing ? 'fa fa-eye' : 'fa fa-eye-slash';
      input.focus({preventScroll:true});
    });
    form.addEventListener('submit', async function(event){
      event.preventDefault();
      if (!pendingGo) return;
      var password = input.value || '';
      if (!password) {
        error.textContent = 'كلمة المرور مطلوبة.';
        input.focus({preventScroll:true});
        return;
      }
      var oldLabel = submit.textContent;
      submit.disabled = true;
      submit.textContent = 'جاري التحقق...';
      error.textContent = '';
      try {
        var data = new FormData();
        data.append('password', password);
        data.append('go', pendingGo);
        var response = await fetch('api/super_admin_session.php', {
          method: 'POST', body: data, credentials: 'same-origin',
          headers: {'X-Requested-With':'XMLHttpRequest', 'Accept':'application/json'}
        });
        var result = await response.json().catch(function(){ return {ok:false,message:'تعذر قراءة استجابة التحقق.'}; });
        if (!response.ok || !result.ok) {
          if (result.logout && result.redirect) {
            window.location.assign(result.redirect);
            return;
          }
          throw new Error(result.message || 'فشل التحقق من كلمة المرور.');
        }
        var next = pendingGo;
        submit.textContent = 'جاري الفتح...';
        shell.hidden = true;
        document.body.classList.remove('ua-android-protected-open');
        window.location.assign(next);
      } catch (failure) {
        error.textContent = failure && failure.message ? failure.message : 'فشل التحقق من كلمة المرور.';
        input.select();
      } finally {
        submit.disabled = false;
        submit.textContent = oldLabel || 'متابعة';
      }
    });
  }

  function mount(){
    document.documentElement.classList.add('ua-android-app-ready');
    mountMenuCloseButton();
    mountProtectedLinkFlow();
    window.uaAndroidToggleMenu = function(){
      var willOpen = !document.body.classList.contains('ua-mobile-sb-open');
      closeSubmenu();
      document.body.classList.remove('ua-sidebar-open');
      document.body.classList.toggle('ua-mobile-sb-open', willOpen);
      return willOpen;
    };
    prepareTables(document);
    prepareLayouts(document);

    document.addEventListener('click', function(event){
      var group = event.target && event.target.closest ? event.target.closest('[data-sb3-group]') : null;
      if (group) {
        event.preventDefault();
        event.stopPropagation();
        if (event.stopImmediatePropagation) event.stopImmediatePropagation();
        document.body.classList.add('ua-mobile-sb-open');
        openSubmenu(group);
        return;
      }
      if (event.target && event.target.closest && event.target.closest('.ua-android-submenu .ua-sb3-link')) {
        closeSubmenu();
        document.body.classList.remove('ua-mobile-sb-open');
      }
    }, true);

    var queued = false;
    var observer = new MutationObserver(function(records){
      var relevant = records.some(function(record){
        if (record.target && record.target.closest && record.target.closest('table')) return true;
        return Array.from(record.addedNodes || []).some(function(node){
          return node && node.nodeType === 1 && (node.matches('table,tr,td,th') || node.querySelector('table'));
        });
      });
      if (!relevant || queued) return;
      queued = true;
      requestAnimationFrame(function(){ queued = false; prepareTables(document); prepareLayouts(document); });
    });
    observer.observe(document.body, {childList:true, subtree:true});

    document.addEventListener('shown.bs.modal', function(event){ prepareTables(event.target); prepareLayouts(event.target); });
  }

  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', mount);
  else mount();
})();
