// Smooth Scroll for Anchor Links
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        // Re-read href at click time: some links (e.g. modal choice buttons)
        // start as "#" placeholders and get rewritten to a real URL by other
        // scripts before the user clicks. Only intercept if it's still a
        // same-page fragment link pointing at an element that exists.
        const targetSelector = this.getAttribute('href');
        if (!targetSelector || targetSelector === '#' || !targetSelector.startsWith('#')) {
            return;
        }

        let target;
        try {
            target = document.querySelector(targetSelector);
        } catch (error) {
            return;
        }

        if (!target) {
            return;
        }

        e.preventDefault();
        target.scrollIntoView({
            behavior: 'smooth'
        });
    });
});

// Card Hover Animation
document.querySelectorAll('.card-hover').forEach(card => {
    card.addEventListener('mouseenter', () => {
        card.style.transform = 'translateY(-5px)';
        card.style.boxShadow = '0 4px 15px rgba(0, 0, 0, 0.1)';
    });

    card.addEventListener('mouseleave', () => {
        card.style.transform = 'translateY(0)';
        card.style.boxShadow = '0 2px 4px rgba(0, 0, 0, 0.1)';
    });
});

// Toast Notifications
function showToast(message, type = 'success') {
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.innerText = message;

    document.body.appendChild(toast);

    setTimeout(() => {
        toast.remove();
    }, 3000);
}

// Dynamic Content Loading (Example: Load Sales Reports)
function loadSalesReports() {
    fetch('/IMS/api/sales/report.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            branchId: 1, // example
            startDate: '2023-01-01',
            endDate: '2023-12-31'
        })
    })
        .then(response => response.json())
        .then(data => {
            console.log('Sales report response:', data.message);
            // Since the API generates report, not returns data, just log the message
        })
        .catch(error => {
            console.error('Error loading sales reports:', error);
            showToast('Failed to load sales reports.', 'error');
        });
}

// Load Sales Reports on Page Load
document.addEventListener('DOMContentLoaded', () => {
    if (document.getElementById('reports-container')) {
        loadSalesReports();
    }
});

// Interactive Charts (Using Chart.js)
function renderSalesChart() {
    const chartElement = document.getElementById('salesChart');
    if (chartElement) {
        const ctx = chartElement.getContext('2d');
        new Chart(ctx, {
            type: 'line',
            data: {
                labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
                datasets: [{
                    label: 'Sales',
                    data: [65, 59, 80, 81, 56, 55],
                    backgroundColor: 'rgba(0, 123, 255, 0.2)',
                    borderColor: 'rgba(0, 123, 255, 1)',
                    borderWidth: 1
                }]
            },
            options: {
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    }
}

// Render Chart on Page Load
document.addEventListener('DOMContentLoaded', () => {
    renderSalesChart();
});

// Dashboard sidebar section dropdowns
function initDashboardDropdownMenus() {
    document.querySelectorAll('.dashboard-container .sidebar').forEach(sidebar => {
        const sections = Array.from(sidebar.querySelectorAll('.sidebar-section'));

        sections.forEach((section, index) => {
            const heading = Array.from(section.children).find(child => child.classList.contains('sidebar-heading'));
            const menu = Array.from(section.children).find(child => child.classList.contains('sidebar-menu'));

            if (!heading || !menu || section.classList.contains('dashboard-dropdown-section')) {
                return;
            }

            const links = Array.from(menu.querySelectorAll('a[href]'));
            const hasCurrentLink = links.some(link => {
                try {
                    return new URL(link.getAttribute('href'), window.location.href).pathname === window.location.pathname;
                } catch (error) {
                    return false;
                }
            });
            const storageKey = `dashboardDropdownOpen:${window.location.pathname}:${index}`;
            let savedState = null;

            try {
                savedState = localStorage.getItem(storageKey);
            } catch (error) {
                savedState = null;
            }

            const shouldOpen = savedState ? savedState === '1' : hasCurrentLink || index === 0;
            const caret = document.createElement('span');

            section.classList.add('dashboard-dropdown-section');
            heading.classList.add('dashboard-dropdown-heading');
            menu.classList.add('dashboard-dropdown-menu');
            caret.className = 'dashboard-dropdown-caret';
            caret.innerHTML = '<i class="fas fa-chevron-down" aria-hidden="true"></i>';

            heading.setAttribute('role', 'button');
            heading.setAttribute('tabindex', '0');
            heading.setAttribute('aria-controls', `dashboard-dropdown-menu-${index}`);
            heading.setAttribute('aria-expanded', shouldOpen ? 'true' : 'false');
            menu.id = menu.id || `dashboard-dropdown-menu-${index}`;
            heading.appendChild(caret);

            if (!shouldOpen) {
                section.classList.add('dropdown-closed');
                menu.hidden = true;
            }

            const toggleDropdown = () => {
                const closed = section.classList.toggle('dropdown-closed');
                const open = !closed;
                heading.setAttribute('aria-expanded', open ? 'true' : 'false');
                menu.hidden = !open;

                try {
                    localStorage.setItem(storageKey, open ? '1' : '0');
                } catch (error) {
                    return;
                }
            };

            heading.addEventListener('click', event => {
                const headingLink = event.target.closest('a[href]');

                if (headingLink) {
                    return;
                }

                toggleDropdown();
            });
            heading.addEventListener('keydown', event => {
                if (event.key === 'Enter' || event.key === ' ') {
                    event.preventDefault();
                    toggleDropdown();
                }
            });
        });
    });
}

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



// Responsive enhancement for legacy and dynamically rendered pages.
function initResponsiveUi(root = document) {
    root.querySelectorAll('table').forEach(table => {
        if (table.dataset.responsiveEnhanced === '1' || table.classList.contains('no-responsive-table')) {
            return;
        }

        table.dataset.responsiveEnhanced = '1';
        const columnCount = table.querySelectorAll('thead tr:first-child th').length
            || table.querySelectorAll('tr:first-child > th, tr:first-child > td').length;

        if (columnCount >= 4) {
            table.classList.add('wide-table');
        }

        if (columnCount >= 4
            && !table.closest('.table-responsive, .responsive-table-shell, .dt-container, .dataTables_wrapper')) {
            const wrapper = document.createElement('div');
            wrapper.className = 'responsive-table-shell';
            wrapper.setAttribute('role', 'region');
            wrapper.setAttribute('aria-label', table.getAttribute('aria-label') || 'Scrollable data table');
            wrapper.setAttribute('tabindex', '0');
            table.parentNode.insertBefore(wrapper, table);
            wrapper.appendChild(table);
        }
    });

    root.querySelectorAll('.dashboard-container').forEach(dashboard => {
        const sidebar = dashboard.querySelector(':scope > .sidebar');
        if (!sidebar || dashboard.querySelector(':scope > .dashboard-mobile-toggle')) {
            return;
        }

        const button = document.createElement('button');
        button.type = 'button';
        button.className = 'dashboard-mobile-toggle';
        button.setAttribute('aria-expanded', 'false');
        button.innerHTML = '<span><i class="fas fa-bars" aria-hidden="true"></i> Dashboard menu</span><i class="fas fa-chevron-down" aria-hidden="true"></i>';
        dashboard.insertBefore(button, sidebar);

        button.addEventListener('click', () => {
            const open = dashboard.classList.toggle('mobile-sidebar-open');
            button.setAttribute('aria-expanded', open ? 'true' : 'false');
            const chevron = button.lastElementChild;
            if (chevron) {
                chevron.className = open ? 'fas fa-chevron-up' : 'fas fa-chevron-down';
            }
        });
    });
}

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