const API = 'api.php';
let authToken = localStorage.getItem('master_token');
let companiesCache = [];
/** Loaded from GET super/permission-modules (same keys as api.php adminPermissionModuleDefinitions) */
let _permissionModuleDefs = [];
const SUB_ADMIN_GROUP_ORDER = ['settings', 'hr', 'attendance', 'reports', 'leave_policies', 'comms', 'tools'];
const SUB_ADMIN_GROUP_LABELS_AR = {
  settings: 'لوحة التحكم والإعدادات',
  hr: 'الموظفون والهيكل التنظيمي',
  attendance: 'الحضور والمواقع',
  reports: 'التقارير والقرارات',
  leave_policies: 'الإجازات والسياسات والعطلات',
  comms: 'الإعلانات والمراسلة',
  tools: 'أدوات'
};
let _savingSubAdmin = false;

/** Mirrors hr/api.php when API is unreachable — keep keys in sync */
function getFallbackPermissionModuleDefs() {
  return [
    { key: 'dashboard', label_ar: 'لوحة التحكم والإعدادات', label_en: 'Dashboard & company settings', group: 'settings' },
    { key: 'employees', label_ar: 'الموظفون', label_en: 'Employees', group: 'hr' },
    { key: 'branches', label_ar: 'الفروع', label_en: 'Branches', group: 'hr' },
    { key: 'departments', label_ar: 'الأقسام', label_en: 'Departments', group: 'hr' },
    { key: 'attendance', label_ar: 'الحضور والانصراف', label_en: 'Attendance', group: 'attendance' },
    { key: 'final_report', label_ar: 'التقرير النهائي للحضور', label_en: 'Final attendance report', group: 'reports' },
    { key: 'final_decision', label_ar: 'التقرير النهائي — القرار', label_en: 'Final decision report', group: 'reports' },
    { key: 'leave_settlement', label_ar: 'تقرير تسوية الإجازات', label_en: 'Leave settlement report', group: 'reports' },
    { key: 'deductions_report', label_ar: 'تقرير الخصومات', label_en: 'Deductions report', group: 'reports' },
    { key: 'leave_overview', label_ar: 'نظرة عامة على الإجازات', label_en: 'Leave overview', group: 'reports' },
    { key: 'leave', label_ar: 'طلبات الإجازات', label_en: 'Leave requests', group: 'leave_policies' },
    { key: 'policies', label_ar: 'سياسات الإجازات', label_en: 'Leave policies', group: 'leave_policies' },
    { key: 'official_holidays', label_ar: 'العطلات الرسمية', label_en: 'Official holidays', group: 'leave_policies' },
    { key: 'company_news', label_ar: 'إعلانات الشركة', label_en: 'Company news', group: 'comms' },
    { key: 'employee_messages', label_ar: 'مراسلة الموظفين', label_en: 'Employee messages (admin)', group: 'comms' },
    { key: 'qr', label_ar: 'رمز QR للحضور', label_en: 'Attendance QR', group: 'tools' }
  ];
}

async function ensurePermissionModuleDefs() {
  if (_permissionModuleDefs.length) return;
  const res = await api('GET', 'super/permission-modules');
  if (res.success && res.data && Array.isArray(res.data.modules) && res.data.modules.length) {
    _permissionModuleDefs = res.data.modules;
    return;
  }
  _permissionModuleDefs = getFallbackPermissionModuleDefs();
}

function getPermissionModuleDefs() {
  return _permissionModuleDefs.length ? _permissionModuleDefs : getFallbackPermissionModuleDefs();
}

function getSubAdminModuleKeys() {
  return getPermissionModuleDefs().map((m) => m.key);
}

function subAdminPermSelectAll(on) {
  document.querySelectorAll('#subAdminPermGrid input[type="checkbox"]').forEach((el) => {
    el.checked = !!on;
  });
}

function subAdminPermSelectModule(moduleKey, on) {
  document.querySelectorAll(`#subAdminPermGrid input[data-m="${moduleKey}"]`).forEach((el) => {
    el.checked = !!on;
  });
}

// ── AUTH ──────────────────────────────────────────────────────────
async function doLogin() {
  const username = document.getElementById('loginUser').value.trim();
  const password = document.getElementById('loginPass').value;
  if (!username || !password) return showToast('Fill in credentials', 'error');
  const res = await api('POST', 'auth/super-login', {username, password});
  if (res.success) {
    authToken = res.data.token;
    localStorage.setItem('master_token', authToken);
    document.getElementById('loginScreen').style.display = 'none';
    document.getElementById('appShell').style.display = 'block';
    loadCompanies();
    loadStats();
  } else showToast(res.message, 'error');
}

function logout() {
  localStorage.removeItem('master_token');
  localStorage.removeItem('admin_token');
  localStorage.removeItem('admin_company_id');
  localStorage.removeItem('emp_token');
  location.reload();
}

// ── API ───────────────────────────────────────────────────────────
async function api(method, endpoint, body = null) {
  const opts = { 
    method: 'POST', 
    headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + (authToken||'') }
  };
  const payload = body ? { ...body } : {};
  if (method !== 'POST') payload._method = method;
  opts.body = JSON.stringify(payload);
  try {
    const r = await fetch(`${API}?route=${encodeURIComponent(endpoint)}`, opts);
    return await r.json();
  } catch(e) { return {success:false, message:'Network error'}; }
}

// ── TABS ──────────────────────────────────────────────────────────
function toggleSidebar(){
  const sb = document.querySelector('.sidebar');
  const ov = document.querySelector('.sidebar-overlay');
  sb.classList.toggle('open');
  ov.classList.toggle('open');
}

function showTab(name) {
  document.querySelectorAll('[id^="tab-"]').forEach(el => el.style.display = 'none');
  const target = document.getElementById('tab-' + name);
  if(target) target.style.display = 'block';
  document.querySelectorAll('.sidebar-nav .nav-item[data-tab]').forEach(el => {
    el.classList.toggle('active', el.getAttribute('data-tab') === name);
  });
  
  if(window.innerWidth <= 768){
    document.querySelector('.sidebar').classList.remove('open');
    document.querySelector('.sidebar-overlay').classList.remove('open');
  }

  if (name === 'stats') loadStats();
  if (name === 'companies') loadCompanies();
  if (name === 'trials') loadTrialRequests();
  if (name === 'login-insights') loadLoginInsights();
  if (name === 'outbound-mail') { loadSmtpSettings(); loadSmtpTestLog(); }
  if (name === 'company-admins') {
    syncSubAdminCompanySelect();
    void ensurePermissionModuleDefs();
    loadCompanySubAdmins();
  }
}

