// Therapy Schedule Module

let currentEditingSchedule = null;

const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];

const therapyTypes = [
    'Speech Therapy',
    'Occupational Therapy', 
    'Play and Social Skills Therapy',
    'Special Education',
    'Deep Tissue Massage',
    'Physiotherapy',
    'Comprehensive Neurohabilitative Assessment',
    'Paediatric Neurologist Consultation'
];

// Department mapping for therapy types
function getTherapyDepartment(therapyType) {
    const departmentMap = {
        'Speech Therapy': 'Speech Department',
        'Occupational Therapy': 'Occupational Therapy',
        'Play and Social Skills Therapy': 'Special Education',
        'Special Education': 'Special Education',
        'Deep Tissue Massage': 'Physical Therapy',
        'Physiotherapy': 'Physical Therapy',
        'Comprehensive Neurohabilitative Assessment': 'Assessment Unit',
        'Paediatric Neurologist Consultation': 'Medical Consultation'
    };
    return departmentMap[therapyType] || 'General';
}

function loadScheduleData() {
    const scheduleTableBody = document.querySelector('#schedule-table tbody');
    const schedules = window.app.getData('schedules');
    
    // Populate therapy type filter
    const therapyFilter = document.getElementById('schedule-therapy-filter');
    if (therapyFilter && therapyFilter.children.length === 1) {
        therapyTypes.forEach(type => {
            const option = document.createElement('option');
            option.value = type;
            option.textContent = type;
            therapyFilter.appendChild(option);
        });
    }
    
    // Sort schedules by date and time
    const sortedSchedules = schedules.sort((a, b) => {
        const dateA = new Date(`${a.date} ${a.time}`);
        const dateB = new Date(`${b.date} ${b.time}`);
        return dateA - dateB;
    });
    
    scheduleTableBody.innerHTML = sortedSchedules.map(schedule => {
        const isUpcoming = new Date(`${schedule.date} ${schedule.time}`) > new Date();
        const statusClass = isUpcoming ? 'upcoming' : 'completed';
        
        // Get department based on therapy type
        const department = getTherapyDepartment(schedule.therapyType);
        
        // Create a safe ID for expandable details
        const safeId = `schedule-details-${schedule.id}`;
        
        return `
            <tr class="schedule-row ${statusClass}">
                <td><strong>${schedule.patientName}</strong></td>
                <td>${schedule.therapistName}</td>
                <td>
                    <div class="datetime-info">
                        <span class="day-badge">${schedule.day}</span>
                        <div>${window.app.formatDate(schedule.date)}</div>
                        <span class="time-badge">${window.app.formatTime(schedule.time)}</span>
                    </div>
                </td>
                <td>
                    <span class="therapy-type-badge">${schedule.therapyType}</span>
                </td>
                <td>
                    <span class="dept-badge dept-${department.toLowerCase().replace(/\s+/g, '-')}">${department}</span>
                </td>
                <td><span class="duration-badge">${schedule.duration || 60} min</span></td>
                <td>
                    <span class="location-info">${schedule.location || 'Not specified'}</span>
                </td>
                <td>
                    <span class="status-badge ${statusClass}">
                        ${isUpcoming ? 'Upcoming' : 'Completed'}
                        ${schedule.recurring ? '<br><small class="recurring-badge">Recurring</small>' : ''}
                    </span>
                </td>
                <td>
                    <button class="btn btn-sm btn-info" onclick="toggleScheduleDetails('${safeId}')" title="View Details">
                        <i class="fas fa-info-circle"></i>
                    </button>
                </td>
                <td>
                    <div class="action-buttons">
                        <button class="btn btn-sm btn-warning" onclick="editSchedule(${schedule.id})" title="Edit Schedule">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-sm btn-danger" onclick="deleteSchedule(${schedule.id})" title="Delete Schedule">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </td>
            </tr>
            <tr id="${safeId}" class="schedule-details-row" style="display: none;">
                <td colspan="10">
                    <div class="schedule-details-content">
                        <div class="details-grid">
                            <div class="detail-item">
                                <strong>Notes:</strong>
                                <p>${schedule.notes || 'No notes provided'}</p>
                            </div>
                            ${schedule.recurring ? `
                            <div class="detail-item">
                                <strong>Recurrence:</strong>
                                <p>${schedule.recurrencePattern} until ${schedule.recurrenceEndDate ? window.app.formatDate(schedule.recurrenceEndDate) : 'Not specified'}</p>
                            </div>
                            ` : ''}
                            <div class="detail-item">
                                <strong>Created:</strong>
                                <p>${schedule.createdAt ? window.app.formatDateTime(schedule.createdAt) : 'Unknown'}</p>
                            </div>
                            ${schedule.updatedAt && schedule.updatedAt !== schedule.createdAt ? `
                            <div class="detail-item">
                                <strong>Last Updated:</strong>
                                <p>${window.app.formatDateTime(schedule.updatedAt)}</p>
                            </div>
                            ` : ''}
                        </div>
                    </div>
                </td>
            </tr>
        `;
    }).join('');

    // Setup therapy type filter
    const scheduleTherapyFilter = document.getElementById('schedule-therapy-filter');
    if (scheduleTherapyFilter) {
        scheduleTherapyFilter.addEventListener('change', filterSchedulesByTherapy);
    }

    // Setup date range filter
    const dateFilter = document.getElementById('schedule-date-filter');
    if (dateFilter) {
        dateFilter.addEventListener('change', filterSchedulesByDate);
    }

    // Load schedule summary
    loadScheduleSummary();
}

