import { render } from 'preact';
import { App } from './app';
import { applyDisguise } from './lib/disguise';
import { installQuickExitShortcut } from './lib/quickExit';
import { session } from './lib/session';
import { refreshDirectory } from './lib/resources';
import { setLanguage } from './i18n';
import './styles.css';

// Referral links carry a partner tag (FR-ON-01), e.g. /?src=uva. Keep it in
// memory and strip it from the address bar and history entry right away.
const params = new URLSearchParams(location.search);
const source = (params.get('src') ?? params.get('ref') ?? '').replace(/[^a-z0-9_-]/gi, '').slice(0, 32);
if (source) session.set({ referralSource: source.toLowerCase() });
if (location.search || location.hash) history.replaceState(null, '', location.pathname);

applyDisguise();
setLanguage('en');
installQuickExitShortcut();
refreshDirectory();

const root = document.getElementById('app')!;
if (location.pathname.startsWith('/admin')) {
  import('./admin/Admin').then(({ Admin }) => render(<Admin />, root));
} else {
  render(<App />, root);
}

if ('serviceWorker' in navigator && import.meta.env.PROD) {
  navigator.serviceWorker.register('/sw.js').catch(() => {});
}
