/**
 * ================================================
 * ESTREKA KALENDRI PÕHIFUNKTSIOONID - PARANDATUD WIZARD SÜSTEEMIGA
 * ================================================
 * 
 * Funktsioonid:
 * - Kalendri renderdamine
 * - Sündmuste CRUD
 * - Samm-sammuline wizard
 * - PARANDATUD: Meeldetuletuste täpne kellaaeg
 * - PARANDATUD: Vaadete süsteem (kuu, nädal, päev)
 * - PARANDATUD: Kuupäeval klõpsamise UX
 * - Integratsioon olemasoleva süsteemiga
 * 
 * ================================================
 */

// ==========================================
// GLOBAALSED MUUTUJAD JA KONFIGURATSIOON
// ==========================================

const API_BASE_URL = window.calendarConfig ? window.calendarConfig.apiBaseUrl : '/ratsaklubi.estreka/calendar/api/';
const DEBUG_MODE = window.calendarConfig ? window.calendarConfig.debugMode : false;

let currentDate = new Date();
let currentEvents = [];
let categories = window.calendarData ? window.calendarData.categories : [];

// Wizard state
let currentWizardStep = 1;
let wizardData = {};

// View state - UUENDATUD!
let currentView = 'month';

const estMonths = [
    'Jaanuar', 'Veebruar', 'Märts', 'Aprill', 'Mai', 'Juuni',
    'Juuli', 'August', 'September', 'Oktoober', 'November', 'Detsember'
];
const estDays = ['E', 'T', 'K', 'N', 'R', 'L', 'P'];

function debugLog(message, data = null) {
    if (DEBUG_MODE) {
        console.log('DEBUG:', message, data || '');
    }
}

// ==========================================
// INITSIALISEERIME KALENDRI
// ==========================================
document.addEventListener('DOMContentLoaded', async function() {
    debugLog('Kalender laadib...', {
        apiUrl: API_BASE_URL,
        categoriesCount: categories.length,
        debugMode: DEBUG_MODE
    });
    
    try {
        await loadEventsFromAPI();
        renderCalendarByView();
        updateTodayEvents();
        initializeWizard();
        
        debugLog('Kalender edukalt laaditud!', {
            eventsCount: currentEvents.length
        });
        
    } catch (error) {
        console.error('Kalendri laadimisel tekkis viga:', error);
        showNotification('Kalendri laadimisel tekkis viga: ' + error.message, 'error');
    }
});

// ==========================================
// API FUNKTSIOONID
// ==========================================

async function loadEventsFromAPI() {
    try {
        debugLog('Laadin sündmusi API-st...', API_BASE_URL + 'events.php?action=list');
        
        const response = await fetch(API_BASE_URL + 'events.php?action=list');
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const result = await response.json();
        debugLog('API vastus:', result);
        
        if (result.success) {
            currentEvents = result.data || [];
            debugLog('Sündmused laaditud:', currentEvents.length);
        } else {
            throw new Error(result.error || 'API tagastas vea');
        }
        
    } catch (error) {
        console.error('Sündmuste laadimisel tekkis viga:', error);
        
        const phpEvents = window.calendarData ? window.calendarData.events : [];
        currentEvents = phpEvents;
        debugLog('Kasutan PHP fallback andmeid:', currentEvents.length);
        
        if (currentEvents.length === 0) {
            throw new Error('Ei suutnud sündmusi laadida');
        }
    }
}

async function refreshCalendar() {
    try {
        debugLog('Uuendan kalendrit...');
        await loadEventsFromAPI();
        renderCalendarByView();
        updateTodayEvents();
        
        const totalEventsEl = document.getElementById('total-events');
        if (totalEventsEl) {
            totalEventsEl.textContent = currentEvents.length;
        }
        
        debugLog('Kalender uuendatud');
    } catch (error) {
        console.error('Kalendri uuendamisel tekkis viga:', error);
        showNotification('Kalendri uuendamisel tekkis viga', 'error');
    }
}

// ==========================================
// TURVALINE HELPER FUNKTSIOON
// ==========================================

function safeGetElement(id) {
    const element = document.getElementById(id);
    if (!element) {
        console.warn(`Element not found: ${id}`);
    }
    return element;
}

// ==========================================
// KALENDRI VAADETE SÜSTEEM - PARANDATUD!
// ==========================================

function changeView(view) {
    debugLog('Muudan vaadet:', view);
    
    // Eemaldame aktiivsuse kõigilt nuppudelt
    document.querySelectorAll('.header-actions .btn-outline').forEach(btn => {
        btn.classList.remove('active');
    });
    
    // Leiame klõpsatud nupu ja märgime aktiivseks
    const clickedButton = event?.target || document.querySelector(`[onclick*="${view}"]`);
    if (clickedButton) {
        clickedButton.classList.add('active');
    }
    
    // Seame uue vaate
    currentView = view;
    
    // Renderdame kalendri uuesti vastavalt vaatele
    renderCalendarByView();
}

function renderCalendarByView() {
    const grid = safeGetElement('calendar-grid');
    const title = safeGetElement('calendar-title');
    
    if (!grid || !title) {
        console.error('Kalendri elemendid ei leitud');
        return;
    }
    
    debugLog('Renderin kalendrit vaates:', currentView);
    
    switch (currentView) {
        case 'month':
            renderMonthView();
            break;
        case 'week':
            renderWeekView();
            break;
        case 'day':
            renderDayView();
            break;
        default:
            renderMonthView();
    }
}

// ==========================================
// KUU VAADE (olemasolev loogika)
// ==========================================

function renderMonthView() {
    const grid = safeGetElement('calendar-grid');
    const title = safeGetElement('calendar-title');
    
    title.textContent = `${estMonths[currentDate.getMonth()]} ${currentDate.getFullYear()}`;
    grid.innerHTML = '';
    grid.className = 'calendar-grid'; // Reset klassid
    
    // Nädalapäevade päised
    estDays.forEach(day => {
        const cell = document.createElement('div');
        cell.className = 'calendar-header-cell';
        cell.textContent = day;
        grid.appendChild(cell);
    });
    
    // Päevade renderdamine (olemasolev loogika)
    const firstDay = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1);
    const lastDay = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0);
    const prevLastDay = new Date(currentDate.getFullYear(), currentDate.getMonth(), 0);
    const startWeekday = (firstDay.getDay() + 6) % 7;
    
    // Eelmise kuu päevad
    for (let i = startWeekday - 1; i >= 0; i--) {
        const dayNum = prevLastDay.getDate() - i;
        const cell = createDayCell(dayNum, true, prevLastDay.getMonth(), prevLastDay.getFullYear());
        grid.appendChild(cell);
    }
    
    // Praeguse kuu päevad
    for (let day = 1; day <= lastDay.getDate(); day++) {
        const cell = createDayCell(day, false, currentDate.getMonth(), currentDate.getFullYear());
        grid.appendChild(cell);
    }
    
    // Järgmise kuu päevad
    const cellsAdded = startWeekday + lastDay.getDate();
    const remainingCells = 42 - cellsAdded;
    for (let day = 1; day <= remainingCells; day++) {
        const nextMonth = currentDate.getMonth() + 1;
        const nextYear = nextMonth > 11 ? currentDate.getFullYear() + 1 : currentDate.getFullYear();
        const cell = createDayCell(day, true, nextMonth % 12, nextYear);
        grid.appendChild(cell);
    }
}

