// Global variables
let teachersData = [];
let filteredTeachers = [];

// DOM elements
const searchInput = document.getElementById('searchInput');
const titleFilter = document.getElementById('titleFilter');
const teachersGrid = document.getElementById('teachersGrid');
const categorySections = document.getElementById('categorySections');
const resultsCount = document.getElementById('resultsCount');
const noResults = document.getElementById('noResults');

// Initialize the application
document.addEventListener('DOMContentLoaded', function() {
    loadTeachersData();
    setupEventListeners();
    setupLogoHandling();
});

// Setup logo handling
function setupLogoHandling() {
    const logo = document.querySelector('.school-logo');
    if (logo) {
        logo.addEventListener('error', function() {
            console.warn('School logo failed to load, showing fallback');
            this.style.display = 'none';
            const fallback = this.nextElementSibling;
            if (fallback) {
                fallback.style.display = 'flex';
            }
        });
        
        logo.addEventListener('load', function() {
            console.log('School logo loaded successfully');
            const fallback = this.nextElementSibling;
            if (fallback) {
                fallback.style.display = 'none';
            }
        });
        
        // Check if logo is already loaded
        if (logo.complete && logo.naturalHeight !== 0) {
            console.log('School logo already loaded');
        } else if (logo.complete) {
            console.warn('School logo failed to load (already complete)');
            logo.style.display = 'none';
            const fallback = logo.nextElementSibling;
            if (fallback) {
                fallback.style.display = 'flex';
            }
        }
        
        // Set timeout to show fallback if logo doesn't load within 3 seconds
        setTimeout(() => {
            if (logo.naturalHeight === 0) {
                console.warn('School logo timeout, showing fallback');
                logo.style.display = 'none';
                const fallback = logo.nextElementSibling;
                if (fallback) {
                    fallback.style.display = 'flex';
                }
            }
        }, 3000);
    }
}

// Load teachers data from API
async function loadTeachersData() {
    try {
        showLoading();
        const response = await fetch('api/v1/personnel.php?action=stats');
        if (!response.ok) {
            throw new Error('Failed to load personnel stats');
        }
        const statsData = await response.json();
        
        if (statsData.success) {
            // Load personnel list
            const personnelResponse = await fetch('api/v1/personnel.php');
            if (!personnelResponse.ok) {
                throw new Error('Failed to load personnel data');
            }
            const personnelData = await personnelResponse.json();
            
            if (personnelData.success) {
                teachersData = personnelData.data.map(person => ({
                    id: person.id,
                    name: person.full_name,
                    title: person.rank_name || 'ไม่ระบุ',
                    rank_level: person.rank_level,
                    gender: person.gender,
                    image: person.image_path,
                    googleSiteUrl: `#personnel-${person.id}` // Placeholder for now
                }));
                filteredTeachers = [...teachersData];
                updateSummaryStatsFromAPI(statsData.data);
                renderTeachersByCategory();
                updateResultsCount();
            } else {
                throw new Error(personnelData.error || 'Failed to load personnel data');
            }
        } else {
            throw new Error(statsData.error || 'Failed to load stats');
        }
    } catch (error) {
        console.error('Error loading teachers data:', error);
        showError('ไม่สามารถโหลดข้อมูลครูได้ กรุณาลองใหม่อีกครั้ง');
    }
}

// Setup event listeners
function setupEventListeners() {
    searchInput.addEventListener('input', handleSearch);
    titleFilter.addEventListener('change', handleFilter);
}

// Handle search input
function handleSearch() {
    const searchTerm = searchInput.value.toLowerCase().trim();
    filterTeachers(searchTerm, titleFilter.value);
}

// Handle title filter
function handleFilter() {
    const searchTerm = searchInput.value.toLowerCase().trim();
    filterTeachers(searchTerm, titleFilter.value);
}

// Filter teachers based on search term and title
function filterTeachers(searchTerm, selectedTitle) {
    filteredTeachers = teachersData.filter(teacher => {
        const matchesSearch = teacher.name.toLowerCase().includes(searchTerm);
        const matchesTitle = !selectedTitle || teacher.rank_level === selectedTitle;
        return matchesSearch && matchesTitle;
    });
    
    updateSummaryStats();
    renderTeachersByCategory();
    updateResultsCount();
}

