// ===== DEFAULT SVG IMAGE HELPERS =====
function getDefaultImg(type, label) {
    const icons = {
        training: '<path d="M20 15 L40 25 L20 35 L0 25Z" fill="#4338CA" opacity="0.9"/>',
        facility: '<rect x="5" y="22" width="50" height="36" rx="3" fill="#4338CA" opacity="0.8"/>',
        equipment: '<circle cx="30" cy="30" r="20" fill="none" stroke="#4338CA" stroke-width="3" opacity="0.8"/><circle cx="30" cy="30" r="9" fill="#06B6D4" opacity="0.9"/>',
        gallery: '<rect x="5" y="15" width="50" height="40" rx="4" fill="#4338CA" opacity="0.8"/>',
        default: '<rect x="10" y="5" width="40" height="50" rx="4" fill="#4338CA" opacity="0.7"/>'
    };
    const icon = icons[type] || icons.default;
    return `data:image/svg+xml,${encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" width="400" height="300" viewBox="0 0 60 60"><rect fill="#1E1B4B" width="60" height="60"/>${icon}</svg>`)}`;
}

function getDefaultAvatar(name) {
    const initial = (name || 'U').charAt(0).toUpperCase();
    const colors = ['#312E81', '#4338CA', '#06B6D4', '#059669', '#D97706', '#7C3AED'];
    const bg = colors[(name || '').split('').reduce((acc, c) => acc + c.charCodeAt(0), 0) % colors.length];
    return `data:image/svg+xml,${encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 200 200"><rect fill="${bg}" width="200" height="200"/><circle cx="100" cy="72" r="32" fill="rgba(255,255,255,0.25)"/><ellipse cx="100" cy="165" rx="50" ry="38" fill="rgba(255,255,255,0.25)"/><text x="100" y="88" font-family="Arial" font-size="42" font-weight="700" fill="#fff" text-anchor="middle">${initial}</text></svg>`)}`;
}

function handleImgError(el, type, label) {
    el.onerror = null;
    el.src = getDefaultImg(type || 'default', label || '');
}

// ===== API & DATA LAYER =====
const API = 'api.php';

async function api(entity, method = 'GET', data = null) {
    let url = `${API}?entity=${entity}`;
    let opts = { method, headers: { 'Content-Type': 'application/json' } };
    if (method === 'POST' && data) opts.body = JSON.stringify(data);
    // FIX #2: Only append &id= if data.id actually exists (was appending "undefined")
    if (method === 'DELETE' && data && data.id != null) url += `&id=${data.id}`;
    if (method === 'GET' && data && data.id != null) url += `&id=${data.id}`;
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 8000);
    opts.signal = controller.signal;
    try {
        const res = await fetch(url, opts);
        clearTimeout(timeoutId);
        // FIX #3: res.json() can throw on non-JSON responses (e.g. HTML error pages)
        //         which would crash Promise.all in loadAllData
        const text = await res.text();
        try {
            return JSON.parse(text);
        } catch (parseErr) {
            return { error: "Invalid server response" };
        }
    } catch (e) {
        clearTimeout(timeoutId);
        return { error: "Network Error" };
    }
}

// FIX #1: Proper date arithmetic — getMonth()+2 overflows to 13 in December
const _now = new Date();
const _y = _now.getFullYear();
const _m = String(_now.getMonth() + 1).padStart(2, '0');
const _d = String(_now.getDate()).padStart(2, '0');
// Use Date constructor to handle year rollover correctly
const _nextMonthDate = new Date(_now.getFullYear(), _now.getMonth() + 1, 1);
const _nm_y = _nextMonthDate.getFullYear();
const _nm_m = String(_nextMonthDate.getMonth() + 1).padStart(2, '0');