// ── COMPANIES ─────────────────────────────────────────────────────
function syncLoginInsightsCompanySelect() {
  const sel = document.getElementById('loginInsightsCompany');
  if (!sel) return;
  const prev = sel.value;
  const opts = ['<option value="">كل الشركات</option>'];
  for (const c of companiesCache) {
    const id = String(c.company_id || '');
    opts.push(`<option value="${escapeHtml(id)}">${escapeHtml(c.name || '')}</option>`);
  }
  sel.innerHTML = opts.join('');
  if (prev && [...sel.options].some(o => o.value === prev)) sel.value = prev;
}

function syncSmtpTestCompanySelect() {
  const sel = document.getElementById('smtpTestCompany');
  if (!sel) return;
  const prev = sel.value;
  const opts = ['<option value="">— اختر شركة —</option>'];
  for (const c of companiesCache) {
    const id = String(c.company_id || '');
    opts.push(`<option value="${escapeHtml(id)}">${escapeHtml(c.name || '')}</option>`);
  }
  sel.innerHTML = opts.join('');
  if (prev && [...sel.options].some(o => o.value === prev)) sel.value = prev;
}

function syncSubAdminCompanySelect() {
  const sel = document.getElementById('subAdminCompanySelect');
  if (!sel) return;
  const prev = sel.value;
  const opts = ['<option value="">— Choose company —</option>'];
  for (const c of companiesCache) {
    const id = String(c.company_id || '');
    opts.push(`<option value="${escapeHtml(id)}">${escapeHtml(c.name || '')}</option>`);
  }
  sel.innerHTML = opts.join('');
  if (prev && [...sel.options].some(o => o.value === prev)) sel.value = prev;
}

function buildSubAdminPermissionGrid(permissionMap = null) {
  const mount = document.getElementById('subAdminPermGrid');
  if (!mount) return;
  const map = permissionMap || {};
  const defs = getPermissionModuleDefs();
  const byGroup = new Map();
  for (const d of defs) {
    const g = d.group || 'settings';
    if (!byGroup.has(g)) byGroup.set(g, []);
    byGroup.get(g).push(d);
  }
  const orderedGroups = [
    ...SUB_ADMIN_GROUP_ORDER.filter((g) => byGroup.has(g)),
    ...[...byGroup.keys()].filter((g) => !SUB_ADMIN_GROUP_ORDER.includes(g))
  ];
  const toolbar = `<div class="sub-admin-perm-toolbar" style="display:flex;flex-wrap:wrap;gap:8px;margin-bottom:14px;align-items:center;">
    <button type="button" class="btn btn-sm btn-ghost" onclick="subAdminPermSelectAll(1)">تحديد الكل</button>
    <button type="button" class="btn btn-sm btn-ghost" onclick="subAdminPermSelectAll(0)">مسح الكل</button>
    <span style="font-size:11px;color:var(--textM);line-height:1.4;">يتطلب «قراءة» تفعيل أي إجراء آخر ضمن نفس الوحدة (كما في الخادم).</span>
  </div>`;
  const parts = [];
  for (const g of orderedGroups) {
    const list = byGroup.get(g);
    if (!list || !list.length) continue;
    const gLabel = SUB_ADMIN_GROUP_LABELS_AR[g] || g;
    parts.push(`<div style="grid-column:1/-1;font-size:12px;font-weight:700;color:var(--accent);margin-top:8px;margin-bottom:4px;border-bottom:1px solid var(--border);padding-bottom:6px;">${escapeHtml(gLabel)}</div>`);
    for (const mod of list) {
      const mk = mod.key;
      const p = map[mk] || {};
      const checked = (k) => (p[k] ? 'checked' : '');
      const titleAr = escapeHtml(mod.label_ar || mk);
      const titleEn = mod.label_en ? escapeHtml(mod.label_en) : '';
      parts.push(`<div style="border:1px solid var(--border);border-radius:10px;padding:10px;">
        <div style="display:flex;justify-content:space-between;align-items:flex-start;gap:8px;margin-bottom:8px;">
          <div style="min-width:0;">
            <div style="font-weight:600;font-size:13px;line-height:1.35;">${titleAr}</div>
            <div style="font-size:10px;color:var(--textM);font-family:var(--mono);margin-top:2px;word-break:break-all;">${escapeHtml(mk)}</div>
            ${titleEn ? `<div style="font-size:11px;color:var(--text-muted);margin-top:2px;">${titleEn}</div>` : ''}
          </div>
          <button type="button" class="btn btn-sm btn-ghost" style="flex-shrink:0;padding:4px 8px;font-size:11px;" onclick="subAdminPermSelectModule(${JSON.stringify(mk)},1)">صف الكل</button>
        </div>
        <label style="display:block;font-size:12px;"><input type="checkbox" data-m="${escapeHtml(mk)}" data-a="read" ${checked('read')}> قراءة</label>
        <label style="display:block;font-size:12px;"><input type="checkbox" data-m="${escapeHtml(mk)}" data-a="create" ${checked('create')}> إنشاء</label>
        <label style="display:block;font-size:12px;"><input type="checkbox" data-m="${escapeHtml(mk)}" data-a="update" ${checked('update')}> تعديل</label>
        <label style="display:block;font-size:12px;"><input type="checkbox" data-m="${escapeHtml(mk)}" data-a="delete" ${checked('delete')}> حذف</label>
      </div>`);
    }
  }
  mount.innerHTML = `${toolbar}<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:10px;align-items:start;">${parts.join('')}</div>`;
}

function collectSubAdminPermissions() {
  const out = {};
  getSubAdminModuleKeys().forEach((mk) => {
    out[mk] = { read: 0, create: 0, update: 0, delete: 0 };
  });
  document.querySelectorAll('#subAdminPermGrid input[type="checkbox"]').forEach((el) => {
    const mk = el.getAttribute('data-m');
    const ak = el.getAttribute('data-a');
    if (out[mk] && out[mk][ak] != null) out[mk][ak] = el.checked ? 1 : 0;
  });
  return out;
}

