/**
 * KSO Chandigarh Breadcrumb Navigation System
 * Consistent breadcrumb navigation across all pages
 */

class KSOBreadcrumbs {
    constructor() {
        this.breadcrumbs = [];
        this.routes = {
            'dashboard.php': { title: 'Dashboard', icon: 'fas fa-chart-line' },
            'index.php': { title: 'Legacy Dashboard', icon: 'fas fa-tachometer-alt' },
            'members.php': { title: 'Members', icon: 'fas fa-users', parent: 'dashboard.php' },
            'member-registration.php': { title: 'New Registration', icon: 'fas fa-user-plus', parent: 'members.php' },
            'member-approval.php': { title: 'Pending Approvals', icon: 'fas fa-user-check', parent: 'members.php' },
            'events.php': { title: 'Events', icon: 'fas fa-calendar-alt', parent: 'dashboard.php' },
            'event-calendar.php': { title: 'Calendar', icon: 'fas fa-calendar', parent: 'events.php' },
            'finance.php': { title: 'Finance', icon: 'fas fa-coins', parent: 'dashboard.php' },
            'expenses.php': { title: 'Expenses', icon: 'fas fa-receipt', parent: 'finance.php' },
            'expense-categories.php': { title: 'Categories', icon: 'fas fa-tags', parent: 'expenses.php' },
            'documents.php': { title: 'Documents', icon: 'fas fa-file-alt', parent: 'dashboard.php' },
            'notifications.php': { title: 'Notifications', icon: 'fas fa-bell', parent: 'dashboard.php' },
            'email-templates.php': { title: 'Email Templates', icon: 'fas fa-envelope', parent: 'notifications.php' },
            'reports.php': { title: 'Reports', icon: 'fas fa-chart-bar', parent: 'dashboard.php' },
            'settings.php': { title: 'Settings', icon: 'fas fa-cog', parent: 'dashboard.php' },
            'system-settings.php': { title: 'System Settings', icon: 'fas fa-server', parent: 'settings.php' },
            'security-monitoring.php': { title: 'Security', icon: 'fas fa-shield-alt', parent: 'settings.php' },
            'audit-logs.php': { title: 'Audit Logs', icon: 'fas fa-history', parent: 'security-monitoring.php' },
            'membership-fees.php': { title: 'Membership Fees', icon: 'fas fa-credit-card', parent: 'finance.php' }
        };
        this.init();
    }

    init() {
        this.addStyles();
        this.generateBreadcrumbs();
        this.updateActiveMenu();
    }

    addStyles() {
        const style = document.createElement('style');
        style.textContent = `
            .kso-breadcrumb {
                background: #fff;
                padding: 15px 20px;
                margin: 0;
                border-bottom: 1px solid #e3e6f0;
                border-radius: 0;
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
            }

            .kso-breadcrumb-list {
                display: flex;
                flex-wrap: wrap;
                list-style: none;
                margin: 0;
                padding: 0;
                align-items: center;
            }

            .kso-breadcrumb-item {
                display: flex;
                align-items: center;
                font-size: 14px;
                color: #6c757d;
                position: relative;
            }

            .kso-breadcrumb-item:not(:last-child)::after {
                content: '/';
                margin: 0 12px;
                color: #dee2e6;
                font-weight: 400;
            }

            .kso-breadcrumb-item a {
                display: flex;
                align-items: center;
                color: #007bff;
                text-decoration: none;
                transition: color 0.2s ease;
                padding: 4px 8px;
                border-radius: 4px;
            }

            .kso-breadcrumb-item a:hover {
                color: #0056b3;
                background-color: #f8f9fa;
                text-decoration: none;
            }

            .kso-breadcrumb-item.active {
                color: #495057;
                font-weight: 500;
            }

            .kso-breadcrumb-item .breadcrumb-icon {
                margin-right: 6px;
                font-size: 12px;
            }

            .kso-breadcrumb-actions {
                margin-left: auto;
                display: flex;
                align-items: center;
                gap: 10px;
            }

            .kso-breadcrumb-action {
                background: #f8f9fa;
                border: 1px solid #dee2e6;
                color: #6c757d;
                padding: 6px 12px;
                border-radius: 4px;
                font-size: 13px;
                cursor: pointer;
                transition: all 0.2s ease;
                text-decoration: none;
                display: flex;
                align-items: center;
                gap: 5px;
            }

            .kso-breadcrumb-action:hover {
                background: #e9ecef;
                color: #495057;
                text-decoration: none;
            }

            .kso-breadcrumb-action.primary {
                background: #007bff;
                color: white;
                border-color: #007bff;
            }

            .kso-breadcrumb-action.primary:hover {
                background: #0056b3;
                border-color: #0056b3;
                color: white;
            }

            .kso-breadcrumb-mobile {
                display: none;
            }

            @media (max-width: 768px) {
                .kso-breadcrumb {
                    padding: 10px 15px;
                }

                .kso-breadcrumb-list {
                    flex-direction: column;
                    align-items: flex-start;
                    gap: 5px;
                }

                .kso-breadcrumb-actions {
                    margin-left: 0;
                    margin-top: 10px;
                    width: 100%;
                    justify-content: flex-start;
                }

                .kso-breadcrumb-mobile {
                    display: block;
                }

                .kso-breadcrumb-desktop {
                    display: none;
                }
            }

            /* Dark mode */
            .dark-mode .kso-breadcrumb {
                background: #343a40;
                border-bottom-color: #495057;
                color: #fff;
            }

            .dark-mode .kso-breadcrumb-item {
                color: #adb5bd;
            }

            .dark-mode .kso-breadcrumb-item.active {
                color: #fff;
            }

            .dark-mode .kso-breadcrumb-item a {
                color: #80bdff;
            }

            .dark-mode .kso-breadcrumb-item a:hover {
                color: #66a3ff;
                background-color: #495057;
            }

            .dark-mode .kso-breadcrumb-action {
                background: #495057;
                border-color: #6c757d;
                color: #adb5bd;
            }

            .dark-mode .kso-breadcrumb-action:hover {
                background: #6c757d;
                color: #fff;
            }

            /* Integration with existing breadcrumb */
            .content-header .breadcrumb {
                background: transparent;
                padding: 0;
                margin: 0;
                border: none;
                box-shadow: none;
            }

            .content-header .breadcrumb-item {
                display: flex;
                align-items: center;
            }

            .content-header .breadcrumb-item + .breadcrumb-item::before {
                content: '/';
                margin: 0 8px;
                color: #6c757d;
            }
        `;
        document.head.appendChild(style);
    }

