const mainContent = document.querySelector('.main-content');
const mainFotter = document.querySelector('.custom-fotter');
const controlesFotter = document.querySelectorAll('.custom-fotter div');
const mainTools = document.querySelector('.custom-tools');
const deskTitle = document.querySelector('.desk-title');
const deskBody = document.querySelector('.desk-body');

const modalDisclaimer = document.getElementById('modal-disclaimer');
const btnCloseDisclaimer = document.getElementById('btn-close-disclaimer');

let isDoublePage = true; // Asumimos que el libro es a doble página
let currentIndex = 0; // Índice actual en el array
let currentReference = -1;

let componentData;
let componentId;
let iSolutionsData;

const btnSwitch = document.getElementById('btnSwitchPage');
const iconImg = btnSwitch.querySelector('img');

const loader = document.querySelector(".loaderpage");

const showLoader = () => {
    loader.classList.remove("loader-hidden");
};

const hideLoader = () => {
    loader.classList.add("loader-hidden");
};

const buildMenuList = (items, depth = 0) => {
    if (!items || !items.length) return '';

    const listClasses = depth === 0 ? 'menu-list' : 'menu-list nested-group';
    let html = `<ul class="${listClasses}">\n`;

    for (const item of items) {
        html += `    <li class="menu-item">\n`;

        if (item.content && Array.isArray(item.content) && item.content.length > 0) {
            // Elemento desplegable (<details>)
            const nameAttr = depth === 0 ? 'main-nav' : `sub-nav-${depth}`;

            html += `        <details name="${nameAttr}">\n`;
            html += `            <summary>${item.label}</summary>\n`;
            html += `            <div class="content-wrapper">\n`;
            html += `                <div class="content-inner">\n`;

            const subMenu = buildMenuList(item.content, depth + 1);

            const indentedSubMenu = subMenu
                .split('\n')
                .map(line => line ? `                    ${line}` : '')
                .join('\n');

            html += `${indentedSubMenu}\n`;
            html += `                </div>\n`;
            html += `            </div>\n`;
            html += `        </details>\n`;
        } else {
            // Enlace directo
            const pageNum = item.link !== null && item.link !== undefined ? item.link : '';
            html += `        <a href="javascript:irPagina(${pageNum});" class="direct-link">${item.label}</a>\n`;
        }

        html += `    </li>\n`;
    }

    html += `</ul>`;
    return html;
}