async function openCreateSubAdmin() {
  const sel = document.getElementById('subAdminCompanySelect');
  if (!sel || !sel.value) return showToast('Choose company first', 'error');
  document.getElementById('subAdminId').value = '';
  document.getElementById('subAdminModalTitle').textContent = 'Create Sub Admin';
  document.getElementById('saUsername').value = '';
  document.getElementById('saPassword').value = '';
  document.getElementById('saDisplayName').value = '';
  await ensurePermissionModuleDefs();
  buildSubAdminPermissionGrid();
  openModal('subAdminModal');
}

async function loadCompanySubAdmins() {
  const sel = document.getElementById('subAdminCompanySelect');
  const tbody = document.getElementById('subAdminsTable');
  if (!sel || !tbody) return;
  const cid = sel.value.trim();
  if (!cid) {
    tbody.innerHTML = '<tr><td colspan="5" style="text-align:center;padding:32px;color:var(--text-muted);">Choose company first.</td></tr>';
    return;
  }
  const res = await api('GET', 'super/company-admins', { company_id: cid });
  if (!res.success) {
    tbody.innerHTML = `<tr><td colspan="5" style="text-align:center;padding:32px;color:var(--danger);">${escapeHtml(res.message || 'Load failed')}</td></tr>`;
    return;
  }
  const rows = Array.isArray(res.data) ? res.data : [];
  if (!rows.length) {
    tbody.innerHTML = '<tr><td colspan="5" style="text-align:center;padding:32px;color:var(--text-muted);">No sub-admin accounts.</td></tr>';
    return;
  }
  tbody.innerHTML = rows.map((r) => `<tr>
    <td>${escapeHtml(r.username || '')}</td>
    <td>${escapeHtml(r.display_name || '—')}</td>
    <td>${Number(r.is_active) === 1 ? '<span class="badge badge-active">ACTIVE</span>' : '<span class="badge badge-suspended">DISABLED</span>'}</td>
    <td style="font-size:12px;color:var(--textM);">${escapeHtml(String(r.created_at || '').substring(0, 19))}</td>
    <td>
      <button type="button" class="btn btn-sm btn-ghost" onclick='editSubAdmin(${JSON.stringify(r)})'>Edit</button>
      <button type="button" class="btn btn-sm btn-ghost" onclick='resetSubAdminPassword(${Number(r.id)})'>Reset password</button>
      <button type="button" class="btn btn-sm ${Number(r.is_active) === 1 ? 'btn-danger' : 'btn-ghost'}" onclick='toggleSubAdminStatus(${Number(r.id)}, ${Number(r.is_active) === 1 ? 0 : 1})'>${Number(r.is_active) === 1 ? 'Disable' : 'Enable'}</button>
    </td>
  </tr>`).join('');
}

async function editSubAdmin(row) {
  await ensurePermissionModuleDefs();
  document.getElementById('subAdminId').value = String(row.id || '');
  document.getElementById('subAdminModalTitle').textContent = 'Edit Sub Admin';
  document.getElementById('saUsername').value = row.username || '';
  document.getElementById('saPassword').value = '';
  document.getElementById('saDisplayName').value = row.display_name || '';
  const perm = await api('GET', 'super/company-admin-permissions', { sub_admin_id: row.id });
  buildSubAdminPermissionGrid(perm.success ? (perm.data || {}) : {});
  openModal('subAdminModal');
}

async function saveSubAdmin() {
  if (_savingSubAdmin) return;
  const sel = document.getElementById('subAdminCompanySelect');
  const id = document.getElementById('subAdminId').value.trim();
  const username = document.getElementById('saUsername').value.trim();
  const password = document.getElementById('saPassword').value;
  const displayName = document.getElementById('saDisplayName').value.trim();
  const permissions = collectSubAdminPermissions();
  if (!sel || !sel.value) return showToast('Choose company first', 'error');
  if (!username) return showToast('Username is required', 'error');
  if (!id && !password) return showToast('Password is required', 'error');
  const saveBtn = document.querySelector('#subAdminModal .btn.btn-primary[onclick="saveSubAdmin()"]');
  _savingSubAdmin = true;
  if (saveBtn) {
    saveBtn.disabled = true;
    saveBtn.style.opacity = '0.6';
    saveBtn.style.pointerEvents = 'none';
  }
  try {
    const res = !id
      ? await api('POST', 'super/company-admins', { company_id: sel.value, username, password, display_name: displayName, permissions })
      : await api('PUT', 'super/company-admins', { sub_admin_id: Number(id), username, display_name: displayName });
    if (!res.success) return showToast(res.message || 'Save failed', 'error');
    if (id && password) {
      const pwRes = await api('PUT', 'super/company-admins/password', { sub_admin_id: Number(id), password });
      if (!pwRes.success) return showToast(pwRes.message || 'Password save failed', 'error');
    }
    if (id) {
      const rp = await api('PUT', 'super/company-admin-permissions', { sub_admin_id: Number(id), permissions });
      if (!rp.success) return showToast(rp.message || 'Permissions save failed', 'error');
    }
    closeModal('subAdminModal');
    showToast('Saved', 'success');
    loadCompanySubAdmins();
  } finally {
    _savingSubAdmin = false;
    if (saveBtn) {
      saveBtn.disabled = false;
      saveBtn.style.opacity = '1';
      saveBtn.style.pointerEvents = 'all';
    }
  }
}

function resetSubAdminPassword(id) {
  const subAdminId = Number(id);
  if (!Number.isFinite(subAdminId) || subAdminId <= 0) return showToast('Invalid sub-admin id', 'error');
  const idEl = document.getElementById('subAdminResetId');
  const pwEl = document.getElementById('subAdminResetPassword');
  if (!idEl || !pwEl) return showToast('Password modal not available', 'error');
  idEl.value = String(subAdminId);
  pwEl.value = '';
  openModal('subAdminResetPasswordModal');
  setTimeout(() => pwEl.focus(), 0);
}