function filterSchedulesByTherapy() {
    applyScheduleFilters();
}

function filterSchedulesByDate() {
    applyScheduleFilters();
}

function applyScheduleFilters() {
    const therapyFilter = document.getElementById('schedule-therapy-filter').value;
    const dateFilter = document.getElementById('schedule-date-filter').value;
    const schedules = window.app.getData('schedules');
    
    let filteredSchedules = schedules;
    
    // Apply therapy filter
    if (therapyFilter) {
        filteredSchedules = filteredSchedules.filter(schedule => schedule.therapyType === therapyFilter);
    }
    
    // Apply date filter
    if (dateFilter) {
        const today = new Date();
        const startOfWeek = new Date(today);
        startOfWeek.setDate(today.getDate() - today.getDay());
        const endOfWeek = new Date(startOfWeek);
        endOfWeek.setDate(startOfWeek.getDate() + 6);
        
        const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
        const endOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0);
        
        filteredSchedules = filteredSchedules.filter(schedule => {
            const scheduleDate = new Date(schedule.date);
            
            switch (dateFilter) {
                case 'today':
                    return scheduleDate.toDateString() === today.toDateString();
                case 'week':
                    return scheduleDate >= startOfWeek && scheduleDate <= endOfWeek;
                case 'month':
                    return scheduleDate >= startOfMonth && scheduleDate <= endOfMonth;
                case 'upcoming':
                    return new Date(`${schedule.date} ${schedule.time}`) > new Date();
                default:
                    return true;
            }
        });
    }
    
    // Update table
    const scheduleTableBody = document.querySelector('#schedule-table tbody');
    const sortedSchedules = filteredSchedules.sort((a, b) => {
        const dateA = new Date(`${a.date} ${a.time}`);
        const dateB = new Date(`${b.date} ${b.time}`);
        return dateA - dateB;
    });
    
    scheduleTableBody.innerHTML = sortedSchedules.map(schedule => {
        const isUpcoming = new Date(`${schedule.date} ${schedule.time}`) > new Date();
        const statusClass = isUpcoming ? 'upcoming' : 'completed';
        
        // Get department based on therapy type
        const department = getTherapyDepartment(schedule.therapyType);
        
        // Create a safe ID for expandable details
        const safeId = `schedule-details-${schedule.id}`;
        
        return `
            <tr class="schedule-row ${statusClass}">
                <td><strong>${schedule.patientName}</strong></td>
                <td>${schedule.therapistName}</td>
                <td>
                    <div class="datetime-info">
                        <span class="day-badge">${schedule.day}</span>
                        <div>${window.app.formatDate(schedule.date)}</div>
                        <span class="time-badge">${window.app.formatTime(schedule.time)}</span>
                    </div>
                </td>
                <td>
                    <span class="therapy-type-badge">${schedule.therapyType}</span>
                </td>
                <td>
                    <span class="dept-badge dept-${department.toLowerCase().replace(/\s+/g, '-')}">${department}</span>
                </td>
                <td><span class="duration-badge">${schedule.duration || 60} min</span></td>
                <td>
                    <span class="location-info">${schedule.location || 'Not specified'}</span>
                </td>
                <td>
                    <span class="status-badge ${statusClass}">
                        ${isUpcoming ? 'Upcoming' : 'Completed'}
                        ${schedule.recurring ? '<br><small class="recurring-badge">Recurring</small>' : ''}
                    </span>
                </td>
                <td>
                    <button class="btn btn-sm btn-info" onclick="toggleScheduleDetails('${safeId}')" title="View Details">
                        <i class="fas fa-info-circle"></i>
                    </button>
                </td>
                <td>
                    <div class="action-buttons">
                        <button class="btn btn-sm btn-warning" onclick="editSchedule(${schedule.id})" title="Edit Schedule">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-sm btn-danger" onclick="deleteSchedule(${schedule.id})" title="Delete Schedule">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </td>
            </tr>
            <tr id="${safeId}" class="schedule-details-row" style="display: none;">
                <td colspan="10">
                    <div class="schedule-details-content">
                        <div class="details-grid">
                            <div class="detail-item">
                                <strong>Notes:</strong>
                                <p>${schedule.notes || 'No notes provided'}</p>
                            </div>
                            ${schedule.recurring ? `
                            <div class="detail-item">
                                <strong>Recurrence:</strong>
                                <p>${schedule.recurrencePattern} until ${schedule.recurrenceEndDate ? window.app.formatDate(schedule.recurrenceEndDate) : 'Not specified'}</p>
                            </div>
                            ` : ''}
                            <div class="detail-item">
                                <strong>Created:</strong>
                                <p>${schedule.createdAt ? window.app.formatDateTime(schedule.createdAt) : 'Unknown'}</p>
                            </div>
                            ${schedule.updatedAt && schedule.updatedAt !== schedule.createdAt ? `
                            <div class="detail-item">
                                <strong>Last Updated:</strong>
                                <p>${window.app.formatDateTime(schedule.updatedAt)}</p>
                            </div>
                            ` : ''}
                        </div>
                    </div>
                </td>
            </tr>
        `;
    }).join('');
}