// Update summary statistics from API data
function updateSummaryStatsFromAPI(stats) {
    document.getElementById('totalTeachers').textContent = stats.total_personnel || 0;
    document.getElementById('specializedTeachers').textContent = stats.specialized_count || 0;
    document.getElementById('expertTeachers').textContent = stats.expert_count || 0;
    document.getElementById('teacherAssistantTeachers').textContent = (stats.teacher_count || 0) + (stats.assistant_count || 0);
}

// Update summary statistics from filtered data
function updateSummaryStats() {
    const total = filteredTeachers.length;
    const specialized = filteredTeachers.filter(t => t.rank_level === 'ครูชำนาญการพิเศษ').length;
    const expert = filteredTeachers.filter(t => t.rank_level === 'ครูชำนาญการ').length;
    const teacher = filteredTeachers.filter(t => t.rank_level === 'ครู').length;
    const assistant = filteredTeachers.filter(t => t.rank_level === 'ครูผู้ช่วย').length;
    const teacherAssistant = teacher + assistant;
    
    document.getElementById('totalTeachers').textContent = total;
    document.getElementById('specializedTeachers').textContent = specialized;
    document.getElementById('expertTeachers').textContent = expert;
    document.getElementById('teacherAssistantTeachers').textContent = teacherAssistant;
}

// Render teachers by category
function renderTeachersByCategory() {
    if (filteredTeachers.length === 0) {
        showNoResults();
        return;
    }
    
    hideNoResults();
    
    const categories = [
        {
            title: 'ครูชำนาญการพิเศษ',
            icon: 'fas fa-star',
            class: 'specialized-category',
            teachers: filteredTeachers.filter(t => t.rank_level === 'ครูชำนาญการพิเศษ')
        },
        {
            title: 'ครูชำนาญการ',
            icon: 'fas fa-check-circle',
            class: 'expert-category',
            teachers: filteredTeachers.filter(t => t.rank_level === 'ครูชำนาญการ')
        },
        {
            title: 'ครู',
            icon: 'fas fa-user',
            class: 'teacher-category',
            teachers: filteredTeachers.filter(t => t.rank_level === 'ครู')
        },
        {
            title: 'ครูผู้ช่วย',
            icon: 'fas fa-user-plus',
            class: 'assistant-category',
            teachers: filteredTeachers.filter(t => t.rank_level === 'ครูผู้ช่วย')
        }
    ];
    
    categorySections.innerHTML = categories.map(category => {
        if (category.teachers.length === 0) return '';
        
        return `
            <div class="category-section ${category.class}">
                <div class="category-header">
                    <div class="category-icon">
                        <i class="${category.icon}"></i>
                    </div>
                    <h3 class="category-title">${category.title}</h3>
                    <span class="category-count">${category.teachers.length} คน</span>
                </div>
                <div class="teachers-grid">
                    ${category.teachers.map(teacher => `
                        <div class="teacher-card">
                            <div class="teacher-image-container">
                                ${teacher.image ? 
                                    `<img src="${teacher.image}" alt="${teacher.name}" class="teacher-image" onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">
                                     <div class="teacher-image-fallback" style="display: none;">
                                        <i class="fas fa-user"></i>
                                     </div>` :
                                    `<div class="teacher-image-fallback">
                                        <i class="fas fa-user"></i>
                                     </div>`
                                }
                            </div>
                            <h4 class="teacher-name">${teacher.name}</h4>
                            <span class="teacher-title">${teacher.title}</span>
                            <a href="${teacher.googleSiteUrl}" 
                               target="_blank" 
                               rel="noopener noreferrer" 
                               class="view-report-btn"
                               onclick="trackClick('${teacher.name}', '${teacher.googleSiteUrl}')">
                                <i class="fas fa-external-link-alt"></i>
                                ดูรายงานเต็ม
                            </a>
                        </div>
                    `).join('')}
                </div>
            </div>
        `;
    }).join('');
}