async function submitSubAdminPasswordReset() {
  const idEl = document.getElementById('subAdminResetId');
  const pwEl = document.getElementById('subAdminResetPassword');
  if (!idEl || !pwEl) return showToast('Password modal not available', 'error');
  const subAdminId = Number(idEl.value);
  const nextPassword = String(pwEl.value || '').trim();
  if (!Number.isFinite(subAdminId) || subAdminId <= 0) return showToast('Invalid sub-admin id', 'error');
  if (!nextPassword) return showToast('Password is required', 'error');
  if (nextPassword.length < 8) return showToast('Password must be at least 8 chars', 'error');
  const res = await api('PUT', 'super/company-admins/password', { sub_admin_id: subAdminId, password: nextPassword });
  if (res.success) showToast('Password updated', 'success');
  else showToast(res.message || 'Failed', 'error');
  if (res.success) {
    pwEl.value = '';
    closeModal('subAdminResetPasswordModal');
  }
}

async function toggleSubAdminStatus(id, isActive) {
  const res = await api('PUT', 'super/company-admins/status', { sub_admin_id: id, is_active: isActive ? 1 : 0 });
  if (res.success) { showToast('Updated', 'success'); loadCompanySubAdmins(); }
  else showToast(res.message || 'Failed', 'error');
}

async function loadSmtpSettings() {
  if (!companiesCache.length) {
    await loadCompanies();
  }
  syncSmtpTestCompanySelect();
  const res = await api('GET', 'super/smtp-settings');
  const src = document.getElementById('smtpEffectiveSource');
  const pwHint = document.getElementById('smtpPwHint');
  if (!res.success) {
    if (src) src.textContent = '';
    showToast(res.message || 'Failed to load SMTP settings', 'error');
    await loadWebpushSettings();
    return;
  }
  const d = res.data || {};
  if (src) {
    const eff = d.effective_source === 'database' ? 'active: DB' : 'active: config constants';
    src.textContent = eff;
  }
  document.getElementById('smtpHost').value = d.smtp_host || '';
  document.getElementById('smtpPort').value = d.smtp_port != null ? String(d.smtp_port) : '587';
  const enc = (d.smtp_encryption || 'tls').toLowerCase();
  document.getElementById('smtpEncryption').value = ['tls', 'ssl', 'none'].includes(enc) ? enc : 'tls';
  document.getElementById('smtpUsername').value = d.smtp_username || '';
  document.getElementById('smtpFromEmail').value = d.from_email || '';
  document.getElementById('smtpFromName').value = d.from_name || 'HR Pro';
  document.getElementById('smtpReplyTo').value = d.reply_to_email || '';
  const pw = document.getElementById('smtpPassword');
  if (pw) pw.value = '';
  if (pwHint) {
    pwHint.textContent = d.password_set ? '(saved — leave password blank to keep)' : '(not set yet)';
  }
  await loadWebpushSettings();
}

async function loadWebpushSettings() {
  const line = document.getElementById('webpushStatusLine');
  const pubEl = document.getElementById('wpPublic');
  const subEl = document.getElementById('wpSubject');
  const priv = document.getElementById('wpPrivate');
  const hint = document.getElementById('wpPrivHint');
  if (!pubEl || !subEl) return;
  const res = await api('GET', 'super/webpush-settings');
  if (!res.success) {
    if (line) line.textContent = '';
    showToast(res.message || 'Failed to load Web Push settings', 'error');
    return;
  }
  const d = res.data || {};
  pubEl.value = d.vapid_public_key || '';
  subEl.value = d.vapid_subject || 'mailto:admin@localhost';
  if (priv) priv.value = '';
  if (hint) {
    hint.textContent = d.private_key_set ? '(saved — leave blank to keep)' : '(required on first save)';
  }
  if (line) {
    const k = d.keys_effective ? 'keys OK' : 'no keys';
    const c = d.composer_installed ? 'composer OK' : 'no composer lib';
    const src = d.effective_source ? ` · ${d.effective_source}` : '';
    line.textContent = `${k} · ${c}${src}`;
  }
}

async function saveWebpushSettings() {
  const body = {
    vapid_public_key: document.getElementById('wpPublic').value.trim(),
    vapid_subject: document.getElementById('wpSubject').value.trim() || 'mailto:admin@localhost'
  };
  const pv = document.getElementById('wpPrivate').value;
  if (pv) body.vapid_private_key = pv;
  const res = await api('PUT', 'super/webpush-settings', body);
  if (res.success) {
    showToast(res.message || 'Saved', 'success');
    document.getElementById('wpPrivate').value = '';
    await loadWebpushSettings();
  } else {
    showToast(res.message || 'Save failed', 'error');
  }
}

async function saveSmtpSettings() {
  const body = {
    smtp_host: document.getElementById('smtpHost').value.trim(),
    smtp_port: parseInt(document.getElementById('smtpPort').value, 10) || 587,
    smtp_encryption: document.getElementById('smtpEncryption').value,
    smtp_username: document.getElementById('smtpUsername').value.trim(),
    from_email: document.getElementById('smtpFromEmail').value.trim(),
    from_name: document.getElementById('smtpFromName').value.trim() || 'HR Pro',
    reply_to_email: document.getElementById('smtpReplyTo').value.trim()
  };
  const p = document.getElementById('smtpPassword').value;
  if (p) body.smtp_password = p;
  const res = await api('PUT', 'super/smtp-settings', body);
  if (res.success) {
    showToast(res.message || 'Saved', 'success');
    document.getElementById('smtpPassword').value = '';
    loadSmtpSettings();
  } else {
    showToast(res.message || 'Save failed', 'error');
  }
}

async function sendSmtpTest() {
  const to = document.getElementById('smtpTestTo').value.trim();
  if (!to) return showToast('Enter a test recipient email', 'error');
  const res = await api('POST', 'super/smtp-test', { to });
  if (res.success) showToast(res.message || 'Sent', 'success');
  else showToast(res.message || 'Failed', 'error');
  loadSmtpTestLog();
}