let trainings = [
    { id: 1, title: 'Road Construction Technology', start: `${_y}-${_m}-${_d}`, end: `${_y}-${_m}-${_d}`, category: 'Short Course', status: 'ongoing', desc: 'Modern road construction methods.' },
    { id: 2, title: 'Concrete Quality Control', start: `${_y}-${_m}-15`, end: `${_y}-${_m}-20`, category: 'Workshop', status: 'upcoming', desc: 'Compressive strength testing.' },
    { id: 3, title: 'Bridge Design Workshop', start: `${_y}-${_m}-22`, end: `${_y}-${_m}-25`, category: 'Workshop', status: 'upcoming', desc: 'Bridge engineering.' },
    // FIX #1 applied: was `${_y}-${String(_now.getMonth() + 2).padStart(2,'0')}` → invalid month 13 in December
    { id: 4, title: 'Project Management', start: `${_nm_y}-${_nm_m}-05`, end: `${_nm_y}-${_nm_m}-10`, category: 'Certificate Program', status: 'upcoming', desc: 'PMP prep.' },
    { id: 5, title: 'Soil Investigation', start: `${_y}-${_m}-08`, end: `${_y}-${_m}-12`, category: 'Short Course', status: 'upcoming', desc: 'Soil testing.' }
];
let testings = [
    { id: 1, title: 'Concrete Compression Test', testType: 'Concrete', turnaround: '3', desc: 'Compressive strength test.' },
    { id: 2, title: 'Soil Bearing Capacity', testType: 'Soil', turnaround: '5', desc: 'Bearing capacity analysis.' },
    { id: 3, title: 'Steel Tensile Test', testType: 'Steel', turnaround: '2', desc: 'Tensile strength testing.' }
];
let notices = [
    { id: 1, title: 'Admission Notice - July 2025', content: 'Applications invited for training programs.', date: `${_y}-${_m}-${_d}`, type: 'new', category: 'Training' },
    { id: 2, title: 'Holiday Notice', content: 'Office closed on public holidays.', date: `${_y}-${_m}-${_d}`, type: 'important', category: 'Holiday' }
];
let officers = [
    { id: 1, name: 'Md. Abdul Karim', designation: 'Superintending Engineer', email: 'karim@pwd.gov.bd', phone: '+880171234567' },
    { id: 2, name: 'Md. Rahim Uddin', designation: 'Executive Engineer', email: 'rahim@pwd.gov.bd', phone: '+880171234568' }
];
let equipment = [], trainees = [], galleryItems = [], videoItems = [], facilities = [], sliders = [], employees = [], siteStats = {};

// FIX #5: Use Promise.allSettled so one failed request doesn't kill all data loading
async function loadAllData() {
    const entities = ['trainings', 'testings', 'notices', 'officers', 'equipment', 'trainees', 'gallery', 'videos', 'facilities', 'sliders', 'employees', 'stats'];
    const results = await Promise.allSettled(entities.map(e => api(e)));

    const assign = (index, setter) => {
        const r = results[index];
        if (r.status === 'fulfilled' && !r.value.error) {
            setter(r.value);
        } else {
            const entityName = entities[index];
            if (r.status === 'rejected') {
                console.error(`❌ API ${entityName}: request failed`, r.reason);
            } else if (r.value && r.value.error) {
                console.error(`❌ API ${entityName}: ${r.value.error}`);
            }
        }
    };

    assign(0, v => { if (Array.isArray(v) && v.length > 0) trainings = v; });
    assign(1, v => { if (Array.isArray(v) && v.length > 0) testings = v; });
    assign(2, v => { if (Array.isArray(v) && v.length > 0) notices = v; });
    assign(3, v => { if (Array.isArray(v) && v.length > 0) officers = v; });
    assign(4, v => { equipment = Array.isArray(v) ? v : []; });
    assign(5, v => { trainees = Array.isArray(v) ? v : []; });
    assign(6, v => { galleryItems = Array.isArray(v) ? v : []; });
    assign(7, v => { videoItems = Array.isArray(v) ? v : []; });
    assign(8, v => { facilities = Array.isArray(v) ? v : []; });
    assign(9, v => { sliders = Array.isArray(v) ? v : []; });
    assign(10, v => { employees = Array.isArray(v) ? v : []; });
    assign(11, v => { if (v && !v.error) siteStats = v; });
}

