/**
 * ================================================
 * ESTREKA KALENDRI KATEGOORIATE HALDUS - KASUTAJASÕBRALIK KUSTUTAMINE
 * ================================================
 * 
 * See fail sisaldab:
 * - Kategooriate CRUD operatsioone
 * - Kategooriate halduse modal
 * - Kategooriate filtreerimine
 * - PARANDATUD: Kasutajasõbralik kustutamise kinnitused
 * - PARANDATUD: Detailne sündmuste info kuvamine
 * 
 * ================================================
 */

// CategoryManager instance
let categoryManager = null;

// ==========================================
// KATEGOORIATE HALDUSE INITSIALISEERMINE
// ==========================================

function initializeCategoryManager() {
    debugLog('Kasutan sisseehitatud CategoryManager...');
    createAdvancedCategoryManager();
}

function createAdvancedCategoryManager() {
    categoryManager = {
        isInitialized: true,
        
        open: function() {
            debugLog('Avan kategooriahalduse modal');
            const modal = document.getElementById('categoryManagerModal');
            if (modal) {
                modal.style.display = 'flex';
                this.renderCategoryManager();
            }
        },
        
        renderCategoryManager: function() {
            const container = document.getElementById('category-manager-inner');
            if (!container) return;
            
            container.innerHTML = `
                <div style="padding: 20px;">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                        <h3 style="margin: 0;">Kategooriate haldus</h3>
                        <button class="btn btn-primary" onclick="categoryManager.showAddForm()">
                            Lisa kategooria
                        </button>
                    </div>
                    
                    <div id="categories-list">
                        ${this.renderCategoriesList()}
                    </div>
                    
                    <div id="category-form" style="display: none; margin-top: 20px; padding: 20px; background: #f9f9f9; border-radius: 8px;">
                        <h4 id="form-title">Lisa uus kategooria</h4>
                        <form onsubmit="categoryManager.saveCategory(event)">
                            <input type="hidden" id="edit-category-id">
                            
                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 500;">Kategooria nimi:</label>
                                <input type="text" id="category-name" class="form-control" required placeholder="nt. Treening, Võistlus">
                            </div>
                            
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
                                <div>
                                    <label style="display: block; margin-bottom: 5px; font-weight: 500;">Märgistus:</label>
                                    <select id="category-icon" class="form-control">
                                        <option value="📅">📅 Kalender</option>
                                        <option value="🏃">🏃 Treening</option>
                                        <option value="🏆">🏆 Võistlus</option>
                                        <option value="💼">💼 Koosolek</option>
                                        <option value="🏠">🏠 Isiklik</option>
                                        <option value="❤️">❤️ Tervis</option>
                                        <option value="📚">📚 Õppimine</option>
                                        <option value="🎉">🎉 Üritus</option>
                                        <option value="⭐">⭐ Oluline</option>
                                        <option value="🎯">🎯 Eesmärk</option>
                                    </select>
                                </div>
                                
                                <div>
                                    <label style="display: block; margin-bottom: 5px; font-weight: 500;">Värv:</label>
                                    <select id="category-color" class="form-control">
                                        <option value="#3B82F6" style="background: #3B82F6; color: white;">Sinine</option>
                                        <option value="#10B981" style="background: #10B981; color: white;">Roheline</option>
                                        <option value="#F59E0B" style="background: #F59E0B; color: white;">Kollane</option>
                                        <option value="#EF4444" style="background: #EF4444; color: white;">Punane</option>
                                        <option value="#8B5CF6" style="background: #8B5CF6; color: white;">Violetne</option>
                                        <option value="#EC4899" style="background: #EC4899; color: white;">Roosa</option>
                                        <option value="#06B6D4" style="background: #06B6D4; color: white;">Helesinine</option>
                                        <option value="#6B7280" style="background: #6B7280; color: white;">Hall</option>
                                    </select>
                                </div>
                            </div>
                            
                            <div style="display: flex; gap: 10px;">
                                <button type="submit" class="btn btn-primary">Salvesta</button>
                                <button type="button" class="btn btn-secondary" onclick="categoryManager.hideForm()">Tühista</button>
                            </div>
                        </form>
                    </div>
                </div>
            `;
        },
        
        renderCategoriesList: function() {
            if (categories.length === 0) {
                return '<p style="text-align: center; color: #666; padding: 40px;">Kategooriaid pole veel lisatud.</p>';
            }
            
            return categories.map(category => `
                <div style="display: flex; align-items: center; justify-content: space-between; padding: 15px; border: 1px solid #e0e0e0; border-radius: 8px; margin-bottom: 10px; background: white;">
                    <div style="display: flex; align-items: center; gap: 15px;">
                        <div style="width: 16px; height: 16px; background: ${category.color}; border-radius: 50%; border: 2px solid white; box-shadow: 0 2px 4px rgba(0,0,0,0.1);"></div>
                        <span style="font-size: 18px;">${category.icon || '📅'}</span>
                        <div>
                            <strong>${category.name}</strong>
                            ${category.is_system ? '<span style="background: #dcfce7; color: #166534; padding: 2px 8px; border-radius: 12px; font-size: 12px; margin-left: 10px;">Vaikimisi</span>' : '<span style="background: #e0e7ff; color: #3730a3; padding: 2px 8px; border-radius: 12px; font-size: 12px; margin-left: 10px;">Minu</span>'}
                            <br>
                            <small style="color: #666;">${category.event_count} sündmust</small>
                        </div>
                    </div>
                    
                    <div style="display: flex; gap: 10px;">
                        <button class="btn btn-secondary btn-sm" onclick="categoryManager.editCategory(${category.id})" title="Muuda">
                            Muuda
                        </button>
                        <button class="btn btn-danger btn-sm" onclick="categoryManager.confirmDeleteCategory(${category.id})" title="Kustuta">
                            Kustuta
                        </button>
                    </div>
                </div>
            `).join('');
        },
        
        showAddForm: function() {
            document.getElementById('form-title').textContent = 'Lisa uus kategooria';
            document.getElementById('edit-category-id').value = '';
            document.getElementById('category-name').value = '';
            document.getElementById('category-icon').value = '📅';
            document.getElementById('category-color').value = '#3B82F6';
            document.getElementById('category-form').style.display = 'block';
        },
        
        hideForm: function() {
            document.getElementById('category-form').style.display = 'none';
        },
        
        editCategory: function(categoryId) {
            const category = categories.find(c => c.id == categoryId);
            if (!category) return;
            
            document.getElementById('form-title').textContent = 'Muuda kategooriat';
            document.getElementById('edit-category-id').value = category.id;
            document.getElementById('category-name').value = category.name;
            document.getElementById('category-icon').value = category.icon || '📅';
            document.getElementById('category-color').value = category.color;
            document.getElementById('category-form').style.display = 'block';
        },
        
        confirmDeleteCategory: function(categoryId) {
            const category = categories.find(c => c.id == categoryId);
            if (!category) {
                debugLog('Kategooriat ei leitud ID-ga:', categoryId);
                showNotification('Kategooriat ei leitud', 'error');
                return;
            }
            
            debugLog('Alustan kategooria kustutamise protsessi:', category);
            
            // Saada esialgu DELETE päring et saada detailne info
            this.requestCategoryDeletion(categoryId);
        },
        
        /**
         * UUENDATUD: Saada DELETE päring et saada detailne info kategooriast ja sündmustest
         */
        requestCategoryDeletion: async function(categoryId) {
            debugLog('Pärin kategooria kustutamise infot:', categoryId);
            
            try {
                const response = await fetch(API_BASE_URL + 'categories-api.php', {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ id: categoryId })
                });
                
                const result = await response.json();
                debugLog('Kategooria kustutamise vastus:', result);
                
                if (result.success) {
                    // Kustutamine õnnestus kohe - tõenäoliselt polnud seotud sündmusi
                    this.handleSuccessfulDeletion(result);
                } else if (result.needs_confirmation) {
                    // Vajab kinnitust - näita detailset dialoogi
                    this.showDetailedDeleteConfirmation(result);
                } else {
                    // Tavaline viga
                    throw new Error(result.error || 'Kategooria kustutamine ebaõnnestus');
                }
                
            } catch (error) {
                console.error('Kategooria kustutamise päring ebaõnnestus:', error);
                showNotification('Viga: ' + error.message, 'error');
            }
        },
        
        /**
         * UUENDATUD: Näita detailset kustutamise kinnituse dialoogi koos sündmuste infoga
         */
        showDetailedDeleteConfirmation: function(confirmationData) {
            debugLog('Näitan detailset kustutamise dialoogi:', confirmationData);
            
            const { category, events, total_events, future_events, past_events, user_friendly_message } = confirmationData;
            
            // Loo detailne kinnitus modal
            const confirmModal = document.createElement('div');
            confirmModal.className = 'modal-overlay';
            confirmModal.style.display = 'flex';
            confirmModal.style.zIndex = '1100';
            
            // Gruppeeri sündmused staatuse järgi
            const futureEventsList = events.filter(e => e.event_status === 'future');
            const pastEventsList = events.filter(e => e.event_status === 'past');
            const currentEventsList = events.filter(e => e.event_status === 'current');
            
            let eventsListHtml = '';
            
            if (futureEventsList.length > 0) {
                eventsListHtml += `
                    <div class="events-section">
                        <h4 style="color: #dc2626; margin: 15px 0 10px 0;">
                            🔴 Tulevased sündmused (${futureEventsList.length})
                        </h4>
                        <div class="events-list">
                            ${futureEventsList.map(event => `
                                <div class="event-item future-event">
                                    <div class="event-title">${event.title}</div>
                                    <div class="event-time">${event.formatted_start}</div>
                                    ${event.location ? `<div class="event-location">📍 ${event.location}</div>` : ''}
                                </div>
                            `).join('')}
                        </div>
                    </div>
                `;
            }
            
            if (currentEventsList.length > 0) {
                eventsListHtml += `
                    <div class="events-section">
                        <h4 style="color: #f59e0b; margin: 15px 0 10px 0;">
                            🟡 Praegu toimuvad sündmused (${currentEventsList.length})
                        </h4>
                        <div class="events-list">
                            ${currentEventsList.map(event => `
                                <div class="event-item current-event">
                                    <div class="event-title">${event.title}</div>
                                    <div class="event-time">${event.formatted_start}</div>
                                    ${event.location ? `<div class="event-location">📍 ${event.location}</div>` : ''}
                                </div>
                            `).join('')}
                        </div>
                    </div>
                `;
            }
            
            if (pastEventsList.length > 0) {
                eventsListHtml += `
                    <div class="events-section">
                        <h4 style="color: #6b7280; margin: 15px 0 10px 0;">
                            ⚪ Möödunud sündmused (${pastEventsList.length})
                        </h4>
                        <div class="events-list" style="max-height: 200px; overflow-y: auto;">
                            ${pastEventsList.slice(0, 10).map(event => `
                                <div class="event-item past-event">
                                    <div class="event-title" style="color: #6b7280;">${event.title}</div>
                                    <div class="event-time" style="color: #9ca3af;">${event.formatted_start}</div>
                                    ${event.location ? `<div class="event-location" style="color: #9ca3af;">📍 ${event.location}</div>` : ''}
                                </div>
                            `).join('')}
                            ${pastEventsList.length > 10 ? `<div style="text-align: center; color: #6b7280; font-size: 12px; margin-top: 10px;">... ja veel ${pastEventsList.length - 10} sündmust</div>` : ''}
                        </div>
                    </div>
                `;
            }
            
            confirmModal.innerHTML = `
                <div class="modal-content" style="max-width: 600px; max-height: 90vh; overflow-y: auto;">
                    <div class="modal-header">
                        <h3 class="modal-title">Kustuta kategooria</h3>
                        <button class="modal-close" onclick="this.closest('.modal-overlay').remove()">×</button>
                    </div>
                    <div class="modal-body">
                        <div class="delete-confirmation-header">
                            <div style="display: flex; align-items: center; gap: 15px; padding: 15px; background: #f3f4f6; border-radius: 8px; margin-bottom: 20px;">
                                <div style="width: 24px; height: 24px; background: ${category.color}; border-radius: 50%;"></div>
                                <span style="font-size: 20px;">${category.icon || '📅'}</span>
                                <div>
                                    <strong style="font-size: 18px;">${category.name}</strong><br>
                                    <small style="color: #666;">${total_events} sündmust kokku</small>
                                </div>
                            </div>
                        </div>
                        
                        <div class="user-friendly-message">
                            <p style="background: ${future_events > 0 ? '#fef2f2' : '#f0f9ff'}; border: 1px solid ${future_events > 0 ? '#fecaca' : '#bfdbfe'}; padding: 15px; border-radius: 8px; margin: 15px 0; line-height: 1.5;">
                                ${user_friendly_message}
                            </p>
                        </div>
                        
                        ${eventsListHtml}
                        
                        <div class="confirmation-info" style="background: #f9fafb; border: 1px solid #e5e7eb; padding: 15px; border-radius: 8px; margin-top: 20px;">
                            <h4 style="margin: 0 0 10px 0; color: #374151;">ℹ️ Mida see tähendab?</h4>
                            <ul style="margin: 0; padding-left: 20px; line-height: 1.6;">
                                <li><strong>Sündmused jäävad alles</strong> - ühtegi sündmust ei kustutata</li>
                                <li><strong>Sündmused muutuvad kategooriata</strong> - neil ei ole enam kategooriat määratud</li>
                                <li><strong>Saad hiljem uue kategooria määrata</strong> - sündmusi saab alati redigeerida</li>
                            </ul>
                        </div>
                    </div>
                    
                    <div class="modal-footer">
                        <button class="btn btn-secondary" onclick="this.closest('.modal-overlay').remove()">
                            ❌ Tühista
                        </button>
                        <button class="btn btn-danger" onclick="categoryManager.executeConfirmedDelete(${category.id}); this.closest('.modal-overlay').remove();">
                            ✅ Jah, kustuta kategooria
                        </button>
                    </div>
                </div>
            `;
            
            // Lisa CSS stiilid modali jaoks
            if (!document.getElementById('category-delete-styles')) {
                const style = document.createElement('style');
                style.id = 'category-delete-styles';
                style.textContent = `
                    .events-section {
                        margin-bottom: 20px;
                    }
                    .events-list {
                        display: flex;
                        flex-direction: column;
                        gap: 8px;
                    }
                    .event-item {
                        padding: 12px;
                        border-radius: 8px;
                        border: 1px solid #e5e7eb;
                        background: white;
                    }
                    .event-item.future-event {
                        border-left: 4px solid #dc2626;
                        background: #fef2f2;
                    }
                    .event-item.current-event {
                        border-left: 4px solid #f59e0b;
                        background: #fffbeb;
                    }
                    .event-item.past-event {
                        border-left: 4px solid #9ca3af;
                        background: #f9fafb;
                    }
                    .event-title {
                        font-weight: 600;
                        margin-bottom: 4px;
                    }
                    .event-time {
                        font-size: 14px;
                        color: #6b7280;
                        margin-bottom: 2px;
                    }
                    .event-location {
                        font-size: 12px;
                        color: #9ca3af;
                    }
                `;
                document.head.appendChild(style);
            }
            
            document.body.appendChild(confirmModal);
        },
        
        /**
         * UUENDATUD: Täida kinnitatud kustutamine
         */
        executeConfirmedDelete: async function(categoryId) {
            debugLog('Täidan kinnitatud kategooria kustutamise:', categoryId);
            
            try {
                const response = await fetch(API_BASE_URL + 'categories-api.php', {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ 
                        id: categoryId,
                        confirmed: true 
                    })
                });
                
                const result = await response.json();
                debugLog('Kinnitatud kustutamise vastus:', result);
                
                if (result.success) {
                    this.handleSuccessfulDeletion(result);
                } else {
                    throw new Error(result.error || 'Kategooria kustutamine ebaõnnestus');
                }
                
            } catch (error) {
                console.error('Kinnitatud kategooria kustutamine ebaõnnestus:', error);
                showNotification('Viga: ' + error.message, 'error');
            }
        },
        
        /**
         * UUENDATUD: Käsitle edukat kustutamist
         */
        handleSuccessfulDeletion: async function(result) {
            debugLog('Kategooria edukalt kustutatud:', result);
            
            // Näita kasutajasõbralikku teadet
            const message = result.message || 'Kategooria edukalt kustutatud!';
            showNotification(message, 'success');
            
            // Uuenda UI-d
            await this.loadCategories();
            this.renderCategoryManager();
            updateCategoryDropdown();
            
            // Uuenda kalendrit
            if (typeof refreshCalendar === 'function') {
                await refreshCalendar();
            }
            
            debugLog('Kategooria kustutamine lõpetatud edukalt');
        },
        
        saveCategory: async function(e) {
            e.preventDefault();
            
            const categoryId = document.getElementById('edit-category-id').value;
            const isEdit = categoryId !== '';
            
            const categoryData = {
                name: document.getElementById('category-name').value,
                icon: document.getElementById('category-icon').value,
                color: document.getElementById('category-color').value,
                default_reminder_minutes: 60,
                reminder_enabled: 1
            };
            
            debugLog('Salvestan kategooriat:', { categoryData, isEdit });
            
            try {
                const url = API_BASE_URL + 'categories-api.php';
                const response = await fetch(url, {
                    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) {
                    showNotification(
                        isEdit ? 'Kategooria edukalt muudetud!' : 'Kategooria edukalt lisatud!', 
                        'success'
                    );
                    
                    await this.loadCategories();
                    this.renderCategoryManager();
                    this.hideForm();
                    updateCategoryDropdown();
                    
                } else {
                    throw new Error(result.error || 'Salvestamine ebaõnnestus');
                }
            } catch (error) {
                console.error('Kategooria salvestamise viga:', error);
                showNotification('Viga: ' + error.message, 'error');
            }
        },
        
        loadCategories: async function() {
            try {
                const response = await fetch(API_BASE_URL + 'categories-api.php?action=list');
                const result = await response.json();
                
                if (result.success) {
                    categories = result.data;
                    debugLog('Kategooriad uuendatud:', categories.length);
                    return true;
                } else {
                    throw new Error(result.error);
                }
            } catch (error) {
                console.error('Kategooriate laadimine ebaõnnestus:', error);
                return false;
            }
        }
    };
    
    debugLog('Täiustatud CategoryManager loodud kasutajasõbraliku kustutamisega');
}

