<!DOCTYPE html>
<html lang="es">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Eventos Actualizados Elcano.top by TokyoGhoull</title>
  <style>
    body {
      text-align: center;
      background-color: #1a1a1a;
      color: #ffffff;
      transition: background-color 0.5s, color 0.5s;
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 20px;
      display: flex;
      flex-direction: column;
      align-items: center;
      min-height: 100vh;
    }

    h1 {
      text-align: center;
      color: white;
    }

    a {
      text-align: center;
      color: #ff4d4d;
    }

    #estado-carga {
      text-align: center;
      margin: 20px 0;
      color: white;
    }

    .acestream-detectado {
      color: #4CAF50;
    }

    .acestream-no-detectado {
      color: #ff4d4d;
    }

    #tabla-eventos {
      width: 80%;
      max-width: 800px;
      margin: 0 auto;
      border-collapse: collapse;
      background-color: #2d2d2d;
      border-radius: 8px;
      overflow: hidden;
    }

    #tabla-eventos th,
    #tabla-eventos td {
      padding: 12px;
      text-align: center;
      border: 1px solid #404040;
    }

    #tabla-eventos th {
      background-color: #404040;
      color: white;
    }

    #tabla-eventos tr:hover {
      background-color: #363636;
    }


    .source-0 {
      color: #FF6B6B;
    }



    .source-1 {
      color: #4ECDC4;
    }



    .source-2 {
      color: #FFD93D;
    }

    .source-3 {
      color: #A3E635;
    }

    /* New bright lime color for source 4 */

    button {
      background-color: #4CAF50;
      color: white;
      border: none;
      padding: 8px 16px;
      border-radius: 4px;
      cursor: pointer;
    }

    button:hover {
      background-color: #45a049;
    }

    .modal {
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background-color: #2d2d2d;
      border: 1px solid #404040;
      padding: 20px;
      z-index: 1000;
      width: 300px;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.4);
      color: white;
    }

    .modal h3,
    .modal h4 {
      margin: 0;
      text-align: center;
      color: white;
    }

    .modal-button {
      width: 100%;
      margin: 5px 0;
      padding: 10px;
      font-size: 16px;
    }

    .cancel-button {
      background-color: #ff4d4d;
    }

    hr {
      border-color: #404040;
      margin: 15px 0;
    }

    .legend {
      margin-top: 20px;
      padding: 10px;
      background-color: #2d2d2d;
      border-radius: 8px;
      display: inline-block;
    }

    .legend-item {
      margin: 5px;
      display: inline-block;
    }
  </style>
</head>

