const STORAGE = {
  token: 'gs_token',
  email: 'gs_email',
};

const LOGIN_MESSAGE_KEY = 'rexr_login_message';

const messageEl = document.getElementById('message');
const sessionBoxEl = document.getElementById('sessionBox');
const fieldGridEl = document.getElementById('fieldGrid');
const emailEl = document.getElementById('email');
const passwordEl = document.getElementById('password');
const loginBtn = document.getElementById('loginBtn');
const continueBtn = document.getElementById('continueBtn');
const clearSessionBtn = document.getElementById('clearSessionBtn');
const minimizeBtn = document.getElementById('minimizeBtn');
const fullscreenBtn = document.getElementById('fullscreenBtn');
const closeBtn = document.getElementById('closeBtn');

let config = null;
let apiBase = '';
let authMode = 'user';
let savedSession = null;

function normalizeBase(url) {
  return String(url || '').replace(/\s+/g, '').replace(/\/?$/, '/');
}

function deriveApiBaseFromSignalBase(base) {
  return normalizeBase(base).replace(/gamestream\/?$/i, '') + 'api/';
}

function hasValidDevKey() {
  return !!(config && config.devKey && !/^CHANGE-ME/i.test(config.devKey));
}

async function postJson(url, body) {
  const response = await fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body || {}),
  });

  let data = null;
  try {
    data = await response.json();
  } catch (error) {
    data = null;
  }

  if (!response.ok && !data) {
    return { ok: false, error: `HTTP ${response.status}` };
  }

  if (data && typeof data === 'object') {
    if (!response.ok && !('ok' in data)) data.ok = false;
    return data;
  }

  return { ok: response.ok };
}

function setMessage(text, isError) {
  messageEl.textContent = text;
  messageEl.classList.toggle('error', !!isError);
}

function showSessionBox(html) {
  sessionBoxEl.innerHTML = html;
  sessionBoxEl.style.display = 'block';
}

function hideSessionBox() {
  sessionBoxEl.innerHTML = '';
  sessionBoxEl.style.display = 'none';
}

function clearStoredAuth() {
  localStorage.removeItem(STORAGE.token);
  localStorage.removeItem(STORAGE.email);
  savedSession = null;
}

function goToDashboard() {
  window.location.replace('/capture.html');
}

async function toggleFullscreen() {
  if (!window.rexrHost || typeof window.rexrHost.toggleFullscreen !== 'function') return;
  try {
    await window.rexrHost.toggleFullscreen();
  } catch (error) {
    setMessage(`Could not change fullscreen mode: ${error.message}`, true);
  }
}

async function minimizeWindow() {
  if (!window.rexrHost || typeof window.rexrHost.minimizeWindow !== 'function') return;
  try {
    await window.rexrHost.minimizeWindow();
  } catch (error) {
    setMessage(`Could not minimize the desktop app: ${error.message}`, true);
  }
}

async function closeWindow() {
  if (!window.rexrHost || typeof window.rexrHost.closeWindow !== 'function') return;
  try {
    await window.rexrHost.closeWindow();
  } catch (error) {
    setMessage(`Could not close the desktop app: ${error.message}`, true);
  }
}

function applyModeUi() {
  if (authMode === 'dev') {
    fieldGridEl.classList.add('hidden');
    loginBtn.classList.add('hidden');

    if (!hasValidDevKey()) {
      continueBtn.classList.add('hidden');
      clearSessionBtn.classList.add('hidden');
      hideSessionBox();
      setMessage('This DEV build still needs a valid DEV key in config.dev.json before the dashboard can open.', true);
      return;
    }

    showSessionBox('<strong>Developer mode is ready.</strong>This app will open the dashboard with unlimited testing access.');
    continueBtn.classList.remove('hidden');
    continueBtn.textContent = 'Open Dashboard';
    clearSessionBtn.classList.add('hidden');
    setMessage('Developer mode is configured. Continue to the dashboard when you are ready.', false);
    return;
  }

  fieldGridEl.classList.remove('hidden');
  loginBtn.classList.remove('hidden');
  continueBtn.classList.add('hidden');
  clearSessionBtn.classList.add('hidden');
  hideSessionBox();
  setMessage('Sign in with the same email and password you use on the PocketVR website to launch the Steam games you already own.', false);
}