// ==========================================
// NÄDALA VAADE
// ==========================================

function renderWeekView() {
    const grid = safeGetElement('calendar-grid');
    const title = safeGetElement('calendar-title');
    
    // Leia nädala algus (esmaspäev)
    const weekStart = new Date(currentDate);
    const dayOfWeek = (currentDate.getDay() + 6) % 7; // Teisenda et esmaspäev = 0
    weekStart.setDate(currentDate.getDate() - dayOfWeek);
    
    const weekEnd = new Date(weekStart);
    weekEnd.setDate(weekStart.getDate() + 6);
    
    title.textContent = `${weekStart.getDate()}.${weekStart.getMonth() + 1} - ${weekEnd.getDate()}.${weekEnd.getMonth() + 1}.${weekEnd.getFullYear()}`;
    
    grid.innerHTML = '';
    grid.className = 'calendar-grid week-view'; // Lisa spetsiaalse klassi
    
    // Nädalapäevade päised
    estDays.forEach(day => {
        const cell = document.createElement('div');
        cell.className = 'calendar-header-cell';
        cell.textContent = day;
        grid.appendChild(cell);
    });
    
    // 7 päeva
    for (let i = 0; i < 7; i++) {
        const day = new Date(weekStart);
        day.setDate(weekStart.getDate() + i);
        
        const cell = createDayCell(
            day.getDate(), 
            false, 
            day.getMonth(), 
            day.getFullYear()
        );
        
        // Täna esiletõstmine
        const today = new Date();
        if (day.toDateString() === today.toDateString()) {
            cell.classList.add('today');
        }
        
        grid.appendChild(cell);
    }
}

// ==========================================
// PÄEVA VAADE
// ==========================================

function renderDayView() {
    const grid = safeGetElement('calendar-grid');
    const title = safeGetElement('calendar-title');
    
    const day = currentDate.getDate();
    const month = currentDate.getMonth();
    const year = currentDate.getFullYear();
    
    title.textContent = `${day}. ${estMonths[month]} ${year}`;
    
    grid.innerHTML = '';
    grid.className = 'calendar-grid day-view'; // Lisa spetsiaalse klassi
    
    // Päeva sündmused
    const dayEvents = filterEventsByDate(year, month, day);
    
    if (dayEvents.length === 0) {
        grid.innerHTML = `
            <div class="day-view-empty">
                <div class="empty-icon">📅</div>
                <h3>Sel päeval sündmusi ei ole</h3>
                <button class="btn btn-primary" onclick="openEventWizard(currentDate)">
                    + Lisa sündmus
                </button>
            </div>
        `;
    } else {
        grid.innerHTML = `
            <div class="day-view-events">
                <div class="day-view-header">
                    <h3>${dayEvents.length} sündmust</h3>
                    <button class="btn btn-primary btn-sm" onclick="openEventWizard(currentDate)">
                        + Lisa uus
                    </button>
                </div>
                <div class="day-events-list">
                    ${dayEvents.map(event => `
                        <div class="day-event-item" onclick="openEventModal(${JSON.stringify(event).replace(/"/g, '&quot;')})">
                            <div class="event-time">${formatEventTime(event.start_datetime)}</div>
                            <div class="event-details">
                                <div class="event-title" style="border-left: 4px solid ${event.category_color || '#4285F4'}">
                                    ${event.title}
                                </div>
                                ${event.description ? `<div class="event-description">${event.description}</div>` : ''}
                                ${event.location ? `<div class="event-location">📍 ${event.location}</div>` : ''}
                            </div>
                        </div>
                    `).join('')}
                </div>
            </div>
        `;
    }
}

// ==========================================
// NAVIGATION - UUENDATUD!
// ==========================================

function previousMonth() {
    if (currentView === 'month') {
        currentDate.setMonth(currentDate.getMonth() - 1);
    } else if (currentView === 'week') {
        currentDate.setDate(currentDate.getDate() - 7);
    } else if (currentView === 'day') {
        currentDate.setDate(currentDate.getDate() - 1);
    }
    renderCalendarByView();
    updateTodayEvents();
    debugLog('Liikus eelmisele:', currentView);
}

function nextMonth() {
    if (currentView === 'month') {
        currentDate.setMonth(currentDate.getMonth() + 1);
    } else if (currentView === 'week') {
        currentDate.setDate(currentDate.getDate() + 7);
    } else if (currentView === 'day') {
        currentDate.setDate(currentDate.getDate() + 1);
    }
    renderCalendarByView();
    updateTodayEvents();
    debugLog('Liikus järgmisele:', currentView);
}

function goToToday() {
    currentDate = new Date();
    renderCalendarByView();
    updateTodayEvents();
    debugLog('Liikus tänasele päevale');
}

// Asenda olemasolev renderCalendar funktsioon
function renderCalendar() {
    renderCalendarByView();
}

// ==========================================
// KALENDRI RENDERDAMINE (helper funktsioonid)
// ==========================================

function createDayCell(dayNum, isOtherMonth, month, year) {
    const cell = document.createElement('div');
    cell.className = 'calendar-day';
    
    if (isOtherMonth) {
        cell.classList.add('other-month');
    }
    
    const today = new Date();
    if (!isOtherMonth && 
        dayNum === today.getDate() && 
        month === today.getMonth() && 
        year === today.getFullYear()) {
        cell.classList.add('today');
    }
    
    const dayNumber = document.createElement('div');
    dayNumber.className = 'day-number';
    dayNumber.textContent = dayNum;
    cell.appendChild(dayNumber);
    
    const eventsContainer = document.createElement('div');
    eventsContainer.className = 'day-events';
    
    const dayEvents = filterEventsByDate(year, month, dayNum);
    
    dayEvents.slice(0, 3).forEach(event => {
        const eventEl = document.createElement('div');
        eventEl.className = 'day-event';
        eventEl.style.backgroundColor = event.category_color || '#4285F4';
        eventEl.textContent = event.title;
        eventEl.title = `${event.title}\n${formatEventTime(event.start_datetime)}`;
        eventEl.onclick = (e) => {
            e.stopPropagation();
            openEventModal(event);
        };
        eventsContainer.appendChild(eventEl);
    });
    
    if (dayEvents.length > 3) {
        const moreEl = document.createElement('div');
        moreEl.className = 'day-event';
        moreEl.style.backgroundColor = '#666';
        moreEl.textContent = `+${dayEvents.length - 3} veel`;
        moreEl.onclick = (e) => {
            e.stopPropagation();
            showDayEvents(year, month, dayNum, dayEvents);
        };
        eventsContainer.appendChild(moreEl);
    }
    
    cell.appendChild(eventsContainer);
    
    // UUENDATUD: Parandatud click handling
    cell.onclick = (e) => {
        // Kontrolli, et ei klõpsata sündmuse peal
        if (e.target.classList.contains('day-event')) {
            return;
        }
        
        const clickDate = new Date(year, month, dayNum);
        
        // Lisa visuaalne feedback
        cell.style.transform = 'scale(0.98)';
        setTimeout(() => {
            cell.style.transform = '';
        }, 150);
        
        // Ava wizard valitud kuupäevaga
        openEventWizard(clickDate);
    };
    
    // UUENDATUD: Lisa hover efektid
    cell.addEventListener('mouseenter', () => {
        if (!cell.classList.contains('hover-disabled')) {
            cell.style.transform = 'translateY(-2px)';
        }
    });
    
    cell.addEventListener('mouseleave', () => {
        if (!cell.classList.contains('hover-disabled')) {
            cell.style.transform = '';
        }
    });
    
    // Lisa accessibility
    cell.setAttribute('role', 'button');
    cell.setAttribute('tabindex', '0');
    cell.setAttribute('aria-label', `Lisa sündmus ${dayNum}. ${estMonths[month]} ${year}`);
    
    // Klaviatuuri tugi
    cell.addEventListener('keydown', (e) => {
        if (e.key === 'Enter' || e.key === ' ') {
            e.preventDefault();
            const clickDate = new Date(year, month, dayNum);
            openEventWizard(clickDate);
        }
    });
    
    return cell;
}