// Dynamic modal function - commented out to use static modal instead
/*
function showScheduleModal(scheduleId = null) {
    const schedule = scheduleId ? window.app.getData('schedules').find(s => s.id === scheduleId) : null;
    const isEdit = !!schedule;
    
    const modalContent = `
        <div class="modal">
            <div class="modal-header">
                <h3>${isEdit ? 'Edit Schedule' : 'Add New Schedule'}</h3>
                <button class="modal-close" onclick="window.app.closeModal()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body">
                <form id="schedule-form">
                    <div class="form-group">
                        <label for="schedule-patient">Patient *</label>
                        <select id="schedule-patient" name="patientId" required>
                            <option value="">Select Patient</option>
                            ${getPatientOptions(schedule?.patientId)}
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="schedule-therapist">Therapist *</label>
                        <select id="schedule-therapist" name="therapistId" required>
                            <option value="">Select Therapist</option>
                            ${getTherapistOptionsForSchedule(schedule?.therapistId)}
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="schedule-date">Date *</label>
                        <input type="date" id="schedule-date" name="date" required 
                               value="${schedule ? schedule.date : ''}" 
                               min="${new Date().toISOString().split('T')[0]}">
                    </div>
                    
                    <div class="form-group">
                        <label for="schedule-time">Time *</label>
                        <input type="time" id="schedule-time" name="time" required 
                               value="${schedule ? schedule.time : ''}">
                    </div>
                    
                    <div class="form-group">
                        <label for="schedule-therapy-type">Therapy Type *</label>
                        <select id="schedule-therapy-type" name="therapyType" required>
                            <option value="">Select Therapy Type</option>
                            ${therapyTypes.map(type => `
                                <option value="${type}" ${schedule && schedule.therapyType === type ? 'selected' : ''}>${type}</option>
                            `).join('')}
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="schedule-duration">Duration (minutes)</label>
                        <input type="number" id="schedule-duration" name="duration" min="15" max="240" step="15"
                               value="${schedule ? schedule.duration || 60 : 60}" placeholder="60">
                    </div>
                    
                    <div class="form-group">
                        <label for="schedule-location">Location/Room</label>
                        <input type="text" id="schedule-location" name="location" 
                               value="${schedule ? schedule.location || '' : ''}" 
                               placeholder="e.g., Room 1, Therapy Room A">
                    </div>
                    
                    <div class="form-group">
                        <label for="schedule-notes">Notes</label>
                        <textarea id="schedule-notes" name="notes" rows="3" 
                                  placeholder="Additional notes for this session">${schedule ? schedule.notes || '' : ''}</textarea>
                    </div>
                    
                    <div class="form-group">
                        <label>
                            <input type="checkbox" id="schedule-recurring" name="recurring" 
                                   ${schedule && schedule.recurring ? 'checked' : ''}>
                            Recurring Session
                        </label>
                    </div>
                    
                    <div id="recurring-options" style="display: ${schedule && schedule.recurring ? 'block' : 'none'};">
                        <div class="form-group">
                            <label for="schedule-recurrence">Recurrence Pattern</label>
                            <select id="schedule-recurrence" name="recurrencePattern">
                                <option value="weekly" ${schedule && schedule.recurrencePattern === 'weekly' ? 'selected' : ''}>Weekly</option>
                                <option value="biweekly" ${schedule && schedule.recurrencePattern === 'biweekly' ? 'selected' : ''}>Bi-weekly</option>
                                <option value="monthly" ${schedule && schedule.recurrencePattern === 'monthly' ? 'selected' : ''}>Monthly</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label for="schedule-end-date">End Date</label>
                            <input type="date" id="schedule-end-date" name="recurrenceEndDate" 
                                   value="${schedule ? schedule.recurrenceEndDate || '' : ''}">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="window.app.closeModal()">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="saveSchedule(${scheduleId})">
                    <i class="fas fa-save"></i> ${isEdit ? 'Update' : 'Add'} Schedule
                </button>
            </div>
        </div>
    `;
    
    window.app.showModal(modalContent);
    currentEditingSchedule = scheduleId;
    
    // Setup recurring checkbox handler
    document.getElementById('schedule-recurring').addEventListener('change', function() {
        document.getElementById('recurring-options').style.display = this.checked ? 'block' : 'none';
    });
    
    // Auto-populate therapy type based on patient selection
    document.getElementById('schedule-patient').addEventListener('change', function() {
        const patientId = parseInt(this.value);
        if (patientId) {
            const patients = window.app.getData('patients');
            const patient = patients.find(p => p.id === patientId);
            if (patient) {
                document.getElementById('schedule-therapy-type').value = patient.therapyType;
            }
        }
    });
}
*/

// Make showScheduleModal globally accessible (using static modal now)
// window.showScheduleModal = showScheduleModal;

function getPatientOptions(selectedId = null) {
    const patients = window.app.getData('patients');
    return patients.map(patient => 
        `<option value="${patient.id}" ${selectedId === patient.id ? 'selected' : ''}>${patient.name} (${patient.therapyType})</option>`
    ).join('');
}

