export class MobileNav {
    constructor() {
        this.initMobileNav();
        this.initMessagesResponsive();
        this.initMessageThread();
    }

    initMobileNav() {
        const btn = document.getElementById("hamburger-btn");
        const panel = document.getElementById("mobile-panel");
        const overlay = document.getElementById("mobile-overlay");
        if (!btn || !panel || !overlay) return;

        const close = () => {
            panel.classList.remove("open");
            overlay.style.display = "none";
            btn.innerHTML = "☰";
        };

        const open = () => {
            panel.classList.add("open");
            overlay.style.display = "block";
            btn.innerHTML = "✕";
        };

        btn.addEventListener("click", () => {
            if (panel.classList.contains("open")) {
                close();
            } else {
                open();
            }
        });

        overlay.addEventListener("click", close);

        panel.querySelectorAll("a").forEach((link) => {
            link.addEventListener("click", close);
        });

        document.addEventListener("keydown", (e) => {
            if (e.key === "Escape" && panel.classList.contains("open")) {
                close();
            }
        });
    }

    initMessagesResponsive() {
        const list = document.querySelector(".messages-list");
        const main = document.querySelector(".messages-main");
        const backBtn = document.getElementById("messages-back-btn");
        if (!list || !main) return;

        const isMobile = () => window.innerWidth <= 768;

        if (isMobile()) {
            if (window.location.search.includes("with_uid=")) {
                list.classList.add("hide");
                main.classList.remove("hide");
            } else {
                list.classList.remove("hide");
                main.classList.add("hide");
            }
        }

        if (backBtn) {
            backBtn.addEventListener("click", () => {
                if (!isMobile()) return;
                list.classList.remove("hide");
                main.classList.add("hide");
                window.history.replaceState(null, "", "/messages");
            });
        }

        list.querySelectorAll(".conversation-item").forEach((item) => {
            item.addEventListener("click", (e) => {
                if (!isMobile()) return;
                list.classList.add("hide");
                main.classList.remove("hide");
            });
        });

        const mq = window.matchMedia("(max-width: 768px)");
        mq.addEventListener("change", () => {
            if (!isMobile()) {
                list.classList.remove("hide");
                main.classList.remove("hide");
            }
        });
    }

    initMessageThread() {
        const thread = document.querySelector(".messages-thread");
        if (thread) thread.scrollTop = thread.scrollHeight;
    }
}
