/* scripts.js — FastPluggy Admin UI */

// ------------------------------------------------------
// Console Banner
// ------------------------------------------------------
(function() {
    var v = window.APP_VERSION || '';
    console.log(
        '%c\n' +
        '  ╔═╗╔═╗╔═╗╦ ╦╔═╗╦  ╦ ╦╔═╗╔═╗╦ ╦\n' +
        '  ╠╣ ╠═╣╚═╗║ ║╠═╝║  ║ ║║ ╦║ ╦╚╦╝\n' +
        '  ╚  ╩ ╩╚═╝╚═╝╩  ╩═╝╚═╝╚═╝╚═╝ ╩ \n' +
        '  v' + v + '\n' +
        '  Plugin-powered FastAPI framework\n' +
        '  https://fastpluggy.xyz\n',
        'color:#0ea5e9;font-family:monospace'
    );
})();

// ------------------------------------------------------
// Toast Notification
// ------------------------------------------------------
function showNotification(message, level = "info", link = null, { sticky = false } = {}) {
    const container = document.getElementById("notifications");

    if (!container) {
        console.warn("[Notification] Container not found");
        return;
    }

    const levelClasses = {
        info:    "bg-primary text-white",
        warning: "bg-warning text-dark",
        error:   "bg-danger text-white",
        success: "bg-success text-white"
    };
    const colorClass = levelClasses[level] || "bg-primary text-white";

    const notification = document.createElement("div");
    notification.className = "toast show mb-3 " + colorClass;
    notification.role = "alert";

    const toastHeader = document.createElement("div");
    toastHeader.className = "toast-header";

    const strong = document.createElement("strong");
    strong.className = "me-auto";
    strong.textContent = "Task Update";

    const closeBtn = document.createElement("button");
    closeBtn.type = "button";
    closeBtn.className = "btn-close ms-2 mb-1";
    closeBtn.setAttribute("data-bs-dismiss", "toast");
    closeBtn.setAttribute("aria-label", "Close");

    toastHeader.appendChild(strong);
    toastHeader.appendChild(closeBtn);

    const toastBody = document.createElement("div");
    toastBody.className = "toast-body";
    toastBody.textContent = message;

    if (link) {
        const linkDiv = document.createElement("div");
        linkDiv.className = "mt-2";
        const anchor = document.createElement("a");
        anchor.href = link;
        anchor.target = "_blank";
        anchor.className = "text-white text-decoration-underline";
        anchor.rel = "noopener noreferrer";
        anchor.textContent = "View details";
        linkDiv.appendChild(anchor);
        toastBody.appendChild(linkDiv);
    }

    notification.appendChild(toastHeader);
    notification.appendChild(toastBody);
    container.appendChild(notification);

    if (!sticky) {
        setTimeout(() => {
            if (container.contains(notification)) container.removeChild(notification);
        }, 5000);
    }

    closeBtn.addEventListener('click', () => {
        if (container.contains(notification)) container.removeChild(notification);
    });
}

// ------------------------------------------------------
// Auto LocalStorage for Form Elements
// ------------------------------------------------------
(function () {
    function loadFromLocalStorage(key, defaultValue = null) {
        try {
            const value = localStorage.getItem(key);
            return value !== null ? JSON.parse(value) : defaultValue;
        } catch (e) {
            console.warn("Error loading key:", key, e);
            return defaultValue;
        }
    }

    function saveToLocalStorage(key, value) {
        try {
            localStorage.setItem(key, JSON.stringify(value));
        } catch (e) {
            console.warn("Error saving key:", key, e);
        }
    }

    function initAutoLocalStorage() {
        document.querySelectorAll('[data-ls-key]').forEach(el => {
            const key = el.dataset.lsKey;
            const saved = loadFromLocalStorage(key);
            if (saved !== null) {
                if (el.type === 'checkbox') {
                    el.checked = !!saved;
                } else {
                    el.value = saved;
                }
            }
            const eventType = (el.type === 'checkbox' || el.tagName === 'SELECT') ? 'change' : 'input';
            el.addEventListener(eventType, () => {
                const value = (el.type === 'checkbox') ? el.checked : el.value;
                saveToLocalStorage(key, value);
            });
        });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initAutoLocalStorage);
    } else {
        initAutoLocalStorage();
    }
})();