const buildExtraMenuList = (items, depth = 0) => {
    if (!items || !items.length) return '';

    const listClasses = depth === 0 ? 'menu-list' : 'menu-list nested-group';
    let html = `<ul class="${listClasses}">\n`;

    for (const item of items) {
        html += `    <li class="menu-item">\n`;

        if (item.content && Array.isArray(item.content) && item.content.length > 0) {
            // Elemento desplegable (<details>)
            const nameAttr = depth === 0 ? 'main-nav' : `sub-nav-${depth}`;

            html += `        <details name="${nameAttr}">\n`;
            html += `            <summary>${item.label}</summary>\n`;
            html += `            <div class="content-wrapper">\n`;
            html += `                <div class="content-inner">\n`;

            const subMenu = buildExtraMenuList(item.content, depth + 1);

            const indentedSubMenu = subMenu
                .split('\n')
                .map(line => line ? `                    ${line}` : '')
                .join('\n');

            html += `${indentedSubMenu}\n`;
            html += `                </div>\n`;
            html += `            </div>\n`;
            html += `        </details>\n`;
        } else {
            // Enlace directo
            const resource = item.resourcePath !== null && item.resourcePath !== undefined && item.resourcePath !== false ? item.resource : false;
            const label = item.label.replace(/'/g, "\\'");

            if (resource) {
                switch (item.resourceFormat) {
                    case 'folder':
                        if (item.resourceType == 'audios') {
                            const dataString = JSON.stringify(item.playlist);
                            const dataEscaped = encodeURIComponent(dataString);


                            html += `<a href="#" class="direct-link openPlayer" data-title="${iSolutionsData.generalSettings.serie_name}"
                                        data-subtitle="${item.label}" data-info="${dataEscaped}" data-path="recursos/extra/audios/${resource}">
                                        ${item.label}
                                    </a>\n`;
                        } else if (item.resourceType == 'videof') {
                            html += `<a href="javascript:abrirModal('vd', 'recursos/extra/videos/${resource}');" class="direct-link">${item.label}</a>\n`;
                        } else if (item.resourceType == 'flashCard') {
                            html += `<a href="javascript:abrirModal('fc', 'recursos/extra/flashCard/${resource}', '${label}');" class="direct-link">${item.label}</a>\n`;
                        } else {
                            html += `<a href="javascript:abrirModal('stand', 'recursos/extra/${item.resourceType}/${resource}', '${label}');" class="direct-link">${item.label}</a>\n`;
                        }
                        break;
                    case 'audios':
                        html += `<a href="javascript:abrirModal('audio', 'recursos/extra/audios/${resource}', '${label}');" class="direct-link">${item.label}</a>\n`;
                        break;
                    case 'documentos':
                        html += `<a href="javascript:abrirModal('docs', 'recursos/extra/documents/${resource}', '${label}');" class="direct-link">${item.label}</a>\n`;
                        break;
                    case 'videos':
                        html += `<a href="javascript:abrirModal('video', 'recursos/extra/videos/${resource}', '${label}');" class="direct-link">${item.label}</a>\n`;
                        break;
                    default:
                        break;
                }
            }
        }

        html += `    </li>\n`;
    }

    html += `</ul>`;
    return html;
}

const activateComponent = () => {
    let linkComponents = document.querySelectorAll('.link-component');
    linkComponents.forEach(link => {
        link.addEventListener('click', function () {

            componentId = this.getAttribute('data-component');

            if (isDoublePage) {
                iconImg.src = "icons/34.svg";
            } else {
                iconImg.src = "icons/17.svg";
            }

            const badagesLinks = document.querySelectorAll(`[data-indexcomponente]`);
            badagesLinks.forEach(l => l.classList.remove('badage-active-component'));

            document.querySelector(`[data-indexcomponente="${componentId}"]`)?.classList.add('badage-active-component');

            // currentIndex = currentReference == -1 ? 1 : currentReference;

            showLoader();
            setTimeout(async () => {
                // Nombre de menus
                const titulosMenus = document.querySelectorAll('div.menu-title-bar span');
                titulosMenus.forEach(elemento => {
                    elemento.innerHTML = `${iSolutionsData.components[componentId].isolutions_component_name}`;
                });

                // Renderizado menu principal
                try {
                    const response = await fetch(`menu_principal${componentId}.json`);
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }

                    const menuData = await response.json();
                    const menuHtml = buildMenuList(menuData);

                    const container = document.querySelector('#menuLista');
                    if (container) {
                        const existingUl = container.querySelector('ul');

                        if (existingUl) {
                            existingUl.remove();
                        }

                        container.insertAdjacentHTML('beforeend', menuHtml);
                    } else {
                        console.warn(`No se encontró el contenedor: ${containerSelector}`);
                    }
                } catch (error) {
                    console.error('Error al cargar o renderizar el menú:', error);
                }

                // Renderizado menu recurso extra
                try {
                    const response = await fetch(`menu_extra.json`);
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }

                    const menuData = await response.json();
                    const menuHtml = buildExtraMenuList(menuData);

                    const container = document.querySelector('#menuRecursosExtras');
                    if (container) {
                        const existingUl = container.querySelector('ul');

                        if (existingUl) {
                            existingUl.remove();
                        }

                        container.insertAdjacentHTML('beforeend', menuHtml);
                    } else {
                        console.warn(`No se encontró el contenedor: ${containerSelector}`);
                    }
                } catch (error) {
                    console.error('Error al cargar o renderizar el menú:', error);
                }

                let jsonData = this.getAttribute('data-config');

                sidebar.classList.add('d-none');

                let library = document.querySelector('.Library');
                library.classList.add('d-none');

                let mainTitle = document.querySelector('.main-title');
                mainTitle.classList.add('d-none');

                let title = this.getAttribute('data-title');
                let shortTitle = this.getAttribute('data-short-title');

                let currentTitle = document.querySelector('#desk-text');
                currentTitle.textContent = title;

                deskTitle.classList.remove('d-none');
                deskBody.classList.remove('d-none');

                cambiarFondos(`url('bg/1.svg'), url('bg/2.svg')`, '20px');

                controlesFotter.forEach(div => {
                    div.classList.remove('d-none');
                });

                mainFotter.style.justifyContent = 'space-between';
                mainTools.classList.remove('d-none');

                fetch(`componentes/${componentId}/${jsonData}`)
                    .then(response => response.json())
                    .then(data => {

                        if (isDoublePage) {
                            if (currentReference === 1) {
                                currentIndex = 1;
                            } else if (currentReference >= data.length) {
                                currentIndex = data.length;
                            } else {
                                currentIndex = (currentReference % 2 !== 0) ? currentReference - 1 : currentReference;
                                if (currentIndex < 1) currentIndex = 1;
                            }
                        } else {
                            currentIndex = currentReference;
                        }

                        componentData = data;
                        updateView();

                        openModal();

                        if (typeof limpiarMosaicos === 'function') {
                            limpiarMosaicos();
                        }
                    })
                    .catch(error => console.error('Error:', error));
            }, 1500); // Simular delay
        });
    });

    let btnBack = document.querySelector('#btnBack');
    btnBack.addEventListener('click', function () {
        showLoader();
        setTimeout(() => {
            sidebar.classList.remove('d-none');

            let library = document.querySelector('.Library');
            library.classList.remove('d-none');
            let mainTitle = document.querySelector('.main-title');
            mainTitle.classList.remove('d-none');

            deskTitle.classList.add('d-none');
            deskBody.classList.add('d-none');

            cambiarFondos('none', '20px 20px 20px 50px');

            controlesFotter.forEach(div => {
                div.classList.add('d-none');
            });

            mainFotter.style.justifyContent = 'center';
            mainTools.classList.add('d-none');
            hideLoader();
        }, 500);
    });
}