function getTherapistOptionsForSchedule(selectedId = null) {
    const staff = window.app.getData('staff');
    const therapists = staff.filter(member => member.department === 'therapist');
    return therapists.map(therapist => 
        `<option value="${therapist.id}" ${selectedId === therapist.id ? 'selected' : ''}>${therapist.name} - ${therapist.role}</option>`
    ).join('');
}

function saveSchedule(scheduleId) {
    const form = document.getElementById('schedule-form');
    const formData = new FormData(form);
    
    // Validate required fields
    const requiredFields = ['patientId', 'therapistId', 'date', 'time', 'therapyType'];
    for (const field of requiredFields) {
        if (!formData.get(field)) {
            window.app.showNotification(`Please fill in the ${field.replace(/([A-Z])/g, ' $1').toLowerCase()} field`, 'error');
            return;
        }
    }
    
    const patientId = parseInt(formData.get('patientId'));
    const therapistId = parseInt(formData.get('therapistId'));
    const patients = window.app.getData('patients');
    const staff = window.app.getData('staff');
    
    const patient = patients.find(p => p.id === patientId);
    const therapist = staff.find(s => s.id === therapistId);
    
    if (!patient || !therapist) {
        window.app.showNotification('Invalid patient or therapist selection', 'error');
        return;
    }
    
    const scheduleDate = new Date(formData.get('date'));
    const dayName = days[scheduleDate.getDay()];
    
    const scheduleData = {
        id: scheduleId || window.app.generateId('schedules'),
        patientId: patientId,
        patientName: patient.name,
        therapistId: therapistId,
        therapistName: therapist.name,
        date: formData.get('date'),
        day: dayName,
        time: formData.get('time'),
        therapyType: formData.get('therapyType'),
        duration: parseInt(formData.get('duration') || 60),
        location: formData.get('location') || '',
        notes: formData.get('notes') || '',
        recurring: formData.get('recurring') === 'on',
        recurrencePattern: formData.get('recurrencePattern') || null,
        recurrenceEndDate: formData.get('recurrenceEndDate') || null,
        createdAt: scheduleId ? undefined : new Date().toISOString(),
        updatedAt: new Date().toISOString()
    };
    
    let schedules = window.app.getData('schedules');
    
    if (scheduleId) {
        // Update existing schedule
        const index = schedules.findIndex(s => s.id === scheduleId);
        if (index !== -1) {
            schedules[index] = { ...schedules[index], ...scheduleData };
        }
    } else {
        // Add new schedule(s)
        schedules.push(scheduleData);
        
        // Handle recurring schedules
        if (scheduleData.recurring && scheduleData.recurrenceEndDate) {
            const recurringSchedules = generateRecurringSchedules(scheduleData);
            schedules.push(...recurringSchedules);
        }
    }
    
    window.app.saveData('schedules', schedules);
    window.app.closeModal();
    loadScheduleData();
    
    window.app.showNotification(
        `Schedule ${scheduleId ? 'updated' : 'added'} successfully!`,
        'success'
    );
}

// Make saveSchedule globally accessible
window.saveSchedule = saveSchedule;

function generateRecurringSchedules(baseSchedule) {
    const schedules = [];
    const startDate = new Date(baseSchedule.date);
    const endDate = new Date(baseSchedule.recurrenceEndDate);
    let currentDate = new Date(startDate);
    
    // Skip the first occurrence as it's already added
    switch (baseSchedule.recurrencePattern) {
        case 'weekly':
            currentDate.setDate(currentDate.getDate() + 7);
            break;
        case 'biweekly':
            currentDate.setDate(currentDate.getDate() + 14);
            break;
        case 'monthly':
            currentDate.setMonth(currentDate.getMonth() + 1);
            break;
    }
    
    while (currentDate <= endDate) {
        const dayName = days[currentDate.getDay()];
        const recurringSchedule = {
            ...baseSchedule,
            id: window.app.generateId('schedules') + Date.now() + Math.random(),
            date: currentDate.toISOString().split('T')[0],
            day: dayName,
            createdAt: new Date().toISOString()
        };
        
        schedules.push(recurringSchedule);
        
        // Move to next occurrence
        switch (baseSchedule.recurrencePattern) {
            case 'weekly':
                currentDate.setDate(currentDate.getDate() + 7);
                break;
            case 'biweekly':
                currentDate.setDate(currentDate.getDate() + 14);
                break;
            case 'monthly':
                currentDate.setMonth(currentDate.getMonth() + 1);
                break;
        }
    }
    
    return schedules;
}

function editSchedule(scheduleId) {
    showScheduleModal(scheduleId);
}

// Make editSchedule globally accessible
window.editSchedule = editSchedule;

function deleteSchedule(scheduleId) {
    const schedule = window.app.getData('schedules').find(s => s.id === scheduleId);
    if (confirm(`Are you sure you want to delete the schedule for ${schedule?.patientName}? This action cannot be undone.`)) {
        let schedules = window.app.getData('schedules');
        schedules = schedules.filter(s => s.id !== scheduleId);
        window.app.saveData('schedules', schedules);
        loadScheduleData();
        window.app.showNotification('Schedule deleted successfully!', 'success');
    }
}