// ------------------------------------------------------
// Theme Toggle (Dark / Light)
// Key: fp-theme | Sets: data-theme + data-bs-theme
// ------------------------------------------------------
(function() {
    function applyTheme(theme) {
        document.documentElement.setAttribute('data-theme', theme);
        document.documentElement.setAttribute('data-bs-theme', theme);

        const icon  = document.getElementById('theme-icon');
        const label = document.getElementById('theme-label');

        if (icon) {
            icon.className = theme === 'dark' ? 'ti ti-sun' : 'ti ti-moon';
        }
        if (label) {
            label.textContent = theme === 'dark' ? 'Light' : 'Dark';
        }

        const btn = document.getElementById('theme-toggle');
        if (btn) {
            btn.setAttribute('title', theme === 'dark' ? 'Switch to Light Mode' : 'Switch to Dark Mode');
        }
    }

    function initThemeToggle() {
        const btn = document.getElementById('theme-toggle');
        if (!btn) return;

        // Anti-FOUC already applied the saved theme — just sync the icon
        const currentTheme = document.documentElement.getAttribute('data-theme') || 'dark';
        applyTheme(currentTheme);

        btn.addEventListener('click', function() {
            const current = document.documentElement.getAttribute('data-theme') || 'dark';
            const next = current === 'dark' ? 'light' : 'dark';
            applyTheme(next);
            localStorage.setItem('fp-theme', next);
        });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initThemeToggle);
    } else {
        initThemeToggle();
    }
})();

// ------------------------------------------------------
// Sidebar Toggle — desktop collapse + mobile open/close
// Desktop (≥992px): toggles html.sidebar-collapsed
// Mobile  (<992px): toggles #sidebar.show + backdrop
// Key: fp-sidebar | Values: 'collapsed' / 'expanded'
// ------------------------------------------------------
(function() {
    var MOBILE_BP = 992;

    function isMobile() {
        return window.innerWidth < MOBILE_BP;
    }

    function applySidebarState(collapsed) {
        if (collapsed) {
            document.documentElement.classList.add('sidebar-collapsed');
        } else {
            document.documentElement.classList.remove('sidebar-collapsed');
        }
    }

    function openMobileSidebar(sidebar, backdrop) {
        sidebar.classList.add('show');
        if (backdrop) backdrop.classList.add('show');
        document.body.classList.add('sidebar-open');
    }

    function closeMobileSidebar(sidebar, backdrop) {
        sidebar.classList.remove('show');
        if (backdrop) backdrop.classList.remove('show');
        document.body.classList.remove('sidebar-open');
    }

    function updateToggleIcon(btn) {
        var icon = btn.querySelector('i');
        if (!icon) return;
        if (isMobile()) {
            icon.className = 'ti ti-menu-2';
        } else {
            icon.className = 'ti ti-layout-sidebar';
        }
    }

    function initSidebarToggle() {
        var btn = document.getElementById('sidebar-toggle');
        var sidebar = document.getElementById('sidebar');
        var backdrop = document.getElementById('sidebar-backdrop');
        if (!btn || !sidebar) return;

        // Swap icon for mobile
        updateToggleIcon(btn);
        window.addEventListener('resize', function() { updateToggleIcon(btn); });

        // Anti-FOUC already applied the saved state — just keep it in sync
        var savedState = localStorage.getItem('fp-sidebar');
        applySidebarState(savedState === 'collapsed');

        btn.addEventListener('click', function() {
            if (isMobile()) {
                // Mobile: toggle overlay
                if (sidebar.classList.contains('show')) {
                    closeMobileSidebar(sidebar, backdrop);
                } else {
                    openMobileSidebar(sidebar, backdrop);
                }
            } else {
                // Desktop: toggle collapse
                var isCollapsed = document.documentElement.classList.contains('sidebar-collapsed');
                var next = !isCollapsed;
                applySidebarState(next);
                localStorage.setItem('fp-sidebar', next ? 'collapsed' : 'expanded');
            }
        });

        // Also wire the in-sidebar mobile toggle (for closing)
        var mobileBtn = document.getElementById('mobile-menu-toggle');
        if (mobileBtn) {
            mobileBtn.addEventListener('click', function() {
                if (sidebar.classList.contains('show')) {
                    closeMobileSidebar(sidebar, backdrop);
                } else {
                    openMobileSidebar(sidebar, backdrop);
                }
            });
        }

        // Backdrop click closes sidebar
        if (backdrop) {
            backdrop.addEventListener('click', function() {
                closeMobileSidebar(sidebar, backdrop);
            });
        }

        // Close sidebar when a nav link is tapped (mobile UX)
        sidebar.querySelectorAll('.nav-link, .dropdown-item').forEach(function(link) {
            link.addEventListener('click', function() {
                if (isMobile()) closeMobileSidebar(sidebar, backdrop);
            });
        });

        // Close mobile sidebar if window resizes past breakpoint
        window.addEventListener('resize', function() {
            if (!isMobile() && sidebar.classList.contains('show')) {
                closeMobileSidebar(sidebar, backdrop);
            }
        });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initSidebarToggle);
    } else {
        initSidebarToggle();
    }
})();