const cambiarFondos = (urlS, padding) => {
    mainContent.style.backgroundImage = urlS;
    mainContent.style.padding = padding;
}

// Función para abrir el disclaimer
const openModal = () => {
    // Verificar si el disclaimer debe mostrarse
    const hideDisclaimer = localStorage.getItem('hideDisclaimer');
    if (hideDisclaimer === 'true') {
        return; // No mostrar el disclaimer si el usuario eligió no verlo de nuevo
    }
    modalDisclaimer.style.display = 'flex';
}

// Función para cerrar el disclaimer
const closeModal = () => {
    modalDisclaimer.style.display = 'none';
}


document.querySelectorAll('.lp-trigger').forEach(trigger => {
    trigger.addEventListener('click', function (e) {
        const parent = this.parentElement;
        const isActive = parent.classList.contains('open');

        // 1. Cerramos cualquier menú abierto antes
        document.querySelectorAll('.desk-tools').forEach(tool => {
            tool.classList.remove('open');
            tool.querySelector('.lp-trigger').classList.remove('active');
        });

        // 2. Si no estaba activo, lo activamos
        if (!isActive) {
            parent.classList.add('open');
            this.classList.add('active');
        }

        e.stopPropagation(); // Evita que el clic se propague al body
    });
});

// Cerrar menús al hacer clic fuera
document.addEventListener('click', () => {
    document.querySelectorAll('.desk-tools').forEach(tool => {
        tool.classList.remove('open');
        tool.querySelector('.lp-trigger').classList.remove('active');
    });
});

// Evento para el botón aceptar
btnCloseDisclaimer.addEventListener('click', () => {
    // Aquí puedes guardar en localStorage si el checkbox está marcado
    const isChecked = document.getElementById('dontShowAgain').checked;
    localStorage.setItem('hideDisclaimer', isChecked);

    closeModal();
});

window.addEventListener("load", () => {
    fetch('config.json')
        .then(response => response.json())
        .then(datos => {
            iSolutionsData = datos;
            // Configurar componente
            const contenedorComponentes = document.getElementById('contenedor-componentes');
            const contenedorSwitchComponentes = document.getElementById('contenedor-switch-componentes');

            iSolutionsData.components.forEach((item, index) => {
                const divComponente = document.createElement('div');

                divComponente.className = 'component link-component';

                divComponente.setAttribute('data-component', index);
                divComponente.setAttribute('data-config', `thumbs.json`);
                divComponente.setAttribute('data-title', `${item.isolutions_component_name}`);
                divComponente.setAttribute('data-short-title', 'Component');
                divComponente.setAttribute('tabindex', '0');
                divComponente.setAttribute('role', 'button');
                divComponente.setAttribute('aria-label', `Abrir ${item.isolutions_component_name}`);

                const imageSrc = item.isolutions_component_cover ? item.isolutions_component_cover : `images/componente.jpg`;

                divComponente.innerHTML = `
                    <img src="${imageSrc}" alt="Portada para el componente">
                    <span>${item.isolutions_component_name}</span>
                `;

                contenedorComponentes.appendChild(divComponente);

                const spanSwitch = document.createElement('span');

                spanSwitch.className = 'badage-active-desk link-component';

                spanSwitch.setAttribute('data-indexcomponente', index);
                spanSwitch.setAttribute('data-component', index);
                spanSwitch.setAttribute('data-config', `thumbs.json`);
                spanSwitch.setAttribute('data-title', `${item.isolutions_component_name}`);
                spanSwitch.setAttribute('role', 'button');
                spanSwitch.setAttribute('aria-label', `Abrir ${item.isolutions_component_name}`);
                spanSwitch.innerHTML = item.isolutions_component_name;

                contenedorSwitchComponentes.appendChild(spanSwitch);
            });

            // Configurar titulos
            const subtitulos = document.querySelectorAll('h2.sub-title-section');
            subtitulos.forEach(elemento => {
                elemento.textContent = `${iSolutionsData.generalSettings.serie_name} ${iSolutionsData.generalSettings.audience_target_name} ${iSolutionsData.generalSettings.audience_level_name}`;
            });

            document.title = `${iSolutionsData.generalSettings.serie_name} - ${iSolutionsData.generalSettings.audience_target_name} - ${iSolutionsData.generalSettings.audience_level_name}`;

            setTimeout(() => {
                hideLoader();
                activateComponent();
            }, 2000);
        })
        .catch(error => console.error('Error al leer el JSON de configuracion:', error));
});