/*
 * Page checkpoint - calcul des scores et affichage
 */

(function () {
  'use strict';

  // params URL
  const params = new URLSearchParams(window.location.search);
  const difficulty = parseFloat(params.get('difficulty')) || 1;
  const previousScore = parseInt(params.get('score')) || 0;
  const containersRemaining = parseInt(params.get('containers')) || 0;

  // cargaison cumulée sur tous les niveaux
  const totalDeliveredPrev = parseInt(params.get('totalDelivered')) || 0;
  const totalPossiblePrev = parseInt(params.get('totalPossible')) || 0;
  const checkpointsPrev = parseInt(params.get('checkpoints')) || 0;

  // 20 containers par niveau
  const containersThisLevel = 20;

  // Mise à jour des totaux cumulatifs
  const totalDelivered = totalDeliveredPrev + containersRemaining;
  const totalPossible = totalPossiblePrev + containersThisLevel;
  const checkpoints = checkpointsPrev + 1;

  // Calcul des scores
  let totalScore = 0;

  document.addEventListener('DOMContentLoaded', init);

  function init() {
    calculateAndDisplayScores();
    displayCaptainName();
    initSnowEffect();
    bindEvents();
    renderContainersOnBoat();
    initAudio();
  }

  function initAudio() {
    // volume
    let masterVolume = 0.8;
    if (typeof IceBreakerStorage !== 'undefined') {
      const settings = IceBreakerStorage.getSettings();
      masterVolume = settings.masterVolume || 0.8;
    }

    // son victoire
    const successSound = document.getElementById('checkpoint-success');
    if (successSound) {
      successSound.volume = masterVolume * 0.8;
      successSound.play().catch(() => { });
    }

    // ambiance port (mouettes etc)
    const portAmbiance = document.getElementById('port-ambiance');
    if (portAmbiance) {
      portAmbiance.volume = masterVolume * 0.4;
      setTimeout(() => {
        portAmbiance.play().catch(() => { });
      }, 1500);
    }
  }

  function calculateAndDisplayScores() {
    // bonus niveau terminé
    const levelBonus = Math.round(125 * difficulty);

    // bonus containers restants
    const containerBonus = Math.round(containersRemaining * difficulty * 30);

    // Score total
    totalScore = previousScore + levelBonus + containerBonus;

    // Affichage
    const scoreprec = document.getElementById('scoreprec');
    const scoreniv = document.getElementById('scoreniv');
    const contbonus = document.getElementById('contbonus');
    const scoretot = document.getElementById('scoretot');

    if (scoreprec) scoreprec.textContent = previousScore.toLocaleString();
    if (scoreniv) scoreniv.textContent = `+${levelBonus.toLocaleString()}`;
    if (contbonus) contbonus.textContent = `+${containerBonus.toLocaleString()}`;
    if (scoretot) scoretot.textContent = totalScore.toLocaleString();

    // anim score
    if (scoretot) {
      scoretot.classList.add('animate-score');
    }
  }

  function displayCaptainName() {
    const badge = document.getElementById('captain-badge');
    if (badge && typeof IceBreakerStorage !== 'undefined') {
      const name = IceBreakerStorage.getCaptainName();
      if (name) {
        badge.innerHTML = `<span class="badge-icon">⚓</span> Capitaine ${name}`;
      }
    }
  }

  function initSnowEffect() {
    const container = document.getElementById('snow-container');
    if (!container) return;

    const snowflakeCount = 25;
    const fragment = document.createDocumentFragment();

    for (let i = 0; i < snowflakeCount; i++) {
      const flake = document.createElement('div');
      flake.className = 'snowflake';
      flake.style.cssText = `
                left: ${Math.random() * 100}%;
                animation-delay: ${Math.random() * 10}s;
                animation-duration: ${10 + Math.random() * 10}s;
                opacity: ${0.2 + Math.random() * 0.5};
                font-size: ${6 + Math.random() * 10}px;
            `;
      flake.textContent = '❄';
      fragment.appendChild(flake);
    }

    container.appendChild(fragment);
  }

  function renderContainersOnBoat() {
    const deck = document.getElementById('container-deck');
    if (!deck) return;

    deck.innerHTML = '';
    const colors = ['#4fc3f7', '#ffd54f', '#ff8a80'];
    let remaining = containersRemaining;

    for (let r = 0; r < 5; r++) {
      const row = document.createElement('div');
      row.className = 'container-row';

      for (let c = 0; c < 4; c++) {
        const cont = document.createElement('div');
        cont.className = 'container';

        if (remaining > 0) {
          cont.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
          remaining--;
        } else {
          cont.style.opacity = '0';
        }

        row.appendChild(cont);
      }
      deck.appendChild(row);
    }
  }

  function bindEvents() {
    const continueBtn = document.getElementById('continue-btn');
    const lobbyBtn = document.getElementById('lobby-btn');

    continueBtn?.addEventListener('click', continueGame);
    lobbyBtn?.addEventListener('click', returnToLobby);
  }

  function continueGame() {
    const nextDifficulty = difficulty + 0.5;
    // on passe tout au niveau suivant
    window.location.href = `cruise.html?difficulty=${nextDifficulty}&score=${totalScore}&totalDelivered=${totalDelivered}&totalPossible=${totalPossible}&checkpoints=${checkpoints}`;
  }

  function returnToLobby() {
    // retour accueil avec le score
    window.location.href = `index.html?finalScore=${totalScore}&finalDifficulty=${difficulty}&totalDelivered=${totalDelivered}&totalPossible=${totalPossible}&checkpoints=${checkpoints}`;
  }
})();