async function loadSmtpTestLog() {
  const body = document.getElementById('smtpTestLogBody');
  if (!body) return;
  try {
    const res = await api('GET', 'super/smtp-test-log');
    if (!res.success || !Array.isArray(res.data) || res.data.length === 0) {
      body.innerHTML = '<span style="color:var(--textM);">No tests yet.</span>';
      return;
    }
    const rows = res.data.map(r => {
      const sent = r.status === 'sent';
      const icon = sent
        ? '<span style="color:#22c55e;font-size:15px;">&#10003;</span>'
        : '<span style="color:#ef4444;font-size:15px;">&#10007;</span>';
      const statusLabel = sent
        ? '<strong style="color:#22c55e;">Sent</strong>'
        : '<strong style="color:#ef4444;">Failed</strong>';
      const errHtml = (!sent && r.error_detail)
        ? `<div style="margin-top:4px;padding:6px 10px;background:rgba(239,68,68,.08);border-radius:6px;font-family:var(--mono);font-size:11px;color:#ef4444;word-break:break-all;">${escHtml(r.error_detail)}</div>`
        : '';
      const ts = r.tested_at ? r.tested_at.replace('T', ' ').replace(/\.\d+$/, '') : '';
      const transport = `${escHtml(r.smtp_host)}:${r.smtp_port} (${escHtml(r.smtp_encryption)})`;
      return `<div style="padding:10px 0;border-bottom:1px solid var(--border);">
        <div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;">
          ${icon} ${statusLabel}
          <span style="color:var(--textM);">${escHtml(r.recipient)}</span>
          <span style="margin-left:auto;color:var(--textM);font-size:11px;font-family:var(--mono);">${ts}</span>
        </div>
        <div style="margin-top:2px;font-size:11px;color:var(--textM);font-family:var(--mono);">${transport}</div>
        ${errHtml}
      </div>`;
    });
    body.innerHTML = `<div style="line-height:1.6;">${rows.join('')}</div>`;
  } catch (e) {
    body.innerHTML = '<span style="color:var(--textM);">Could not load log.</span>';
  }
}

function escHtml(str) {
  if (!str) return '';
  return String(str)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;');
}

async function sendSuperNotificationTestFromTab() {
  const sel = document.getElementById('smtpTestCompany');
  const cid = sel && sel.value ? sel.value.trim() : '';
  if (!cid) return showToast('Choose a company for the leave notification test', 'error');
  const res = await api('POST', 'super/notification-test', { company_id: cid });
  if (res.success) showToast(res.message || 'Test email sent', 'success');
  else showToast(res.message || 'Failed', 'error');
}

function fmtLoginDt(v) {
  if (v == null || v === '') return '—';
  const s = String(v).trim();
  // UTC instant (Z or offset) → always show Africa/Cairo
  if (/^\d{4}-\d{2}-\d{2}T/.test(s) && (s.includes('Z') || /[+-]\d{2}:\d{2}$/.test(s) || /[+-]\d{4}$/.test(s))) {
    const d = new Date(s);
    if (!Number.isNaN(d.getTime())) {
      return new Intl.DateTimeFormat('sv-SE', {
        timeZone: 'Africa/Cairo',
        year: 'numeric', month: '2-digit', day: '2-digit',
        hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false
      }).format(d).replace('T', ' ').substring(0, 19);
    }
  }
  // API already sends Cairo as Y-m-d H:i:s — show as-is (do not pass through local browser TZ)
  return s.replace('T', ' ').substring(0, 19);
}

async function loadLoginInsights() {
  const tbodyA = document.getElementById('loginInsightsAdminTable');
  const tbodyE = document.getElementById('loginInsightsEmployeeTable');
  if (!tbodyA || !tbodyE) return;
  tbodyA.innerHTML = '<tr><td colspan="4" style="text-align:center;padding:24px;color:var(--text-muted);">جاري التحميل…</td></tr>';
  tbodyE.innerHTML = '<tr><td colspan="6" style="text-align:center;padding:24px;color:var(--text-muted);">جاري التحميل…</td></tr>';
  const sel = document.getElementById('loginInsightsCompany');
  const companyId = sel && sel.value ? sel.value.trim() : '';
  const body = companyId ? { company_id: companyId } : {};
  const res = await api('GET', 'super/login-insights', body);
  if (!res.success) {
    const msg = escapeHtml(res.message || 'خطأ في التحميل');
    tbodyA.innerHTML = `<tr><td colspan="4" style="text-align:center;padding:24px;color:var(--danger);">${msg}</td></tr>`;
    tbodyE.innerHTML = `<tr><td colspan="6" style="text-align:center;padding:24px;color:var(--danger);">${msg}</td></tr>`;
    return;
  }
  const d = res.data || {};
  const admins = Array.isArray(d.admin_logins) ? d.admin_logins : [];
  const emps = Array.isArray(d.employee_logins) ? d.employee_logins : [];
  if (!admins.length) {
    tbodyA.innerHTML = '<tr><td colspan="4"><div class="empty-state"><p>لا توجد سجلات دخول لمدراء الشركات ضمن النطاق الحالي.</p></div></td></tr>';
  } else {
    tbodyA.innerHTML = admins.map((r) => `
      <tr>
        <td><strong>${escapeHtml(r.company_name || r.company_id || '—')}</strong></td>
        <td>${escapeHtml(r.admin_username || '—')}</td>
        <td style="font-size:12px;color:var(--textM);">${escapeHtml(fmtLoginDt(r.created_at))}</td>
        <td style="font-size:11px;font-family:var(--mono);">${escapeHtml(r.ip_address || '—')}</td>
      </tr>
    `).join('');
  }
  if (!emps.length) {
    tbodyE.innerHTML = '<tr><td colspan="6"><div class="empty-state"><p>لا توجد سجلات دخول للموظفين ضمن النطاق الحالي.</p></div></td></tr>';
  } else {
    tbodyE.innerHTML = emps.map((r) => `
      <tr>
        <td><strong>${escapeHtml(r.company_name || r.company_id || '—')}</strong></td>
        <td>${escapeHtml(r.employee_name || '—')}</td>
        <td style="direction:ltr;text-align:left;">${escapeHtml(r.employee_username || '—')}</td>
        <td style="font-family:var(--mono);">${escapeHtml(r.employee_code || '—')}</td>
        <td style="font-size:12px;color:var(--textM);">${escapeHtml(fmtLoginDt(r.created_at))}</td>
        <td style="font-size:11px;font-family:var(--mono);">${escapeHtml(r.ip_address || '—')}</td>
      </tr>
    `).join('');
  }
}