    generateBreadcrumbs() {
        const currentPage = this.getCurrentPage();
        const breadcrumbPath = this.buildBreadcrumbPath(currentPage);
        
        this.replaceBreadcrumbs(breadcrumbPath);
        this.addBreadcrumbActions(currentPage);
    }

    getCurrentPage() {
        const path = window.location.pathname;
        const filename = path.split('/').pop() || 'index.php';
        return filename;
    }

    buildBreadcrumbPath(page) {
        const path = [];
        let current = page;
        
        while (current && this.routes[current]) {
            path.unshift(current);
            current = this.routes[current].parent;
        }
        
        return path;
    }

    replaceBreadcrumbs(path) {
        const breadcrumbContainers = document.querySelectorAll('.breadcrumb');
        
        breadcrumbContainers.forEach(container => {
            const breadcrumbHTML = this.generateBreadcrumbHTML(path);
            container.innerHTML = breadcrumbHTML;
            container.className = 'kso-breadcrumb';
        });
    }

    generateBreadcrumbHTML(path) {
        const breadcrumbItems = path.map((page, index) => {
            const route = this.routes[page];
            const isLast = index === path.length - 1;
            
            if (isLast) {
                return `
                    <li class="kso-breadcrumb-item active">
                        <i class="${route.icon} breadcrumb-icon"></i>
                        ${route.title}
                    </li>
                `;
            } else {
                return `
                    <li class="kso-breadcrumb-item">
                        <a href="${page}">
                            <i class="${route.icon} breadcrumb-icon"></i>
                            ${route.title}
                        </a>
                    </li>
                `;
            }
        }).join('');

        return `
            <ol class="kso-breadcrumb-list">
                ${breadcrumbItems}
            </ol>
        `;
    }

    addBreadcrumbActions(currentPage) {
        const actions = this.getPageActions(currentPage);
        
        if (actions.length > 0) {
            const breadcrumbs = document.querySelectorAll('.kso-breadcrumb');
            
            breadcrumbs.forEach(breadcrumb => {
                const actionsHTML = `
                    <div class="kso-breadcrumb-actions">
                        ${actions.map(action => `
                            <a href="${action.href || '#'}" class="kso-breadcrumb-action ${action.class || ''}" 
                               onclick="${action.onclick || ''}" title="${action.title || ''}">
                                <i class="${action.icon}"></i>
                                <span class="kso-breadcrumb-desktop">${action.label}</span>
                            </a>
                        `).join('')}
                    </div>
                `;
                
                breadcrumb.innerHTML += actionsHTML;
            });
        }
    }