// FIX #4: Removed data.length > 0 checks so admin sees empty state after deleting all items
async function refreshEntity(entity) {
    const data = await api(entity);
    if (data.error) return;
    switch (entity) {
        case 'trainings': if (Array.isArray(data)) trainings = data; break;
        case 'testings': if (Array.isArray(data)) testings = data; break;
        case 'notices': if (Array.isArray(data)) notices = data; break;
        case 'officers': if (Array.isArray(data)) officers = data; break;
        case 'equipment': equipment = Array.isArray(data) ? data : []; break;
        case 'trainees': trainees = Array.isArray(data) ? data : []; break;
        case 'gallery': galleryItems = Array.isArray(data) ? data : []; break;
        case 'videos': videoItems = Array.isArray(data) ? data : []; break;
        case 'facilities': facilities = Array.isArray(data) ? data : []; break;
        case 'sliders': sliders = Array.isArray(data) ? data : []; break;
        case 'employees': employees = Array.isArray(data) ? data : []; break;
    }
}
function renderEmployees() {
    const bn = currentLang === 'bn';
    const title = bn ? 'কর্মকর্তাগণ' : 'Employees';
    if (!employees || employees.length === 0) return pageHeader(title, t('nav_about'), `<div class="card p-12 text-center"><i class="fas fa-users text-4xl text-gray-300 mb-4"></i><p class="text-gray-500">${bn ? 'কোনো কর্মকর্তার তথ্য নেই।' : 'No employee records found.'}</p></div>`);
    const listHTML = `<div class="space-y-3">${employees.map(e => {
        const initial = (e.name || 'U').charAt(0).toUpperCase();
        const colors = ['#312E81', '#06B6D4', '#059669', '#D97706', '#DC2626', '#7C3AED'];
        const color = colors[(e.id || 0) % colors.length];
        const imgSrc = e.img ? e.img : getDefaultAvatar(e.name);
        return `<div class="card p-4 flex items-center gap-4">
            <div class="w-12 h-12 rounded-full overflow-hidden shrink-0 border-2" style="border-color:${color}20">
                <img src="${imgSrc}" class="w-full h-full object-cover" alt="${e.name || ''}" onerror="this.onerror=null;this.src=getDefaultAvatar('${(e.name || '').replace(/'/g, "\\'")}')">
            </div>
            <div class="flex-1 min-w-0">
                <h4 class="font-semibold text-sm">${e.name || '-'}</h4>
                <p class="text-xs text-gray-500">${e.designation || ''}</p>
                <p class="text-xs text-gray-400">${e.department || ''}</p>
            </div>
            <div class="flex gap-3 text-gray-400 shrink-0">
                ${e.email ? `<a href="mailto:${e.email}" class="hover:text-blue-500 transition"><i class="fas fa-envelope text-sm"></i></a>` : ''}
                ${e.phone ? `<a href="tel:${e.phone}" class="hover:text-green-500 transition"><i class="fas fa-phone text-sm"></i></a>` : ''}
            </div>
        </div>`;
    }).join('')}</div>`;
    return pageHeader(title, t('nav_about'), `<div class="flex items-center justify-between mb-6"><p class="text-sm text-gray-500">${bn ? 'মোট' : 'Total'}: <span class="font-semibold" style="color:var(--primary)">${employees.length}</span></p></div>${listHTML}`);
}
// ===== UI HELPERS =====
function showToast(msg, type = 'success') { const el = document.getElementById('toast'); el.className = `toast toast-${type} show`; el.textContent = msg; setTimeout(() => el.classList.remove('show'), 3000); }
function openModal(html) { document.getElementById('modal-content').innerHTML = html; document.getElementById('modal-overlay').classList.add('show'); setTimeout(() => applyTranslations(), 50); }
function closeModal() { const overlay = document.getElementById('modal-overlay'); overlay.classList.remove('show'); setTimeout(() => { const content = document.getElementById('modal-content'); if (content) { const video = content.querySelector('video'); if (video) { video.pause(); video.src = ''; } const iframe = content.querySelector('iframe'); if (iframe) iframe.src = ''; content.innerHTML = ''; } }, 250); }
function openLightbox(src) { document.getElementById('lightbox-img').src = src; document.getElementById('lightbox').classList.add('show'); }
function closeLightbox() { document.getElementById('lightbox').classList.remove('show'); }
function toggleMobileNav() { document.getElementById('mobile-nav').classList.toggle('hidden'); }
function toggleTheme() { document.body.classList.toggle('dark-mode'); const icon = document.getElementById('theme-icon'); icon.classList.toggle('fa-moon'); icon.classList.toggle('fa-sun'); }
function pageHeader(title, breadcrumb, content) { return `<div class="mb-8"><div class="flex items-center gap-2 text-xs text-gray-400 mb-3"><a class="cursor-pointer hover:text-gray-600" onclick="navigate('home')">${t('nav_home')}</a><i class="fas fa-chevron-right" style="font-size:8px"></i><span>${breadcrumb}</span></div><h1 class="text-2xl font-bold">${title}</h1></div>${content}`; }

