/**
 * KSO Chandigarh Theme Manager
 * Handles dark mode, color themes, and UI preferences
 */

class ThemeManager {
    constructor() {
        this.themes = {
            light: {
                name: 'Light',
                class: '',
                navbar: 'navbar-light',
                sidebar: 'sidebar-light-primary'
            },
            dark: {
                name: 'Dark',
                class: 'dark-mode',
                navbar: 'navbar-dark',
                sidebar: 'sidebar-dark-primary'
            }
        };

        this.colorSchemes = {
            primary: 'primary',
            secondary: 'secondary',
            success: 'success',
            info: 'info',
            warning: 'warning',
            danger: 'danger',
            indigo: 'indigo',
            navy: 'navy',
            purple: 'purple',
            pink: 'pink',
            teal: 'teal',
            orange: 'orange'
        };

        this.currentTheme = localStorage.getItem('kso-theme') || 'light';
        this.currentColor = localStorage.getItem('kso-color') || 'primary';
        
        this.init();
    }

    init() {
        this.applyTheme();
        this.createThemeToggle();
        this.createColorSelector();
        this.bindEvents();
    }

    applyTheme() {
        const body = document.body;
        const theme = this.themes[this.currentTheme];
        
        // Remove all theme classes
        Object.values(this.themes).forEach(t => {
            if (t && t.class && typeof t.class === 'string') {
                body.classList.remove(t.class);
            }
        });
        
        // Apply current theme
        if (theme.class) {
            body.classList.add(theme.class);
        }
        
        // Update navbar and sidebar
        const navbar = document.querySelector('.navbar');
        const sidebar = document.querySelector('.main-sidebar');
        
        if (navbar) {
            navbar.className = navbar.className.replace(/navbar-(light|dark)/g, theme.navbar);
        }
        
        if (sidebar) {
            sidebar.className = sidebar.className.replace(/sidebar-(light|dark)-\w+/g, theme.sidebar);
        }
    }

    createThemeToggle() {
        const themeToggle = document.createElement('li');
        themeToggle.className = 'nav-item dropdown';
        themeToggle.innerHTML = `
            <a class="nav-link" data-toggle="dropdown" href="#" title="Theme Toggle">
                <i class="fas fa-palette"></i>
            </a>
            <div class="dropdown-menu dropdown-menu-lg dropdown-menu-right">
                <span class="dropdown-item dropdown-header">Theme Settings</span>
                <div class="dropdown-divider"></div>
                <a href="#" class="dropdown-item theme-toggle" data-theme="light">
                    <i class="fas fa-sun mr-2"></i> Light Mode
                </a>
                <a href="#" class="dropdown-item theme-toggle" data-theme="dark">
                    <i class="fas fa-moon mr-2"></i> Dark Mode
                </a>
                <div class="dropdown-divider"></div>
                <div class="dropdown-item">
                    <small class="text-muted">Color Scheme</small>
                    <div class="color-palette mt-2">
                        ${Object.entries(this.colorSchemes).map(([key, value]) => 
                            `<span class="color-option bg-${value}" data-color="${key}" title="${key}"></span>`
                        ).join('')}
                    </div>
                </div>
            </div>
        `;
        
        // Insert before user dropdown
        const navbar = document.querySelector('.navbar-nav');
        if (navbar) {
            navbar.insertBefore(themeToggle, navbar.lastElementChild);
        }
    }

    createColorSelector() {
        const style = document.createElement('style');
        style.textContent = `
            .color-palette {
                display: flex;
                flex-wrap: wrap;
                gap: 5px;
            }
            .color-option {
                width: 20px;
                height: 20px;
                border-radius: 3px;
                cursor: pointer;
                border: 2px solid transparent;
                transition: all 0.3s ease;
            }
            .color-option:hover {
                transform: scale(1.1);
                border-color: #fff;
            }
            .color-option.active {
                border-color: #fff;
                box-shadow: 0 0 0 2px rgba(0,0,0,0.2);
            }
        `;
        document.head.appendChild(style);
    }

    bindEvents() {
        // Theme toggle events
        document.addEventListener('click', (e) => {
            if (e.target.closest('.theme-toggle')) {
                e.preventDefault();
                const theme = e.target.closest('.theme-toggle').dataset.theme;
                this.setTheme(theme);
            }
            
            if (e.target.closest('.color-option')) {
                const color = e.target.closest('.color-option').dataset.color;
                this.setColor(color);
            }
        });
    }

    setTheme(theme) {
        if (this.themes[theme]) {
            this.currentTheme = theme;
            localStorage.setItem('kso-theme', theme);
            this.applyTheme();
            
            // Trigger theme change event
            window.dispatchEvent(new CustomEvent('themeChanged', {
                detail: { theme: theme }
            }));
        }
    }

    setColor(color) {
        if (this.colorSchemes[color]) {
            this.currentColor = color;
            localStorage.setItem('kso-color', color);
            this.applyColorScheme();
            
            // Update active color indicator
            document.querySelectorAll('.color-option').forEach(option => {
                option.classList.remove('active');
            });
            document.querySelector(`[data-color="${color}"]`).classList.add('active');
        }
    }

    applyColorScheme() {
        const colorClass = this.colorSchemes[this.currentColor];
        const sidebar = document.querySelector('.main-sidebar');
        
        if (sidebar) {
            // Remove existing color classes
            Object.values(this.colorSchemes).forEach(color => {
                sidebar.classList.remove(`sidebar-dark-${color}`);
                sidebar.classList.remove(`sidebar-light-${color}`);
            });
            
            // Apply new color
            const themePrefix = this.currentTheme === 'dark' ? 'sidebar-dark-' : 'sidebar-light-';
            sidebar.classList.add(themePrefix + colorClass);
        }
    }

    getCurrentTheme() {
        return this.currentTheme;
    }

    getCurrentColor() {
        return this.currentColor;
    }
}

// Initialize theme manager when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
    window.themeManager = new ThemeManager();
});