// ------------------------------------------------------
// Layout Toggle — container-xl ↔ fluid
// Key: fp-layout | Values: 'fluid' / (absent)
// ------------------------------------------------------
(function() {
    function applyLayout(fluid) {
        if (fluid) {
            document.documentElement.classList.add('layout-fluid');
        } else {
            document.documentElement.classList.remove('layout-fluid');
        }
        const icon = document.getElementById('layout-icon');
        if (icon) {
            icon.className = fluid ? 'ti ti-minimize' : 'ti ti-maximize';
        }
        const btn = document.getElementById('layout-toggle');
        if (btn) {
            btn.setAttribute('title', fluid ? 'Switch to fixed width' : 'Switch to full width');
        }
    }

    function initLayoutToggle() {
        const btn = document.getElementById('layout-toggle');
        if (!btn) return;

        // Anti-FOUC already applied the saved state — just sync the icon
        const isFluid = document.documentElement.classList.contains('layout-fluid');
        applyLayout(isFluid);

        btn.addEventListener('click', function() {
            const next = !document.documentElement.classList.contains('layout-fluid');
            applyLayout(next);
            if (next) {
                localStorage.setItem('fp-layout', 'fluid');
            } else {
                localStorage.removeItem('fp-layout');
            }
        });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initLayoutToggle);
    } else {
        initLayoutToggle();
    }
})();

// ------------------------------------------------------
// Collapse Button Chevron Toggle
// ------------------------------------------------------
(function() {
    function initCollapseChevrons() {
        document.querySelectorAll('[data-bs-toggle="collapse"]').forEach(function(btn) {
            btn.addEventListener('click', function() {
                const icon = this.querySelector('i');
                if (!icon) return;
                const isUp = icon.classList.contains('ti-chevron-up');
                icon.classList.toggle('ti-chevron-up', !isUp);
                icon.classList.toggle('ti-chevron-down', isUp);
            });
        });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initCollapseChevrons);
    } else {
        initCollapseChevrons();
    }
})();

// ------------------------------------------------------
// Active Nav Link Highlighting
// ------------------------------------------------------
(function() {
    function initActiveNavLinks() {
        const currentPath = window.location.pathname;
        document.querySelectorAll('#sidebar .nav-link, #sidebar .dropdown-item').forEach(item => {
            const href = item.getAttribute('href');
            if (href && href !== '#' && currentPath.startsWith(href) && href !== '/') {
                item.classList.add('active');
                // Open parent dropdown if inside one (Bootstrap 5 requires show on toggle + menu)
                const parentDropdown = item.closest('.nav-item.dropdown');
                if (parentDropdown) {
                    parentDropdown.classList.add('show');
                    const toggle = parentDropdown.querySelector('.dropdown-toggle');
                    if (toggle) {
                        toggle.classList.add('show');
                        toggle.setAttribute('aria-expanded', 'true');
                    }
                    const menu = parentDropdown.querySelector('.dropdown-menu');
                    if (menu) menu.classList.add('show');
                }
            }
        });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initActiveNavLinks);
    } else {
        initActiveNavLinks();
    }
})();

