'use strict';

function applyDesktopScale() {
  const root = document.documentElement;

  if (window.innerWidth <= 600) {
    root.classList.remove('desktop-fixed-ui');
    root.style.removeProperty('--desktop-scale');
    root.style.removeProperty('--desktop-layout-width');
    root.style.removeProperty('--desktop-layout-height');
    return;
  }

  const baseWidth = 1550;
  const scale = Math.min(1, window.innerWidth / baseWidth);
  root.classList.add('desktop-fixed-ui');
  root.style.setProperty('--desktop-scale', scale.toFixed(4));
  root.style.setProperty('--desktop-layout-width', `${(100 / scale).toFixed(4)}%`);
  root.style.setProperty('--desktop-layout-height', `${(100 / scale).toFixed(4)}vh`);
}

applyDesktopScale();
window.addEventListener('resize', applyDesktopScale);

window.appReady = (async () => {
  if (!VegApi.getToken()) {
    window.location.replace('/login.html');
    throw new Error('No session');
  }

  const result = await VegApi.request('/api/auth/me');
  const user = result.user;

  document.querySelectorAll('#userName').forEach((element) => { element.textContent = user.username; });
  document.querySelectorAll('#userCategory').forEach((element) => { element.textContent = user.category; });
  document.querySelectorAll('[data-user-initial]').forEach((element) => {
    element.textContent = String(user.username || 'م').trim().charAt(0).toUpperCase() || 'م';
  });

  document.querySelectorAll('[data-menu]').forEach((element) => {
    if (!user.permissions.includes(element.dataset.menu)) element.hidden = true;
  });

  const required = document.body.dataset.requiredMenu;
  const requiredAny = String(document.body.dataset.requiredAny || '')
    .split(',')
    .map((value) => value.trim())
    .filter(Boolean);

  if (required && !user.permissions.includes(required)) {
    window.location.replace('/app/');
    throw new Error('No permission');
  }

  if (requiredAny.length && !requiredAny.some((key) => user.permissions.includes(key))) {
    window.location.replace('/app/');
    throw new Error('No permission');
  }

  document.querySelectorAll('[data-logout]').forEach((button) => {
    button.addEventListener('click', async () => {
      if (!confirm('هل تريد تسجيل الخروج من النظام؟')) return;
      try { await VegApi.request('/api/auth/logout', { method: 'POST' }); } catch (_) {}
      VegApi.clearToken();
      window.location.replace('/login.html');
    });
  });

  return user;
})().catch((error) => {
  if (!['No session', 'No permission'].includes(error.message)) console.error(error);
  throw error;
});