// ===== NAVIGATION =====
let currentPage = 'home', currentAdminPage = 'dashboard', currentUser = null, sliderIndex = 0;
window.calendarMonth = new Date().getMonth(); window.calendarYear = new Date().getFullYear();

function navigate(page) { currentPage = page; document.querySelectorAll('.nav-link').forEach(l => { l.classList.remove('active'); if (l.dataset.page === page || (l.dataset.page && page.startsWith(l.dataset.page))) l.classList.add('active'); }); renderPage(); document.getElementById('mobile-nav').classList.add('hidden'); window.scrollTo({ top: 0, behavior: 'smooth' }); }
function renderPage() { const c = document.getElementById('page-content'); const renders = { home: renderHome, vision: renderVision, management: renderManagement, employees: renderEmployees, organogram: renderOrganogram, campus: renderCampus, officers: renderOfficers, employees: renderOfficers, classroom: renderClassroom, computerlab: renderComputerLab, library: renderLibrary, residential: renderResidential, playground: renderPlayground, gymnasium: renderGymnasium, swimmingpool: renderSwimmingPool, testinglab: renderTestingLabFacility, photogallery: renderPhotoGallery, videogallery: renderVideoGallery, materialtest: renderMaterialTest, equipment: renderEquipmentPage, testingreport: renderTestingReport, trainings: renderTrainings, testing: renderTesting, notices: renderNotices, contact: renderContact, verify: renderVerify, login: renderLogin, register: renderRegister, dashboard: renderUserDashboard }; const fn = renders[currentPage] || renderHome; c.innerHTML = '<div class="fade-in">' + fn() + '</div>'; setTimeout(() => applyTranslations(), 50); if (currentPage === 'home') initSlider(); }

// ===== TICKER & SLIDER =====
function updateTicker() { const wrap = document.getElementById('ticker-wrap'); if (!notices.length) { wrap.innerHTML = `<span class="ticker-item">${t('notice_no_notices')}</span>`; return; } wrap.innerHTML = notices.map(n => `<span class="ticker-item">📢 ${n.title} ${n.type === 'important' ? '⚠️' : ''}</span>`).join('') + notices.map(n => `<span class="ticker-item">📢 ${n.title} ${n.type === 'important' ? '⚠️' : ''}</span>`).join(''); }
function initSlider() { sliderIndex = 0; updateSlider(); clearInterval(window._sliderInterval); window._sliderInterval = setInterval(() => { sliderIndex = (sliderIndex + 1) % Math.max(sliders.length, 1); updateSlider(); }, 5000); }
function updateSlider() { document.querySelectorAll('.slide').forEach((s, i) => s.classList.toggle('active', i === sliderIndex)); document.querySelectorAll('.slider-dot').forEach((d, i) => d.classList.toggle('active', i === sliderIndex)); }
function nextSlide() { sliderIndex = (sliderIndex + 1) % Math.max(sliders.length, 1); updateSlider(); }
function prevSlide() { sliderIndex = (sliderIndex - 1 + Math.max(sliders.length, 1)) % Math.max(sliders.length, 1); updateSlider(); }
function goSlide(i) { sliderIndex = i; updateSlider(); }

