document.addEventListener("DOMContentLoaded", function () {
    const sidebar = document.querySelector("nav.sidebar");
    const toggleMobile = document.querySelector(".toggle-mobile");
    const toggleDesktop = document.querySelector(".toggle-desktop");
    const overlay = document.querySelector(".overlay");
    const links = document.querySelectorAll(".menu-links a");
    const sections = document.querySelectorAll("#iframe-container section");

    toggleMobile.addEventListener("click", () => {
        sidebar.classList.add("open");
        overlay.style.display = "block";
    });

    if (toggleDesktop) {
        toggleDesktop.addEventListener("click", () => {
            sidebar.classList.toggle("close");
        });
    }

    overlay.addEventListener("click", () => {
        sidebar.classList.remove("open");
        overlay.style.display = "none";
    });

    links.forEach(link => {
        link.addEventListener("click", function (e) {
            e.preventDefault();
            const target = this.getAttribute("data-section");

            sections.forEach(sec => sec.style.display = "none");
            const selected = document.getElementById(target);
            if (selected) {
                selected.style.display = "block";

                const iframe = selected.querySelector("iframe");
                if (iframe) {
                    iframe.onload = () => {
                        try {
                            const innerDoc = iframe.contentDocument || iframe.contentWindow.document;
                            const contentHeight = innerDoc.body.scrollHeight;
                            iframe.style.height = contentHeight + "px";
                        } catch (e) {
                            console.warn("No se pudo ajustar la altura del iframe:", e);
                        }
                    };
                }
            }

            sidebar.classList.remove("open");
            overlay.style.display = "none";
        });
    });
});
