/**
 * ========================================
 * KATEGOORIAHALDUSE FRONTEND
 * ========================================
 * Täielik kasutajaliides kategooriate haldamiseks
 * Ikoonid, värvid, nutikad mallid, meeldetuletused
 * ========================================
 */

class CategoryManager {
    constructor(options = {}) {
        this.options = {
            apiBaseUrl: options.apiBaseUrl || 'calendar/api/',
            containerId: options.containerId || 'category-manager-inner',
            ...options
        };
        
        this.categories = [];
        this.availableIcons = {};
        this.availableColors = {};
        this.reminderTemplates = {};
        
        this.init();
    }
    
    async init() {
        console.log('🎨 Category Manager initializing...');
        
        try {
            // Lae kõik vajalikud andmed
            await this.loadCategories();
            await this.loadAvailableOptions();
            
            // Initsialiseerib UI
            this.renderCategoryManager();
            this.bindEventListeners();
            
            console.log('✅ Category Manager ready!');
        } catch (error) {
            console.error('❌ Category Manager initialization failed:', error);
            this.showError('Kategooriahalduse laadimine ebaõnnestus');
        }
    }
    
    /**
     * ==========================================
     * DATA LOADING FUNCTIONS
     * ==========================================
     */
    
    /**
     * Lae kategooriad
     */
    async loadCategories() {
        try {
            const response = await fetch(this.options.apiBaseUrl + 'categories-api.php?action=list');
            const data = await response.json();
            
            if (data.success) {
                this.categories = data.data;
                console.log('📂 Categories loaded:', this.categories.length);
            } else {
                throw new Error(data.error || 'Kategooriate laadimine ebaõnnestus');
            }
        } catch (error) {
            console.error('❌ Error loading categories:', error);
            throw error;
        }
    }
    
    /**
     * Lae saadaolevad valikud (ikoonid, värvid, mallid)
     */
    async loadAvailableOptions() {
        try {
            // Lae ikoonid
            const iconsResponse = await fetch(this.options.apiBaseUrl + 'categories-api.php?action=icons');
            const iconsData = await iconsResponse.json();
            if (iconsData.success) {
                this.availableIcons = iconsData.data;
            }
            
            // Lae värvid
            const colorsResponse = await fetch(this.options.apiBaseUrl + 'categories-api.php?action=colors');
            const colorsData = await colorsResponse.json();
            if (colorsData.success) {
                this.availableColors = colorsData.data;
            }
            
            // Lae meeldetuletuste mallid
            const templatesResponse = await fetch(this.options.apiBaseUrl + 'categories-api.php?action=templates');
            const templatesData = await templatesResponse.json();
            if (templatesData.success) {
                this.reminderTemplates = templatesData.data;
            }
            
            console.log('🎨 Available options loaded');
        } catch (error) {
            console.error('❌ Error loading options:', error);
            // Jätka ka ilma lisavalikuteta
        }
    }
    
    /**
     * ==========================================
     * UI RENDERING FUNCTIONS
     * ==========================================
     */
    
    /**
     * Renderdab kategooriahalduse UI
     */
    renderCategoryManager() {
        const container = document.getElementById(this.options.containerId);
        if (!container) {
            console.error('Category manager container not found');
            return;
        }
        
        container.innerHTML = `
            <div class="category-manager-wrapper">
                <!-- Header -->
                <div class="category-manager-header">
                    <div style="display: flex; align-items: center; gap: 12px;">
                        <h2 style="margin: 0; font-size: 24px; color: #1f2937;">🏷️ Kategooriate haldus</h2>
                        <span style="background: #e5e7eb; color: #6b7280; padding: 4px 12px; border-radius: 20px; font-size: 12px; font-weight: 500;">
                            ${this.categories.length} kategooriat
                        </span>
                    </div>
                    <button class="btn btn-primary" id="add-category-btn">
                        <span>➕</span>
                        Lisa kategooria
                    </button>
                </div>
                
                <!-- Categories Grid -->
                <div class="categories-grid" id="categories-grid">
                    ${this.renderCategoriesList()}
                </div>
                
                <!-- Help Text -->
                <div style="margin-top: 24px; padding: 20px; background: #f9fafb; border-radius: 12px; border: 1px solid #e5e7eb;">
                    <h4 style="margin: 0 0 8px 0; color: #374151; font-size: 14px;">💡 Nipid:</h4>
                    <ul style="margin: 0; padding-left: 20px; color: #6b7280; font-size: 13px; line-height: 1.6;">
                        <li>Kasutage erinevaid värve kategooriate kiireks eristamiseks</li>
                        <li>Valige sobivad ikoonid, et kategooriad oleksid visuaalselt äratuntavad</li>
                        <li>Seadistage nutikad meeldetuletused kategooriate kaupa</li>
                        <li>Süsteemi kategooriaid ei saa kustutada, kuid saate neid kohandada</li>
                    </ul>
                </div>
            </div>
            
            ${this.renderCategoryModal()}
        `;
    }
    