// Make deleteSchedule globally accessible
window.deleteSchedule = deleteSchedule;

// Toggle schedule details display
function toggleScheduleDetails(detailsId) {
    const detailsRow = document.getElementById(detailsId);
    const toggleButton = event.target.closest('button');
    const icon = toggleButton.querySelector('i');
    
    if (detailsRow.style.display === 'none' || detailsRow.style.display === '') {
        detailsRow.style.display = 'table-row';
        icon.className = 'fas fa-info-circle';
        toggleButton.title = 'Hide Details';
    } else {
        detailsRow.style.display = 'none';
        icon.className = 'fas fa-info-circle';
        toggleButton.title = 'View Details';
    }
}

// Make toggleScheduleDetails globally accessible
window.toggleScheduleDetails = toggleScheduleDetails;

function loadScheduleSummary() {
    const schedules = window.app.getData('schedules');
    const today = new Date();
    const startOfWeek = new Date(today);
    startOfWeek.setDate(today.getDate() - today.getDay());
    const endOfWeek = new Date(startOfWeek);
    endOfWeek.setDate(startOfWeek.getDate() + 6);
    
    // Today's sessions
    const todaySessions = schedules.filter(schedule => {
        const scheduleDate = new Date(schedule.date);
        return scheduleDate.toDateString() === today.toDateString();
    });
    
    // This week's sessions
    const weekSessions = schedules.filter(schedule => {
        const scheduleDate = new Date(schedule.date);
        return scheduleDate >= startOfWeek && scheduleDate <= endOfWeek;
    });
    
    // Upcoming sessions
    const upcomingSessions = schedules.filter(schedule => {
        return new Date(`${schedule.date} ${schedule.time}`) > new Date();
    });
    
    // Update basic counts
    document.getElementById('today-sessions').textContent = todaySessions.length;
    document.getElementById('week-sessions').textContent = weekSessions.length;
    document.getElementById('upcoming-sessions').textContent = upcomingSessions.length;
    
    // Department breakdowns
    const todayDepts = getDepartmentBreakdown(todaySessions);
    const weekDepts = getDepartmentBreakdown(weekSessions);
    const upcomingDepts = getDepartmentBreakdown(upcomingSessions);
    
    document.getElementById('today-departments').innerHTML = formatDepartmentSummary(todayDepts);
    document.getElementById('week-departments').innerHTML = formatDepartmentSummary(weekDepts);
    document.getElementById('upcoming-departments').innerHTML = formatDepartmentSummary(upcomingDepts);
    
    // Find busiest day
    const dayCount = {};
    weekSessions.forEach(schedule => {
        dayCount[schedule.day] = (dayCount[schedule.day] || 0) + 1;
    });
    
    const busiestDay = Object.entries(dayCount).reduce((a, b) => 
        dayCount[a[0]] > dayCount[b[0]] ? a : b, ['None', 0]
    );
    
    document.getElementById('busiest-day').textContent = busiestDay[0];
    document.getElementById('busiest-day-count').textContent = `${busiestDay[1]} sessions`;
    
    // Department statistics
    loadDepartmentStats(schedules);
    
    // Therapist workload
    loadTherapistWorkload(schedules);
    
    // Weekly calendar
    loadWeeklyCalendar(weekSessions);
}

function getDepartmentBreakdown(sessions) {
    const deptCount = {};
    sessions.forEach(schedule => {
        const dept = getTherapyDepartment(schedule.therapyType);
        deptCount[dept] = (deptCount[dept] || 0) + 1;
    });
    return deptCount;
}

function formatDepartmentSummary(deptBreakdown) {
    const entries = Object.entries(deptBreakdown);
    if (entries.length === 0) return '<span class="no-data">No sessions</span>';
    
    return entries.slice(0, 2).map(([dept, count]) => 
        `<span class="dept-summary">${dept}: ${count}</span>`
    ).join('<br>');
}

function loadDepartmentStats(schedules) {
    const deptStats = {};
    const today = new Date();
    
    schedules.forEach(schedule => {
        const dept = getTherapyDepartment(schedule.therapyType);
        const scheduleDate = new Date(`${schedule.date} ${schedule.time}`);
        const isUpcoming = scheduleDate > today;
        
        if (!deptStats[dept]) {
            deptStats[dept] = { total: 0, upcoming: 0, completed: 0 };
        }
        
        deptStats[dept].total++;
        if (isUpcoming) {
            deptStats[dept].upcoming++;
        } else {
            deptStats[dept].completed++;
        }
    });
    
    const deptStatsContainer = document.getElementById('dept-stats');
    deptStatsContainer.innerHTML = Object.entries(deptStats).map(([dept, stats]) => `
        <div class="dept-stat-card">
            <h5>${dept}</h5>
            <div class="dept-numbers">
                <div class="stat-item">
                    <span class="stat-label">Total:</span>
                    <span class="stat-value">${stats.total}</span>
                </div>
                <div class="stat-item">
                    <span class="stat-label">Upcoming:</span>
                    <span class="stat-value upcoming">${stats.upcoming}</span>
                </div>
                <div class="stat-item">
                    <span class="stat-label">Completed:</span>
                    <span class="stat-value completed">${stats.completed}</span>
                </div>
            </div>
            <div class="dept-bar">
                <div class="dept-fill" style="width: ${stats.total > 0 ? (stats.upcoming / stats.total) * 100 : 0}%"></div>
            </div>
        </div>
    `).join('');
}

