/**
 * Pomodoro Timer - Theme Manager
 * 
 * Developer: Molla Samser (Founder, RSK World)
 * Designer: Rima Khatun (Designer & Tester, RSK World)
 * Website: https://rskworld.in/
 * Contact: +91 93305 39277 | hello@rskworld.in | support@rskworld.in
 * Location: Nutanhat, Mongolkote, Purba Burdwan, West Bengal, India - 713147
 * Year: 2026
 * 
 * Description: Theme customization system for Pomodoro Timer
 */

class ThemeManager {
    constructor() {
        this.currentTheme = this.loadTheme();
        this.customThemes = this.loadCustomThemes();
        this.init();
    }

    init() {
        this.applyTheme(this.currentTheme);
        this.setupEventListeners();
        this.createThemeControls();
    }

    setupEventListeners() {
        // Theme toggle button
        const themeToggle = document.getElementById('theme-toggle');
        if (themeToggle) {
            themeToggle.addEventListener('click', () => this.toggleTheme());
        }

        // Theme selector
        const themeSelector = document.getElementById('theme-selector');
        if (themeSelector) {
            themeSelector.addEventListener('change', (e) => this.applyTheme(e.target.value));
        }

        // Custom theme creator
        const createThemeBtn = document.getElementById('create-custom-theme');
        if (createThemeBtn) {
            createThemeBtn.addEventListener('click', () => this.showThemeCreator());
        }

        // System theme detection
        if (window.matchMedia) {
            const darkModeQuery = window.matchMedia('(prefers-color-scheme: dark)');
            darkModeQuery.addListener((e) => {
                if (this.currentTheme === 'auto') {
                    this.applySystemTheme();
                }
            });
        }
    }

    createThemeControls() {
        // Create theme selector if it doesn't exist
        if (!document.getElementById('theme-selector')) {
            const selectorHTML = `
                <div class="theme-controls">
                    <select id="theme-selector" class="theme-selector">
                        <option value="light">Light</option>
                        <option value="dark">Dark</option>
                        <option value="auto">Auto</option>
                        <option value="classic">Classic</option>
                        <option value="ocean">Ocean</option>
                        <option value="forest">Forest</option>
                        <option value="sunset">Sunset</option>
                    </select>
                    <button id="create-custom-theme" class="btn btn-secondary btn-sm">
                        <i class="fas fa-palette"></i> Custom Theme
                    </button>
                </div>
            `;
            
            const settingsPanel = document.querySelector('.settings-panel');
            if (settingsPanel) {
                settingsPanel.insertAdjacentHTML('afterbegin', selectorHTML);
            }
        }
    }

    applyTheme(themeName) {
        const theme = this.getThemeDefinition(themeName);
        if (!theme) return;

        this.currentTheme = themeName;
        this.saveTheme(themeName);

        // Apply CSS variables
        const root = document.documentElement;
        Object.entries(theme).forEach(([key, value]) => {
            const cssVar = `--${this.camelToKebab(key)}`;
            root.style.setProperty(cssVar, value);
        });

        // Update theme selector
        const selector = document.getElementById('theme-selector');
        if (selector) {
            selector.value = themeName;
        }

        // Update body class
        document.body.className = document.body.className.replace(/theme-\w+/g, '');
        document.body.classList.add(`theme-${themeName}`);

        // Apply system theme if auto
        if (themeName === 'auto') {
            this.applySystemTheme();
        }

        // Dispatch theme change event
        window.dispatchEvent(new CustomEvent('themeChanged', { detail: { theme: themeName } }));
    }

    applySystemTheme() {
        const isDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
        const systemTheme = isDark ? 'dark' : 'light';
        const theme = this.getThemeDefinition(systemTheme);
        
        if (theme) {
            const root = document.documentElement;
            Object.entries(theme).forEach(([key, value]) => {
                const cssVar = `--${this.camelToKebab(key)}`;
                root.style.setProperty(cssVar, value);
            });
        }
    }