    /**
     * Renderdab kategooriate nimekirja
     */
    renderCategoriesList() {
        if (this.categories.length === 0) {
            return `
                <div style="text-align: center; padding: 60px 20px; color: #6b7280;">
                    <div style="font-size: 48px; margin-bottom: 16px;">📂</div>
                    <h3 style="margin: 0 0 8px 0; color: #374151;">Kategooriaid pole veel</h3>
                    <p style="margin: 0;">Lisage oma esimene kategooria, et alustada paremini organiseeritud kalendriga!</p>
                </div>
            `;
        }
        
        return this.categories.map(category => `
            <div class="category-card ${category.is_system ? 'system-category' : 'user-category'}" data-category-id="${category.id}">
                <div class="category-card-header">
                    <div class="category-visual">
                        <span class="category-icon" style="font-size: 24px;">${category.icon}</span>
                        <div class="category-color-dot" style="background-color: ${category.color}; width: 16px; height: 16px; border-radius: 50%; border: 2px solid white; box-shadow: 0 2px 4px rgba(0,0,0,0.1);"></div>
                    </div>
                    <div class="category-info">
                        <h3 class="category-name" style="margin: 0; font-size: 16px; font-weight: 600; color: #1f2937;">${category.name}</h3>
                        <div class="category-meta" style="margin-top: 4px; display: flex; align-items: center; gap: 12px; font-size: 12px; color: #6b7280;">
                            ${category.is_system ? 
                                '<span style="background: #dbeafe; color: #1d4ed8; padding: 2px 8px; border-radius: 12px; font-weight: 500;">🔒 Süsteemi</span>' : 
                                '<span style="background: #dcfce7; color: #166534; padding: 2px 8px; border-radius: 12px; font-weight: 500;">👤 Isiklik</span>'
                            }
                            <span>${category.event_count} sündmust</span>
                            ${category.reminder_enabled ? '<span>🔔 Teavitused</span>' : ''}
                        </div>
                    </div>
                </div>
                
                <div class="category-card-body" style="padding: 16px;">
                    ${category.custom_message_template ? `
                        <div style="background: #f3f4f6; padding: 12px; border-radius: 8px; margin-bottom: 12px;">
                            <div style="font-size: 11px; color: #6b7280; text-transform: uppercase; font-weight: 600; letter-spacing: 0.5px; margin-bottom: 4px;">Meeldetuletuse mall:</div>
                            <div style="font-size: 13px; color: #374151; font-style: italic;">"${category.custom_message_template}"</div>
                        </div>
                    ` : ''}
                    
                    <div style="display: flex; align-items: center; justify-content: space-between; font-size: 12px; color: #6b7280;">
                        <span>Meeldetuletus: ${category.default_reminder_minutes} min enne</span>
                        <div class="category-actions">
                            ${category.can_edit ? `
                                <button class="btn-icon" onclick="categoryManager.editCategory(${category.id})" title="Muuda">
                                    ✏️
                                </button>
                            ` : ''}
                            ${category.can_delete ? `
                                <button class="btn-icon btn-danger" onclick="categoryManager.deleteCategory(${category.id})" title="Kustuta">
                                    🗑️
                                </button>
                            ` : ''}
                        </div>
                    </div>
                </div>
            </div>
        `).join('');
    }
    
