/**
 * Canva-style sidebar tab navigation for the designer panels.
 */
(function (global) {
    "use strict";

    global.IAPC = global.IAPC || {};
    var MOBILE_BREAKPOINT = 900;
    var uidCounter = 0;
    var lastPanelId = "";
    var ICON_BY_PANEL = {
        ai: "IA",
        text: "T",
        paint: "✎",
        image: "▣",
        sticker: "★",
        graphic: "◆"
    };

    function isAiPremiumEnabled() {
        return !!(global.IAPC_DATA && global.IAPC_DATA.aiPremiumActive);
    }

    function syncAiTabAccess(menu) {
        var aiTab = menu ? menu.querySelector(".iapc-canva-tab-ai") : null;
        var enabled = isAiPremiumEnabled();

        if (!aiTab) {
            return;
        }

        if (enabled) {
            aiTab.removeAttribute("disabled");
            aiTab.removeAttribute("aria-disabled");
            return;
        }

        aiTab.setAttribute("disabled", "disabled");
        aiTab.setAttribute("aria-disabled", "true");
        aiTab.classList.remove("iapc-active");
    }

    function getDesignerRoot(menu) {
        return menu ? menu.closest(".iapc-designer-wrapper") || document : document;
    }

    function ensureRootUid(root) {
        if (!root || !root.getAttribute) {
            return "";
        }
        var uid = root.getAttribute("data-iapc-uid");
        if (!uid) {
            uidCounter += 1;
            uid = "iapc-root-" + uidCounter;
            root.setAttribute("data-iapc-uid", uid);
        }
        return uid;
    }

    function isMobileToolsMode() {
        return global.matchMedia && global.matchMedia("(max-width: " + MOBILE_BREAKPOINT + "px)").matches;
    }

    function getModalContent(root) {
        if (!root) {
            return null;
        }
        var uid = root.getAttribute && root.getAttribute("data-iapc-uid");
        if (uid) {
            var portaled = document.querySelector('.iapc-canva-content[data-iapc-owner="' + uid + '"]');
            if (portaled) {
                return portaled;
            }
        }
        return root.querySelector ? root.querySelector(".iapc-canva-content") : null;
    }

    function getModalBackdrop(root) {
        if (!root) {
            return null;
        }
        var uid = root.getAttribute && root.getAttribute("data-iapc-uid");
        if (uid) {
            var portaled = document.querySelector('.iapc-mobile-sheet-backdrop[data-iapc-owner="' + uid + '"]');
            if (portaled) {
                return portaled;
            }
        }
        return root.querySelector ? root.querySelector(".iapc-mobile-sheet-backdrop") : null;
    }

    function getHomeSlot(root) {
        if (!root || !root.querySelector) {
            return null;
        }
        return root.querySelector(".iapc-canva-content-home") || root.querySelector(".iapc-designer-left");
    }

    function portalModalToBody(root, content, backdrop) {
        var uid = ensureRootUid(root);
        if (content) {
            content.classList.add("iapc-mobile-portal");
            content.setAttribute("data-iapc-owner", uid);
            if (content.parentNode !== document.body) {
                document.body.appendChild(content);
            }
        }
        if (backdrop) {
            backdrop.classList.add("iapc-mobile-portal");
            backdrop.setAttribute("data-iapc-owner", uid);
            if (backdrop.parentNode !== document.body) {
                document.body.appendChild(backdrop);
            }
        }
    }

    function restoreModalHome(root) {
        var content = getModalContent(root);
        var backdrop = getModalBackdrop(root);
        var home = getHomeSlot(root);

        if (content && home && content.parentNode !== home) {
            content.classList.remove("iapc-mobile-portal");
            home.appendChild(content);
        }

        if (backdrop && backdrop.parentNode) {
            backdrop.parentNode.removeChild(backdrop);
        }
    }

    function closeMobileSheet(root) {
        if (!root || !root.classList) {
            return;
        }
        root.classList.remove("iapc-mobile-sheet-open");
        document.body.classList.remove("iapc-mobile-tools-open");
        document.documentElement.classList.remove("iapc-mobile-tools-open");
        document.body.classList.remove("iapc-mobile-sheet--compact");

        // En móvil, sin sheet no hay tab “activo” visualmente.
        if (isMobileToolsMode()) {
            var menu = root.querySelector(".iapc-canva-menu");
            if (menu) {
                menu.querySelectorAll(".iapc-canva-tab, .iapc-canva-tab-ai").forEach(function (btn) {
                    btn.classList.remove("iapc-active");
                });
            }
        }
    }

    function resetMobileSheetScroll(root) {
        var content = getModalContent(root);
        if (!content) {
            return;
        }
        var scrollBody = content.querySelector(".iapc-mobile-modal-scroll");
        var targets = [content, scrollBody, content.querySelector(".iapc-canva-panel.iapc-active")];
        targets.forEach(function (el) {
            if (el) {
                el.scrollTop = 0;
            }
        });
        global.requestAnimationFrame(function () {
            targets.forEach(function (el) {
                if (el) {
                    el.scrollTop = 0;
                }
            });
        });
    }

    function ensureMobileScrollBody(content, header) {
        if (!content) {
            return null;
        }
        var scroll = content.querySelector(".iapc-mobile-modal-scroll");
        if (!scroll) {
            scroll = document.createElement("div");
            scroll.className = "iapc-mobile-modal-scroll";
            var move = [];
            Array.prototype.forEach.call(content.children, function (child) {
                if (child !== header && !child.classList.contains("iapc-mobile-modal-header")) {
                    move.push(child);
                }
            });
            move.forEach(function (child) {
                scroll.appendChild(child);
            });
            content.appendChild(scroll);
        } else if (header && header.nextSibling !== scroll) {
            content.appendChild(scroll);
        }
        return scroll;
    }

    function syncCompactSheetMode(root, panelId) {
        var content = getModalContent(root);
        // All mobile tool panels use a low bottom sheet so the canvas stays visible.
        var compact = isMobileToolsMode();
        if (content && content.classList) {
            content.classList.toggle("iapc-mobile-sheet--compact", compact);
        }
        if (root && root.classList) {
            root.classList.toggle("iapc-mobile-sheet--compact", compact);
        }
        document.body.classList.toggle("iapc-mobile-sheet--compact", compact);
    }

    function syncMobileModalTitle(root) {
        var content = getModalContent(root);
        if (!content) {
            return;
        }
        var titleEl = content.querySelector(".iapc-mobile-modal-title");
        if (!titleEl) {
            return;
        }
        var activePanel = content.querySelector(".iapc-canva-panel.iapc-active");
        var intro = activePanel ? activePanel.querySelector(".iapc-panel-intro") : null;
        var text = intro ? (intro.textContent || "").trim() : "";
        titleEl.textContent = text;
        titleEl.hidden = !text;
    }

    function openMobileSheet(root) {
        if (!root || !root.classList) {
            return;
        }
        if (!isMobileToolsMode()) {
            return;
        }
        var content = getModalContent(root);
        var backdrop = getModalBackdrop(root);
        portalModalToBody(root, content, backdrop);

        root.classList.add("iapc-mobile-sheet-open");
        document.body.classList.add("iapc-mobile-tools-open");
        document.documentElement.classList.add("iapc-mobile-tools-open");
        // Keep compact class in sync when reopening (e.g. Options from fullscreen).
        syncCompactSheetMode(root, getLastPanelId(root));
        syncMobileModalTitle(root);
        resetMobileSheetScroll(root);

        // Any tool open on mobile → canvas-only fullscreen (exit icon only).
        if (global.IAPC && IAPC.canvasFs && typeof IAPC.canvasFs.set === "function") {
            IAPC.canvasFs.set(true);
        }
    }

    function ensureMobileSheetUi(menu, root) {
        if (!menu || !root || !root.classList) {
            return;
        }

        root.classList.add("iapc-mobile-tools-mode");
        ensureRootUid(root);

        menu.querySelectorAll(".iapc-canva-tab, .iapc-canva-tab-ai").forEach(function (btn) {
            var panel = btn.dataset.panel || "";
            var icon = ICON_BY_PANEL[panel] || "•";
            btn.setAttribute("data-icon", icon);

            var label = (btn.textContent || "").trim();
            if (label) {
                btn.setAttribute("aria-label", label);
                btn.setAttribute("title", label);
            }
        });

        var left = root.querySelector(".iapc-designer-left");
        var content = getModalContent(root) || (left ? left.querySelector(".iapc-canva-content") : null);
        if (!content) {
            return;
        }

        // Marker so we can restore the panel beside the menu on desktop.
        if (left && !left.querySelector(".iapc-canva-content-home")) {
            var home = document.createElement("div");
            home.className = "iapc-canva-content-home";
            if (content.parentNode === left) {
                left.insertBefore(home, content);
                home.appendChild(content);
            } else {
                left.appendChild(home);
            }
        }

        var header = content.querySelector(".iapc-mobile-modal-header");
        if (!header) {
            header = document.createElement("div");
            header.className = "iapc-mobile-modal-header";
            content.insertBefore(header, content.firstChild);
        }

        var titleEl = header.querySelector(".iapc-mobile-modal-title");
        if (!titleEl) {
            titleEl = document.createElement("p");
            titleEl.className = "iapc-mobile-modal-title";
            header.insertBefore(titleEl, header.firstChild);
        }

        var closeBtn = content.querySelector(".iapc-mobile-sheet-close");
        if (!closeBtn) {
            closeBtn = document.createElement("button");
            closeBtn.type = "button";
            closeBtn.className = "iapc-mobile-sheet-close";
            closeBtn.setAttribute("aria-label", "Close");
            closeBtn.textContent = "✕";
            closeBtn.addEventListener("click", function () {
                closeMobileSheet(root);
            });
        }
        if (closeBtn.parentNode !== header) {
            header.appendChild(closeBtn);
        }

        ensureMobileScrollBody(content, header);
        syncMobileModalTitle(root);

        var backdrop = getModalBackdrop(root);
        if (!backdrop) {
            backdrop = document.createElement("button");
            backdrop.type = "button";
            backdrop.className = "iapc-mobile-sheet-backdrop";
            backdrop.setAttribute("aria-label", "Close tools panel");
            backdrop.addEventListener("click", function () {
                closeMobileSheet(root);
            });
        }

        portalModalToBody(root, content, backdrop);
    }

    function syncMobileMode(menu, root) {
        if (!menu || !root || !root.classList) {
            return;
        }

        if (isMobileToolsMode()) {
            ensureMobileSheetUi(menu, root);
            return;
        }

        root.classList.remove("iapc-mobile-tools-mode");
        closeMobileSheet(root);
        restoreModalHome(root);
    }

    function activateCanvaTab(tab, options) {
        var menu = document.querySelector(".iapc-canva-menu");
        var opts = options || {};
        var openSheet = opts.openSheet !== false;

        if (!menu || !tab || tab.disabled || tab.getAttribute("aria-disabled") === "true") {
            return;
        }

        if (tab.classList.contains("iapc-canva-tab-ai") && !isAiPremiumEnabled()) {
            return;
        }

        var panelId = tab.dataset.panel;

        if (!panelId) {
            return;
        }

        lastPanelId = panelId;

        var root = getDesignerRoot(menu);
        root.setAttribute("data-iapc-last-panel", panelId);
        var alreadyActive = tab.classList.contains("iapc-active");

        // On mobile, tapping the active tool again closes the sheet.
        if (openSheet && isMobileToolsMode() && alreadyActive && root.classList.contains("iapc-mobile-sheet-open")) {
            closeMobileSheet(root);
            return;
        }

        menu.querySelectorAll(".iapc-canva-tab, .iapc-canva-tab-ai").forEach(function (btn) {
            btn.classList.remove("iapc-active");
        });

        var content = getModalContent(root) || root;
        content.querySelectorAll(".iapc-canva-panel").forEach(function (box) {
            box.classList.remove("iapc-active");
        });

        tab.classList.add("iapc-active");

        var activePanel = content.querySelector('[data-panel-content="' + panelId + '"]');

        if (activePanel) {
            activePanel.classList.add("iapc-active");
        }

        syncMobileModalTitle(root);
        syncCompactSheetMode(root, panelId);

        if (openSheet) {
            openMobileSheet(root);
        } else {
            closeMobileSheet(root);
        }
    }

    function initCanvaTabs() {
        var menu = document.querySelector(".iapc-canva-menu");

        if (!menu) {
            return;
        }

        syncAiTabAccess(menu);
        var root = getDesignerRoot(menu);
        syncMobileMode(menu, root);

        menu.addEventListener("click", function (e) {
            var tab = e.target.closest(".iapc-canva-tab, .iapc-canva-tab-ai");

            if (!tab || tab.disabled || tab.getAttribute("aria-disabled") === "true") {
                return;
            }

            if (tab.classList.contains("iapc-canva-tab-ai") && !isAiPremiumEnabled()) {
                return;
            }

            activateCanvaTab(tab, { openSheet: true });
        });

        var wasMobileToolsMode = isMobileToolsMode();

        global.addEventListener("resize", function () {
            var isMobileNow = isMobileToolsMode();

            // Only react when crossing the mobile/desktop breakpoint.
            // Mobile keyboard also fires resize — must NOT close the modal.
            if (isMobileNow === wasMobileToolsMode) {
                return;
            }

            wasMobileToolsMode = isMobileNow;
            syncMobileMode(menu, root);

            if (isMobileNow) {
                closeMobileSheet(root);
            }
        });

        document.addEventListener("keydown", function (e) {
            if (e.key === "Escape") {
                closeMobileSheet(root);
            }
        });

        var defaultTab = null;

        if (isAiPremiumEnabled()) {
            defaultTab = menu.querySelector(".iapc-canva-tab-ai:not([disabled])");
        }

        if (!defaultTab) {
            defaultTab =
                menu.querySelector('.iapc-canva-tab[data-panel="text"]:not([disabled])') ||
                menu.querySelector(".iapc-canva-tab.iapc-active:not([disabled])") ||
                menu.querySelector(".iapc-canva-tab:not([disabled])");
        }

        // Select default panel for desktop, but never auto-open the mobile sheet.
        if (defaultTab) {
            activateCanvaTab(defaultTab, { openSheet: false });
        }
    }

    function getLastPanelId(root) {
        if (lastPanelId) {
            return lastPanelId;
        }
        if (root && root.getAttribute) {
            return root.getAttribute("data-iapc-last-panel") || "";
        }
        return "";
    }

    function getLastPanelTab(root) {
        var menu = root ? root.querySelector(".iapc-canva-menu") : document.querySelector(".iapc-canva-menu");
        if (!menu) {
            return null;
        }
        var panelId = getLastPanelId(root);
        if (panelId) {
            var remembered = menu.querySelector(
                '.iapc-canva-tab[data-panel="' + panelId + '"], .iapc-canva-tab-ai[data-panel="' + panelId + '"]'
            );
            if (remembered && remembered.getAttribute("aria-disabled") !== "true" && !remembered.disabled) {
                return remembered;
            }
        }
        return (
            menu.querySelector(".iapc-canva-tab.iapc-active, .iapc-canva-tab-ai.iapc-active") ||
            menu.querySelector('.iapc-canva-tab[data-panel="paint"]') ||
            menu.querySelector(".iapc-canva-tab:not([disabled])")
        );
    }

    global.IAPC.tabs = {
        init: initCanvaTabs,
        activate: activateCanvaTab,
        isAiPremiumEnabled: isAiPremiumEnabled,
        closeMobileSheet: closeMobileSheet,
        getLastPanelId: getLastPanelId,
        getLastPanelTab: getLastPanelTab
    };
})(window);