    getThemeDefinition(themeName) {
        // Built-in themes
        const builtInThemes = {
            light: {
                primaryColor: '#FF6B6B',
                accentColor: '#4ECDC4',
                backgroundColor: '#FFFFFF',
                textColor: '#2C3E50',
                cardBackground: '#F8F9FA',
                borderColor: '#E9ECEF',
                shadowColor: 'rgba(0, 0, 0, 0.1)',
                gradientStart: '#FF6B6B',
                gradientEnd: '#4ECDC4'
            },
            dark: {
                primaryColor: '#FF6B6B',
                accentColor: '#4ECDC4',
                backgroundColor: '#1A1A1A',
                textColor: '#E0E0E0',
                cardBackground: '#2D2D2D',
                borderColor: '#404040',
                shadowColor: 'rgba(0, 0, 0, 0.3)',
                gradientStart: '#FF6B6B',
                gradientEnd: '#4ECDC4'
            },
            classic: {
                primaryColor: '#FF6B6B',
                accentColor: '#4ECDC4',
                backgroundColor: '#FFFFFF',
                textColor: '#2C3E50',
                cardBackground: '#F8F9FA',
                borderColor: '#E9ECEF',
                shadowColor: 'rgba(0, 0, 0, 0.1)',
                gradientStart: '#FF6B6B',
                gradientEnd: '#4ECDC4'
            },
            ocean: {
                primaryColor: '#006BA6',
                accentColor: '#0496FF',
                backgroundColor: '#F0F8FF',
                textColor: '#0C2D48',
                cardBackground: '#E6F3FF',
                borderColor: '#B8D4E8',
                shadowColor: 'rgba(0, 107, 166, 0.1)',
                gradientStart: '#006BA6',
                gradientEnd: '#0496FF'
            },
            forest: {
                primaryColor: '#2D6A4F',
                accentColor: '#52B788',
                backgroundColor: '#F1F8E9',
                textColor: '#1B4332',
                cardBackground: '#E8F5E9',
                borderColor: '#C8E6C9',
                shadowColor: 'rgba(45, 106, 79, 0.1)',
                gradientStart: '#2D6A4F',
                gradientEnd: '#52B788'
            },
            sunset: {
                primaryColor: '#FF6B35',
                accentColor: '#F77F00',
                backgroundColor: '#FFF5E6',
                textColor: '#3A0CA3',
                cardBackground: '#FFE8CC',
                borderColor: '#FFD8A8',
                shadowColor: 'rgba(255, 107, 53, 0.1)',
                gradientStart: '#FF6B35',
                gradientEnd: '#F77F00'
            }
        };

        // Check custom themes
        if (this.customThemes[themeName]) {
            return this.customThemes[themeName];
        }

        return builtInThemes[themeName] || builtInThemes.light;
    }

    toggleTheme() {
        const themes = ['light', 'dark', 'auto'];
        const currentIndex = themes.indexOf(this.currentTheme);
        const nextIndex = (currentIndex + 1) % themes.length;
        this.applyTheme(themes[nextIndex]);
    }

    showThemeCreator() {
        const modal = document.getElementById('theme-modal');
        if (!modal) {
            this.createThemeModal();
        }
        
        const modalElement = document.getElementById('theme-modal');
        modalElement.classList.add('active');
        this.populateThemeCreator();
    }

    createThemeModal() {
        const modalHTML = `
            <div id="theme-modal" class="modal">
                <div class="modal-content theme-creator">
                    <div class="modal-header">
                        <h2>Create Custom Theme</h2>
                        <button id="close-theme-modal" class="btn-close">&times;</button>
                    </div>
                    <div class="modal-body">
                        <form id="custom-theme-form">
                            <div class="form-group">
                                <label for="theme-name">Theme Name</label>
                                <input type="text" id="theme-name" required>
                            </div>
                            <div class="color-inputs">
                                <div class="form-group">
                                    <label for="primary-color">Primary Color</label>
                                    <input type="color" id="primary-color" value="#FF6B6B">
                                </div>
                                <div class="form-group">
                                    <label for="accent-color">Accent Color</label>
                                    <input type="color" id="accent-color" value="#4ECDC4">
                                </div>
                                <div class="form-group">
                                    <label for="background-color">Background Color</label>
                                    <input type="color" id="background-color" value="#FFFFFF">
                                </div>
                                <div class="form-group">
                                    <label for="text-color">Text Color</label>
                                    <input type="color" id="text-color" value="#2C3E50">
                                </div>
                                <div class="form-group">
                                    <label for="card-background">Card Background</label>
                                    <input type="color" id="card-background" value="#F8F9FA">
                                </div>
                            </div>
                            <div class="theme-preview">
                                <h3>Preview</h3>
                                <div class="preview-card">
                                    <h4>Sample Card</h4>
                                    <p>This is how your theme will look</p>
                                    <button class="btn btn-primary">Primary Button</button>
                                    <button class="btn btn-secondary">Secondary Button</button>
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" id="save-custom-theme" class="btn btn-primary">Save Theme</button>
                        <button type="button" id="cancel-theme" class="btn btn-secondary">Cancel</button>
                    </div>
                </div>
            </div>
        `;
        
        document.body.insertAdjacentHTML('beforeend', modalHTML);
        this.setupThemeCreatorEvents();
    }

    setupThemeCreatorEvents() {
        const closeBtn = document.getElementById('close-theme-modal');
        const cancelBtn = document.getElementById('cancel-theme');
        const saveBtn = document.getElementById('save-custom-theme');
        const form = document.getElementById('custom-theme-form');
        const colorInputs = form.querySelectorAll('input[type="color"]');

        if (closeBtn) closeBtn.addEventListener('click', () => this.hideThemeCreator());
        if (cancelBtn) cancelBtn.addEventListener('click', () => this.hideThemeCreator());
        if (saveBtn) saveBtn.addEventListener('click', () => this.saveCustomTheme());

        // Live preview
        colorInputs.forEach(input => {
            input.addEventListener('input', () => this.updateThemePreview());
        });
    }