function loadTherapistWorkload(schedules) {
    const therapistStats = {};
    const today = new Date();
    
    schedules.forEach(schedule => {
        const therapist = schedule.therapistName;
        const scheduleDate = new Date(`${schedule.date} ${schedule.time}`);
        const isUpcoming = scheduleDate > today;
        
        if (!therapistStats[therapist]) {
            therapistStats[therapist] = { total: 0, upcoming: 0, thisWeek: 0 };
        }
        
        therapistStats[therapist].total++;
        if (isUpcoming) {
            therapistStats[therapist].upcoming++;
        }
        
        // Check if this week
        const startOfWeek = new Date(today);
        startOfWeek.setDate(today.getDate() - today.getDay());
        const endOfWeek = new Date(startOfWeek);
        endOfWeek.setDate(startOfWeek.getDate() + 6);
        
        if (scheduleDate >= startOfWeek && scheduleDate <= endOfWeek) {
            therapistStats[therapist].thisWeek++;
        }
    });
    
    const therapistStatsContainer = document.getElementById('therapist-stats');
    therapistStatsContainer.innerHTML = Object.entries(therapistStats)
        .sort(([,a], [,b]) => b.upcoming - a.upcoming)
        .map(([therapist, stats]) => `
        <div class="therapist-stat-card">
            <div class="therapist-name">${therapist}</div>
            <div class="therapist-numbers">
                <span class="stat-badge">This Week: ${stats.thisWeek}</span>
                <span class="stat-badge upcoming">Upcoming: ${stats.upcoming}</span>
                <span class="stat-badge">Total: ${stats.total}</span>
            </div>
        </div>
    `).join('');
}

function loadWeeklyCalendar(weekSessions) {
    const calendarGrid = document.getElementById('calendar-grid');
    const dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    
    const sessionsByDay = {};
    dayNames.forEach(day => {
        sessionsByDay[day] = weekSessions.filter(session => session.day === day);
    });
    
    const calendarHTML = `
        <div class="calendar-header">
            ${dayNames.map(day => `<div class="day-header">${day}</div>`).join('')}
        </div>
        <div class="calendar-body">
            ${dayNames.map(day => {
                const daySessions = sessionsByDay[day];
                return `
                    <div class="day-column">
                        <div class="day-sessions">
                            ${daySessions.map(session => {
                                const isUpcoming = new Date(`${session.date} ${session.time}`) > new Date();
                                const statusClass = isUpcoming ? 'upcoming' : 'completed';
                                return `
                                    <div class="session-item ${statusClass}">
                                        <div class="session-time">${session.time}</div>
                                        <div class="session-patient">${session.patientName}</div>
                                        <div class="session-therapy">${session.therapyType}</div>
                                        <div class="session-therapist">${session.therapistName}</div>
                                    </div>
                                `;
                            }).join('')}
                            ${daySessions.length === 0 ? '<div class="no-sessions">No sessions</div>' : ''}
                        </div>
                    </div>
                `;
            }).join('')}
        </div>
    `;
    
    calendarGrid.innerHTML = calendarHTML;
}

function exportSchedule() {
    const schedules = window.app.getData('schedules');
    
    if (schedules.length === 0) {
        window.app.showNotification('No schedules to export', 'error');
        return;
    }
    
    const exportData = schedules.map(schedule => ({
        'Patient Name': schedule.patientName,
        'Therapist Name': schedule.therapistName,
        'Date': schedule.date,
        'Day': schedule.day,
        'Time': schedule.time,
        'Therapy Type': schedule.therapyType,
        'Duration (minutes)': schedule.duration || 60,
        'Location': schedule.location || '',
        'Notes': schedule.notes || '',
        'Recurring': schedule.recurring ? 'Yes' : 'No'
    }));
    
    const currentDate = new Date().toISOString().split('T')[0];
    window.app.exportToCSV(exportData, `schedule-${currentDate}.csv`);
    window.app.showNotification('Schedule exported successfully!', 'success');
}

// Make exportSchedule globally accessible
window.exportSchedule = exportSchedule;