// ==========================================
// KATEGOORIATE AVALIKUD FUNKTSIOONID
// ==========================================

function openCategoryManager() {
    if (!categoryManager || !categoryManager.isInitialized) {
        createAdvancedCategoryManager();
    }
    
    categoryManager.open();
    debugLog('Kategooriahaldus avatud');
}

function closeCategoryManager() {
    const modal = document.getElementById('categoryManagerModal');
    if (modal) {
        modal.style.display = 'none';
    }
    
    // Eemalda kõik kustutamise kinnituse modalid
    document.querySelectorAll('.modal-overlay').forEach(modal => {
        if (modal.style.zIndex === '1100') {
            modal.remove();
        }
    });
    
    setTimeout(async () => {
        try {
            const response = await fetch(API_BASE_URL + 'categories-api.php?action=list');
            const result = await response.json();
            
            if (result.success) {
                categories = result.data;
                updateCategoryDropdown();
                if (typeof refreshCalendar === 'function') {
                    await refreshCalendar();
                }
            }
        } catch (error) {
            console.error('Kategooriate uuendamine ebaõnnestus:', error);
        }
    }, 500);
    
    debugLog('Sulgen kategooriahalduse');
}

function updateCategoryDropdown() {
    const select = document.getElementById('event-category');
    if (!select) {
        console.warn('event-category dropdown not found');
        return;
    }
    
    const currentValue = select.value;
    select.innerHTML = '<option value="">Vali kategooria</option>';
    
    categories.forEach(category => {
        const option = document.createElement('option');
        option.value = category.id;
        option.textContent = `${category.icon || '📅'} ${category.name}`;
        select.appendChild(option);
    });
    
    select.value = currentValue;
    debugLog('Category dropdown updated successfully');
}