    populateThemeCreator() {
        const currentTheme = this.getThemeDefinition(this.currentTheme);
        if (currentTheme) {
            document.getElementById('primary-color').value = currentTheme.primaryColor || '#FF6B6B';
            document.getElementById('accent-color').value = currentTheme.accentColor || '#4ECDC4';
            document.getElementById('background-color').value = currentTheme.backgroundColor || '#FFFFFF';
            document.getElementById('text-color').value = currentTheme.textColor || '#2C3E50';
            document.getElementById('card-background').value = currentTheme.cardBackground || '#F8F9FA';
        }
        this.updateThemePreview();
    }

    updateThemePreview() {
        const preview = document.querySelector('.preview-card');
        if (!preview) return;

        const primaryColor = document.getElementById('primary-color').value;
        const accentColor = document.getElementById('accent-color').value;
        const backgroundColor = document.getElementById('background-color').value;
        const textColor = document.getElementById('text-color').value;
        const cardBackground = document.getElementById('card-background').value;

        preview.style.backgroundColor = cardBackground;
        preview.style.color = textColor;
        preview.style.border = `1px solid ${this.adjustColor(cardBackground, -20)}`;

        const primaryBtn = preview.querySelector('.btn-primary');
        if (primaryBtn) {
            primaryBtn.style.backgroundColor = primaryColor;
            primaryBtn.style.borderColor = primaryColor;
        }

        const secondaryBtn = preview.querySelector('.btn-secondary');
        if (secondaryBtn) {
            secondaryBtn.style.backgroundColor = accentColor;
            secondaryBtn.style.borderColor = accentColor;
        }
    }

    saveCustomTheme() {
        const themeName = document.getElementById('theme-name').value.trim();
        if (!themeName) {
            alert('Please enter a theme name');
            return;
        }

        const theme = {
            primaryColor: document.getElementById('primary-color').value,
            accentColor: document.getElementById('accent-color').value,
            backgroundColor: document.getElementById('background-color').value,
            textColor: document.getElementById('text-color').value,
            cardBackground: document.getElementById('card-background').value,
            borderColor: this.adjustColor(document.getElementById('card-background').value, -20),
            shadowColor: 'rgba(0, 0, 0, 0.1)',
            gradientStart: document.getElementById('primary-color').value,
            gradientEnd: document.getElementById('accent-color').value
        };

        this.customThemes[themeName] = theme;
        this.saveCustomThemes();
        this.addThemeToSelector(themeName);
        this.applyTheme(themeName);
        this.hideThemeCreator();

        // Show success notification
        if (window.pomodoroApp && window.pomodoroApp.showNotification) {
            window.pomodoroApp.showNotification(`Custom theme "${themeName}" created successfully`, 'success');
        }
    }

    addThemeToSelector(themeName) {
        const selector = document.getElementById('theme-selector');
        if (selector) {
            const option = document.createElement('option');
            option.value = themeName;
            option.textContent = themeName;
            selector.appendChild(option);
        }
    }

    hideThemeCreator() {
        const modal = document.getElementById('theme-modal');
        if (modal) {
            modal.classList.remove('active');
        }
    }

    adjustColor(color, amount) {
        const num = parseInt(color.replace('#', ''), 16);
        const r = Math.max(0, Math.min(255, (num >> 16) + amount));
        const g = Math.max(0, Math.min(255, ((num >> 8) & 0x00FF) + amount));
        const b = Math.max(0, Math.min(255, (num & 0x0000FF) + amount));
        return '#' + ((r << 16) | (g << 8) | b).toString(16).padStart(6, '0');
    }

    camelToKebab(str) {
        return str.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, '$1-$2').toLowerCase();
    }

    saveTheme(themeName) {
        localStorage.setItem('pomodoro_theme', themeName);
    }

    loadTheme() {
        return localStorage.getItem('pomodoro_theme') || 'light';
    }

    saveCustomThemes() {
        localStorage.setItem('pomodoro_custom_themes', JSON.stringify(this.customThemes));
    }

    loadCustomThemes() {
        try {
            const saved = localStorage.getItem('pomodoro_custom_themes');
            return saved ? JSON.parse(saved) : {};
        } catch (error) {
            console.error('Failed to load custom themes:', error);
            return {};
        }
    }

    exportTheme(themeName) {
        const theme = this.getThemeDefinition(themeName);
        if (!theme) return;

        const data = {
            name: themeName,
            theme: theme,
            exportDate: new Date().toISOString(),
            version: '1.0.0'
        };

        const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `pomodoro-theme-${themeName}.json`;
        a.click();
        URL.revokeObjectURL(url);
    }

    importTheme(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = (e) => {
                try {
                    const data = JSON.parse(e.target.result);
                    if (data.name && data.theme) {
                        this.customThemes[data.name] = data.theme;
                        this.saveCustomThemes();
                        this.addThemeToSelector(data.name);
                        resolve(data.name);
                    } else {
                        reject(new Error('Invalid theme file format'));
                    }
                } catch (error) {
                    reject(error);
                }
            };
            reader.onerror = () => reject(new Error('Failed to read theme file'));
            reader.readAsText(file);
        });
    }
}

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