import { t } from '../lang/language.js';

const screens = {
  splash: document.querySelector('#studioSplash'),
  menu: document.querySelector('#menuScreen'),
  game: document.querySelector('#gameScreen')
};

export function showScreen(name) {
  Object.values(screens).forEach(screen => screen.classList.remove('is-active'));
  screens[name].classList.add('is-active');
}

function formatScore(value) {
  return String(Math.max(0, Math.floor(value))).padStart(6, '0');
}

export function createGameOver() {
  const overlay = document.querySelector('#gameOverOverlay');
  const panel = overlay.querySelector('.game-over-panel');
  const reason = document.querySelector('#gameOverReason');
  const score = document.querySelector('#gameOverScore');
  const best = document.querySelector('#gameOverBest');
  const celebration = document.querySelector('#recordCelebration');
  const recordScore = document.querySelector('#recordScore');
  const previousRecord = document.querySelector('#previousRecord');
  const newRecordValue = document.querySelector('#newRecordValue');
  const recordMargin = document.querySelector('#recordMargin');
  let lastState = null;
  let lastRecord = null;

  function updateRecordCopy() {
    if (!lastRecord?.isNewRecord) return;
    const margin = Math.max(1, lastState.score - lastRecord.previousHighscore);
    recordMargin.textContent = margin === 1
      ? t('byOnePoint')
      : t('recordMargin').replace('{points}', margin.toLocaleString());
  }

  return {
    show(state, record = { previousHighscore: state.highscore, isNewRecord: false }) {
      lastState = { ...state };
      lastRecord = { ...record };
      reason.textContent = t(state.gameOverReason);
      score.textContent = formatScore(state.score);
      best.textContent = formatScore(state.highscore);

      panel.classList.toggle('has-new-record', record.isNewRecord);
      celebration.classList.toggle('is-visible', record.isNewRecord);
      if (record.isNewRecord) {
        recordScore.textContent = formatScore(state.score);
        previousRecord.textContent = formatScore(record.previousHighscore);
        newRecordValue.textContent = formatScore(state.score);
        updateRecordCopy();
      }
      overlay.classList.add('is-visible');
    },
    refresh() {
      if (lastState?.gameOverReason) reason.textContent = t(lastState.gameOverReason);
      updateRecordCopy();
    },
    hide() {
      lastState = null;
      lastRecord = null;
      panel.classList.remove('has-new-record');
      celebration.classList.remove('is-visible');
      overlay.classList.remove('is-visible');
    }
  };
}