// Add CSS for schedule styles
const scheduleStyles = `
    <style>
        .schedule-summary {
            background: var(--white);
            padding: 1.5rem;
            border-radius: var(--border-radius);
            box-shadow: var(--shadow);
            margin-top: 2rem;
        }
        
        .schedule-summary h3 {
            color: var(--primary-teal);
            margin-bottom: 1rem;
        }
        
        .schedule-row.upcoming {
            background-color: rgba(32, 178, 170, 0.1);
        }
        
        .schedule-row.completed {
            background-color: rgba(0, 0, 0, 0.05);
        }
        
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 500;
        }
        
        .status-badge.upcoming {
            background: var(--primary-teal);
            color: var(--white);
        }
        
        .status-badge.completed {
            background: var(--medium-gray);
            color: var(--dark-gray);
        }
        
        .day-badge {
            background: var(--primary-yellow);
            color: var(--dark-gray);
            padding: 0.2rem 0.6rem;
            border-radius: 15px;
            font-size: 0.8rem;
            font-weight: 500;
        }
        
        .time-badge {
            background: var(--primary-orange);
            color: var(--white);
            padding: 0.2rem 0.6rem;
            border-radius: 15px;
            font-size: 0.8rem;
            font-weight: 500;
        }
        
        .dept-badge {
            padding: 0.3rem 0.8rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .dept-speech-department { background: #e3f2fd; color: #1565c0; }
        .dept-occupational-therapy { background: #f3e5f5; color: #7b1fa2; }
        .dept-special-education { background: #e8f5e8; color: #2e7d32; }
        .dept-physical-therapy { background: #fff3e0; color: #ef6c00; }
        .dept-assessment-unit { background: #fce4ec; color: #c2185b; }
        .dept-medical-consultation { background: #ffebee; color: #d32f2f; }
        
        .summary-detail {
            font-size: 0.75rem;
            color: #666;
            margin-top: 0.25rem;
        }
        
        .dept-summary {
            display: inline-block;
            background: var(--light-teal);
            color: var(--primary-teal);
            padding: 0.1rem 0.4rem;
            border-radius: 10px;
            font-size: 0.7rem;
        }
        
        .no-data {
            color: #999;
            font-style: italic;
            font-size: 0.8rem;
        }
        
        .department-breakdown, .therapist-workload {
            margin-top: 2rem;
            padding: 1.5rem;
            background: var(--white);
            border-radius: var(--border-radius);
            box-shadow: var(--shadow);
        }
        
        .department-breakdown h4, .therapist-workload h4 {
            color: var(--primary-teal);
            margin-bottom: 1rem;
            border-bottom: 2px solid var(--light-teal);
            padding-bottom: 0.5rem;
        }
        
        .dept-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 1.5rem;
        }
        
        .dept-stat-card {
            background: var(--light-gray);
            padding: 1.5rem;
            border-radius: var(--border-radius);
            border-left: 4px solid var(--primary-orange);
        }
        
        .dept-stat-card h5 {
            color: var(--primary-teal);
            margin-bottom: 1rem;
            font-size: 1.1rem;
        }
        
        .dept-numbers {
            display: flex;
            justify-content: space-between;
            margin-bottom: 1rem;
        }
        
        .stat-item {
            text-align: center;
        }
        
        .stat-label {
            display: block;
            font-size: 0.8rem;
            color: #666;
            margin-bottom: 0.25rem;
        }
        
        .stat-value {
            display: block;
            font-size: 1.2rem;
            font-weight: bold;
            color: var(--primary-teal);
        }
        
        .stat-value.upcoming {
            color: var(--primary-orange);
        }
        
        .stat-value.completed {
            color: var(--medium-gray);
        }
        
        .dept-bar {
            height: 8px;
            background: var(--light-gray);
            border-radius: 4px;
            overflow: hidden;
        }
        
        .dept-fill {
            height: 100%;
            background: linear-gradient(90deg, var(--primary-teal), var(--primary-orange));
            transition: width 0.3s ease;
        }
        
        .therapist-stats {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 1rem;
        }
        
        .therapist-stat-card {
            background: var(--white);
            padding: 1rem;
            border-radius: var(--border-radius);
            border: 1px solid var(--light-gray);
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .therapist-name {
            font-weight: bold;
            color: var(--primary-teal);
            margin-bottom: 0.75rem;
            font-size: 1rem;
        }
        
        .therapist-numbers {
            display: flex;
            flex-wrap: wrap;
            gap: 0.5rem;
        }
        
        .stat-badge {
            background: var(--light-teal);
            color: var(--primary-teal);
            padding: 0.25rem 0.6rem;
            border-radius: 15px;
            font-size: 0.75rem;
            font-weight: 500;
        }
        
        .stat-badge.upcoming {
            background: var(--primary-orange);
            color: var(--white);
        }
        
        .calendar-grid {
            background: var(--white);
            border-radius: var(--border-radius);
            overflow: hidden;
            box-shadow: var(--shadow);
        }
        
        .calendar-header {
            display: grid;
            grid-template-columns: repeat(7, 1fr);
            background: var(--primary-teal);
        }
        
        .day-header {
            padding: 1rem;
            color: var(--white);
            text-align: center;
            font-weight: bold;
            font-size: 0.9rem;
        }
        
        .calendar-body {
            display: grid;
            grid-template-columns: repeat(7, 1fr);
            min-height: 300px;
        }
        
        .day-column {
            border-right: 1px solid var(--light-gray);
            padding: 0.5rem;
        }
        
        .day-column:last-child {
            border-right: none;
        }
        
        .day-sessions {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
        }
        
        .session-item {
            background: var(--light-gray);
            padding: 0.5rem;
            border-radius: 6px;
            border-left: 3px solid var(--medium-gray);
            font-size: 0.75rem;
        }
        
        .session-item.upcoming {
            background: rgba(32, 178, 170, 0.1);
            border-left-color: var(--primary-teal);
        }
        
        .session-item.completed {
            background: rgba(0, 0, 0, 0.05);
            border-left-color: var(--medium-gray);
        }
        
        .session-time {
            font-weight: bold;
            color: var(--primary-orange);
            margin-bottom: 0.25rem;
        }
        
        .session-patient {
            font-weight: 600;
            color: var(--primary-teal);
            margin-bottom: 0.25rem;
        }
        
        .session-therapy {
            color: #666;
            font-size: 0.7rem;
            margin-bottom: 0.25rem;
        }
        
        .session-therapist {
            color: #888;
            font-size: 0.7rem;
            font-style: italic;
        }
        
        .no-sessions {
            color: #999;
            font-style: italic;
            text-align: center;
            padding: 1rem;
        }
        
        #recurring-options {
            margin-top: 1rem;
            padding: 1rem;
            background: var(--light-gray);
            border-radius: var(--border-radius);
            border-left: 4px solid var(--primary-orange);
        }
        
        .schedule-calendar {
            margin-top: 2rem;
            padding: 1.5rem;
            background: var(--white);
            border-radius: var(--border-radius);
            box-shadow: var(--shadow);
        }
        
        .schedule-calendar h4 {
            color: var(--primary-teal);
            margin-bottom: 1rem;
            border-bottom: 2px solid var(--light-teal);
            padding-bottom: 0.5rem;
        }
        
        @media (max-width: 768px) {
            .dept-stats {
                grid-template-columns: 1fr;
            }
            
            .therapist-stats {
                grid-template-columns: 1fr;
            }
            
            .calendar-header, .calendar-body {
                grid-template-columns: 1fr;
            }
            
            .day-column {
                border-right: none;
                border-bottom: 1px solid var(--light-gray);
            }
        }
    </style>
`;