async function purgeLoginLogs() {
  const sel = document.getElementById('loginInsightsCompany');
  const companyId = sel && sel.value ? sel.value.trim() : '';
  const arMsg = companyId
    ? 'سيتم حذف جميع سجلات دخول المدير والموظفين لهذه الشركة فقط من سجل التدقيق. متابعة؟'
    : 'سيتم حذف جميع سجلات دخول مدراء الشركات والموظفين في النظام بالكامل من سجل التدقيق. لا يمكن التراجع. متابعة؟';
  if (!confirm(arMsg)) return;
  const res = await api('POST', 'super/purge-login-logs', companyId ? { company_id: companyId } : {});
  if (res.success) {
    const n = (res.data && res.data.deleted != null) ? res.data.deleted : '';
    showToast(res.message || (n !== '' ? `تم الحذف (${n} صف).` : 'تم التنفيذ.'), 'success');
    loadLoginInsights();
  } else {
    showToast(res.message || 'فشل المسح', 'error');
  }
}

async function loadTrialRequests() {
  const tbody = document.getElementById('trialRequestsTable');
  if (!tbody) return;
  tbody.innerHTML = '<tr><td colspan="6" style="text-align:center;padding:24px;color:var(--text-muted);">Loading…</td></tr>';
  const res = await api('GET', 'super/trial-requests');
  if (!res.success) {
    tbody.innerHTML = `<tr><td colspan="6" style="text-align:center;padding:24px;color:var(--danger);">${escapeHtml(res.message || 'Error')}</td></tr>`;
    return;
  }
  const rows = (res.data && res.data.rows) ? res.data.rows : [];
  if (!rows.length) {
    tbody.innerHTML = '<tr><td colspan="6"><div class="empty-state"><p>No trial signups yet.</p></div></td></tr>';
    return;
  }
  tbody.innerHTML = rows.map((r) => `
    <tr>
      <td>${r.id}</td>
      <td><strong>${escapeHtml(r.company_name || '')}</strong></td>
      <td style="font-family:var(--mono);direction:ltr;text-align:left;">${escapeHtml(r.phone || '')}</td>
      <td style="direction:ltr;text-align:left;">${escapeHtml(r.email || '')}</td>
      <td style="font-size:11px;color:var(--textM);font-family:var(--mono);">${escapeHtml(r.ip_address || '—')}</td>
      <td style="font-size:12px;color:var(--textM);">${escapeHtml((r.created_at || '').replace('T', ' ').substring(0, 19))}</td>
    </tr>
  `).join('');
}

async function suspendCompanyAccount(companyId) {
  if (!confirm('Suspend this company? Admins and employees will be blocked until you activate again.')) return;
  const res = await api('PUT', `companies/${companyId}`, { subscription_status: 'suspended' });
  if (res.success) { showToast('Company suspended', 'success'); loadCompanies(); }
  else showToast(res.message || 'Error', 'error');
}

async function activateCompanyAccount(companyId) {
  const res = await api('PUT', `companies/${companyId}`, { subscription_status: 'active' });
  if (res.success) { showToast('Company activated', 'success'); loadCompanies(); }
  else showToast(res.message || 'Error', 'error');
}

async function loadCompanies() {
  const res = await api('GET', 'companies');
  const tbody = document.getElementById('companiesTable');
  if (!res.success || !Array.isArray(res.data) || !res.data.length) {
    companiesCache = [];
    syncLoginInsightsCompanySelect();
    syncSmtpTestCompanySelect();
    tbody.innerHTML = `<tr><td colspan="9"><div class="empty-state"><p>No companies yet. Create your first tenant.</p></div></td></tr>`;
    return;
  }
  companiesCache = res.data;
  syncLoginInsightsCompanySelect();
  syncSmtpTestCompanySelect();
  syncSubAdminCompanySelect();
  tbody.innerHTML = res.data.map(c => {
    const cn = c.contact_person_name || '';
    const cp = c.contact_person_phone || '';
    const contact = (!cn && !cp) ? '—' : `${escapeHtml(cn)}${cn && cp ? ' · ' : ''}<span style="direction:ltr;unicode-bidi:embed;">${escapeHtml(String(cp))}</span>`;
    const close = (c.account_close_at && String(c.account_close_at).substring(0, 10) !== '0000-00-00')
      ? escapeHtml(String(c.account_close_at).substring(0, 10))
      : '—';
    return `
    <tr>
      <td><strong>${escapeHtml(c.name)}</strong></td>
      <td><span class="company-id">${escapeHtml(c.company_id.substring(0, 8))}…</span></td>
      <td>${escapeHtml(c.admin_username)}</td>
      <td style="font-size:12px;">${contact}</td>
      <td>${c.employee_count}</td>
      <td><span class="badge badge-${c.subscription_status}">${String(c.subscription_status).toUpperCase()}</span></td>
      <td style="font-size:12px;color:var(--textM);font-family:var(--mono);">${close}</td>
      <td style="color:var(--text-muted);font-size:12px;">${escapeHtml(String(c.created_at || '').substring(0, 10))}</td>
      <td>
        ${c.subscription_status === 'suspended'
          ? `<button type="button" class="btn btn-sm btn-ghost" onclick='activateCompanyAccount(${JSON.stringify(c.company_id)})'>Activate</button>`
          : `<button type="button" class="btn btn-sm btn-danger" onclick='suspendCompanyAccount(${JSON.stringify(c.company_id)})'>Suspend</button>`}
        <button class="btn btn-sm btn-ghost" onclick='editCompany(${JSON.stringify(c)})'>Edit</button>
        <button class="btn btn-sm btn-danger" onclick='deleteCompany(${JSON.stringify(c.company_id)}, ${JSON.stringify(c.name)})'>Delete</button>
      </td>
    </tr>`;
  }).join('');
}

function openCreateCompany() {
  document.getElementById('editCompanyId').value = '';
  document.getElementById('modalTitle').textContent = 'Create New Company';
  document.getElementById('cName').value = '';
  document.getElementById('cUsername').value = '';
  document.getElementById('cPassword').value = '';
  document.getElementById('cStatus').value = 'trial';
  document.getElementById('cMax').value = '50';
  document.getElementById('cCloseAt').value = '';
  document.getElementById('cContactName').value = '';
  document.getElementById('cContactPhone').value = '';
  const ne = document.getElementById('cNotifEmail');
  if (ne) ne.value = '';
  openModal('companyModal');
}