// Render teachers to the grid
function renderTeachers() {
    if (filteredTeachers.length === 0) {
        showNoResults();
        return;
    }
    
    hideNoResults();
    
    teachersGrid.innerHTML = filteredTeachers.map(teacher => `
        <div class="teacher-card">
            <h3 class="teacher-name">${teacher.name}</h3>
            <span class="teacher-title">${teacher.title}</span>
            <a href="${teacher.googleSiteUrl}" 
               target="_blank" 
               rel="noopener noreferrer" 
               class="view-report-btn">
                <i class="fas fa-external-link-alt"></i>
                ดูรายงานเต็ม
            </a>
        </div>
    `).join('');
}

// Update results count
function updateResultsCount() {
    const total = teachersData.length;
    const filtered = filteredTeachers.length;
    
    if (filtered === total) {
        resultsCount.textContent = `แสดงทั้งหมด ${total} คน`;
    } else {
        resultsCount.textContent = `แสดง ${filtered} จาก ${total} คน`;
    }
}

// Show loading state
function showLoading() {
    categorySections.innerHTML = '<div class="loading"></div>';
    resultsCount.textContent = 'กำลังโหลด...';
}

// Show no results
function showNoResults() {
    categorySections.innerHTML = '';
    noResults.style.display = 'block';
}

// Hide no results
function hideNoResults() {
    noResults.style.display = 'none';
}

// Show error message
function showError(message) {
    categorySections.innerHTML = `
        <div class="no-results">
            <i class="fas fa-exclamation-triangle"></i>
            <p>${message}</p>
        </div>
    `;
    resultsCount.textContent = 'เกิดข้อผิดพลาด';
}

// Utility function to debounce search input
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// Add debounced search for better performance
const debouncedSearch = debounce(handleSearch, 300);
searchInput.addEventListener('input', debouncedSearch);

// Add keyboard shortcuts
document.addEventListener('keydown', function(e) {
    // Focus search input with Ctrl/Cmd + K
    if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
        e.preventDefault();
        searchInput.focus();
    }
    
    // Clear search with Escape
    if (e.key === 'Escape') {
        searchInput.value = '';
        titleFilter.value = '';
        filterTeachers('', '');
    }
});

// Add smooth scrolling for better UX
function smoothScrollToElement(element) {
    element.scrollIntoView({
        behavior: 'smooth',
        block: 'start'
    });
}

// Add click tracking for analytics (optional)
function trackClick(teacherName, url) {
    // This can be extended to send analytics data
    console.log(`Teacher clicked: ${teacherName}, URL: ${url}`);
}

// Enhanced teacher card rendering with click tracking
function renderTeachersWithTracking() {
    if (filteredTeachers.length === 0) {
        showNoResults();
        return;
    }
    
    hideNoResults();
    
    teachersGrid.innerHTML = filteredTeachers.map(teacher => `
        <div class="teacher-card">
            <h3 class="teacher-name">${teacher.name}</h3>
            <span class="teacher-title">${teacher.title}</span>
            <a href="${teacher.googleSiteUrl}" 
               target="_blank" 
               rel="noopener noreferrer" 
               class="view-report-btn"
               onclick="trackClick('${teacher.name}', '${teacher.googleSiteUrl}')">
                <i class="fas fa-external-link-alt"></i>
                ดูรายงานเต็ม
            </a>
        </div>
    `).join('');
}

// Export data functionality (for admin use)
function exportTeachersData() {
    const dataStr = JSON.stringify(teachersData, null, 2);
    const dataBlob = new Blob([dataStr], {type: 'application/json'});
    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = 'teachers_data.json';
    link.click();
    URL.revokeObjectURL(url);
}

// Add export button (hidden by default, can be enabled for admin)
function addExportButton() {
    const exportBtn = document.createElement('button');
    exportBtn.textContent = 'Export Data';
    exportBtn.className = 'export-btn';
    exportBtn.style.cssText = `
        position: fixed;
        bottom: 20px;
        right: 20px;
        background: #1B5E20;
        color: white;
        border: none;
        padding: 10px 15px;
        border-radius: 5px;
        cursor: pointer;
        display: none;
    `;
    exportBtn.onclick = exportTeachersData;
    document.body.appendChild(exportBtn);
}

// Initialize export functionality
addExportButton();