// ------------------------------------------------------
// JSON Modal Preview (moved from ui-tools)
// ------------------------------------------------------
(function() {
    function getOrCreateJsonModal() {
        let modalEl = document.getElementById('jsonPreviewModal');
        if (modalEl) return modalEl;

        modalEl = document.createElement('div');
        modalEl.id = 'jsonPreviewModal';
        modalEl.className = 'modal';
        modalEl.tabIndex = -1;
        modalEl.setAttribute('role', 'dialog');

        const dialog = document.createElement('div');
        dialog.className = 'modal-dialog modal-lg modal-dialog-centered';
        dialog.setAttribute('role', 'document');

        const content = document.createElement('div');
        content.className = 'modal-content';

        const header = document.createElement('div');
        header.className = 'modal-header';

        const title = document.createElement('h5');
        title.className = 'modal-title';
        title.textContent = 'JSON Preview';

        const closeBtn = document.createElement('button');
        closeBtn.type = 'button';
        closeBtn.className = 'btn-close';
        closeBtn.setAttribute('data-bs-dismiss', 'modal');
        closeBtn.setAttribute('aria-label', 'Close');

        header.appendChild(title);
        header.appendChild(closeBtn);

        const body = document.createElement('div');
        body.className = 'modal-body';

        content.appendChild(header);
        content.appendChild(body);
        dialog.appendChild(content);
        modalEl.appendChild(dialog);
        document.body.appendChild(modalEl);
        return modalEl;
    }

    function initJsonModal() {
        // Inline toggle logic
        document.body.addEventListener('click', e => {
            if (!e.target.classList.contains('json-toggle')) return;
            const cell = e.target.closest('.json-modal-json-cell');
            const pre = cell.querySelector('.json-modal-json-content');
            const open = getComputedStyle(pre).display === 'none';
            pre.style.display = open ? 'block' : 'none';
            e.target.textContent = open ? '\u25BC' : '\u25B6';
        });

        // Open modal & inject cloned .pre-container
        document.body.addEventListener('click', e => {
            if (!e.target.classList.contains('view-json')) return;
            const cell = e.target.closest('.json-modal-json-cell');
            const preWrapper = cell.querySelector('.json-modal-pre-container');
            const cloneWrap = preWrapper.cloneNode(true);
            cloneWrap.style.display = 'block';

            const modalEl = getOrCreateJsonModal();
            const modalBody = modalEl.querySelector('.modal-body');
            // Clear previous content safely
            while (modalBody.firstChild) modalBody.removeChild(modalBody.firstChild);
            modalBody.appendChild(cloneWrap);
            new bootstrap.Modal(modalEl).show();
        });

        // Copy-button handler
        document.body.addEventListener('click', e => {
            if (!e.target.classList.contains('json-modal-copy-btn')) return;
            const wrapper = e.target.closest('.json-modal-pre-container');
            const pre = wrapper.querySelector('pre');
            if (!pre) return;
            navigator.clipboard.writeText(pre.textContent.trim())
                .then(() => {
                    e.target.textContent = '\u2713';
                    setTimeout(() => {
                        const icon = document.createElement('i');
                        icon.className = 'fa-regular fa-copy';
                        e.target.textContent = '';
                        e.target.appendChild(icon);
                    }, 1500);
                })
                .catch(() => {
                    e.target.textContent = '\u2717';
                    setTimeout(() => {
                        const icon = document.createElement('i');
                        icon.className = 'fa-regular fa-copy';
                        e.target.textContent = '';
                        e.target.appendChild(icon);
                    }, 1500);
                });
        });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initJsonModal);
    } else {
        initJsonModal();
    }
})();
