<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>La Luna - Video Interactivo</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      margin: 0;
      padding: 20px;
      background-color: #000;
    }
    #player-container {
      width: 100%;
      max-width: 800px;
      aspect-ratio: 16 / 9;
      position: relative;
      overflow: hidden;
      background-color: #000;
      border: 2px solid #ccc;
      border-radius: 20px;
    }
    #player {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      cursor: pointer;
      border-radius: 20px;
    }
    #controls-overlay {
      position: absolute;
      bottom: 10px;
      right: 10px;
      z-index: 10;
      opacity: 0;
      transition: opacity 0.3s ease;
      pointer-events: none;
      display: flex;
      align-items: center;
      gap: 10px;
    }
    #player-container:hover #controls-overlay {
      opacity: 1;
      pointer-events: auto;
    }
    #controls-overlay button {
      padding: 8px 16px;
      font-size: 15px;
      cursor: pointer;
      background-color: rgba(0, 140, 186, 0.85);
      color: white;
      border: none;
      border-radius: 8px;
      transition: background-color 0.3s ease;
    }
    #controls-overlay button:hover {
      background-color: rgba(0, 95, 127, 0.9);
    }
    #volume-bar {
      display: flex;
      align-items: flex-end;
      height: 30px;
      width: 60px;
      cursor: pointer;
      margin-left: 10px;
    }
    .vol-line {
      width: 6px;
      margin: 0 1px;
      background-color: #90ee90;
      border-radius: 2px;
      transition: height 0.2s ease, background-color 0.3s ease;
    }
    .vol-line.inactive {
      background-color: #ccc;
    }
    #quiz-container {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background-color: rgba(255, 255, 255, 0.9);
      padding: 20px;
      border-radius: 10px;
      box-shadow: 0 0 10px rgba(0,0,0,0.3);
      text-align: center;
      z-index: 20;
    }
    #rewind-message {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background-color: rgba(255, 0, 0, 0.8);
      color: white;
      padding: 10px 20px;
      border-radius: 5px;
      z-index: 30;
      display: none;
    }
    #time-display {
      position: absolute;
      top: 10px;
      right: 10px;
      font-size: 20px;
      color: #90EE90;
      text-shadow: 2px 2px 4px black;
      z-index: 10;
    }
    #timeline {
      width: 100%;
      max-width: 800px;
      height: 20px;
      background-color: #ddd;
      position: relative;
      margin-top: 20px;
      border-radius: 10px;
      overflow: hidden;
    }
    #progress {
      width: 0;
      height: 100%;
      background-color: #4CAF50;
      position: absolute;
      top: 0;
      left: 0;
    }
    .marker {
      position: absolute;
      width: 2px;
      height: 20px;
      background-color: #FF5722;
      z-index: 2;
    }
    #feedback {
      margin-top: 10px;
      font-size: 16px;
    }
	button {
            margin: 5px;
            padding: 10px;
            cursor: pointer;
            background-color: #008CBA;
            color: white;
            border: none;
            border-radius: 5px;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: #005f7f;
        }
  </style>
</head>
<body>

  <div id="player-container">
    <video id="player" autoplay>
      <source src="videos/video1_fases_luna.mp4" type="video/mp4">
      Tu navegador no soporta la reproducción de video.
    </video>

    <div id="controls-overlay">
      <button id="playBtn">▶️ Iniciar</button>
      <button id="pauseBtn">⏸️ Pausar</button>
      <div id="volume-bar" title="Control de volumen">
        <div class="vol-line" style="height: 20%;"></div>
        <div class="vol-line" style="height: 40%;"></div>
        <div class="vol-line" style="height: 60%;"></div>
        <div class="vol-line" style="height: 80%;"></div>
        <div class="vol-line" style="height: 100%;"></div>
      </div>
    </div>

    <div id="quiz-container" style="display: none;">
      <h4 id="question"></h4>
      <div id="options"></div>
      <p id="feedback"></p>
    </div>

    <div id="rewind-message">Retroceso por responder mal</div>
    <div id="time-display">00:00/00:00</div>
  </div>

  <div id="timeline">
    <div id="progress"></div>
  </div>