// ===== ADMIN PANEL =====
function showAdminPanel() { if (!currentUser || currentUser.role !== 'admin') { navigate('login'); showToast('Please login as admin', 'info'); setTimeout(() => { const e = document.getElementById('login-email'); if (e) e.value = 'admin@pwd.gov.bd'; const p = document.getElementById('login-pass'); if (p) p.focus(); }, 200); return; } document.getElementById('admin-panel').style.display = 'block'; document.getElementById('public-site').style.display = 'none'; adminNav('dashboard', document.querySelector('.admin-nav-item.active')); }
function prefillAdminLogin() { const e = document.getElementById('login-email'); const p = document.getElementById('login-pass'); if (e) e.value = 'admin@pwd.gov.bd'; if (p) p.focus(); showToast('Enter admin password', 'info'); }
async function goToPublic() {
    document.getElementById('admin-panel').style.display = 'none';
    document.getElementById('public-site').style.display = 'block';
    await loadAllData();
    navigate('home');
    setTimeout(() => updateTicker(), 100);
}
function logoutAdmin() { currentUser = null; updateLoginButton(); goToPublic(); showToast(t('toast_logged_out'), 'info'); }
function adminNav(page, el) {
    currentAdminPage = page;
    document.querySelectorAll('.admin-nav-item').forEach(n => n.classList.remove('active'));
    if (el) el.classList.add('active');
    const titles = {
        dashboard: t('admin_dashboard'),
        'admin-trainings': t('admin_trainings'),
        'admin-testings': t('admin_testings'),
        'admin-notices': t('admin_notices'),
        'admin-officers': t('admin_management'),
        'admin-employees': t('admin_employees'),
        'admin-trainees': t('admin_trainees'),
        'admin-equipment': t('admin_equipment'),
        'admin-gallery': t('admin_gallery'),
        'admin-videos': t('admin_videos'),
        'admin-facilities': t('admin_facilities'),
        'admin-sliders': t('admin_sliders'),
        'admin-settings': t('admin_settings'),
        'admin-reports': t('admin_reports')
    };
    document.getElementById('admin-page-title').textContent = titles[page] || t('admin_dashboard');
    renderAdminPage();
    document.getElementById('admin-sidebar').classList.remove('open');
}

async function renderAdminPage() {
    const c = document.getElementById('admin-content');
    c.innerHTML = '<div class="flex justify-center items-center h-64"><div class="loader"></div></div>';
    const entityMap = { dashboard: ['stats', 'trainings', 'testings', 'trainees'], 'admin-trainings': ['trainings'], 'admin-testings': ['testings'], 'admin-notices': ['notices'], 'admin-officers': ['officers'], 'admin-employees': ['employees'], 'admin-trainees': ['trainees'], 'admin-equipment': ['equipment'], 'admin-gallery': ['gallery'], 'admin-videos': ['videos'], 'admin-facilities': ['facilities'], 'admin-sliders': ['sliders'] };
    const entities = entityMap[currentAdminPage] || [];
    for (const e of entities) {
        try {
            if (e === 'stats') { siteStats = (await api('stats')) || {}; }
            else { await refreshEntity(e); }
        } catch (err) { console.error('Refresh error:', err); }
    }
    const renders = {
        dashboard: adminDashboard,
        'admin-trainings': () => adminCrudList('trainings', t('admin_trainings'), [currentLang === 'bn' ? 'শিরোনাম' : 'Title', currentLang === 'bn' ? 'বিভাগ' : 'Category', currentLang === 'bn' ? 'তারিখ' : 'Date', currentLang === 'bn' ? 'অবস্থা' : 'Status']),
        'admin-testings': () => adminCrudList('testings', currentLang === 'bn' ? 'পরীক্ষা সেবা' : 'Testing Services', [currentLang === 'bn' ? 'শিরোনাম' : 'Title', currentLang === 'bn' ? 'ধরন' : 'Type', currentLang === 'bn' ? 'সময়' : 'Turnaround']),
        'admin-notices': () => adminCrudList('notices', t('admin_notices'), [currentLang === 'bn' ? 'শিরোনাম' : 'Title', currentLang === 'bn' ? 'তারিখ' : 'Date', currentLang === 'bn' ? 'ধরন' : 'Type']),
        'admin-officers': () => adminCrudList('officers', t('admin_management'), [currentLang === 'bn' ? 'ফটো' : 'Photo', currentLang === 'bn' ? 'নাম' : 'Name', currentLang === 'bn' ? 'পদবি' : 'Designation', currentLang === 'bn' ? 'ইমেইল' : 'Email']),
        'admin-employees': () => adminCrudList('employees', t('admin_employees'), [currentLang === 'bn' ? 'ফটো' : 'Photo', currentLang === 'bn' ? 'নাম' : 'Name', currentLang === 'bn' ? 'পদবি' : 'Designation', currentLang === 'bn' ? 'বিভাগ' : 'Department']),
        'admin-trainees': () => adminCrudList('trainees', t('admin_trainees'), [currentLang === 'bn' ? 'নাম' : 'Name', currentLang === 'bn' ? 'ইমেইল' : 'Email', currentLang === 'bn' ? 'প্রতিষ্ঠান' : 'Organization']),
        'admin-equipment': () => adminCrudList('equipment', t('admin_equipment'), [currentLang === 'bn' ? 'নাম' : 'Name', currentLang === 'bn' ? 'ক্ষমতা' : 'Capacity', currentLang === 'bn' ? 'মান' : 'Standard']),
        'admin-gallery': () => adminCrudList('gallery', t('admin_gallery'), [currentLang === 'bn' ? 'শিরোনাম' : 'Title', currentLang === 'bn' ? 'বিভাগ' : 'Category']),
        'admin-videos': () => adminCrudList('videos', t('admin_videos'), [currentLang === 'bn' ? 'শিরোনাম' : 'Title', currentLang === 'bn' ? 'URL' : 'URL']),
        'admin-facilities': () => adminCrudList('facilities', t('admin_facilities'), [currentLang === 'bn' ? 'ধরন' : 'Type', currentLang === 'bn' ? 'শিরোনাম' : 'Title']),
        'admin-sliders': () => adminCrudList('sliders', t('admin_sliders'), [currentLang === 'bn' ? 'শিরোনাম' : 'Title', currentLang === 'bn' ? 'উপশিরোনাম' : 'Subtitle']),
        'admin-settings': adminSettings,
        'admin-reports': adminReports
    };
    const fn = renders[currentAdminPage] || adminDashboard;
    c.innerHTML = '<div class="fade-in">' + fn() + '</div>';
}