function filterEventsByDate(year, month, day) {
    return currentEvents.filter(event => {
        if (!event.start_datetime) return false;
        
        const eventDate = new Date(event.start_datetime);
        
        if (isNaN(eventDate.getTime())) {
            console.warn('Vigane kuupäev sündmusel:', event);
            return false;
        }
        
        return eventDate.getFullYear() === year &&
               eventDate.getMonth() === month &&
               eventDate.getDate() === day;
    });
}

function formatEventTime(datetime) {
    if (!datetime) return '';
    const date = new Date(datetime);
    return date.toLocaleTimeString('et-EE', { hour: '2-digit', minute: '2-digit' });
}

function showDayEvents(year, month, day, events) {
    const dateStr = `${day}.${month + 1}.${year}`;
    let content = `<h3>Sündmused ${dateStr}</h3>`;
    
    events.forEach(event => {
        content += `
            <div style="padding: 8px; margin: 4px 0; border-left: 3px solid ${event.category_color}; background: #f9f9f9; cursor: pointer;" 
                 onclick="openEventModal(${JSON.stringify(event).replace(/"/g, '&quot;')})">
                <strong>${event.title}</strong><br>
                <small>${formatEventTime(event.start_datetime)}</small>
            </div>
        `;
    });
    
    const modal = document.createElement('div');
    modal.className = 'modal-overlay';
    modal.style.display = 'flex';
    modal.innerHTML = `
        <div class="modal-content" style="max-width: 500px;">
            <div class="modal-header">
                <h3 class="modal-title">Päeva sündmused</h3>
                <button class="modal-close" onclick="this.closest('.modal-overlay').remove()">×</button>
            </div>
            <div class="modal-body">
                ${content}
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" onclick="this.closest('.modal-overlay').remove()">Sulge</button>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
}

// ==========================================
// TÄNA SÜNDMUSED
// ==========================================

function updateTodayEvents() {
    const today = new Date();
    const todayEvents = filterEventsByDate(today.getFullYear(), today.getMonth(), today.getDate());
    
    const container = document.getElementById('today-events');
    if (!container) return;
    
    if (todayEvents.length === 0) {
        container.innerHTML = '<p style="color: var(--gray-600); font-size: var(--font-size-sm);">Täna sündmusi ei ole</p>';
    } else {
        container.innerHTML = todayEvents.map(event => 
            `<div style="padding: 4px 0; border-left: 3px solid ${event.category_color}; padding-left: 8px; margin: 4px 0; cursor: pointer;" onclick="openEventModal(${JSON.stringify(event).replace(/"/g, '&quot;')})">
                <strong>${event.title}</strong><br>
                <small>${formatEventTime(event.start_datetime)}</small>
            </div>`
        ).join('');
    }
    
    debugLog('Täna sündmused uuendatud:', todayEvents.length);
}

// ==========================================
// EESTI KUUPÄEVA FORMATEERIMISE FUNKTSIOON - UUS!
// ==========================================

function formatEstonianDate(date) {
    const estonianMonths = [
        'jaanuar', 'veebruar', 'märts', 'aprill', 'mai', 'juuni',
        'juuli', 'august', 'september', 'oktoober', 'november', 'detsember'
    ];
    
    const day = date.getDate();
    const month = estonianMonths[date.getMonth()];
    const year = date.getFullYear();
    
    const today = new Date();
    const tomorrow = new Date(today);
    tomorrow.setDate(today.getDate() + 1);
    
    const yesterday = new Date(today);
    yesterday.setDate(today.getDate() - 1);
    
    // Kontrolli erinevaid kuupäevi
    if (date.toDateString() === today.toDateString()) {
        return 'täna';
    } else if (date.toDateString() === tomorrow.toDateString()) {
        return 'homme';
    } else if (date.toDateString() === yesterday.toDateString()) {
        return 'eile';
    } else {
        // Kontrolli kas sama nädal
        const startOfWeek = new Date(today);
        startOfWeek.setDate(today.getDate() - today.getDay() + 1); // Esmaspäev
        const endOfWeek = new Date(startOfWeek);
        endOfWeek.setDate(startOfWeek.getDate() + 6); // Pühapäev
        
        if (date >= startOfWeek && date <= endOfWeek) {
            const weekdays = ['pühapäev', 'esmaspäev', 'teisipäev', 'kolmapäev', 'neljapäev', 'reede', 'laupäev'];
            return weekdays[date.getDay()];
        } else {
            return `${day}. ${month} ${year}`;
        }
    }
}

// ==========================================
// EELVALITUD KUUPÄEVA INFO FUNKTSIOON - UUS!
// ==========================================

function addPreselectedDateInfo() {
    const step2Content = safeGetElement('wizard-step-2')?.querySelector('.wizard-step-content');
    
    if (step2Content && wizardData.selectedDate) {
        // Eemalda vana info kui on
        const existingInfo = step2Content.querySelector('.preselected-date-info');
        if (existingInfo) {
            existingInfo.remove();
        }
        
        // Lisa uus info
        const dateInfo = document.createElement('div');
        dateInfo.className = 'preselected-date-info';
        dateInfo.innerHTML = `
            <div style="
                background: linear-gradient(135deg, var(--primary-light), #bfdbfe);
                border: 1px solid var(--primary-color);
                border-radius: var(--radius-lg);
                padding: var(--spacing-3) var(--spacing-4);
                margin-bottom: var(--spacing-4);
                display: flex;
                align-items: center;
                gap: var(--spacing-3);
                animation: slideInFromTop 0.4s ease-out;
            ">
                <span style="font-size: 20px;">📅</span>
                <div>
                    <strong style="color: var(--primary-color);">Valitud kuupäev:</strong>
                    <span style="color: var(--gray-700); margin-left: var(--spacing-2);">
                        ${formatEstonianDate(wizardData.selectedDate)}
                    </span>
                    <br>
                    <small style="color: var(--gray-600);">
                        Algus- ja lõpuaeg on eeltäidetud sellele kuupäevale
                    </small>
                </div>
            </div>
        `;
        
        // Lisa info päise järele
        const heading = step2Content.querySelector('h4');
        if (heading) {
            heading.parentNode.insertBefore(dateInfo, heading.nextSibling);
        }
    }
}

// ==========================================
// WIZARD SÜSTEEM - PARANDATUD!
// ==========================================

function initializeWizard() {
    debugLog('Initsialiseerin wizard süsteemi...');
    
    // Korduvuse checkbox
    const recurringCheckbox = safeGetElement('reminder-recurring');
    if (recurringCheckbox) {
        recurringCheckbox.addEventListener('change', function() {
            const settings = safeGetElement('recurring-settings');
            if (settings) {
                settings.style.display = this.checked ? 'block' : 'none';
            }
        });
    }
    
    // Wizard modal ESC key
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            const wizardModal = safeGetElement('eventWizardModal');
            if (wizardModal && wizardModal.style.display === 'flex') {
                closeEventWizard();
            }
            
            const eventModal = safeGetElement('eventModal');
            if (eventModal && eventModal.style.display === 'flex') {
                closeEventModal();
            }
        }
    });
    
    // Wizard modal overlay click
    const wizardModal = safeGetElement('eventWizardModal');
    if (wizardModal) {
        wizardModal.addEventListener('click', function(e) {
            if (e.target === this) {
                closeEventWizard();
            }
        });
    }
    
    debugLog('Wizard süsteem valmis');
}

function openEventWizard(date = null) {
    debugLog('Avan event wizard...', { date: date });
    
    const modal = safeGetElement('eventWizardModal');
    if (!modal) {
        console.error('Event wizard modal ei leitud');
        return;
    }
    
    // Reset wizard
    currentWizardStep = 1;
    wizardData = {};
    
    // Reset vorm
    const form = safeGetElement('event-wizard-form');
    if (form) form.reset();
    
    // UUENDATUD: Muuda modal pealkiri vastavalt sellele, kas kuupäev on valitud
    const modalTitle = modal.querySelector('.modal-title');
    if (modalTitle) {
        if (date) {
            const estonianDate = formatEstonianDate(date);
            modalTitle.textContent = `Lisa sündmus ${estonianDate}`;
            modalTitle.style.color = 'var(--primary-color)';
            
            // Lisa väike ikoon märgistamaks, et kuupäev on valitud
            const dateIcon = document.createElement('span');
            dateIcon.innerHTML = ' 📅';
            dateIcon.style.fontSize = '18px';
            modalTitle.appendChild(dateIcon);
        } else {
            modalTitle.textContent = 'Lisa uus sündmus';
            modalTitle.style.color = '';
        }
    }
    
    // Sea vaikimisi kuupäev
    if (date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const now = new Date();
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        
        const startField = safeGetElement('wizard-start');
        if (startField) {
            startField.value = `${year}-${month}-${day}T${hours}:${minutes}`;
            // UUENDATUD: Lisa visuaalne märge, et kuupäev on eelvalitud
            startField.style.borderColor = 'var(--primary-color)';
            startField.style.background = 'linear-gradient(135deg, var(--primary-light), #bfdbfe)';
            startField.style.boxShadow = '0 0 0 3px rgba(59, 130, 246, 0.1)';
            startField.classList.add('preselected');
        }
        
        const endField = safeGetElement('wizard-end');
        if (endField) {
            const endDate = new Date(date);
            endDate.setHours(now.getHours() + 1);
            const endHours = String(endDate.getHours()).padStart(2, '0');
            endField.value = `${year}-${month}-${day}T${endHours}:${minutes}`;
            // Lisa sama visuaalne märge
            endField.style.borderColor = 'var(--primary-color)';
            endField.style.background = 'linear-gradient(135deg, var(--primary-light), #bfdbfe)';
            endField.style.boxShadow = '0 0 0 3px rgba(59, 130, 246, 0.1)';
            endField.classList.add('preselected');
        }
        
        // Salvesta valitud kuupäev wizard andmetesse
        wizardData.selectedDate = date;
        wizardData.isDatePreselected = true;
    }
    
    // Näita esimest sammu
    showWizardStep(1);
    
    // Ava modal
    modal.style.display = 'flex';
    
    // Focus esimesele väljale
    const titleInput = safeGetElement('wizard-title');
    if (titleInput) titleInput.focus();
    
    debugLog('Event wizard avatud');
}

function closeEventWizard() {
    const modal = safeGetElement('eventWizardModal');
    if (modal) {
        modal.style.display = 'none';
    }
    
    // Reset wizard state
    currentWizardStep = 1;
    wizardData = {};
    
    // UUENDATUD: Reset modal tiitel ja stiilid
    const modalTitle = modal?.querySelector('.modal-title');
    if (modalTitle) {
        modalTitle.textContent = 'Lisa uus sündmus';
        modalTitle.style.color = '';
        // Eemalda kuupäeva ikoon
        const dateIcon = modalTitle.querySelector('span');
        if (dateIcon) {
            dateIcon.remove();
        }
    }
    
    // Reset väljades olevad erilised stiilid
    const startField = safeGetElement('wizard-start');
    const endField = safeGetElement('wizard-end');
    
    if (startField) {
        startField.style.borderColor = '';
        startField.style.background = '';
        startField.style.boxShadow = '';
        startField.classList.remove('preselected');
    }
    
    if (endField) {
        endField.style.borderColor = '';
        endField.style.background = '';
        endField.style.boxShadow = '';
        endField.classList.remove('preselected');
    }
    
    // Eemalda eelvalitud kuupäeva info
    const preselectedInfo = document.querySelector('.preselected-date-info');
    if (preselectedInfo) {
        preselectedInfo.remove();
    }
    
    // Reset wizard sammude tekst tagasi
    resetWizardTexts();
    
    debugLog('Event wizard suletud');
}

function resetWizardTexts() {
    // Reset step 2 nupud
    const step2Actions = safeGetElement('wizard-step-2')?.querySelector('.wizard-actions');
    if (step2Actions) {
        const skipBtn = step2Actions.querySelector('button:nth-child(2)');
        const nextBtn = step2Actions.querySelector('button:nth-child(3)');
        
        if (skipBtn) {
            skipBtn.textContent = 'Lõpeta ilma meeldetuletuseta';
            skipBtn.onclick = () => wizardSkipReminder();
        }
        
        if (nextBtn) {
            nextBtn.textContent = 'Lisa meeldetuletus';
        }
    }
    
    // UUENDATUD: Peida step 1 kustutamise nupp
    const deleteBtn1 = safeGetElement('wizard-delete-btn-step1');
    if (deleteBtn1) {
        deleteBtn1.style.display = 'none';
    }
    
    // Reset step 3 nupp
    const step3Actions = safeGetElement('wizard-step-3')?.querySelector('.wizard-actions');
    if (step3Actions) {
        const saveBtn = step3Actions.querySelector('button[type="submit"]');
        const deleteBtn3 = safeGetElement('wizard-delete-btn');
        
        if (saveBtn) {
            saveBtn.textContent = 'Salvesta sündmus';
        }
        
        if (deleteBtn3) {
            deleteBtn3.style.display = 'none';
        }
    }
}

function showWizardStep(stepNumber) {
    debugLog('Näitan wizard sammu:', stepNumber);
    
    // Peida kõik sammud
    for (let i = 1; i <= 3; i++) {
        const step = safeGetElement(`wizard-step-${i}`);
        const progress = safeGetElement(`progress-step-${i}`);
        
        if (step) {
            step.classList.remove('active');
        }
        
        if (progress) {
            progress.classList.remove('active');
        }
    }
    
    // Näita praegust sammu
    const currentStep = safeGetElement(`wizard-step-${stepNumber}`);
    const currentProgress = safeGetElement(`progress-step-${stepNumber}`);
    
    if (currentStep) {
        currentStep.classList.add('active');
    }
    
    if (currentProgress) {
        currentProgress.classList.add('active');
    }
    
    // UUENDATUD: Kui jõuame sammu 2 ja kuupäev on eelvalitud, lisa selgitus
    if (stepNumber === 2 && wizardData.isDatePreselected) {
        addPreselectedDateInfo();
    }
    
    currentWizardStep = stepNumber;
}

function wizardNextStep() {
    debugLog('Wizard järgmine samm:', currentWizardStep);
    
    // Valideeri praegune samm
    if (!validateWizardStep(currentWizardStep)) {
        return;
    }
    
    // Salvesta praeguse sammu andmed
    saveWizardStepData(currentWizardStep);
    
    if (currentWizardStep < 3) {
        showWizardStep(currentWizardStep + 1);
        
        // Kui liigume 3. sammu, valmista ette meeldetuletuse valikud
        if (currentWizardStep === 3) {
            prepareReminderStep();
        }
    }
}

function wizardPrevStep() {
    debugLog('Wizard eelmine samm:', currentWizardStep);
    
    if (currentWizardStep > 1) {
        showWizardStep(currentWizardStep - 1);
    }
}

function wizardSkipReminder() {
    debugLog('Jätan meeldetuletuse vahele');
    
    // Salvesta andmed ilma meeldetuletuseta
    saveWizardStepData(2);
    wizardData.skipReminder = true;
    
    // Salvesta sündmus
    saveEventFromWizard();
}

function validateWizardStep(stepNumber) {
    if (stepNumber === 1) {
        const title = safeGetElement('wizard-title');
        if (!title || !title.value.trim()) {
            showNotification('Palun sisesta sündmuse nimi', 'warning');
            if (title) title.focus();
            return false;
        }
    }
    
    if (stepNumber === 2) {
        const start = safeGetElement('wizard-start');
        if (!start || !start.value) {
            showNotification('Palun vali algusaeg', 'warning');
            if (start) start.focus();
            return false;
        }
    }
    
    return true;
}

function saveWizardStepData(stepNumber) {
    debugLog('Salvestan wizard sammu andmed:', stepNumber);
    
    if (stepNumber === 1) {
        wizardData.title = safeGetElement('wizard-title')?.value || '';
        wizardData.description = safeGetElement('wizard-description')?.value || '';
        wizardData.location = safeGetElement('wizard-location')?.value || '';
        wizardData.category = safeGetElement('wizard-category')?.value || '';
    }
    
    if (stepNumber === 2) {
        wizardData.start = safeGetElement('wizard-start')?.value || '';
        wizardData.end = safeGetElement('wizard-end')?.value || '';
        wizardData.allDay = safeGetElement('wizard-all-day')?.checked || false;
    }
    
    if (stepNumber === 3) {
        const selectedOption = document.querySelector('input[name="reminder_option"]:checked');
        if (selectedOption) {
            wizardData.reminderOption = selectedOption.value;
            
            // PARANDATUD: Täpse kellaaja salvestamine
            if (selectedOption.value === 'custom') {
                const exactTimeField = safeGetElement('wizard-reminder-datetime');
                if (exactTimeField && exactTimeField.value) {
                    wizardData.reminderDatetime = exactTimeField.value;
                    debugLog('Salvestan custom reminder time:', wizardData.reminderDatetime);
                } else {
                    debugLog('HOIATUS: Custom valik, aga datetime field tühi!');
                }
            } else {
                // Eemalda eelmine custom aeg kui valitud on teine variant
                delete wizardData.reminderDatetime;
            }
            
            wizardData.reminderMessage = safeGetElement('wizard-reminder-message')?.value || '';
        }
    }
    
    debugLog('Wizard andmed salvestatud:', wizardData);
}

function prepareReminderStep() {
    debugLog('Valmistan ette meeldetuletuse sammu');
    
    // Auto-genereeri meeldetuletuse tekst
    const messageField = safeGetElement('wizard-reminder-message');
    if (messageField && wizardData.title) {
        const defaultMessage = `Meeldetuletus: ${wizardData.title}`;
        messageField.placeholder = defaultMessage;
    }
    
    // Sea vaikimisi valik
    const defaultOption = safeGetElement('reminder-60');
    if (defaultOption) {
        defaultOption.checked = true;
        selectReminderOption('60');
    }
}

function selectReminderOption(option) {
    debugLog('Valisin meeldetuletuse valiku:', option);
    
    // Peida kõik lisaväljad
    const customTimeField = safeGetElement('custom-reminder-time');
    const reminderMessageSection = safeGetElement('reminder-message-section');
    
    if (customTimeField) {
        customTimeField.style.display = 'none';
    }
    
    if (reminderMessageSection) {
        reminderMessageSection.style.display = 'none';
    }
    
    // Näita vastavaid välju
    if (option === 'custom') {
        if (customTimeField) {
            customTimeField.style.display = 'block';
            
            // PARANDATUD: Sea vaikimisi aeg
            const exactTimeInput = safeGetElement('wizard-reminder-datetime');
            if (exactTimeInput && !exactTimeInput.value) {
                // Vaikimisi täna 1 tund varem kui praegu
                const now = new Date();
                now.setHours(now.getHours() + 1);
                const defaultTime = formatDateForInput(now);
                exactTimeInput.value = defaultTime;
                debugLog('Seatsin vaikimisi custom time:', defaultTime);
            }
        }
    }
    
    if (option !== 'none') {
        if (reminderMessageSection) {
            reminderMessageSection.style.display = 'block';
        }
    }
}

// ==========================================
// KIIRED AJAVALIKUD
// ==========================================

function setQuickTime(option) {
    debugLog('Seadistan kiire aja:', option);
    
    const startField = safeGetElement('wizard-start');
    const endField = safeGetElement('wizard-end');
    
    if (!startField || !endField) return;
    
    const now = new Date();
    let startTime, endTime;
    
    switch (option) {
        case 'today-morning':
            startTime = new Date(now);
            startTime.setHours(9, 0, 0, 0);
            endTime = new Date(startTime);
            endTime.setHours(10, 0, 0, 0);
            break;
            
        case 'today-afternoon':
            startTime = new Date(now);
            startTime.setHours(14, 0, 0, 0);
            endTime = new Date(startTime);
            endTime.setHours(15, 0, 0, 0);
            break;
            
        case 'today-evening':
            startTime = new Date(now);
            startTime.setHours(18, 0, 0, 0);
            endTime = new Date(startTime);
            endTime.setHours(19, 0, 0, 0);
            break;
            
        case 'tomorrow-morning':
            startTime = new Date(now);
            startTime.setDate(startTime.getDate() + 1);
            startTime.setHours(9, 0, 0, 0);
            endTime = new Date(startTime);
            endTime.setHours(10, 0, 0, 0);
            break;
            
        case 'next-week':
            startTime = new Date(now);
            startTime.setDate(startTime.getDate() + 7);
            startTime.setHours(10, 0, 0, 0);
            endTime = new Date(startTime);
            endTime.setHours(11, 0, 0, 0);
            break;
    }
    
    if (startTime && endTime) {
        startField.value = formatDateForInput(startTime);
        endField.value = formatDateForInput(endTime);
    }
}

// ==========================================
// SÜNDMUSE SALVESTAMINE WIZARD-IST - PARANDATUD!
// ==========================================

async function saveEventFromWizard(event = null) {
    if (event) {
        event.preventDefault();
    }
    
    debugLog('Salvestan sündmust wizard-ist...');
    
    // Salvesta viimase sammu andmed
    saveWizardStepData(currentWizardStep);
    
    // Valideeri kõik andmed
    if (!wizardData.title || !wizardData.start) {
        showNotification('Puuduvad kohustuslikud andmed', 'error');
        return;
    }
    
    try {
        // Loo sündmuse andmed
        const eventData = {
            title: wizardData.title,
            description: wizardData.description,
            start_datetime: wizardData.start,
            end_datetime: wizardData.end,
            location: wizardData.location,
            category_id: wizardData.category || null
        };
        
        const isEdit = wizardData.isEdit && wizardData.eventId;
        
        if (isEdit) {
            eventData.id = wizardData.eventId;
        }
        
        debugLog('Salvestan sündmust:', eventData, 'Edit mode:', isEdit);
        
        // Salvesta sündmus
        const response = await fetch(API_BASE_URL + 'events.php', {
            method: isEdit ? 'PUT' : 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(eventData)
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const result = await response.json();
        
        if (result.success) {
            const savedEventId = result.data?.id || wizardData.eventId;
            
            // Lisa meeldetuletus kui valitud (ainult uue sündmuse puhul)
            if (!isEdit && !wizardData.skipReminder && wizardData.reminderOption && wizardData.reminderOption !== 'none' && savedEventId) {
                debugLog('Salvestan wizard meeldetuletust...', {
                    'reminderOption': wizardData.reminderOption,
                    'reminderDatetime': wizardData.reminderDatetime,
                    'reminderMessage': wizardData.reminderMessage,
                    'savedEventId': savedEventId
                });
                await saveWizardReminder(savedEventId);
            }
            
            showNotification(
                isEdit ? 'Sündmus edukalt muudetud!' : 'Sündmus edukalt lisatud!', 
                'success'
            );
            closeEventWizard();
            await refreshCalendar();
            
        } else {
            throw new Error(result.error || 'Salvestamine ebaõnnestus');
        }
        
    } catch (error) {
        console.error('Sündmuse salvestamisel tekkis viga:', error);
        showNotification('Viga: ' + error.message, 'error');
    }
}

async function saveWizardReminder(eventId) {
    debugLog('Salvestan wizard meeldetuletust...', { 
        eventId, 
        wizardData: wizardData,
        reminderOption: wizardData.reminderOption,
        reminderDatetime: wizardData.reminderDatetime
    });
    
    try {
        let reminderData = {
            event_id: eventId,
            custom_message: wizardData.reminderMessage || `Meeldetuletus: ${wizardData.title}`,
            is_recurring: false
        };
        
        // KRITILISELT PARANDATUD: Täpse kellaaja käsitlemine
        if (wizardData.reminderOption === 'custom' && wizardData.reminderDatetime) {
            // Kasuta täpset kellaaega - AINULT exact_time, MITTE minutes_before
            reminderData.exact_time = wizardData.reminderDatetime;
            debugLog('🎯 TÄPNE KELLAAEG: Kasutan exact_time:', wizardData.reminderDatetime);
            
            // ÄRGE SEADKE minutes_before - see rikub täpse kellaaja loogika
        } else if (wizardData.reminderOption && wizardData.reminderOption !== 'none' && wizardData.reminderOption !== 'custom') {
            // Kasuta minuteid enne - AINULT minutes_before, MITTE exact_time
            reminderData.minutes_before = parseInt(wizardData.reminderOption) || 60;
            debugLog('⏰ MINUTID ENNE: Kasutan minutes_before:', reminderData.minutes_before);
            
            // ÄRGE SEADKE exact_time - see rikub minutes_before loogika
        } else {
            // Vaikimisi 60 minutit enne
            reminderData.minutes_before = 60;
            debugLog('🔄 VAIKIMISI: Kasutan 60 minutes_before');
        }
        
        debugLog('📤 SAADAN API-sse:', reminderData);
        
        const response = await fetch(API_BASE_URL + 'reminders.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(reminderData)
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const result = await response.json();
        
        if (result.success) {
            debugLog('✅ Wizard meeldetuletus salvestatud edukalt');
        } else {
            console.warn('⚠️ Wizard meeldetuletuse salvestamine ebaõnnestus:', result.error);
            // Ära katkesta sündmuse salvestamist kui meeldetuletus ebaõnnestub
        }
        
    } catch (error) {
        console.error('❌ Wizard meeldetuletuse salvestamisel tekkis viga:', error);
        // Ära katkesta sündmuse salvestamist kui meeldetuletus ebaõnnestub
    }
}

// ==========================================
// OLEMASOLEV MODAL FUNKTSIOONID - PARANDATUD!
// ==========================================

function openAddEventModal(date = null) {
    debugLog('Avan lisa sündmuse modali');
    
    const modal = safeGetElement('eventModal');
    const title = safeGetElement('modal-title');
    const form = safeGetElement('event-form');
    const deleteBtn = safeGetElement('delete-btn');
    
    if (!modal || !title || !form) {
        console.error('Modal elemendid ei leitud');
        return;
    }
    
    title.textContent = 'Lisa uus sündmus';
    form.reset();
    if (deleteBtn) deleteBtn.style.display = 'none';
    
    const eventIdField = safeGetElement('event-id');
    if (eventIdField) eventIdField.value = '';
    
    if (date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const now = new Date();
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        
        const startField = safeGetElement('event-start');
        if (startField) {
            startField.value = `${year}-${month}-${day}T${hours}:${minutes}`;
        }
        
        const endField = safeGetElement('event-end');
        if (endField) {
            const endDate = new Date(date);
            endDate.setHours(now.getHours() + 1);
            const endHours = String(endDate.getHours()).padStart(2, '0');
            endField.value = `${year}-${month}-${day}T${endHours}:${minutes}`;
        }
    }
    
    modal.style.display = 'flex';
    const titleInput = safeGetElement('event-title');
    if (titleInput) titleInput.focus();
    
    if (typeof window.temporaryReminders !== 'undefined') {
        window.temporaryReminders = [];
    }
    
    if (typeof window.renderReminders === 'function') {
        setTimeout(() => window.renderReminders(), 100);
    }
}

function openEventModal(event) {
    debugLog('Avan sündmuse detailvaate:', event.title);
    
    // Kasuta tavalist modali olemasolevate sündmuste jaoks
    openEventDetailsModal(event);
}

function openEventDetailsModal(eventData) {
    debugLog('Avan sündmuse detailmodali:', eventData);
    
    const modal = safeGetElement('eventModal');
    const title = safeGetElement('modal-title');
    const deleteBtn = safeGetElement('delete-btn');
    
    if (!modal || !title) {
        console.error('Modal elemendid ei leitud');
        return;
    }
    
    title.textContent = 'Sündmuse detailid';
    if (deleteBtn) deleteBtn.style.display = 'inline-flex';
    
    // Täida vorm olemasolevate andmetega
    const fields = {
        'event-id': eventData.id || '',
        'event-title': eventData.title || '',
        'event-description': eventData.description || '',
        'event-location': eventData.location || '',
        'event-category': eventData.category_id || ''
    };
    
    Object.entries(fields).forEach(([id, value]) => {
        const field = safeGetElement(id);
        if (field) field.value = value;
    });
    
    // Täida ajad
    if (eventData.start_datetime) {
        const startDate = new Date(eventData.start_datetime);
        const startField = safeGetElement('event-start');
        if (startField) startField.value = formatDateForInput(startDate);
    }
    
    if (eventData.end_datetime) {
        const endDate = new Date(eventData.end_datetime);
        const endField = safeGetElement('event-end');
        if (endField) endField.value = formatDateForInput(endDate);
    }
    
    // Näita modali
    modal.style.display = 'flex';
    
    // Lae meeldetuletused
    if (typeof loadEventReminders === 'function') {
        setTimeout(() => loadEventReminders(eventData.id), 100);
    }
    
    debugLog('Sündmuse detailmodal avatud');
}

function openWizardForEdit() {
    // Võta praegused andmed modalist
    const eventData = {
        id: safeGetElement('event-id')?.value,
        title: safeGetElement('event-title')?.value,
        description: safeGetElement('event-description')?.value,
        location: safeGetElement('event-location')?.value,
        category_id: safeGetElement('event-category')?.value,
        start_datetime: safeGetElement('event-start')?.value,
        end_datetime: safeGetElement('event-end')?.value
    };
    
    debugLog('Avan wizard olemasolevale sündmusele:', eventData);
    
    // Sulge praegune modal
    closeEventModal();
    
    // Ava wizard
    openEventWizardForEdit(eventData);
}

function openEventWizardForEdit(eventData) {
    debugLog('Avan event wizard muutmiseks...', eventData);
    
    const modal = safeGetElement('eventWizardModal');
    if (!modal) {
        console.error('Event wizard modal ei leitud');
        return;
    }
    
    // Reset wizard
    currentWizardStep = 1;
    wizardData = {};
    
    // Märgi et see on muutmine
    wizardData.isEdit = true;
    wizardData.eventId = eventData.id;
    
    // Täida vorm olemasolevate andmetega
    const form = safeGetElement('event-wizard-form');
    if (form) form.reset();
    
    // Täida sündmuse andmed
    const eventIdField = safeGetElement('wizard-event-id');
    if (eventIdField) eventIdField.value = eventData.id || '';
    
    const titleField = safeGetElement('wizard-title');
    if (titleField) titleField.value = eventData.title || '';
    
    const descField = safeGetElement('wizard-description');
    if (descField) descField.value = eventData.description || '';
    
    const locationField = safeGetElement('wizard-location');
    if (locationField) locationField.value = eventData.location || '';
    
    const categoryField = safeGetElement('wizard-category');
    if (categoryField) categoryField.value = eventData.category_id || '';
    
    // Täida ajad
    if (eventData.start_datetime) {
        const startField = safeGetElement('wizard-start');
        if (startField) {
            if (eventData.start_datetime.includes('T')) {
                startField.value = eventData.start_datetime;
            } else {
                startField.value = formatDateForInput(new Date(eventData.start_datetime));
            }
        }
    }
    
    if (eventData.end_datetime) {
        const endField = safeGetElement('wizard-end');
        if (endField) {
            if (eventData.end_datetime.includes('T')) {
                endField.value = eventData.end_datetime;
            } else {
                endField.value = formatDateForInput(new Date(eventData.end_datetime));
            }
        }
    }
    
    // Muuda modal pealkirja
    const modalTitle = safeGetElement('eventWizardModal')?.querySelector('.modal-title');
    if (modalTitle) modalTitle.textContent = 'Muuda sündmust';
    
    // Muuda wizard sammude tekste
    updateWizardForEdit();
    
    // Näita esimest sammu
    showWizardStep(1);
    
    // Ava modal
    modal.style.display = 'flex';
    
    // Focus esimesele väljale
    const titleInput = safeGetElement('wizard-title');
    if (titleInput) titleInput.focus();
    
    debugLog('Event wizard avatud muutmiseks');
}

function updateWizardForEdit() {
    // Muuda sammude nupud
    const step2Actions = safeGetElement('wizard-step-2')?.querySelector('.wizard-actions');
    if (step2Actions) {
        const skipBtn = step2Actions.querySelector('button:nth-child(2)');
        const nextBtn = step2Actions.querySelector('button:nth-child(3)');
        
        if (skipBtn) {
            skipBtn.textContent = 'Lõpeta ilma muutmata meeldetuletusi';
            skipBtn.onclick = () => saveEventFromWizard();
        }
        
        if (nextBtn) {
            nextBtn.textContent = 'Muuda meeldetuletusi';
        }
    }
    
    // UUENDATUD: Näita kustutamise nuppu step 1's
    const deleteBtn1 = safeGetElement('wizard-delete-btn-step1');
    if (deleteBtn1) {
        deleteBtn1.style.display = 'inline-flex';
    }
    
    // Step 3 kustutamise nupp (jätta ka alles)
    const step3Actions = safeGetElement('wizard-step-3')?.querySelector('.wizard-actions');
    if (step3Actions) {
        const saveBtn = step3Actions.querySelector('button[type="submit"]');
        const deleteBtn3 = safeGetElement('wizard-delete-btn');
        
        if (saveBtn) {
            saveBtn.textContent = 'Salvesta muudatused';
        }
        
        if (deleteBtn3) {
            deleteBtn3.style.display = 'inline-flex';
        }
    }
}

async function deleteEventFromWizard() {
    if (!wizardData.eventId) {
        showNotification('Sündmuse ID ei leitud', 'error');
        return;
    }
    
    const confirmed = confirm('Kas oled kindel, et soovid selle sündmuse kustutada?');
    if (!confirmed) return;
    
    debugLog('Kustutan sündmust wizard-ist:', wizardData.eventId);
    
    try {
        const response = await fetch(API_BASE_URL + 'events.php', {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ id: wizardData.eventId })
        });
        
        const result = await response.json();
        
        if (result.success) {
            showNotification('Sündmus edukalt kustutatud!', 'success');
            closeEventWizard();
            await refreshCalendar();
        } else {
            throw new Error(result.error || 'Kustutamine ebaõnnestus');
        }
    } catch (error) {
        console.error('Sündmuse kustutamisel tekkis viga:', error);
        showNotification('Viga: ' + error.message, 'error');
    }
}

function closeEventModal() {
    const modal = safeGetElement('eventModal');
    if (modal) {
        modal.style.display = 'none';
    }
    debugLog('Sulgen sündmuse modali');
}

function formatDateForInput(date) {
    if (!date || isNaN(date.getTime())) return '';
    
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    
    return `${year}-${month}-${day}T${hours}:${minutes}`;
}

// ==========================================
// SÜNDMUSTE SALVESTAMINE (olemasolev)
// ==========================================

async function saveEvent(e) {
    e.preventDefault();
    
    const form = e.target;
    const formData = new FormData(form);
    
    const eventData = {
        title: formData.get('title'),
        description: formData.get('description'),
        start_datetime: formData.get('start'),
        end_datetime: formData.get('end'),
        location: formData.get('location'),
        category_id: formData.get('category') || null
    };
    
    const eventId = formData.get('event_id');
    const isEdit = eventId && eventId !== '';
    
    debugLog('Salvestan sündmust:', { eventData, isEdit });
    
    try {
        const url = API_BASE_URL + 'events.php';
        const response = await fetch(url, {
            method: isEdit ? 'PUT' : 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(isEdit ? { ...eventData, id: eventId } : eventData)
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const result = await response.json();
        
        if (result.success) {
            const savedEventId = result.data?.id || eventId;
            
            if (!isEdit && savedEventId && typeof window.saveTemporaryReminders === 'function') {
                await window.saveTemporaryReminders(savedEventId);
            }
            
            showNotification(
                isEdit ? 'Sündmus edukalt muudetud!' : 'Sündmus edukalt lisatud!', 
                'success'
            );
            
            closeEventModal();
            await refreshCalendar();
            
        } else {
            throw new Error(result.error || 'Salvestamine ebaõnnestus');
        }
    } catch (error) {
        console.error('Sündmuse salvestamisel tekkis viga:', error);
        showNotification('Viga: ' + error.message, 'error');
    }
}

async function deleteEvent() {
    const eventId = safeGetElement('event-id')?.value;
    if (!eventId) return;
    
    const confirmed = confirm('Kas oled kindel, et soovid selle sündmuse kustutada?');
    if (!confirmed) return;
    
    debugLog('Kustutan sündmust ID:', eventId);
    
    try {
        const response = await fetch(API_BASE_URL + 'events.php', {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ id: eventId })
        });
        
        const result = await response.json();
        
        if (result.success) {
            showNotification('Sündmus edukalt kustutatud!', 'success');
            closeEventModal();
            await refreshCalendar();
        } else {
            throw new Error(result.error || 'Kustutamine ebaõnnestus');
        }
    } catch (error) {
        console.error('Sündmuse kustutamisel tekkis viga:', error);
        showNotification('Viga: ' + error.message, 'error');
    }
}

// ==========================================
// TEAVITUSED
// ==========================================

function showNotification(message, type = 'info') {
    const oldNotifications = document.querySelectorAll('.notification');
    oldNotifications.forEach(n => n.remove());
    
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.innerHTML = `
        <div style="display: flex; align-items: center; gap: 10px;">
            <span style="font-size: 18px;">
                ${type === 'success' ? 'Edukas' : type === 'error' ? 'Viga' : 'Info'}
            </span>
            <span>${message}</span>
            <button onclick="this.parentElement.parentElement.remove()" 
                    style="background: none; border: none; font-size: 18px; cursor: pointer; color: #6b7280; margin-left: auto;">×</button>
        </div>
    `;
    
    document.body.appendChild(notification);
    
    setTimeout(() => notification.classList.add('show'), 100);
    
    setTimeout(() => {
        notification.classList.remove('show');
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 300);
    }, 5000);
    
    debugLog('Teavitus:', { message, type });
}

// ==========================================
// GLOBAALSED EKSPORDID
// ==========================================

window.previousMonth = previousMonth;
window.nextMonth = nextMonth;
window.goToToday = goToToday;
window.changeView = changeView;
window.openAddEventModal = openAddEventModal;
window.openEventModal = openEventModal;
window.openEventDetailsModal = openEventDetailsModal;
window.openWizardForEdit = openWizardForEdit;
window.closeEventModal = closeEventModal;
window.openEventWizard = openEventWizard;
window.closeEventWizard = closeEventWizard;
window.wizardNextStep = wizardNextStep;
window.wizardPrevStep = wizardPrevStep;
window.wizardSkipReminder = wizardSkipReminder;
window.selectReminderOption = selectReminderOption;
window.setQuickTime = setQuickTime;
window.saveEvent = saveEvent;
window.saveEventFromWizard = saveEventFromWizard;
window.deleteEvent = deleteEvent;
window.deleteEventFromWizard = deleteEventFromWizard;
window.refreshCalendar = refreshCalendar;
window.showNotification = showNotification;
window.renderCalendar = renderCalendar;
window.renderCalendarByView = renderCalendarByView;
window.updateTodayEvents = updateTodayEvents;
window.formatEstonianDate = formatEstonianDate;
window.addPreselectedDateInfo = addPreselectedDateInfo;

window.calendarDebug = {
    loadEvents: loadEventsFromAPI,
    refreshCalendar: refreshCalendar,
    showEvents: () => console.table(currentEvents),
    showCategories: () => console.table(categories),
    wizardData: () => console.log('Wizard data:', wizardData),
    currentView: () => console.log('Current view:', currentView),
    changeView: changeView,
    formatEstonianDate: formatEstonianDate,
    testDateFormatting: () => {
        const dates = [
            new Date(), // täna
            new Date(Date.now() + 24*60*60*1000), // homme
            new Date(Date.now() - 24*60*60*1000), // eile
            new Date(2025, 11, 25) // jõulud
        ];
        
        dates.forEach(date => {
            console.log(`${date.toDateString()} -> "${formatEstonianDate(date)}"`);
        });
    },
    showPreselectedInfo: () => {
        if (wizardData.selectedDate) {
            addPreselectedDateInfo();
        } else {
            console.log('No preselected date to show');
        }
    },
    testAPI: async () => {
        try {
            const response = await fetch(API_BASE_URL + 'events.php?action=list');
            const result = await response.json();
            console.log('API test:', result);
            return result;
        } catch (error) {
            console.error('API test failed:', error);
            return error;
        }
    },
    apiUrl: API_BASE_URL
};

debugLog('✅ Kalendri core JavaScript täielikult laaditud (PARANDATUD kuupäeval klõpsamise UX ja wizard süsteemiga)!');