    /**
     * Renderdab kategooria modali
     */
    renderCategoryModal() {
        return `
            <div class="modal-overlay" id="categoryModal" style="display: none;">
                <div class="modal-content" style="max-width: 600px;">
                    <div class="modal-header">
                        <h3 class="modal-title">Lisa kategooria</h3>
                        <button class="modal-close" onclick="categoryManager.closeCategoryModal()">×</button>
                    </div>
                    
                    <form id="category-form" onsubmit="categoryManager.saveCategory(event)">
                        <input type="hidden" id="category-id" name="category_id">
                        <div class="modal-body">
                            <div class="form-grid">
                                <!-- Nimi -->
                                <div class="form-group full-width">
                                    <label class="form-label" for="category-name">Kategooria nimi *</label>
                                    <input type="text" id="category-name" name="name" class="form-control" required placeholder="nt. Treening, Koosolek, Isiklik">
                                </div>
                                
                                <!-- Ikoon ja värv -->
                                <div class="form-group">
                                    <label class="form-label">Ikoon</label>
                                    <div style="display: flex; align-items: center; gap: 8px;">
                                        <span id="selected-icon" style="font-size: 24px; width: 32px; text-align: center;">📅</span>
                                        <button type="button" class="btn btn-outline" id="icon-selector-btn" onclick="categoryManager.openIconPicker()">
                                            Vali ikoon
                                        </button>
                                        <input type="hidden" id="category-icon" name="icon" value="📅">
                                    </div>
                                </div>
                                
                                <div class="form-group">
                                    <label class="form-label">Värv</label>
                                    <div style="display: flex; align-items: center; gap: 8px;">
                                        <div id="selected-color" style="width: 32px; height: 32px; border-radius: 50%; background: #3B82F6; border: 2px solid #e5e7eb;"></div>
                                        <button type="button" class="btn btn-outline" id="color-selector-btn" onclick="categoryManager.openColorPicker()">
                                            Vali värv
                                        </button>
                                        <input type="hidden" id="category-color" name="color" value="#3B82F6">
                                    </div>
                                </div>
                                
                                <!-- Meeldetuletused -->
                                <div class="form-group full-width">
                                    <div class="checkbox-group">
                                        <input type="checkbox" id="reminder-enabled" name="reminder_enabled" checked>
                                        <label for="reminder-enabled">🔔 Luba meeldetuletused</label>
                                    </div>
                                </div>
                                
                                <div id="reminder-settings" class="form-group full-width">
                                    <label class="form-label">Vaikimisi meeldetuletus</label>
                                    <select id="reminder-minutes" name="default_reminder_minutes" class="form-control">
                                        <option value="15">15 minutit enne</option>
                                        <option value="30">30 minutit enne</option>
                                        <option value="60" selected>1 tund enne</option>
                                        <option value="120">2 tundi enne</option>
                                        <option value="1440">1 päev enne</option>
                                    </select>
                                </div>
                                
                                <!-- Kohandatud sõnum -->
                                <div class="form-group full-width">
                                    <label class="form-label">Meeldetuletuse sõnum (valikuline)</label>
                                    <textarea id="message-template" name="custom_message_template" class="form-control" rows="2" placeholder='nt. 🏃 Treening "{title}" algab {time_until} pärast! Sa oled valmis!'></textarea>
                                    <small style="color: #6b7280; font-size: 12px; margin-top: 4px;">
                                        Kasutage: {title} - sündmuse nimi, {time_until} - aeg sündmuseni
                                    </small>
                                </div>
                            </div>
                            
                            <!-- Soovitused -->
                            <div id="template-suggestions" style="margin-top: 16px; display: none;">
                                <div style="font-size: 13px; font-weight: 500; color: #374151; margin-bottom: 8px;">💡 Soovitused:</div>
                                <div id="suggestions-list" style="display: flex; flex-direction: column; gap: 4px;"></div>
                            </div>
                        </div>
                        
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" onclick="categoryManager.closeCategoryModal()">Tühista</button>
                            <button type="submit" class="btn btn-primary" id="save-category-btn">💾 Salvesta</button>
                        </div>
                    </form>
                </div>
            </div>
            
            <!-- Icon Picker Modal -->
            <div class="modal-overlay" id="iconPickerModal" style="display: none;">
                <div class="modal-content" style="max-width: 500px;">
                    <div class="modal-header">
                        <h3 class="modal-title">Vali ikoon</h3>
                        <button class="modal-close" onclick="categoryManager.closeIconPicker()">×</button>
                    </div>
                    <div class="modal-body">
                        <div id="icon-picker-content">
                            <!-- JavaScript täidab selle -->
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Color Picker Modal -->
            <div class="modal-overlay" id="colorPickerModal" style="display: none;">
                <div class="modal-content" style="max-width: 400px;">
                    <div class="modal-header">
                        <h3 class="modal-title">Vali värv</h3>
                        <button class="modal-close" onclick="categoryManager.closeColorPicker()">×</button>
                    </div>
                    <div class="modal-body">
                        <div id="color-picker-content">
                            <!-- JavaScript täidab selle -->
                        </div>
                    </div>
                </div>
            </div>
        `;
    }
    