document.head.insertAdjacentHTML('beforeend', scheduleStyles);

// Initialize schedule module
function initializeScheduleModule() {
    // Create default schedules if none exist
    const schedules = window.app.getData('schedules');
    if (schedules.length === 0) {
        createDefaultSchedules();
    }
    
    // Load schedule data when initialized
    if (document.querySelector('#schedule-table')) {
        loadScheduleData();
    }
}

// Create some default sample schedules for demo purposes
function createDefaultSchedules() {
    const patients = window.app.getData('patients');
    const staff = window.app.getData('staff');
    
    if (patients.length === 0 || staff.length === 0) {
        return; // Can't create schedules without patients and staff
    }
    
    const sampleSchedules = [
        {
            id: window.app.generateId('schedules'),
            patientId: patients[0].id,
            patientName: patients[0].name,
            therapistId: staff[0].id,
            therapistName: staff[0].name,
            date: getNextWeekdayDate(1), // Next Monday
            day: 'Monday',
            time: '09:00',
            therapyType: 'Speech Therapy',
            duration: 60,
            location: 'Therapy Room A',
            notes: 'Initial assessment session',
            recurring: false,
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
        },
        {
            id: window.app.generateId('schedules'),
            patientId: patients[Math.min(1, patients.length - 1)].id,
            patientName: patients[Math.min(1, patients.length - 1)].name,
            therapistId: staff[Math.min(1, staff.length - 1)].id,
            therapistName: staff[Math.min(1, staff.length - 1)].name,
            date: getNextWeekdayDate(3), // Next Wednesday
            day: 'Wednesday',
            time: '14:30',
            therapyType: 'Occupational Therapy',
            duration: 45,
            location: 'OT Room',
            notes: 'Follow-up session - focus on fine motor skills',
            recurring: true,
            recurrencePattern: 'weekly',
            recurrenceEndDate: getDateInFuture(60), // 2 months from now
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
        },
        {
            id: window.app.generateId('schedules'),
            patientId: patients[Math.min(2, patients.length - 1)].id,
            patientName: patients[Math.min(2, patients.length - 1)].name,
            therapistId: staff[Math.min(2, staff.length - 1)].id,
            therapistName: staff[Math.min(2, staff.length - 1)].name,
            date: getTomorrowDate(),
            day: getTomorrowDayName(),
            time: '11:00',
            therapyType: 'Physiotherapy',
            duration: 60,
            location: 'Gym Area',
            notes: 'Strengthening exercises for lower limbs',
            recurring: false,
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
        }
    ];
    
    window.app.saveData('schedules', sampleSchedules);
}

// Helper function to get next weekday
function getNextWeekdayDate(dayOfWeek) {
    const today = new Date();
    const daysUntilTarget = (dayOfWeek - today.getDay() + 7) % 7;
    const targetDate = new Date(today);
    targetDate.setDate(today.getDate() + daysUntilTarget);
    return targetDate.toISOString().split('T')[0];
}

// Helper function to get tomorrow's date
function getTomorrowDate() {
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    return tomorrow.toISOString().split('T')[0];
}

// Helper function to get tomorrow's day name
function getTomorrowDayName() {
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    return days[tomorrow.getDay()];
}

// Helper function to get date in future
function getDateInFuture(daysFromNow) {
    const futureDate = new Date();
    futureDate.setDate(futureDate.getDate() + daysFromNow);
    return futureDate.toISOString().split('T')[0];
}

// Initialize when module loads
if (window.app) {
    initializeScheduleModule();
} else {
    // Wait for app to be ready
    document.addEventListener('DOMContentLoaded', function() {
        setTimeout(initializeScheduleModule, 100);
    });
}