function updateLoginButton() {
    const btn = document.getElementById('header-login-btn');
    if (!btn) return;
    if (currentUser) {
        btn.textContent = currentUser.name ? currentUser.name.split(' ')[0] : t('nav_login');
        btn.onclick = () => navigate('dashboard');
    } else {
        btn.textContent = t('nav_login');
        btn.onclick = () => navigate('login');
    }
}

// =============================================
// INITIALIZATION
// =============================================
async function init() {
    // Restore saved language
    try {
        const savedLang = localStorage.getItem('preferred_lang');
        if (savedLang && (savedLang === 'bn' || savedLang === 'en')) {
            currentLang = savedLang;
            if (currentLang === 'bn') {
                document.body.classList.add('lang-bn');
                const publicLabel = document.getElementById('lang-label');
                const adminLabel = document.getElementById('admin-lang-label');
                if (publicLabel) publicLabel.textContent = 'বাং';
                if (adminLabel) adminLabel.textContent = 'বাং';
            }
        }
    } catch (e) { }

    // Load data with error handling
    try {
        await loadAllData();
    } catch (e) {
        console.error('Failed to load data:', e);
    }

    // FIX #6: Removed dead `typeof employees === 'undefined'` check
    //         (employees is let-declared, always defined — just check if empty)
    if (employees.length === 0) {
        console.warn('⚠️ No employees loaded from API — check api.php?entity=employees');
    }

    // Render the page — data is available
    try {
        updateTicker();
        applyTranslations();
        renderPage();
        updateLoginButton();
    } catch (e) {
        console.error('Render error:', e);
    }

    // Hide loading screen
    const hideLoader = () => {
        const ls = document.getElementById('loading-screen');
        if (ls) {
            ls.style.opacity = '0';
            setTimeout(() => { if (ls) ls.style.display = 'none'; }, 300);
        }
    };

    setTimeout(hideLoader, 800);
    setTimeout(() => {
        const ls = document.getElementById('loading-screen');
        if (ls && ls.style.display !== 'none') ls.style.display = 'none';
    }, 5000);

    // Admin clock
    setInterval(() => {
        const at = document.getElementById('admin-time');
        if (at) at.textContent = new Date().toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
    }, 1000);
}

// ===== START THE APP =====
init();