// Function to inject Sidebar and Header into the page
document.addEventListener("DOMContentLoaded", function () {

    // 1. Create and inject the Left Sidebar
    const sidebarContainer = document.getElementById("sidebar-component");
    if (sidebarContainer) {
        sidebarContainer.innerHTML = `
            <aside class="sidebar">
                <div class="sidebar-brand">AdminPanel</div>
                <ul class="sidebar-menu">
                    <li>
                        <a href="dashboard.html" class="menu-item" id="nav-dashboard">
                            <span><i class="fa-solid fa-chart-pie"></i> Dashboard</span>
                        </a>
                    </li>
                    <li>
                        <a href="user-management.html" class="menu-item" id="nav-orders">
                            <span><i class="fa-solid fa-user"></i> User Management</span>
                        </a>
                    </li>
                    <!-- Dropdown Link Group -->
                    <li class="menu-item-group has-dropdown">
                        <a href="#" class="menu-item dropdown-trigger">
                            <i class="fa-solid fa-line-chart"></i>
                            <span>Stock Management</span>
                            <i class="fa-solid fa-chevron-right arrow-icon"></i>
                        </a>
                        <!-- Submenu Links -->
                        <ul class="submenu">
                            <li>
                                <a href="stock-management.html" class="submenu-item">
                                    <i class="fa-solid fa-eye"></i> View
                                </a>
                            </li>
                            <li>
                                <a href="add-user.html" class="submenu-item">
                                    <i class="fa-solid fa-plus"></i> Create
                                </a>
                            </li>

                        </ul>
                    </li>




                    <li>
                        <a href="" class="menu-item" id="nav-settings">
                            <span><i class="fa-solid fa-calculator"></i> Performance Calculations</span>
                        </a>
                    </li>
                    <li>
                        <a href="" class="menu-item" id="nav-settings">
                            <span><i class="fa-solid fa-file"></i> Files</span>
                        </a>
                    </li>
                    <li>
                        <a href="" class="menu-item" id="nav-settings">
                            <span><i class="fa-solid fa-exchange"></i> Mapping</span>
                        </a>
                    </li>
                </ul>
            </aside>
        `;
    }

    // 2. Create and inject the Top Header
    const headerContainer = document.getElementById("header-component");
    if (headerContainer) {
        // Get custom page title defined on the body element attribute, or fallback to 'Panel'
        const currentTitle = document.body.getAttribute("data-page-title") || "Dashboard Overview";

        headerContainer.innerHTML = `
            <header class="header">
                <div class="page-title">${currentTitle}</div>
                <div class="user-profile">
                    <div class="profile-trigger" onclick="toggleProfileDropdown(event)">
                        <div class="profile-img">JD</div>
                        <span>John Doe</span>
                        <i class="fa-solid fa-caret-down"></i>
                    </div>
                    <div class="profile-dropdown" id="profileDropdown">
                        <a href="profile.html" class="dropdown-item">
                            <i class="fa-solid fa-user"></i> My Profile
                        </a>
                        <a href="change-password.html" class="dropdown-item">
                            <i class="fa-solid fa-key"></i> Change Password
                        </a>
                        <div class="dropdown-divider"></div>
                        <a href="login.html" class="dropdown-item" style="color: #ef4444;">
                            <i class="fa-solid fa-right-from-bracket"></i> Logout
                        </a>
                    </div>
                </div>
            </header>
        `;
    }

    // 3. Automatically mark the current page link as active
    highlightCurrentPage();
});
document.addEventListener("DOMContentLoaded", function () {
    // 1. Extract the current file name from the browser URL path (e.g., "user-management.html")
    const currentPath = window.location.pathname.split("/").pop();

    // 2. Scan and evaluate standalone root links
    const rootMenuItems = document.querySelectorAll(".menu-item:not(.dropdown-trigger)");
    rootMenuItems.forEach(item => {
        if (item.getAttribute("href") === currentPath) {
            item.classList.add("active");
        }
    });

    // 3. Scan and evaluate nested submenu dropdown links
    const submenuItems = document.querySelectorAll(".submenu-item");
    submenuItems.forEach(item => {
        if (item.getAttribute("href") === currentPath) {
            // Highlight the exact active child link
            item.classList.add("active");

            // Travel up the DOM to find the parent dropdown container and open it automatically
            const parentGroup = item.closest(".has-dropdown");
            if (parentGroup) {
                parentGroup.classList.add("open");
            }
        }
    });

    // 4. Manual Dropdown Expand Toggle Click Listener
    const dropdownTriggers = document.querySelectorAll(".dropdown-trigger");
    dropdownTriggers.forEach(trigger => {
        trigger.addEventListener("click", function (e) {
            e.preventDefault(); // Stop raw '#' anchor redirects from altering window scroll position
            const parentElement = this.parentElement;
            parentElement.classList.toggle("open");
        });
    });
});
// Layout Interactive Utilities
function toggleSubmenu(event) {
    const menuItem = event.currentTarget;
    const submenu = menuItem.nextElementSibling;
    const chevron = menuItem.querySelector('.chevron');
    submenu.classList.toggle('open');
    chevron.classList.toggle('rotate');
}

function toggleProfileDropdown(event) {
    event.stopPropagation();
    document.getElementById('profileDropdown').classList.toggle('show');
}

function toggleField(id, icon) {
    const field = document.getElementById(id);
    if (field.type === 'password') {
        field.type = 'text';
        icon.classList.replace('fa-eye', 'fa-eye-slash');
    } else {
        field.type = 'password';
        icon.classList.replace('fa-eye-slash', 'fa-eye');
    }
}

// Global click event window hook to shut open profile drop-lists safely
window.addEventListener('click', function() {
    const dropdown = document.getElementById('profileDropdown');
    if (dropdown && dropdown.classList.contains('show')) {
        dropdown.classList.remove('show');
    }
});

// Helper function to auto-assign active CSS styling states to sidebar items
function highlightCurrentPage() {
    const pagePath = window.location.pathname.split("/").pop();

    // Remove default active if it isn't dashboard
    if (pagePath && pagePath !== "dashboard.html") {
        const defaultActive = document.getElementById("nav-dashboard");
        if(defaultActive) defaultActive.classList.remove("active");
    }

    if (pagePath === "dashboard.html" || pagePath === "") {
        document.getElementById("nav-dashboard")?.classList.add("active");
    } else if (pagePath === "profile.html") {
        // Keeps sidebar clean when inside custom user profile view states
    } else if (pagePath === "change-password.html") {
         // Keep parent options unselected
    } else if (pagePath === "product-list.html" || pagePath === "add-product.html") {
        const subItem = document.getElementById(`nav-${pagePath.replace('.html', '')}`);
        if (subItem) {
            subItem.classList.add("active");
            // Auto open submenu tree
            const submenu = document.getElementById("productSubmenu");
            const parentChevron = submenu.previousElementSibling.querySelector('.chevron');
            submenu.classList.add("open");
            parentChevron.classList.add("rotate");
        }
    }
}