    /**
     * ==========================================
     * EVENT LISTENERS
     * ==========================================
     */
    
    bindEventListeners() {
        // Lisa kategooria nupp
        const addBtn = document.getElementById('add-category-btn');
        if (addBtn) {
            addBtn.addEventListener('click', () => this.openCategoryModal());
        }
        
        // Meeldetuletuse toggle
        const reminderToggle = document.getElementById('reminder-enabled');
        const reminderSettings = document.getElementById('reminder-settings');
        if (reminderToggle && reminderSettings) {
            reminderToggle.addEventListener('change', (e) => this.toggleReminderSettings(e.target.checked));
        }
        
        // Mallide soovitused
        const nameInput = document.getElementById('category-name');
        if (nameInput) {
            nameInput.addEventListener('input', (e) => this.updateTemplateSuggestions(e.target.value));
        }
        
        // ESC klahv modalite sulgemiseks
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                this.closeCategoryModal();
                this.closeIconPicker();
                this.closeColorPicker();
            }
        });
    }
    
    /**
     * ==========================================
     * MODAL FUNCTIONS
     * ==========================================
     */
    
    /**
     * Ava kategooria modal
     */
    openCategoryModal(categoryData = null) {
        const modal = document.getElementById('categoryModal');
        if (!modal) return;
        
        modal.style.display = 'flex';
        document.body.style.overflow = 'hidden';
        
        // Reset vorm
        document.getElementById('category-form').reset();
        document.getElementById('category-id').value = '';
        document.querySelector('.modal-title').textContent = 'Lisa kategooria';
        document.getElementById('save-category-btn').innerHTML = '💾 Salvesta';
        
        // Vaikeväärtused
        document.getElementById('category-icon').value = '📅';
        document.getElementById('selected-icon').textContent = '📅';
        document.getElementById('category-color').value = '#3B82F6';
        document.getElementById('selected-color').style.backgroundColor = '#3B82F6';
        document.getElementById('reminder-enabled').checked = true;
        document.getElementById('reminder-minutes').value = '60';
        
        this.toggleReminderSettings(true);
        
        if (categoryData) {
            // Muutmise režiim
            document.querySelector('.modal-title').textContent = 'Muuda kategooriat';
            document.getElementById('save-category-btn').innerHTML = '💾 Muuda';
            
            // Täida andmed
            document.getElementById('category-id').value = categoryData.id;
            document.getElementById('category-name').value = categoryData.name;
            document.getElementById('category-icon').value = categoryData.icon;
            document.getElementById('selected-icon').textContent = categoryData.icon;
            document.getElementById('category-color').value = categoryData.color;
            document.getElementById('selected-color').style.backgroundColor = categoryData.color;
            document.getElementById('reminder-enabled').checked = categoryData.reminder_enabled;
            document.getElementById('reminder-minutes').value = categoryData.default_reminder_minutes;
            document.getElementById('message-template').value = categoryData.custom_message_template || '';
            
            this.toggleReminderSettings(categoryData.reminder_enabled);
        }
        
        // Fookus nimele
        document.getElementById('category-name').focus();
        this.updateTemplateSuggestions(document.getElementById('category-name').value);
    }
    
    /**
     * Sulge kategooria modal
     */
    closeCategoryModal() {
        const modal = document.getElementById('categoryModal');
        if (modal) {
            modal.style.display = 'none';
            document.body.style.overflow = '';
        }
    }
    
    /**
     * ==========================================
     * CRUD OPERATIONS
     * ==========================================
     */
    
    /**
     * Salvesta kategooria
     */
    async saveCategory(e) {
        e.preventDefault();
        
        const form = e.target;
        const formData = new FormData(form);
        
        const categoryData = {
            name: formData.get('name'),
            icon: formData.get('icon'),
            color: formData.get('color'),
            default_reminder_minutes: parseInt(formData.get('default_reminder_minutes')),
            reminder_enabled: formData.get('reminder_enabled') ? 1 : 0,
            custom_message_template: formData.get('custom_message_template')
        };
        
        const categoryId = formData.get('category_id');
        const isEdit = categoryId && categoryId !== '';
        
        try {
            const response = await fetch(this.options.apiBaseUrl + 'categories-api.php', {
                method: isEdit ? 'PUT' : 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(isEdit ? { ...categoryData, id: categoryId } : categoryData)
            });
            
            const result = await response.json();
            
            if (result.success) {
                this.showSuccess(
                    isEdit ? '✅ Kategooria edukalt muudetud!' : '✅ Kategooria edukalt lisatud!'
                );
                this.closeCategoryModal();
                
                // Uuenda kategoriate nimekirja
                await this.loadCategories();
                this.renderCategoryManager();
                this.bindEventListeners();
            } else {
                throw new Error(result.error || 'Salvestamine ebaõnnestus');
            }
        } catch (error) {
            console.error('❌ Error saving category:', error);
            this.showError('❌ Viga: ' + error.message);
        }
    }
    
    /**
     * Muuda kategooriat
     */
    async editCategory(categoryId) {
        const category = this.categories.find(c => c.id == categoryId);
        if (category) {
            this.openCategoryModal(category);
        }
    }
    
    /**
     * Kustuta kategooria
     */
    async deleteCategory(categoryId) {
        const category = this.categories.find(c => c.id == categoryId);
        if (!category) return;
        
        const confirmed = confirm(
            `Kas oled kindel, et soovid kustutada kategooria "${category.name}"?\n\n` +
            `${category.event_count > 0 ? 
                `HOIATUS: See kategooria sisaldab ${category.event_count} sündmust. ` +
                `Sündmused jäävad alles, kuid kategooria eemaldatakse.` : 
                'See tegevus on pöördumatu.'
            }`
        );
        
        if (!confirmed) return;
        
        try {
            const response = await fetch(this.options.apiBaseUrl + 'categories-api.php', {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ id: categoryId })
            });
            
            const result = await response.json();
            
            if (result.success) {
                this.showSuccess('✅ Kategooria edukalt kustutatud!');
                
                // Uuenda kategoriate nimekirja
                await this.loadCategories();
                this.renderCategoryManager();
                this.bindEventListeners();
            } else {
                throw new Error(result.error || 'Kustutamine ebaõnnestus');
            }
        } catch (error) {
            console.error('❌ Error deleting category:', error);
            this.showError('❌ Viga: ' + error.message);
        }
    }
    
    /**
     * ==========================================
     * PICKER FUNCTIONS
     * ==========================================
     */
    
    /**
     * Ava ikooni valija
     */
    openIconPicker() {
        const modal = document.getElementById('iconPickerModal');
        const content = document.getElementById('icon-picker-content');
        
        if (!modal || !content) return;
        
        // Renderdab ikoonide grid
        let html = '';
        for (const [category, icons] of Object.entries(this.availableIcons)) {
            html += `
                <div style="margin-bottom: 20px;">
                    <h4 style="margin: 0 0 12px 0; font-size: 14px; color: #374151; text-transform: capitalize;">${category}</h4>
                    <div style="display: grid; grid-template-columns: repeat(8, 1fr); gap: 8px;">
                        ${icons.map(icon => `
                            <button type="button" class="icon-option" onclick="categoryManager.selectIcon('${icon}')" 
                                    style="width: 40px; height: 40px; border: 2px solid #e5e7eb; border-radius: 8px; background: white; cursor: pointer; font-size: 18px; display: flex; align-items: center; justify-content: center; transition: all 0.2s;">
                                ${icon}
                            </button>
                        `).join('')}
                    </div>
                </div>
            `;
        }
        
        content.innerHTML = html;
        modal.style.display = 'flex';
    }
    
    /**
     * Ava värvi valija
     */
    openColorPicker() {
        const modal = document.getElementById('colorPickerModal');
        const content = document.getElementById('color-picker-content');
        
        if (!modal || !content) return;
        
        // Renderdab värvide grid
        let html = '';
        for (const [category, colors] of Object.entries(this.availableColors)) {
            html += `
                <div style="margin-bottom: 20px;">
                    <h4 style="margin: 0 0 12px 0; font-size: 14px; color: #374151; text-transform: capitalize;">${category}</h4>
                    <div style="display: grid; grid-template-columns: repeat(5, 1fr); gap: 12px;">
                        ${Object.entries(colors).map(([color, name]) => `
                            <button type="button" class="color-option" onclick="categoryManager.selectColor('${color}')" 
                                    style="width: 50px; height: 50px; border: 3px solid #e5e7eb; border-radius: 50%; background: ${color}; cursor: pointer; transition: all 0.2s;" 
                                    title="${name}">
                            </button>
                        `).join('')}
                    </div>
                </div>
            `;
        }
        
        content.innerHTML = html;
        modal.style.display = 'flex';
    }
    
    /**
     * Vali ikoon
     */
    selectIcon(icon) {
        document.getElementById('category-icon').value = icon;
        document.getElementById('selected-icon').textContent = icon;
        this.closeIconPicker();
    }
    
    /**
     * Vali värv
     */
    selectColor(color) {
        document.getElementById('category-color').value = color;
        document.getElementById('selected-color').style.backgroundColor = color;
        this.closeColorPicker();
    }
    
    /**
     * Sulge ikooni valija
     */
    closeIconPicker() {
        const modal = document.getElementById('iconPickerModal');
        if (modal) {
            modal.style.display = 'none';
        }
    }
    
    /**
     * Sulge värvi valija
     */
    closeColorPicker() {
        const modal = document.getElementById('colorPickerModal');
        if (modal) {
            modal.style.display = 'none';
        }
    }
    
    /**
     * ==========================================
     * HELPER FUNCTIONS
     * ==========================================
     */
    
    /**
     * Toggle meeldetuletuse seaded
     */
    toggleReminderSettings(enabled) {
        const settings = document.getElementById('reminder-settings');
        if (settings) {
            settings.style.display = enabled ? 'block' : 'none';
        }
    }
    
    /**
     * Uuenda mallide soovitusi
     */
    updateTemplateSuggestions(name) {
        const suggestions = document.getElementById('template-suggestions');
        const suggestionsList = document.getElementById('suggestions-list');
        
        if (!suggestions || !suggestionsList) return;
        
        const lowerName = name.toLowerCase();
        let templates = [];
        
        // Leia sobivad mallid
        for (const [category, categoryTemplates] of Object.entries(this.reminderTemplates)) {
            if (lowerName.includes(category)) {
                for (const [context, template] of Object.entries(categoryTemplates)) {
                    templates.push(template);
                }
                break;
            }
        }
        
        if (templates.length > 0) {
            suggestionsList.innerHTML = templates.map(template => `
                <button type="button" class="template-suggestion" onclick="categoryManager.selectTemplate('${template.replace(/'/g, "\\'")}')">
                    ${template}
                </button>
            `).join('');
            suggestions.style.display = 'block';
        } else {
            suggestions.style.display = 'none';
        }
    }
    
    /**
     * Vali mall
     */
    selectTemplate(template) {
        document.getElementById('message-template').value = template;
        document.getElementById('template-suggestions').style.display = 'none';
    }
    
    /**
     * Näita edu teadet
     */
    showSuccess(message) {
        this.showNotification(message, 'success');
    }
    
    /**
     * Näita vea teadet
     */
    showError(message) {
        this.showNotification(message, 'error');
    }
    
    /**
     * Näita teadet
     */
    showNotification(message, type = 'info') {
        // Leia või loo notification container
        let container = document.getElementById('notification-container');
        if (!container) {
            container = document.createElement('div');
            container.id = 'notification-container';
            container.style.cssText = 'position: fixed; top: 20px; right: 20px; z-index: 9999;';
            document.body.appendChild(container);
        }
        
        const notification = document.createElement('div');
        notification.className = `notification ${type}`;
        notification.style.cssText = `
            background: white; 
            border-radius: 12px; 
            padding: 16px; 
            margin-bottom: 12px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1); 
            border-left: 4px solid ${type === 'success' ? '#10b981' : type === 'error' ? '#ef4444' : '#3b82f6'};
            transform: translateX(100%); 
            transition: transform 0.3s ease;
            max-width: 400px;
        `;
        
        notification.innerHTML = `
            <div style="display: flex; align-items: center; gap: 12px;">
                <span style="font-size: 18px;">
                    ${type === 'success' ? '✅' : type === 'error' ? '❌' : '📢'}
                </span>
                <span style="flex: 1;">${message}</span>
                <button onclick="this.parentElement.parentElement.remove()" style="background: none; border: none; font-size: 18px; cursor: pointer; color: #6b7280;">×</button>
            </div>
        `;
        
        container.appendChild(notification);
        
        // Näita animatsiooniga
        setTimeout(() => {
            notification.style.transform = 'translateX(0)';
        }, 100);
        
        // Eemalda 5 sekundi pärast
        setTimeout(() => {
            notification.style.transform = 'translateX(100%)';
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.parentNode.removeChild(notification);
                }
            }, 300);
        }, 5000);
    }
}

// Ekspordi globaalsesse scope'i
window.CategoryManager = CategoryManager;

// Auto-initialize kui DOM on valmis
document.addEventListener('DOMContentLoaded', function() {
    // Ei initsialiseerime automaatselt - ainult kui kutsutakse
    console.log('📦 CategoryManager class loaded and ready');
});