const APP_MODE_KEY = 'preferredAppMode';

export const appModes = {
  auto: 'auto',
  pwa: 'pwa',
  desktop: 'desktop',
};

export function getPreferredAppMode() {
  if (typeof window === 'undefined') return appModes.auto;
  const value = localStorage.getItem(APP_MODE_KEY);
  return Object.values(appModes).includes(value) ? value : appModes.auto;
}

export function setPreferredAppMode(mode) {
  if (typeof window === 'undefined') return;
  const nextMode = Object.values(appModes).includes(mode) ? mode : appModes.auto;
  localStorage.setItem(APP_MODE_KEY, nextMode);
}

export function isStandalonePwa() {
  if (typeof window === 'undefined') return false;
  return Boolean(
    window.matchMedia?.('(display-mode: standalone)').matches
    || window.navigator.standalone
  );
}

export function detectAppMode() {
  if (typeof window === 'undefined') return appModes.desktop;
  if (isStandalonePwa()) return appModes.pwa;

  const preferred = getPreferredAppMode();
  if (preferred === appModes.pwa || preferred === appModes.desktop) return preferred;

  const narrowViewport = window.matchMedia?.('(max-width: 767px)').matches || window.innerWidth < 768;
  const mobileAgent = /Android|iPhone|iPad|iPod|IEMobile|Opera Mini|Mobile|Tablet/i.test(window.navigator.userAgent);

  return narrowViewport || mobileAgent ? appModes.pwa : appModes.desktop;
}

export function defaultRouteForAppMode() {
  return detectAppMode() === appModes.pwa ? '/pwa' : '/';
}