<body>
  <h1>/⁠╲⁠/⁠\⁠╭⁠(⁠•⁠‿⁠•⁠)⁠╮⁠/⁠\⁠╱⁠\</h1>
  <h1>Eventos Actualizados Elcano.top</h1>
  <h1>by TokyoGhoull</h1>

  <div style="text-align: center; margin-bottom: 20px;">

    <a href="json_android.html" class="button">Ids en json Actualizadas</a>

  </div>

  <div id="estado-carga">Iniciando la recuperación de datos...</div>
  <table id="tabla-eventos">
    <thead>
      <tr>
        <th>Nombre</th>
        <th>Content ID</th>
        <th>Acción</th>
      </tr>
    </thead>
    <tbody>
    </tbody>
  </table>

  <div class="legend">
    <div class="legend-item">
      <span class="source-0">■</span> Origen 1
    </div>
    <div class="legend-item">
      <span class="source-1">■</span> Origen 2
    </div>
    <div class="legend-item">
      <span class="source-2">■</span> Origen 3
    </div>
    <div class="legend-item">
      <span class="source-3">■</span> Origen 4
    </div>
  </div>

  <script>
    const urls = [
      "https://ipfs.io/ipns/elcano.top",
      "https://ipfs.io/ipns/k51qzi5uqu5dgg9al11vomikugim0o1i3l3fxp3ym3jwaswmy9uz8pq4brg1u9",
      "htttps://bafybeihaak6jp7c6y3weyynkfruefwtgchvx2uuppmtts775k4z7kyw4ny.ipfs.dweb.link",
      "https://raw.githubusercontent.com/MoDz17/Ace_Data/main/code_data" // Add your fourth source URL here
    ];

    const tablaEventos = document.getElementById("tabla-eventos").getElementsByTagName("tbody")[0];
    const estadoCarga = document.getElementById("estado-carga");
    let acestreamDetectado = false;
    let playersList = [];

    // Rest of the existing functions remain the same until procesarURL

    async function checkServiceVersion() {
      const url = "http://127.0.0.1:6878/webui/api/service?method=get_version";
      try {
        const response = await fetch(url);
        const data = await response.json();

        if (!data.error) {
          estadoCarga.textContent = "Motor Acestream detectado";
          estadoCarga.classList.add("acestream-detectado");
          acestreamDetectado = true;

          await getAvailablePlayers();
        } else {
          throw new Error(data.error);
        }
      } catch (error) {
        estadoCarga.textContent = "Motor Acestream no detectado. Asegúrate de que esté abierto.";
        estadoCarga.classList.add("acestream-no-detectado");
        acestreamDetectado = false;
      }
    }

    async function getAvailablePlayers() {
      const url = "http://127.0.0.1:6878/server/api?api_version=3&method=get_available_players&content_id=test";
      try {
        const response = await fetch(url);
        const data = await response.json();

        if (!data.error && data.result?.players) {
          playersList = data.result.players;
        } else {
          playersList = [];
        }
      } catch (error) {
        estadoCarga.textContent = "Error al obtener reproductores";
        estadoCarga.classList.add("acestream-no-detectado");
        playersList = [];
      }
    }

    function mostrarModal(contentId) {
      const modal = document.createElement("div");
      modal.classList.add("modal");

      const modalContent = document.createElement("div");

      if (!playersList || playersList.length === 0) {
        modalContent.innerHTML = `
          <h3>Enlaces disponibles</h3>
          <div style="display: flex; flex-direction: column; gap: 10px;">
            <button class="button modal-button" onclick="window.open('acestream://${contentId}', '_blank')">
              Abrir en Acestream (PC/Android)
            </button>
            <button class="button modal-button" onclick="window.open('http://127.0.0.1:6878/server/api?method=open_in_player&player_id=&content_id=${contentId}', '_blank')">
              Abrir stream HTTP (PC)
            </button>
            <button class="button modal-button" onclick="window.open('http://127.0.0.1:6878/ace/manifest.m3u8?id=${contentId}', '_blank')">
              Multiplataforma m3u
            </button>
            <button class="button modal-button cancel-button" onclick="this.closest('.modal').remove()">
              Cancelar
            </button>
          </div>
        `;
      } else {
        modalContent.innerHTML = `
          <h3>Selecciona un reproductor</h3>
          ${playersList.map(player => `
            <button class="button modal-button" onclick="handlePlayerSelection('${player.id}', '${contentId}', this.closest('.modal'))">
              ${player.name}
            </button>
          `).join("")}
          <hr>
          <h4>Enlaces alternativos</h4>
          <button class="button modal-button" onclick="window.open('acestream://${contentId}', '_blank')">
            Abrir en Acestream (PC/Android)
          </button>
          <button class="button modal-button" onclick="window.open('http://127.0.0.1:6878/server/api?method=open_in_player&player_id=&content_id=${contentId}', '_blank')">
            Abrir stream HTTP (PC)
          </button>
          <button class="button modal-button" onclick="window.open('http://127.0.0.1:6878/ace/manifest.m3u8?id=${contentId}', '_blank')">
            Multiplataforma m3u
          </button>
          <button class="button modal-button cancel-button" onclick="this.closest('.modal').remove()">
            Cancelar
            </button>
        `;
      }

      modal.appendChild(modalContent);
      document.body.appendChild(modal);
    }

    function handlePlayerSelection(playerId, contentId, modal) {
      const url = `http://127.0.0.1:6878/server/api?method=open_in_player&player_id=${playerId}&content_id=${contentId}`;
      window.open(url, "_blank");
      modal.remove();
    }

    function mostrarEventos(eventos) {
      tablaEventos.innerHTML = "";

      if (eventos.length === 0) {
        const filaNoEventos = document.createElement("tr");
        filaNoEventos.innerHTML = "<td colspan='3'>No se encontraron eventos.</td>";
        tablaEventos.appendChild(filaNoEventos);
      }

      eventos.forEach(evento => {
        const fila = document.createElement("tr");
        fila.innerHTML = `
          <td>${evento.nombre}</td>
          <td><span class="source-${evento.sourceIndex}">${evento.contentId}</span></td>
          <td>
            <button onclick="mostrarModal('${evento.contentId}')">Iniciar</button>
          </td>
        `;
        tablaEventos.appendChild(fila);
      });
    }

    async function procesarURL(url, sourceIndex, nombresExistentes) {
      try {
        const respuesta = await fetch(url);
        const texto = await respuesta.text();

        // If it's the fourth source (index 3), process it differently
        if (sourceIndex === 3) {
          return procesarTextoPlano(texto, nombresExistentes);
        }

        // Original processing for sources 0-2
        const parser = new DOMParser();
        const doc = parser.parseFromString(texto, "text/html");

        const scriptContent = [...doc.scripts].find(script => script.textContent.includes("linksData"));
        if (!scriptContent) return [];

        const linksDataMatch = scriptContent.textContent.match(/const linksData = ({.*?});/s);
        if (!linksDataMatch) return [];

        const linksData = JSON.parse(linksDataMatch[1]);
        const eventos = [];

        linksData.links.forEach(link => {
          const url = link.url;
          const contentId = url.startsWith("acestream://") ? url.replace("acestream://", "") : null;
          const nombre = link.name?.trim();

          if (contentId && nombre) {
            if (sourceIndex === 0 || !nombresExistentes.has(nombre)) {
              eventos.push({
                nombre: nombre,
                contentId: contentId,
                sourceIndex: sourceIndex
              });
            }
          }
        });

        return eventos;
      } catch (error) {
        console.error(`Error al procesar URL ${sourceIndex}:`, error);
        return [];
      }
    }

    function procesarTextoPlano(texto, nombresExistentes) {
      const eventos = [];
      const lineas = texto.split('\n');
      const idsExistentes = new Set();

      // Primero recopilamos todos los IDs existentes de las otras fuentes
      todosLosEventos.forEach(evento => {
        idsExistentes.add(evento.contentId);
      });

      lineas.forEach(linea => {
        if (!linea.trim()) return;

        // Look for all acestream IDs in the line
        const idsMatches = linea.match(/[a-fA-F0-9]{40}/g);
        if (!idsMatches) return;

        // Extract name: everything before the first ID
        let nombre = linea.substring(0, linea.indexOf(idsMatches[0])).trim();
        nombre = nombre.replace(/[\u{1F300}-\u{1F9FF}]/gu, '').trim(); // Remove emojis
        nombre = nombre.replace(/[➜→⚽️📡]/g, '').trim(); // Remove specific symbols
        nombre = nombre.replace(/\s+/g, ' ').trim(); // Normalize spaces

        // For each ID found in the line
        idsMatches.forEach((contentId, index) => {
          // Verificar si el ID ya existe
          if (!idsExistentes.has(contentId)) {
            // For multiple IDs, append a number to the name except for the first one
            const nombreFinal = index === 0 ? nombre : `${nombre} (Opción ${index + 1})`;
            
            if (nombreFinal) {
              eventos.push({
                nombre: nombreFinal,
                contentId: contentId,
                sourceIndex: 3
              });
              // Añadir el ID a la lista de existentes
              idsExistentes.add(contentId);
            }
          }
        });
      });

      return eventos;
    }

    // El obtenerDatos necesita ser modificado para mantener los eventos globalmente
    let todosLosEventos = [];

    async function obtenerDatos() {
      estadoCarga.textContent = "Recuperando datos, por favor espera...";
      estadoCarga.classList.remove("acestream-no-detectado", "acestream-detectado");

      const nombresExistentes = new Set();
      todosLosEventos = []; // Reset the global array

      // Procesar cada origen en orden
      for (let i = 0; i < urls.length; i++) {
        const eventosDeEstaFuente = await procesarURL(urls[i], i, nombresExistentes);

        // Añadir los eventos y actualizar el set de nombres existentes
        eventosDeEstaFuente.forEach(evento => {
          if (!nombresExistentes.has(evento.nombre)) {
            todosLosEventos.push(evento);
            nombresExistentes.add(evento.nombre);
          }
        });
      }

      mostrarEventos(todosLosEventos);

      estadoCarga.textContent = "Datos recuperados correctamente.";
      setTimeout(() => {
        estadoCarga.textContent = acestreamDetectado ? "Motor Acestream detectado" : "Motor Acestream no detectado. Asegúrate de que esté abierto.";
        estadoCarga.classList.toggle("acestream-detectado", acestreamDetectado);
        estadoCarga.classList.toggle("acestream-no-detectado", !acestreamDetectado);
      }, 3000);
    }

    obtenerDatos();
    checkServiceVersion();
  </script>
</body>

</html>