function editCompany(c) {
  document.getElementById('editCompanyId').value = c.company_id;
  document.getElementById('modalTitle').textContent = 'Edit Company';
  document.getElementById('cName').value = c.name;
  document.getElementById('cUsername').value = c.admin_username;
  document.getElementById('cPassword').value = '';
  document.getElementById('cStatus').value = c.subscription_status;
  document.getElementById('cMax').value = c.max_employees;
  const rawClose = c.account_close_at ? String(c.account_close_at).substring(0, 10) : '';
  document.getElementById('cCloseAt').value = (rawClose && rawClose !== '0000-00-00') ? rawClose : '';
  document.getElementById('cContactName').value = c.contact_person_name || '';
  document.getElementById('cContactPhone').value = c.contact_person_phone || '';
  const ne = document.getElementById('cNotifEmail');
  if (ne) ne.value = c.notification_email || '';
  openModal('companyModal');
}

async function saveCompany() {
  const cid = document.getElementById('editCompanyId').value;
  const body = {
    name: document.getElementById('cName').value,
    admin_username: document.getElementById('cUsername').value,
    admin_password: document.getElementById('cPassword').value,
    subscription_status: document.getElementById('cStatus').value,
    max_employees: parseInt(document.getElementById('cMax').value, 10),
    account_close_at: document.getElementById('cCloseAt').value,
    contact_person_name: document.getElementById('cContactName').value.trim(),
    contact_person_phone: document.getElementById('cContactPhone').value.trim(),
    notification_email: (document.getElementById('cNotifEmail') && document.getElementById('cNotifEmail').value) ? document.getElementById('cNotifEmail').value.trim() : ''
  };
  if (!body.name || !body.admin_username) return showToast('Name and username are required', 'error');
  if (!cid && !body.admin_password) return showToast('Password is required for new company', 'error');

  const res = cid
    ? await api('PUT', `companies/${cid}`, body)
    : await api('POST', 'companies', body);

  if (res.success) {
    closeModal('companyModal');
    showToast(cid ? 'Company updated' : 'Company created successfully', 'success');
    loadCompanies();
  } else showToast(res.message, 'error');
}

let pendingCompanyDeleteId = null;
let pendingCompanyDeleteCode = null;

function generateCompanyDeleteSixDigitCode() {
  return String(100000 + Math.floor(Math.random() * 900000));
}

async function deleteCompany(cid, name) {
  if (!confirm(`Delete "${name}" and ALL its data? This cannot be undone.`)) return;
  pendingCompanyDeleteId = cid;
  pendingCompanyDeleteCode = generateCompanyDeleteSixDigitCode();
  const intro = document.getElementById('companyDeleteConfirmIntro');
  if (intro) intro.textContent = `Company: ${name}`;
  const codeEl = document.getElementById('companyDeleteVerificationCode');
  if (codeEl) codeEl.textContent = pendingCompanyDeleteCode;
  const inp = document.getElementById('companyDeleteCodeInput');
  if (inp) {
    inp.value = '';
    openModal('companyDeleteConfirmModal');
    setTimeout(() => inp.focus(), 150);
  } else {
    pendingCompanyDeleteId = null;
    pendingCompanyDeleteCode = null;
  }
}

function closeCompanyDeleteConfirmModal() {
  pendingCompanyDeleteId = null;
  pendingCompanyDeleteCode = null;
  const inp = document.getElementById('companyDeleteCodeInput');
  if (inp) inp.value = '';
  const codeEl = document.getElementById('companyDeleteVerificationCode');
  if (codeEl) codeEl.textContent = '------';
  closeModal('companyDeleteConfirmModal');
}

async function submitCompanyDeleteConfirm() {
  const cid = pendingCompanyDeleteId;
  const expected = pendingCompanyDeleteCode;
  const inp = document.getElementById('companyDeleteCodeInput');
  if (!cid || !expected) {
    closeCompanyDeleteConfirmModal();
    return;
  }
  const typed = (inp && inp.value) ? inp.value.replace(/\D/g, '') : '';
  if (typed !== expected) {
    showToast('Code does not match. Enter the 6-digit number shown above.', 'error');
    return;
  }
  const res = await api('DELETE', `companies/${cid}`);
  if (res.success) {
    closeCompanyDeleteConfirmModal();
    showToast('Company deleted', 'success');
    loadCompanies();
  } else {
    showToast(res.message, 'error');
  }
}

async function sendSuperNotificationTest() {
  const cid = document.getElementById('editCompanyId').value.trim();
  if (!cid) {
    showToast('Open an existing company (Edit) so we know which tenant to test.', 'error');
    return;
  }
  const res = await api('POST', 'super/notification-test', { company_id: cid });
  if (res.success) showToast(res.message || 'Test email sent', 'success');
  else showToast(res.message || 'Failed', 'error');
}

function fmt(n) {
  if (n == null || n === '') return '0';
  const x = Number(n);
  return Number.isFinite(x) ? String(x) : String(n);
}

function renderCompanyStatsRows(list) {
  if (!list || !list.length) return '<p style="padding:16px;color:var(--textM);">No companies.</p>';
  return list.map((c) => {
    const idShort = (c.company_id || '').substring(0, 8) + '…';
    const cells = [
      ['Employees (act/tot)', `${fmt(c.employees_active)}/${fmt(c.employees_total)}`],
      ['Inactive', fmt(c.employees_inactive)],
      ['Int / ext', `${fmt(c.employees_internal)}/${fmt(c.employees_external)}`],
      ['Dept / branches', `${fmt(c.departments_count)}/${fmt(c.branches_count)}`],
      ['Policies', fmt(c.leave_policies_count)],
      ['Check-in/out today', `${fmt(c.checkins_today)}/${fmt(c.checkouts_today)}`],
      ['Attendance rows 7d / 30d', `${fmt(c.attendance_rows_last_7d)}/${fmt(c.attendance_rows_last_30d)}`],
      ['Loc. alerts 30d', fmt(c.location_alerts_last_30d)],
      ['Leave P/A/R', `${fmt(c.leave_pending)}/${fmt(c.leave_approved)}/${fmt(c.leave_rejected)}`],
      ['Leave req. 30d', fmt(c.leave_requests_last_30d)],
      ['Manual deduct.', fmt(c.leave_manual_deductions)],
      ['Msgs total / unread', `${fmt(c.admin_messages_total)}/${fmt(c.admin_messages_unread)}`],
      ['Admin notif. unrd', fmt(c.admin_notifications_unread)],
      ['QR tokens active', fmt(c.qr_tokens_active)],
      ['Photo / device', `${fmt(c.employees_with_photo)}/${fmt(c.employees_device_bound)}`],
      ['Audit 30d', fmt(c.audit_events_last_30d)],
      ['News (active)', fmt(c.company_news_active)],
    ];
    const grid = cells.map(([k, v]) => `<div class="mini-stat"><div class="k">${k}</div><div class="v">${v}</div></div>`).join('');
    return `
      <div class="company-stats-block">
        <div class="company-stats-head">
          <div>
            <h3>${escapeHtml(c.name || '')}</h3>
            <div style="font-size:12px;color:var(--textM);margin-top:4px;">
              <span class="company-id">${escapeHtml(idShort)}</span>
              · admin <code style="font-size:11px;">${escapeHtml(c.admin_username || '')}</code>
              · <span class="badge badge-${(c.subscription_status || 'trial')}">${escapeHtml((c.subscription_status || '').toUpperCase())}</span>
              · max ${fmt(c.max_employees)}
            </div>
          </div>
        </div>
        <div class="company-stats-grid">${grid}</div>
      </div>`;
  }).join('');
}