    getPageActions(page) {
        const actions = {
            'dashboard.php': [
                { icon: 'fas fa-sync-alt', label: 'Refresh', onclick: 'location.reload()', title: 'Refresh Dashboard' },
                { icon: 'fas fa-download', label: 'Export', onclick: 'window.ksoPrint.showPrintOptions()', title: 'Export Data' },
                { icon: 'fas fa-palette', label: 'Themes', onclick: 'document.querySelector(".nav-link[data-toggle=dropdown]").click()', title: 'Change Theme' }
            ],
            'index.php': [
                { icon: 'fas fa-sync-alt', label: 'Refresh', onclick: 'location.reload()', title: 'Refresh Dashboard' },
                { icon: 'fas fa-download', label: 'Export', onclick: 'window.ksoPrint.showPrintOptions()', title: 'Export Data' }
            ],
            'members.php': [
                { icon: 'fas fa-plus', label: 'Add Member', href: 'member-registration.php', class: 'primary', title: 'Add New Member' },
                { icon: 'fas fa-file-export', label: 'Export', onclick: 'window.ksoPrint.quickPrint("#membersTable")', title: 'Export Members' },
                { icon: 'fas fa-sync-alt', label: 'Refresh', onclick: 'location.reload()', title: 'Refresh Members' }
            ],
            'events.php': [
                { icon: 'fas fa-plus', label: 'Add Event', onclick: 'showAddEventModal()', class: 'primary', title: 'Create New Event' },
                { icon: 'fas fa-calendar', label: 'Calendar', href: 'event-calendar.php', title: 'View Calendar' },
                { icon: 'fas fa-sync-alt', label: 'Refresh', onclick: 'location.reload()', title: 'Refresh Events' }
            ],
            'finance.php': [
                { icon: 'fas fa-plus', label: 'Add Transaction', onclick: 'showAddTransactionModal()', class: 'primary', title: 'Add Transaction' },
                { icon: 'fas fa-chart-bar', label: 'Reports', href: 'reports.php', title: 'View Reports' },
                { icon: 'fas fa-sync-alt', label: 'Refresh', onclick: 'location.reload()', title: 'Refresh Finance' }
            ],
            'documents.php': [
                { icon: 'fas fa-upload', label: 'Upload', onclick: 'showUploadModal()', class: 'primary', title: 'Upload Document' },
                { icon: 'fas fa-folder', label: 'Folders', onclick: 'showFolderManager()', title: 'Manage Folders' },
                { icon: 'fas fa-sync-alt', label: 'Refresh', onclick: 'location.reload()', title: 'Refresh Documents' }
            ],
            'notifications.php': [
                { icon: 'fas fa-plus', label: 'Send Notification', onclick: 'showNotificationModal()', class: 'primary', title: 'Send Notification' },
                { icon: 'fas fa-envelope', label: 'Email Templates', href: 'email-templates.php', title: 'Manage Templates' },
                { icon: 'fas fa-sync-alt', label: 'Refresh', onclick: 'location.reload()', title: 'Refresh Notifications' }
            ],
            'settings.php': [
                { icon: 'fas fa-save', label: 'Save Changes', onclick: 'saveSettings()', class: 'primary', title: 'Save Settings' },
                { icon: 'fas fa-undo', label: 'Reset', onclick: 'resetSettings()', title: 'Reset to Default' }
            ]
        };

        return actions[page] || [
            { icon: 'fas fa-sync-alt', label: 'Refresh', onclick: 'location.reload()', title: 'Refresh Page' }
        ];
    }

    updateActiveMenu() {
        const currentPage = this.getCurrentPage();
        const menuItems = document.querySelectorAll('.nav-sidebar .nav-link');
        
        menuItems.forEach(item => {
            const href = item.getAttribute('href');
            if (href && href.includes(currentPage)) {
                item.classList.add('active');
                
                // Expand parent menu if needed
                const parentItem = item.closest('.nav-treeview');
                if (parentItem) {
                    const parentLink = parentItem.previousElementSibling;
                    if (parentLink) {
                        parentLink.classList.add('active');
                        parentItem.style.display = 'block';
                    }
                }
            } else {
                item.classList.remove('active');
            }
        });
    }

    addCustomRoute(page, config) {
        this.routes[page] = config;
    }

    updateBreadcrumb(customPath) {
        const breadcrumbHTML = this.generateBreadcrumbHTML(customPath);
        const breadcrumbs = document.querySelectorAll('.kso-breadcrumb ol');
        
        breadcrumbs.forEach(breadcrumb => {
            breadcrumb.innerHTML = breadcrumbHTML;
        });
    }

    addPageAction(page, action) {
        const actions = this.getPageActions(page);
        actions.push(action);
        this.addBreadcrumbActions(page);
    }

    // Method to add breadcrumb programmatically
    addBreadcrumbItem(title, href = null, icon = 'fas fa-circle') {
        const breadcrumbs = document.querySelectorAll('.kso-breadcrumb-list');
        
        breadcrumbs.forEach(breadcrumb => {
            const item = document.createElement('li');
            item.className = 'kso-breadcrumb-item';
            
            if (href) {
                item.innerHTML = `
                    <a href="${href}">
                        <i class="${icon} breadcrumb-icon"></i>
                        ${title}
                    </a>
                `;
            } else {
                item.innerHTML = `
                    <i class="${icon} breadcrumb-icon"></i>
                    ${title}
                `;
                item.classList.add('active');
            }
            
            breadcrumb.appendChild(item);
        });
    }

    // Method to clear and rebuild breadcrumbs
    rebuild() {
        this.generateBreadcrumbs();
    }
}

// Initialize breadcrumb system
document.addEventListener('DOMContentLoaded', () => {
    window.ksoBreadcrumbs = new KSOBreadcrumbs();
});