<script>
  const player = document.getElementById('player');
  const progress = document.getElementById('progress');
  const rewindMessage = document.getElementById('rewind-message');
  const timeDisplay = document.getElementById('time-display');
  const playBtn = document.getElementById('playBtn');
  const pauseBtn = document.getElementById('pauseBtn');
  const volumeBar = document.getElementById('volume-bar');
  const volLines = volumeBar.querySelectorAll('.vol-line');

  let currentQuestionIndex = 0;
  let isQuestionActive = false;

  // Preguntas base sin tiempo asignado aún
  let questions = [
    {
      text: "¿Las lunas llenas ocurren cada?",
      options: ["14 días aproximadamente", "29,5 días aproximadamente", "31,5 días aproximadamente", "Todas las anteriores"],
      correctAnswer: 1,
      answeredCorrectly: false
    },
    {
      text: "En que fase la mitad de la Luna visible desde la Tierra está iluminada, pero la parte iluminada disminuye con el paso de los días.",
      options: ["Luna Nueva", "Cuarto Creciente", "Luna Llena", "Cuarto Menguante"],
      correctAnswer: 3,
      answeredCorrectly: false
    },
	
	{
      text: "Durante la fase de Luna Nueva, la Luna se encuentra entre la Tierra y el Sol...",
      options: ["Verdadero", "Falso"],
      correctAnswer: 0,
      answeredCorrectly: false
    },
   
	{
      text: " Al igual que la Tierra, la Luna tiene un lado diurno y un lado nocturno, que cambian a medida que gira.",
      options: ["Verdadero", "Falso"],
      correctAnswer: 0,
      answeredCorrectly: false
    },
	{
      text: "Cada dos meses cualquiera vemos ocho fases diferentes de la Luna.",
      options: ["Verdadero", "Falso"],
      correctAnswer: 1,
      answeredCorrectly: false
    },
	{
      text: "Las ocho fases lunares son, en orden: luna nueva , cuarto creciente , cuarto creciente , luna gibosa creciente , luna llena , luna gibosa menguante , cuarto menguante y cuarto menguante ",
      options: ["Verdadero", "Falso"],
      correctAnswer: 0,
      answeredCorrectly: false
    },
	{
      text: "¿En qué fecha aterrizó en la Luna la primera misión tripulada?",
      options: ["19 de junio de 1972", "20 de mayo de 1959", "20 de julio de 1969", "30 de julio de 1970"],
      correctAnswer: 2,
      answeredCorrectly: false
    }
  ];

  // Mezclar aleatoriamente el arreglo de preguntas
  function shuffleArray(arr) {
    for (let i = arr.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [arr[i], arr[j]] = [arr[j], arr[i]];
    }
  }

  // Asignar tiempos crecientes (espaciados) a las preguntas mezcladas
  function assignQuestionTimes() {
    shuffleArray(questions);
    const baseTime = 8; // tiempo inicial
    const increment = 10; // segundos entre preguntas

    questions.forEach((q, i) => {
      q.time = baseTime + i * increment;
    });
  }

  assignQuestionTimes(); // Ejecutar al inicio

  function setMarkers() {
    document.querySelectorAll('.marker').forEach(m => m.remove());
    const duration = player.duration;
    questions.forEach(q => {
      if (!q.answeredCorrectly) {
        const marker = document.createElement('div');
        marker.className = 'marker';
        marker.style.left = `${(q.time / duration) * 100}%`;
        document.getElementById('timeline').appendChild(marker);
      }
    });
  }

    function updateProgress() {
      const currentTime = player.currentTime;
      const duration = player.duration;
      progress.style.width = `${(currentTime / duration) * 100}%`;
      timeDisplay.textContent = `${formatTime(currentTime)}/${formatTime(duration)}`;
      if (!player.paused) requestAnimationFrame(updateProgress);
    }

    function formatTime(sec) {
      const m = String(Math.floor(sec / 60)).padStart(2, '0');
      const s = String(Math.floor(sec % 60)).padStart(2, '0');
      return `${m}:${s}`;
    }

    function checkTime() {
      if (isQuestionActive) return;
      const currentTime = Math.floor(player.currentTime);
      if (currentQuestionIndex < questions.length) {
        const q = questions[currentQuestionIndex];
        if (!q.answeredCorrectly && currentTime >= q.time) {
          isQuestionActive = true;
          player.pause();
          showQuestion(currentQuestionIndex);
        }
      }
    }

    function showQuestion(index) {
      const quiz = document.getElementById('quiz-container');
      const q = questions[index];
      document.getElementById('question').textContent = q.text;
      const options = document.getElementById('options');
      options.innerHTML = '';
      document.getElementById('feedback').textContent = '';
      disableControls(true);

      q.options.forEach((opt, i) => {
        const btn = document.createElement('button');
        btn.textContent = opt;
        btn.onclick = () => checkAnswer(index, i);
        options.appendChild(btn);
      });

      quiz.style.display = 'block';
    }

    function checkAnswer(index, ansIndex) {
      const q = questions[index];
      const feedback = document.getElementById('feedback');
      const quiz = document.getElementById('quiz-container');

      if (ansIndex === q.correctAnswer) {
        feedback.textContent = '¡Respuesta correcta!';
        feedback.style.color = 'green';
        q.answeredCorrectly = true;
        setTimeout(() => {
          quiz.style.display = 'none';
          currentQuestionIndex++;
          setMarkers();
          isQuestionActive = false;
          disableControls(false);
          player.play();
        }, 1500);
      } else {
        feedback.textContent = 'Respuesta incorrecta.';
        feedback.style.color = 'red';
        setTimeout(() => {
          quiz.style.display = 'none';
          player.currentTime = player.currentTime / 2;
          showRewindMessage();
          isQuestionActive = false;
          disableControls(false);
          player.play();
        }, 1500);
      }
    }

    function disableControls(state) {
      const pointer = state ? 'none' : 'auto';
      [playBtn, pauseBtn, player, volumeBar].forEach(el => el.style.pointerEvents = pointer);
    }

    function showRewindMessage() {
      rewindMessage.style.display = 'block';
      setTimeout(() => rewindMessage.style.display = 'none', 2000);
    }

    function updateVolumeDisplay(vol) {
      volLines.forEach((line, i) => {
        if ((i + 1) / volLines.length <= vol) {
          line.classList.remove('inactive');
        } else {
          line.classList.add('inactive');
        }
      });
    }

    volumeBar.addEventListener('click', (e) => {
      const rect = volumeBar.getBoundingClientRect();
      const clickX = e.clientX - rect.left;
      const newVolume = Math.min(1, Math.max(0, clickX / rect.width));
      player.volume = newVolume;
      updateVolumeDisplay(newVolume);
    });

    playBtn.addEventListener('click', () => { if (!isQuestionActive) player.play(); });
    pauseBtn.addEventListener('click', () => { if (!isQuestionActive) player.pause(); });

    player.addEventListener('loadedmetadata', () => {
      setMarkers();
      updateVolumeDisplay(player.volume);
    });

    player.addEventListener('play', updateProgress);
    player.addEventListener('timeupdate', checkTime);
  </script>
</body>
</html>