// ==========================================
// EVENT LISTENERS
// ==========================================

document.addEventListener('DOMContentLoaded', function() {
    // Initsialiseerime kategooriahaldust
    initializeCategoryManager();
    
    // Modal sündmused kategooriahalduse jaoks
    const categoryModal = document.getElementById('categoryManagerModal');
    if (categoryModal) {
        categoryModal.addEventListener('click', function(e) {
            if (e.target === this) closeCategoryManager();
        });
    }
    
    // ESC key handling
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            // Sulge kustutamise kinnituse modalid
            document.querySelectorAll('.modal-overlay').forEach(modal => {
                if (modal.style.zIndex === '1100') {
                    modal.remove();
                }
            });
            
            // Sulge kategooriahaldus kui pole avatud kustutamise dialoogi
            const deleteModals = document.querySelectorAll('.modal-overlay[style*="z-index: 1100"]');
            if (deleteModals.length === 0) {
                closeCategoryManager();
            }
        }
    });
});

// Ekspordi funktsioonid globaalselt
window.openCategoryManager = openCategoryManager;
window.closeCategoryManager = closeCategoryManager;
window.updateCategoryDropdown = updateCategoryDropdown;

debugLog('Kategooriate halduse süsteem laaditud kasutajasõbraliku kustutamisega!');