function escapeHtml(s) {
  if (s == null) return '';
  return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
}

async function loadStats() {
  const res = await api('GET', 'super/stats');
  const mount = document.getElementById('statsByCompanyMount');
  if (!res.success) {
    if (mount) mount.innerHTML = `<p style="color:var(--danger);padding:12px;">${escapeHtml(res.message || 'Failed to load stats')}</p>`;
    return;
  }
  const d = res.data || {};
  document.getElementById('st-companies').textContent = fmt(d.total_companies);
  const act = fmt(d.active_companies);
  const tr = fmt(d.trial_companies);
  const sus = fmt(d.suspended_companies);
  document.getElementById('st-active').textContent = `${act} / ${tr} / ${sus}`;
  document.getElementById('st-employees').textContent = `${fmt(d.active_employees)} / ${fmt(d.total_employees)}`;
  document.getElementById('st-checkins').textContent = `${fmt(d.checkins_today)} / ${fmt(d.checkouts_today)}`;
  const att7 = document.getElementById('st-att7');
  if (att7) att7.textContent = fmt(d.attendance_rows_last_7d);
  const stLeave = document.getElementById('st-leave');
  if (stLeave) stLeave.textContent = `${fmt(d.leave_pending_total)} / ${fmt(d.leave_approved_total)} / ${fmt(d.leave_rejected_total)}`;
  const stMsg = document.getElementById('st-msg-unread');
  if (stMsg) stMsg.textContent = fmt(d.admin_messages_unread_total);
  const stWn = document.getElementById('st-work-nature');
  if (stWn) stWn.textContent = `${fmt(d.internal_employees)} / ${fmt(d.external_employees)}`;
  if (mount) mount.innerHTML = renderCompanyStatsRows(d.by_company || []);
}

async function seedDemoCompany() {
  if (!confirm('Create demo tenant (company name: demo, admin user/password: demo) with 10 employees and sample attendance/leave? Skips if admin username demo already exists.')) return;
  const res = await api('POST', 'super/seed-demo', {});
  if (res.success) {
    showToast(res.message || 'Done', 'success');
    loadCompanies();
    loadStats();
  } else {
    showToast(res.message || 'Error', 'error');
  }
}

function superPasswordRulesOk(p) {
  if (p.length < 12) return 'At least 12 characters';
  if (!/[A-Z]/.test(p)) return 'Need an uppercase letter';
  if (!/[a-z]/.test(p)) return 'Need a lowercase letter';
  if (!/\d/.test(p)) return 'Need a digit';
  if (!/[^A-Za-z0-9]/.test(p)) return 'Need a special character';
  return null;
}

async function submitSuperPasswordChange() {
  const oldP = document.getElementById('superPwOld').value;
  const newP = document.getElementById('superPwNew').value;
  const new2 = document.getElementById('superPwNew2').value;
  if (!oldP || !newP) return showToast('Fill all fields', 'error');
  if (newP !== new2) return showToast('New passwords do not match', 'error');
  const rule = superPasswordRulesOk(newP);
  if (rule) return showToast(rule, 'error');
  const res = await api('POST', 'super/change-password', { old_password: oldP, new_password: newP });
  if (res.success) {
    document.getElementById('superPwOld').value = '';
    document.getElementById('superPwNew').value = '';
    document.getElementById('superPwNew2').value = '';
    closeModal('superPasswordModal');
    showToast(res.message || 'Password updated', 'success');
  } else {
    showToast(res.message || 'Error', 'error');
  }
}

// ── UI UTILS ──────────────────────────────────────────────────────
function openModal(id) { document.getElementById(id).classList.add('open'); }
function closeModal(id) { document.getElementById(id).classList.remove('open'); }

function showToast(msg, type = 'success') {
  const t = document.getElementById('toast');
  t.textContent = msg;
  t.className = `toast show ${type}`;
  setTimeout(() => t.classList.remove('show'), 3000);
}

async function downloadBackup() {
  const btn = event.currentTarget;
  const oldHtml = btn.innerHTML;
  btn.style.pointerEvents = 'none';
  btn.style.opacity = '0.5';
  
  try {
    const response = await fetch(`${API}?route=${encodeURIComponent('super/backup')}`, {
      method: 'POST',
      headers: { 
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + (authToken||'')
      },
      body: JSON.stringify({ _method: 'GET' })
    });

    if (response.status === 200) {
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `HR_Backup_${new Date().toISOString().split('T')[0].replace(/-/g, '_')}.sql`;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      showToast('Backup downloaded successfully', 'success');
    } else {
      const res = await response.json();
      showToast(res.message || 'Backup failed', 'error');
    }
  } catch (e) {
    showToast('Network error during backup', 'error');
  } finally {
    btn.style.pointerEvents = 'all';
    btn.style.opacity = '1';
  }
}

// Close modal on backdrop click
document.querySelectorAll('.modal-backdrop').forEach(bd => {
  bd.addEventListener('click', e => { if (e.target === bd) closeModal(bd.id); });
});

// Enter key login
document.getElementById('loginPass').addEventListener('keydown', e => { if (e.key === 'Enter') doLogin(); });

// Init
if (authToken) {
  document.getElementById('loginScreen').style.display = 'none';
  document.getElementById('appShell').style.display = 'block';
  loadCompanies();
  loadStats();
}