<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Eventos Deportivos Movistar Plus</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
            font-weight: bold;
        }
        .table-title {
            font-size: 1.2em;
            font-weight: bold;
            margin-top: 20px;
        }
        #loading, #error {
            text-align: center;
            padding: 20px;
        }
        #loading { color: #888; }
        #error { color: red; }
        .button-container {
            margin-bottom: 20px;
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }
        button {
            padding: 5px 10px;
        }
    </style>
</head>
<body>
    <h1>Eventos Deportivos Movistar Plus</h1>
    <h2>by TokyoGhoull</h2>
    <div class="button-container" id="sorting-buttons"></div>
    <div id="loading">Cargando eventos...</div>
    <div id="error"></div>
    <div id="events-container"></div>

    <script>
        let globalEvents = {};
        let availableCategories = new Set();

        function getCurrentSystemDate() {
            const days = ['domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'];
            const months = ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre'];
            
            const today = new Date();
            const dayName = days[today.getDay()];
            const monthName = months[today.getMonth()];
            
            return `${dayName} ${today.getDate()} de ${monthName} de ${today.getFullYear()}`;
        }

        function parseEvents(htmlContent) {
            const parser = new DOMParser();
            const doc = parser.parseFromString(htmlContent, 'text/html');
            const eventsByDate = {};
            const currentSystemDate = getCurrentSystemDate();
            
            const dateSections = doc.querySelectorAll('.fecha-bar');
            
            dateSections.forEach(dateSection => {
                const currentDate = dateSection.textContent.trim();
                
                // Solo guardar eventos si la fecha coincide con la fecha del sistema
                if (currentDate === currentSystemDate) {
                    eventsByDate[currentDate] = [];

                    const parentSection = dateSection.closest('.brick.info-bares');
                    const categorySections = parentSection.querySelectorAll('.content-bares > li');

                    categorySections.forEach(section => {
                        if (section.querySelector('.fecha-bar')) return;

                        const category = section.querySelector('.box-medium')?.textContent || 'Categoría Desconocida';
                        availableCategories.add(category);

                        const eventListItems = section.querySelectorAll('li');

                        eventListItems.forEach(eventItem => {
                            const eventLink = eventItem.querySelector('a');
                            const timeBar = eventItem.querySelector('.time-bar');

                            if (eventLink && timeBar) {
                                eventsByDate[currentDate].push({
                                    fecha: currentDate,
                                    categoria: category,
                                    evento: eventLink.textContent.trim(),
                                    canal: timeBar.childNodes[0].textContent.trim(),
                                    hora: timeBar.querySelector('span')?.textContent || 'Hora no especificada'
                                });
                            }
                        });
                    });
                }
            });

            return eventsByDate;
        }

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

            const originalButton = document.createElement('button');
            originalButton.textContent = 'Orden Original';
            originalButton.onclick = () => renderEventsByDate();
            buttonContainer.appendChild(originalButton);

            const alphabeticalButton = document.createElement('button');
            alphabeticalButton.textContent = 'Orden Alfabético por Categoría';
            alphabeticalButton.onclick = () => renderEventsByGeneralCategory();
            buttonContainer.appendChild(alphabeticalButton);

            const eventButton = document.createElement('button');
            eventButton.textContent = 'Ordenar por Evento';
            eventButton.onclick = () => renderEventsByEvent();
            buttonContainer.appendChild(eventButton);

            const channelButton = document.createElement('button');
            channelButton.textContent = 'Ordenar por Canal';
            channelButton.onclick = () => renderEventsByChannel();
            buttonContainer.appendChild(channelButton);

            categories.forEach(category => {
                const categoryButton = document.createElement('button');
                categoryButton.textContent = `Ordenar ${category}`;
                categoryButton.onclick = () => renderEventsBySpecificCategory(category);
                buttonContainer.appendChild(categoryButton);
            });
        }

        function renderEventsByDate() {
            const container = document.getElementById('events-container');
            container.innerHTML = '';

            Object.entries(globalEvents).forEach(([date, events]) => {
                if (events.length === 0) return;

                const dateTitle = document.createElement('div');
                dateTitle.className = 'table-title';
                dateTitle.textContent = date;
                container.appendChild(dateTitle);

                const table = document.createElement('table');
                const thead = document.createElement('thead');
                thead.innerHTML = `
                    <tr>
                        <th>Hora</th>
                        <th>Categoría</th>
                        <th>Evento</th>
                        <th>Canal</th>
                    </tr>
                `;
                table.appendChild(thead);

                const tbody = document.createElement('tbody');
                events.forEach(event => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${event.hora}</td>
                        <td>${event.categoria}</td>
                        <td>${event.evento}</td>
                        <td>${event.canal}</td>
                    `;
                    tbody.appendChild(row);
                });

                table.appendChild(tbody);
                container.appendChild(table);
            });
        }

        function renderEventsByGeneralCategory() {
            const container = document.getElementById('events-container');
            container.innerHTML = '';

            const sortedDates = Object.keys(globalEvents).sort();
            sortedDates.forEach(date => {
                if (globalEvents[date].length === 0) return;

                const dateTitle = document.createElement('div');
                dateTitle.className = 'table-title';
                dateTitle.textContent = date;
                container.appendChild(dateTitle);

                const table = document.createElement('table');
                const thead = document.createElement('thead');
                thead.innerHTML = `
                    <tr>
                        <th>Hora</th>
                        <th>Categoría</th>
                        <th>Evento</th>
                        <th>Canal</th>
                    </tr>
                `;
                table.appendChild(thead);

                const tbody = document.createElement('tbody');
                const sortedEvents = [...globalEvents[date]].sort((a, b) => a.categoria.localeCompare(b.categoria));
                sortedEvents.forEach(event => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${event.hora}</td>
                        <td>${event.categoria}</td>
                        <td>${event.evento}</td>
                        <td>${event.canal}</td>
                    `;
                    tbody.appendChild(row);
                });

                table.appendChild(tbody);
                container.appendChild(table);
            });
        }

        function renderEventsByEvent() {
            const container = document.getElementById('events-container');
            container.innerHTML = '';

            const sortedDates = Object.keys(globalEvents).sort();
            sortedDates.forEach(date => {
                const eventsOnDate = Object.values(globalEvents).flat().filter(event => event.fecha === date);
                if (eventsOnDate.length === 0) return;

                const dateTitle = document.createElement('div');
                dateTitle.className = 'table-title';
                dateTitle.textContent = date;
                container.appendChild(dateTitle);

                const table = document.createElement('table');
                const thead = document.createElement('thead');
                thead.innerHTML = `
                    <tr>
                        <th>Hora</th>
                        <th>Evento</th>
                        <th>Categoría</th>
                        <th>Canal</th>
                    </tr>
                `;
                table.appendChild(thead);

                const tbody = document.createElement('tbody');
                const sortedEvents = [...Object.values(globalEvents).flat()]
                    .filter(event => event.fecha === date)
                    .sort((a, b) => a.evento.localeCompare(b.evento));

                sortedEvents.forEach(event => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${event.hora}</td>
                        <td>${event.evento}</td>
                        <td>${event.categoria}</td>
                        <td>${event.canal}</td>
                    `;
                    tbody.appendChild(row);
                });

                table.appendChild(tbody);
                container.appendChild(table);
            });
        }

        function renderEventsByChannel() {
            const container = document.getElementById('events-container');
            container.innerHTML = '';

            const sortedDates = Object.keys(globalEvents).sort();
            sortedDates.forEach(date => {
                const eventsOnDate = Object.values(globalEvents).flat().filter(event => event.fecha === date);
                if (eventsOnDate.length === 0) return;

                const dateTitle = document.createElement('div');
                dateTitle.className = 'table-title';
                dateTitle.textContent = date;
                container.appendChild(dateTitle);

                const table = document.createElement('table');
                const thead = document.createElement('thead');
                thead.innerHTML = `
                    <tr>
                        <th>Hora</th>
                        <th>Canal</th>
                        <th>Evento</th>
                        <th>Categoría</th>
                    </tr>
                `;
                table.appendChild(thead);

                const tbody = document.createElement('tbody');
                const sortedEvents = [...Object.values(globalEvents).flat()]
                    .filter(event => event.fecha === date)
                    .sort((a, b) => a.canal.localeCompare(b.canal));

                sortedEvents.forEach(event => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${event.hora}</td>
                        <td>${event.canal}</td>
                        <td>${event.evento}</td>
                        <td>${event.categoria}</td>
                    `;
                    tbody.appendChild(row);
                });

                table.appendChild(tbody);
                container.appendChild(table);
            });
        }

        function renderEventsBySpecificCategory(targetCategory) {
            const container = document.getElementById('events-container');
            container.innerHTML = '';

            const sortedDates = Object.keys(globalEvents).sort();
            sortedDates.forEach(date => {
                const eventsForCategory = globalEvents[date].filter(event => event.categoria === targetCategory);
                
                if (eventsForCategory.length === 0) return;

                const dateTitle = document.createElement('div');
                dateTitle.className = 'table-title';
                dateTitle.textContent = date;
                container.appendChild(dateTitle);

                const table = document.createElement('table');
                const thead = document.createElement('thead');
                thead.innerHTML = `
                    <tr>
                        <th>Hora</th>
                        <th>Evento</th>
                        <th>Canal</th>
                    </tr>
                `;
                table.appendChild(thead);

                const tbody = document.createElement('tbody');
                const sortedEvents = [...eventsForCategory].sort((a, b) => a.hora.localeCompare(b.hora));
                
                sortedEvents.forEach(event => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${event.hora}</td>
                        <td>${event.evento}</td>
                        <td>${event.canal}</td>
                    `;
                    tbody.appendChild(row);
                });

                table.appendChild(tbody);
                container.appendChild(table);
            });
        }

        async function fetchSportsEvents() {
            const proxyUrl = 'https://api.codetabs.com/v1/proxy/?quest=';
            const targetUrl = 'https://www.movistarplus.es/deportesendirectobar';
            
            try {
                const response = await fetch(proxyUrl + targetUrl);
                const htmlContent = await response.text();
                
                globalEvents = parseEvents(htmlContent);
                createSortingButtons(Array.from(availableCategories));
                renderEventsByDate(); // Vista por defecto
                
                document.getElementById('loading').style.display = 'none';
            } catch (error) {
                const errorDiv = document.getElementById('error');
                errorDiv.textContent = `Error: ${error.message}`;
                document.getElementById('loading').style.display = 'none';
            }
        }

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