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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Eventos deportivos futbolenlatv.es</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: white;
            color: black;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }

        th,
        td {
            border: 1px solid #cccccc;
            padding: 10px;
            text-align: left;
        }

        th {
            background-color: #f0f0f0;
        }

        .sorting-section {
            margin-bottom: 20px;
            text-align: center;
        }

        .sorting-section button {
            margin: 0 10px 10px 10px;
            padding: 5px 10px;
            background-color: #e0e0e0;
            color: black;
            border: 1px solid #cccccc;
            cursor: pointer;
        }

        td img {
            width: 25px;
            height: 25px;
            vertical-align: middle;
            margin-right: 5px;
        }

        .loading {
            text-align: center;
            color: #666666;
        }

        #debug-iframe {
            width: 100%;
            height: 400px;
            border: 2px solid red;
            margin-top: 20px;
        }
    </style>
</head>

<body>
    <h1>futbolenlatv.es</h1>
    <h2>by TokyoGhoull</h2>

    <div id="sorting-buttons" class="sorting-buttons"></div>
    <div id="category-buttons" class="sorting-section"></div>

    <div id="loading" class="loading">Cargando datos...</div>
    <div id="eventos-container"></div>

    <div>
        <h3>Debugging Information</h3>
        <iframe id="debug-iframe"></iframe>
    </div>

    <script>
        const futbolUrls = [
            'https://www.futbolenlatv.es/deporte',
            'https://www.futbolenlatv.es/deporte/automovilismo',
            'https://www.futbolenlatv.es/deporte/baloncesto',
            'https://www.futbolenlatv.es/deporte/futbol-americano',
            'https://www.futbolenlatv.es/deporte/hockey-patines',
            'https://www.futbolenlatv.es/deporte/rugby',
            'https://www.futbolenlatv.es/deporte/waterpolo',
            'https://www.futbolenlatv.es/deporte/golf',
            'https://www.futbolenlatv.es/deporte/padel',
            'https://www.futbolenlatv.es/deporte/balonmano',
            'https://www.futbolenlatv.es/deporte/boxeo',
            'https://www.futbolenlatv.es/deporte/futbol-sala',
            'https://www.futbolenlatv.es/deporte/motociclismo',
            'https://www.futbolenlatv.es/deporte/tenis',
            'https://www.futbolenlatv.es/deporte/ciclismo',
            'https://www.futbolenlatv.es/deporte/mma',
            'https://www.futbolenlatv.es/competicion/la-liga-promises'
        ];

        const filtrosGenericos = [
            'YouTube', 'Twitch', 'Twitter', 'Facebook', 'DIRECTO', 'directo', 'Directo',
            'Play', 'PLAY', 'play', 'PPV', 'Regístrate', 'acceder', 'Acceder', '.com',
            '.es', 'Web', 'Dispositivos', 'Orange', 'Zapi', 'Galicia', 'Cataluña',
            'OneFootball', 'Lite', '(País Vasco)', 'Aragón', '7Play', 'Netflix',
            'SFC TV', 'La 7', 'Bar', 'App', 'SIN', 'GolTV', 'IMSA', 'Villarreal', 'RugbyPass'
        ];

        const canalesExcluidos = [
            "NBA League Pass", "MAX", "Plaiz", "Canal por confirmar", "FEF TV",
            "GolStadium Premium", "Esport3 Web", "DAZN App Gratis", "EHF TV",
            "Barça One", "Amazon Prime Video", "FCF TV", "Real Betis TV", "RFEF",
            "CONCACAF GO", "LaLiga+", "LaLiga+ Plus", "GolStadium", "CMMPlay",
            "La Xarxa+", "FEB TV", "TV FootballClub", "FANSEA", "FANSEAT",
            "Fight Sports Max", "À Punt (C. Valenciana)", "TV5 Monde",
            "ElCanalDelFutbol", "RTP Internacional", "RCN Nuestra Tele",
            "RFAF TV", "NWSL+", "7 TV Linares", "La Otra (Madrid)", "FIFA+",
            "Extv", "101 TV (Málaga)", "Real Avilés Industrial TV", "VivamóvilTV",
            "Telecartagena", "UEFA TV", "TV Melilla", "La 8 Burgos",
            "IB3 (Baleares)", "Popular TV Murcia", "Betevé (Barcelona)",
            "7 TV Jaén", "Canal Sur", "TPA 1 (Asturias)", "TV Canaria",
            "Real Madrid TV", "Lleida Televisió", "À Punt Mèdia", "Red Bull TV",
            "Eurovision Sports TV", "ATP Tennis TV", "Movistar+",
            "Real Betis TV", "WTA TV", "LFCTV GO",
            "Eurosport 4K (M444 O98)", "VOTV", "GolTV Play"
        ];

        function horaAMinutos(hora) {
            const [horas, minutos] = hora.split(':').map(Number);
            return horas * 60 + minutos;
        }

        function filtrarEventos(eventos) {
            return eventos.filter(evento => {
                const canales = evento.canales.split('<br>').map(canal => canal.trim());

                const canalesFiltrados = canales.filter(canal => {
                    const canalLower = canal.toLowerCase();

                    if (canalesExcluidos.some(excluido => canalLower === excluido.toLowerCase())) {
                        return false;
                    }

                    if (filtrosGenericos.some(filtro => canalLower.includes(filtro.toLowerCase()))) {
                        return false;
                    }

                    return true;
                });

                if (canalesFiltrados.length > 0) {
                    evento.canales = canalesFiltrados.join('<br>');
                    return true;
                }
                return false;
            });
        }

        function agruparPorCategoria(eventos) {
            const categorias = {};
            eventos.forEach(evento => {
                const competicion = evento.competicion.replace(/<[^>]*>/g, '').trim();
                if (!categorias[competicion]) {
                    categorias[competicion] = [];
                }
                categorias[competicion].push(evento);
            });
            return categorias;
        }

        function createSortingButtons(eventos) {
            const buttonContainer = document.getElementById('sorting-buttons');
            buttonContainer.innerHTML = '';

            const buttons = [
                { text: 'Orden Original', action: () => renderEventosPorFecha(eventos) },
                { text: 'Orden Alfabético por Categoría', action: () => renderEventosPorCategoria(eventos) },
                { text: 'Ordenar por Evento', action: () => renderEventosPorEvento(eventos) },
                { text: 'Ordenar por Canal', action: () => renderEventosPorCanal(eventos) }
            ];

            buttons.forEach(btn => {
                const button = document.createElement('button');
                button.textContent = btn.text;
                button.onclick = btn.action;
                buttonContainer.appendChild(button);
            });
        }

        function createCategoryButtons(categorias) {
            const categoryContainer = document.getElementById('category-buttons');
            categoryContainer.innerHTML = '';

            Object.keys(categorias).forEach(categoria => {
                const categoryButton = document.createElement('button');
                categoryButton.textContent = `Ordenar ${categoria}`;
                categoryButton.onclick = () => renderCategoriaPorFecha(categorias[categoria]);
                categoryContainer.appendChild(categoryButton);
            });
        }

        function renderTable(eventos, tbody) {
            eventos.forEach(evento => {
                const fila = document.createElement('tr');
                fila.innerHTML = `
                    <td>${evento.hora}</td>
                    <td>${evento.competicion}</td>
                    <td>${evento.evento}</td>
                    <td>${evento.canales}</td>
                `;
                tbody.appendChild(fila);
            });
        }

        function renderEventosPorFecha(eventos) {
            const container = document.getElementById('eventos-container');
            container.innerHTML = '';

            const tablaEventos = document.createElement('table');
            tablaEventos.innerHTML = `
                <thead>
                    <tr>
                        <th>Hora</th>
                        <th>Competición</th>
                        <th>Evento</th>
                        <th>Canales</th>
                    </tr>
                </thead>
                <tbody></tbody>
            `;
            const tbody = tablaEventos.querySelector('tbody');

            const eventosPorFecha = {};
            eventos.forEach(evento => {
                if (!eventosPorFecha[evento.fecha]) {
                    eventosPorFecha[evento.fecha] = [];
                }
                eventosPorFecha[evento.fecha].push(evento);
            });

            Object.keys(eventosPorFecha).forEach(fecha => {
                eventosPorFecha[fecha].sort((a, b) => a.minutos - b.minutos);
                eventosPorFecha[fecha].forEach(evento => {
                    const fila = document.createElement('tr');
                    fila.innerHTML = `
                        <td>${evento.hora}</td>
                        <td>${evento.competicion}</td>
                        <td>${evento.evento}</td>
                        <td>${evento.canales}</td>
                    `;
                    tbody.appendChild(fila);
                });
            });

            container.appendChild(tablaEventos);
        }

        function renderCategoriaPorFecha(eventos) {
            const container = document.getElementById('eventos-container');
            container.innerHTML = '';

            const tablaEventos = document.createElement('table');
            tablaEventos.innerHTML = `
                <thead>
                    <tr>
                        <th>Hora</th>
                        <th>Competición</th>
                        <th>Evento</th>
                        <th>Canales</th>
                    </tr>
                </thead>
                <tbody></tbody>
            `;
            const tbody = tablaEventos.querySelector('tbody');

            eventos.sort((a, b) => a.minutos - b.minutos);
            renderTable(eventos, tbody);
            container.appendChild(tablaEventos);
        }

        function renderEventosPorCategoria(eventos) {
            const container = document.getElementById('eventos-container');
            container.innerHTML = '';

            const tablaEventos = document.createElement('table');
            tablaEventos.innerHTML = `
                <thead>
                    <tr>
                        <th>Hora</th>
                        <th>Competición</th>
                        <th>Evento</th>
                        <th>Canales</th>
                    </tr>
                </thead>
                <tbody></tbody>
            `;
            const tbody = tablaEventos.querySelector('tbody');

            const eventosOrdenados = eventos.sort((a, b) =>
                a.competicion.localeCompare(b.competicion)
            );

            renderTable(eventosOrdenados, tbody);
            container.appendChild(tablaEventos);
        }

        function renderEventosPorEvento(eventos) {
            const container = document.getElementById('eventos-container');
            container.innerHTML = '';

            const tablaEventos = document.createElement('table');
            tablaEventos.innerHTML = `
                <thead>
                    <tr>
                        <th>Hora</th>
                        <th>Competición</th>
                        <th>Evento</th>
                        <th>Canales</th>
                    </tr>
                </thead>
                <tbody></tbody>
            `;
            const tbody = tablaEventos.querySelector('tbody');

            const eventosOrdenados = eventos.sort((a, b) =>
                a.evento.localeCompare(b.evento)
            );

            renderTable(eventosOrdenados, tbody);
            container.appendChild(tablaEventos);
        }

        function renderEventosPorFecha(eventos) {
            const container = document.getElementById('eventos-container');
            container.innerHTML = '';

            const eventosPorFecha = {};
            eventos.forEach(evento => {
                if (!eventosPorFecha[evento.fecha]) {
                    eventosPorFecha[evento.fecha] = [];
                }
                eventosPorFecha[evento.fecha].push(evento);
            });

            Object.keys(eventosPorFecha).forEach(fecha => {
                const tablaEventos = document.createElement('table');
                tablaEventos.innerHTML = `
                    <thead>
                        <tr>
                            <th colspan="4" style="text-align: center; background-color: #f0f0f0;">
                                Eventos del ${fecha}
                            </th>
                        </tr>
                        <tr>
                            <th>Hora</th>
                            <th>Competición</th>
                            <th>Evento</th>
                            <th>Canales</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                `;
                const tbody = tablaEventos.querySelector('tbody');

                eventosPorFecha[fecha].sort((a, b) => a.minutos - b.minutos);
                eventosPorFecha[fecha].forEach(evento => {
                    const fila = document.createElement('tr');
                    fila.innerHTML = `
                        <td>${evento.hora}</td>
                        <td>${evento.competicion}</td>
                        <td>${evento.evento}</td>
                        <td>${evento.canales}</td>
                    `;
                    tbody.appendChild(fila);
                });

                container.appendChild(tablaEventos);
            });
        }

        async function cargarDatosFutbol() {
            const loading = document.getElementById('loading');
            const container = document.getElementById('eventos-container');
            const debugIframe = document.getElementById('debug-iframe');

            const todosLosEventos = [];

            try {
                const promesas = futbolUrls.map(url => fetch(url));
                const respuestas = await Promise.all(promesas);

                // Create a debug log
                let debugLog = '<html><body><h2>Debugging Information</h2><pre>';

                for (const respuesta of respuestas) {
                    const texto = await respuesta.text();
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(texto, 'text/html');
                    const tablaPrincipal = doc.querySelector('table.tablaPrincipal.detalleVacio');

                    if (!tablaPrincipal) {
                        debugLog += `No se encontró tabla principal en la URL\n`;
                        continue;
                    }
                    const filas = tablaPrincipal.querySelectorAll('tr');
                    let fechaActual = '';

                    debugLog += `Número de filas encontradas: ${filas.length}\n\n`;

                    filas.forEach((fila, index) => {
                        if (fila.classList.contains('cabeceraTabla')) {
                            const fechaTexto = fila.querySelector('td[colspan="5"]').innerText;
                            const match = fechaTexto.match(/(\d{2}\/\d{2}\/\d{4})/);
                            if (match) fechaActual = match[1];
                            debugLog += `Fecha actual encontrada: ${fechaActual}\n`;
                        } else {
                            const hora = fila.querySelector('.hora')?.innerText.trim();
                            const obtenerCompeticion = (fila) => {
                                const contenedor = fila.querySelector('.ajusteDoslineas');
                                if (!contenedor) return { texto: '', imagen: '' };

                                const labelTitle = contenedor.querySelector('label')?.getAttribute('title');
                                const spanTitle = contenedor.querySelector('span > span[title]')?.getAttribute('title');
                                const compImg = contenedor.parentElement.querySelector('img')?.getAttribute('src') || '';

                                if (labelTitle && spanTitle) {
                                    return {
                                        texto: `${labelTitle} - ${spanTitle}`,
                                        imagen: compImg
                                    };
                                }
                                return {
                                    texto: labelTitle || '',
                                    imagen: compImg
                                };
                            };

                            const competicionInfo = obtenerCompeticion(fila);
                            const canalesList = fila.querySelectorAll('.listaCanales li');
                            const canales = [];

                            let evento = '';
                            let imagenLocal = '';
                            let imagenVisitante = '';

                            const eventoUnico = fila.querySelector('.eventoUnico');
                            if (eventoUnico) {
                                evento = eventoUnico.innerHTML;
                            } else {
                                const localElement = fila.querySelector('.local');
                                const visitanteElement = fila.querySelector('.visitante');

                                if (localElement && visitanteElement) {
                                    const local = localElement.querySelector('span')?.getAttribute('title');
                                    const visitante = visitanteElement.querySelector('span')?.getAttribute('title');

                                    imagenLocal = localElement.querySelector('img')?.getAttribute('src') || '';
                                    imagenVisitante = visitanteElement.querySelector('img')?.getAttribute('src') || '';

                                    if (local && visitante) {
                                        evento = `
                                        ${imagenLocal ? `<img src="${imagenLocal}" width="32" height="32" alt="${local}">` : ''}
                                        ${local}
                                        ${imagenVisitante ? `<img src="${imagenVisitante}" width="32" height="32" alt="${visitante}">` : ''}
                                        ${visitante}
                                    `;
                                    }
                                }
                            }

                            canalesList.forEach(canal => {
                                const canalTitulo = canal.getAttribute('title');
                                canales.push(canalTitulo);
                            });

                            if (hora && competicionInfo.texto && evento && canales.length > 0) {
                                todosLosEventos.push({
                                    fecha: fechaActual,
                                    hora,
                                    competicion: `
                                    ${competicionInfo.imagen ? `<img src="${competicionInfo.imagen}" width="22" height="22" alt="Competición">` : ''}
                                    ${competicionInfo.texto}
                                `,
                                    evento,
                                    canales: canales.join('<br>'),
                                    minutos: horaAMinutos(hora)
                                });
                            }
                        }
                    });
                }

                // Escribir información de depuración en el iframe
                debugLog += '</pre></body></html>';
                debugIframe.srcdoc = debugLog;

                todosLosEventos.sort((a, b) => a.minutos - b.minutos);
                const eventosFiltrados = filtrarEventos(todosLosEventos);
                renderEventosPorFecha(eventosFiltrados);
                createSortingButtons(eventosFiltrados);

                loading.style.display = 'none';

                const tablaEventos = document.querySelector("table");
                if (tablaEventos) {
                    tablaEventos.style.display = 'table';
                } else {
                    console.warn("No se encontró la tabla de eventos");
                }

            } catch (error) {
                loading.textContent = 'Error al cargar los datos.';
                console.error(error);
            }
        }

        document.addEventListener('DOMContentLoaded', cargarDatosFutbol);
    </script>
</body>

</html>