async function checkSavedSession() {
  if (authMode !== 'user') return;

  const token = (localStorage.getItem(STORAGE.token) || '').trim();
  const email = (localStorage.getItem(STORAGE.email) || '').trim().toLowerCase();
  if (!token) return;

  setMessage('Checking your saved desktop session...', false);
  const data = await postJson(apiBase + 'account.php', { token });
  if (!data.ok) {
    clearStoredAuth();
    hideSessionBox();
    setMessage('Your saved desktop session expired. Sign in again to continue.', true);
    return;
  }

  savedSession = {
    email: data.email || email,
    credits: null,
    unlimited: !!data.unlimited,
    freeLibraryAccess: !!data.freeLibraryAccess,
  };

  if (emailEl) emailEl.value = savedSession.email || '';
  showSessionBox(
    `<strong>${savedSession.email}</strong><br>${savedSession.unlimited ? 'Unlimited access is active for this account.' : 'Owned Steam games launch for free on this account.'}`,
  );
  continueBtn.classList.remove('hidden');
  continueBtn.textContent = 'Continue To Dashboard';
  clearSessionBtn.classList.remove('hidden');
  setMessage('Your saved session is still valid. Continue to the dashboard or sign in with a different account.', false);
}

async function login() {
  const email = (emailEl.value || '').trim().toLowerCase();
  const password = passwordEl.value || '';

  if (!email || !password) {
    setMessage('Enter your website email and password first.', true);
    return;
  }

  loginBtn.disabled = true;
  setMessage('Signing in to the PocketVR website backend...', false);

  try {
    const data = await postJson(apiBase + 'login.php', { email, password });
    if (!data.ok) {
      setMessage(data.error || 'Login failed.', true);
      return;
    }

    localStorage.setItem(STORAGE.email, data.email || email);
    localStorage.setItem(STORAGE.token, data.token || '');
    showSessionBox(
      `<strong>${data.email || email}</strong><br>${data.unlimited ? 'Unlimited access is active for this account.' : 'Owned Steam games launch for free on this account.'}`,
    );
    passwordEl.value = '';
    continueBtn.classList.remove('hidden');
    clearSessionBtn.classList.remove('hidden');
    setMessage('Sign in complete. Opening your PocketVR library...', false);
    goToDashboard();
  } catch (error) {
    setMessage(`Could not reach the website backend: ${error.message}`, true);
  } finally {
    loginBtn.disabled = false;
  }
}

async function init() {
  const forwardedMessage = sessionStorage.getItem(LOGIN_MESSAGE_KEY);
  if (forwardedMessage) {
    sessionStorage.removeItem(LOGIN_MESSAGE_KEY);
  }

  if (minimizeBtn) minimizeBtn.addEventListener('click', () => minimizeWindow());
  if (fullscreenBtn) fullscreenBtn.addEventListener('click', () => toggleFullscreen());
  if (closeBtn) closeBtn.addEventListener('click', () => closeWindow());
  if (loginBtn) loginBtn.addEventListener('click', login);
  if (continueBtn) continueBtn.addEventListener('click', goToDashboard);
  if (clearSessionBtn) {
    clearSessionBtn.addEventListener('click', () => {
      clearStoredAuth();
      continueBtn.classList.add('hidden');
      clearSessionBtn.classList.add('hidden');
      hideSessionBox();
      setMessage('Saved session cleared. Sign in with a different account to continue.', false);
      if (passwordEl) passwordEl.focus();
    });
  }

  if (emailEl) {
    emailEl.addEventListener('keydown', (event) => {
      if (event.key === 'Enter') {
        event.preventDefault();
        passwordEl.focus();
      }
    });
  }

  if (passwordEl) {
    passwordEl.addEventListener('keydown', (event) => {
      if (event.key === 'Enter') {
        event.preventDefault();
        login();
      }
    });
  }

  document.addEventListener('keydown', (event) => {
    if (event.key === 'F11') {
      event.preventDefault();
      toggleFullscreen();
      return;
    }

    if (event.key === 'Enter' && event.altKey) {
      event.preventDefault();
      toggleFullscreen();
    }
  });

  try {
    config = await fetch('/config.json').then((response) => response.json());
  } catch (error) {
    setMessage('The desktop app could not read config.json. Fix the app package and try again.', true);
    return;
  }

  authMode = /^dev$/i.test(config.appMode || '') ? 'dev' : 'user';
  apiBase = normalizeBase(config.apiBase || deriveApiBaseFromSignalBase(config.signalBase || ''));

  if (!apiBase || apiBase.includes('YOUR-DOMAIN')) {
    setMessage('The desktop app config is still using placeholder URLs. Update config.json and try again.', true);
    return;
  }

  applyModeUi();
  await checkSavedSession().catch((error) => {
    setMessage(`Could not verify the saved desktop session: ${error.message}`, true);
  });

  if (forwardedMessage) {
    setMessage(forwardedMessage, true);
  }
}

init().catch((error) => {
  setMessage(error.message || 'The desktop login screen failed to start.', true);
});
