// =============================================
// FALLBACK DECLARATIONS (Safe for let/const)
// =============================================
if (typeof currentLang === 'undefined') window.currentLang = 'en';
if (typeof t !== 'function') window.t = function (key) { return key; };
if (typeof applyTranslations !== 'function') window.applyTranslations = function () { };
if (typeof toggleLanguage !== 'function') {
    window.toggleLanguage = function () {
        window.currentLang = window.currentLang === 'bn' ? 'en' : 'bn';
        document.body.classList.toggle('lang-bn');
        const pl = document.getElementById('lang-label');
        const al = document.getElementById('admin-lang-label');
        if (pl) pl.textContent = window.currentLang === 'bn' ? 'বাং' : 'EN';
        if (al) al.textContent = window.currentLang === 'bn' ? 'বাং' : 'EN';
    };
}

// =============================================
// API & DATA LAYER (With Bug Fixes & Compatibility)
// =============================================
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);
    if (method === 'DELETE' && data && data.id != null) url += `&id=${data.id}`;
    if (method === 'GET' && data && data.id != null) url += `&id=${data.id}`;
    try {
        const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
        const timeoutId = controller ? setTimeout(() => controller.abort(), 8000) : null;
        if (controller) opts.signal = controller.signal;

        const res = await fetch(url, opts);
        if (timeoutId) clearTimeout(timeoutId);
        const text = await res.text();
        try { return JSON.parse(text); }
        catch (parseErr) { return { error: "Invalid server response" }; }
    } catch (e) {
        return { error: "Network Error" };
    }
}

// FIX: Proper date arithmetic to prevent month 13 overflow 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');
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.' },
    { 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: Replaced Promise.allSettled with Promise.all fallback for older browsers
async function loadAllData() {
    const entities = ['trainings', 'testings', 'notices', 'officers', 'equipment', 'trainees', 'gallery', 'videos', 'facilities', 'sliders', 'employees', 'stats'];
    const results = await Promise.all(entities.map(e => api(e).then(v => ({ status: 'fulfilled', value: v })).catch(e => ({ status: 'rejected', reason: 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: 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;
    }
}

// =============================================
// UI HELPERS
// =============================================
function showToast(msg, type = 'success') { const el = document.getElementById('toast'); if (!el) return; 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(() => { if (typeof applyTranslations === 'function') applyTranslations(); }, 50); }
function closeModal() { const overlay = document.getElementById('modal-overlay'); if (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'); if (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,
        organogram: renderOrganogram,
        campus: renderCampus,
        officers: renderOfficers,
        employees: renderEmployees,
        classroom: renderClassroom,
        computerlab: renderComputerLab,
        library: renderLibrary,
        residential: renderResidential,
        playground: renderPlayground,
        gymnasium: renderGymnasium,
        swimmingpool: renderSwimmingPool,
        testinglab: renderTestingLabFacility,
        photogallery: renderPhotoGallery,
        videogallery: renderVideoGallery,
        trainings: renderTrainings,
        testing: renderTesting,
        materialtest: renderMaterialTest,
        equipment: renderEquipmentPage,
        testingreport: renderTestingReport,
        notices: renderNotices,          // ← MUST BE PRESENT
        contact: renderContact,
        verify: renderVerify,
        login: renderLogin,
        register: renderRegister,
        dashboard: renderUserDashboard
    };
    const fn = renders[currentPage] || renderHome;
    c.innerHTML = '<div class="fade-in">' + fn() + '</div>';
    setTimeout(() => {
        if (typeof applyTranslations === 'function') applyTranslations();
    }, 50);
    if (currentPage === 'home') initSlider();
    setTimeout(() => updateTicker(), 100);
}
// =============================================
// 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}</span>`).join('') + notices.map(n => `<span class="ticker-item">📢 ${n.title}</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 BRIDGE (Connects app.js to admin.js)
// =============================================
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'; if (typeof adminNav === 'function') 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.training.gov.bd'; if (p) p.value = 'admin123'; if (p) p.focus(); showToast('Admin credentials filled', '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 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() {
    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 pl = document.getElementById('lang-label'); const al = document.getElementById('admin-lang-label'); if (pl) pl.textContent = 'বাং'; if (al) al.textContent = 'বাং'; } } } catch (e) { }
    try { await loadAllData(); } catch (e) { console.error('Failed to load data:', e); }
    try { updateTicker(); if (typeof applyTranslations === 'function') applyTranslations(); renderPage(); updateLoginButton(); } catch (e) { console.error('Render error:', e); }
    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);
    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();

// =============================================
// HELPER: Escape HTML attribute values
// =============================================
function escAttr(str) {
    if (str === null || str === undefined) return '';
    return String(str).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

// =============================================
// DEFAULT SVG PLACEHOLDERS
// =============================================
function getDefaultPersonSVG(name) {
    const initial = (name || 'U').charAt(0).toUpperCase();
    const colors = ['#003366', '#0d6efd', '#059669', '#7c3aed', '#d97706', '#dc2626', '#0891b2', '#be185d'];
    const color = colors[(name || 'A').charCodeAt(0) % colors.length];
    const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 200 200">
        <rect width="200" height="200" fill="${color}" rx="16"/>
        <text x="100" y="128" text-anchor="middle" font-family="Arial,Helvetica,sans-serif" font-size="90" font-weight="bold" fill="white">${initial}</text>
    </svg>`;
    return 'data:image/svg+xml,' + encodeURIComponent(svg);
}

function getDefaultSilhouetteSVG() {
    const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 200 200">
        <rect width="200" height="200" fill="#e2e8f0" rx="16"/>
        <circle cx="100" cy="68" r="30" fill="#94a3b8"/>
        <ellipse cx="100" cy="162" rx="48" ry="40" fill="#94a3b8"/>
    </svg>`;
    return 'data:image/svg+xml,' + encodeURIComponent(svg);
}
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>`);
    }

    return pageHeader(title, t('nav_about'), `<div class="management-wrapper">${employees.sort((a, b) => (a.display_order || 0) - (b.display_order || 0)).map(e => {
        const imgSrc = e.img ? escAttr(e.img) : getDefaultPersonSVG(e.name);
        return `<div class="management-card"><div class="management-image"><img src="${imgSrc}" alt="${escAttr(e.name || '')}" onerror="handleImgError(this,'person','')"></div><div class="management-content"><h2 class="management-name">${escAttr(e.name || '')}</h2><div class="management-designation">${escAttr(e.designation || '')}</div>${e.department ? `<div class="management-office">${escAttr(e.department)}</div>` : ''}${e.phone ? `<div class="management-line"><i class="fas fa-phone-alt"></i>${escAttr(e.phone)}</div>` : ''}${e.mobile ? `<div class="management-line"><i class="fas fa-mobile-alt"></i>${escAttr(e.mobile)}</div>` : ''}${e.email ? `<div class="management-line"><i class="fas fa-envelope"></i>${escAttr(e.email)}</div>` : ''}</div></div>`;
    }).join('')}</div><style>.management-wrapper{display:flex;flex-direction:column;gap:16px}.management-card{display:flex;align-items:center;gap:18px;padding:18px;background:#fff;border-radius:18px;border:1px solid rgba(0,0,0,0.06);box-shadow:0 5px 18px rgba(0,0,0,0.06);transition:.3s}.management-card:hover{transform:translateY(-3px);box-shadow:0 10px 24px rgba(0,45,94,0.12)}.management-image{flex-shrink:0}.management-image img{width:95px;height:95px;border-radius:16px;object-fit:cover;border:3px solid #fff;box-shadow:0 4px 12px rgba(0,0,0,0.10)}.management-content{flex:1;min-width:0}.management-name{font-size:20px;font-weight:700;color:#003366;margin-bottom:5px}.management-designation{font-size:15px;font-weight:600;color:#0d6efd;margin-bottom:4px}.management-office{font-size:13px;color:#666;margin-bottom:10px}.management-line{display:flex;align-items:center;gap:8px;font-size:13px;color:#444;margin-bottom:6px}.management-line i{width:16px;color:#0d6efd;flex-shrink:0}@media(max-width:768px){.management-card{align-items:flex-start;padding:16px;gap:14px}.management-image img{width:75px;height:75px;border-radius:14px}.management-name{font-size:17px}}</style>`);
}
function getDefaultThumbSVG(type) {
    const configs = {
        training: { bg: '#eff6ff', icon: '#3b82f6', label: currentLang === 'bn' ? 'প্রশিক্ষণ' : 'Training' },
        equipment: { bg: '#fef3c7', icon: '#f59e0b', label: currentLang === 'bn' ? 'যন্ত্রপাতি' : 'Equipment' },
        testing: { bg: '#fef2f2', icon: '#ef4444', label: currentLang === 'bn' ? 'পরীক্ষা' : 'Testing' },
        gallery: { bg: '#f0fdf4', icon: '#22c55e', label: currentLang === 'bn' ? 'গ্যালারি' : 'Gallery' },
        video: { bg: '#fdf2f8', icon: '#ec4899', label: currentLang === 'bn' ? 'ভিডিও' : 'Video' },
        facility: { bg: '#f5f3ff', icon: '#8b5cf6', label: currentLang === 'bn' ? 'সুবিধা' : 'Facility' },
        default: { bg: '#f1f5f9', icon: '#94a3b8', label: currentLang === 'bn' ? 'ছবি নেই' : 'No Image' }
    };
    const c = configs[type] || configs.default;
    const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="400" height="300" viewBox="0 0 400 300">
        <rect width="400" height="300" fill="${c.bg}" rx="8"/>
        <rect x="160" y="80" width="80" height="60" rx="6" fill="${c.icon}22" stroke="${c.icon}44" stroke-width="2"/>
        <circle cx="185" cy="103" r="9" fill="${c.icon}55"/>
        <polygon points="160,140 200,110 240,140" fill="${c.icon}55"/>
        <line x1="180" y1="170" x2="220" y2="170" stroke="${c.icon}66" stroke-width="3" stroke-linecap="round"/>
        <line x1="170" y1="182" x2="230" y2="182" stroke="${c.icon}33" stroke-width="2" stroke-linecap="round"/>
        <text x="200" y="215" text-anchor="middle" font-family="Arial,sans-serif" font-size="14" fill="${c.icon}" font-weight="600">${c.label}</text>
    </svg>`;
    return 'data:image/svg+xml,' + encodeURIComponent(svg);
}

// =============================================
// IMAGE ERROR HANDLER (Single Definition)
// =============================================
function handleImgError(el, type, fallback) {
    if (type === 'person' || type === 'officer' || type === 'employee') {
        el.src = getDefaultSilhouetteSVG();
    } else if (type === 'default') {
        el.src = getDefaultThumbSVG('default');
    } else {
        el.src = getDefaultThumbSVG(type || 'default');
    }
    el.style.objectFit = 'cover';
    el.onerror = null;
}

// =============================================
// GLOBAL PROGRAM ENROLLMENT & INTEREST TRACKING
// =============================================
function getProgramTracking() {
    const data = localStorage.getItem('pwdta_program_tracking');
    return data ? JSON.parse(data) : {};
}

function saveProgramTracking(tracking) {
    localStorage.setItem('pwdta_program_tracking', JSON.stringify(tracking));
}

function getProgramStats(programId) {
    const tracking = getProgramTracking();
    const program = tracking[programId] || { enrolled: [], interested: [] };
    return {
        enrolledCount: (program.enrolled || []).length,
        interestedCount: (program.interested || []).length
    };
}

function addProgramEnrollment(programId, user) {
    const tracking = getProgramTracking();
    if (!tracking[programId]) tracking[programId] = { enrolled: [], interested: [] };
    const email = user.email || user.userEmail || '';
    const exists = tracking[programId].enrolled.find(e => e.email === email);
    if (!exists) {
        tracking[programId].enrolled.push({
            name: user.name || '-',
            email: email,
            designation: user.designation || '',
            org: user.org || user.organization || '',
            phone: user.phone || '',
            date: new Date().toISOString()
        });
        saveProgramTracking(tracking);
    }
}

function addProgramInterest(programId, user) {
    const tracking = getProgramTracking();
    if (!tracking[programId]) tracking[programId] = { enrolled: [], interested: [] };
    const email = user.email || user.userEmail || '';
    const exists = tracking[programId].interested.find(e => e.email === email);
    if (!exists) {
        tracking[programId].interested.push({
            name: user.name || '-',
            email: email,
            designation: user.designation || '',
            org: user.org || user.organization || '',
            phone: user.phone || '',
            date: new Date().toISOString()
        });
        saveProgramTracking(tracking);
    }
}

function getProgramEnrolledList(programId) {
    const tracking = getProgramTracking();
    return (tracking[programId]?.enrolled) || [];
}

function getProgramInterestedList(programId) {
    const tracking = getProgramTracking();
    return (tracking[programId]?.interested) || [];
}

function removeProgramEnrollment(programId, email) {
    const tracking = getProgramTracking();
    if (!tracking[programId]) return;
    tracking[programId].enrolled = tracking[programId].enrolled.filter(e => e.email !== email);
    saveProgramTracking(tracking);
}

function removeProgramInterest(programId, email) {
    const tracking = getProgramTracking();
    if (!tracking[programId]) return;
    tracking[programId].interested = tracking[programId].interested.filter(e => e.email !== email);
    saveProgramTracking(tracking);
}

function migrateProgramTracking() {
    const tracking = getProgramTracking();
    let changed = false;
    Object.keys(tracking).forEach(pid => {
        ['enrolled', 'interested'].forEach(list => {
            if (tracking[pid][list]) {
                tracking[pid][list] = tracking[pid][list].map(entry => {
                    if (entry.userName && !entry.name) { entry.name = entry.userName; delete entry.userName; changed = true; }
                    if (entry.userEmail && !entry.email) { entry.email = entry.userEmail; delete entry.userEmail; changed = true; }
                    return entry;
                });
            }
        });
    });
    if (changed) saveProgramTracking(tracking);
}
migrateProgramTracking();

// =============================================
// USER COURSE TRACKING (Local Storage)
// =============================================
function getUserCourses() {
    if (!currentUser) return [];
    const data = localStorage.getItem(`pwdta_user_${currentUser.email}_courses`);
    return data ? JSON.parse(data) : [];
}

function saveUserCourses(courses) {
    if (!currentUser) return;
    localStorage.setItem(`pwdta_user_${currentUser.email}_courses`, JSON.stringify(courses));
}

function addUserCourse(trainingId, status) {
    let courses = getUserCourses();
    const existingIndex = courses.findIndex(c => c.trainingId === trainingId);
    if (existingIndex !== -1) {
        courses[existingIndex].status = status;
    } else {
        courses.push({ trainingId, status });
    }
    saveUserCourses(courses);
}

// =============================================
// SHARED: Get all engagements of a trainee
// (Used by both public viewTraineeProfile and admin viewAdminTraineeDashboard)
// =============================================
function getTraineeAllEngagements(userEmail) {
    const tracking = getProgramTracking();
    const enrolled = [];
    const interested = [];

    Object.keys(tracking).forEach(pid => {
        const progId = parseInt(pid);
        const program = tracking[pid];
        const item = trainings.find(t => t.id === progId) || testings.find(t => t.id === progId);
        if (!item) return;
        const isTraining = !!trainings.find(t => t.id === progId);

        if (program.enrolled) {
            const entry = program.enrolled.find(e => e.email === userEmail);
            if (entry) {
                enrolled.push({ ...entry, programId: progId, programTitle: item.title, programType: isTraining ? 'training' : 'testing', programStatus: item.status || '-' });
            }
        }
        if (program.interested) {
            const entry = program.interested.find(e => e.email === userEmail);
            if (entry) {
                interested.push({ ...entry, programId: progId, programTitle: item.title, programType: isTraining ? 'training' : 'testing', programStatus: item.status || '-' });
            }
        }
    });
    return { enrolled, interested };
}

// =============================================
// SHARED: Move trainee from Interested to Enrolled
// (Used by both public and admin contexts)
// =============================================
function moveInterestToEnrollment(programId, userEmail) {
    const tracking = getProgramTracking();
    if (!tracking[programId]) return;

    const idx = tracking[programId].interested.findIndex(e => e.email === userEmail);
    if (idx === -1) return;

    const [entry] = tracking[programId].interested.splice(idx, 1);
    const existsInEnrolled = tracking[programId].enrolled.find(e => e.email === userEmail);
    if (!existsInEnrolled) {
        entry.date = new Date().toISOString();
        tracking[programId].enrolled.push(entry);
    }
    saveProgramTracking(tracking);
    showToast(currentLang === 'bn' ? 'সফলভাবে এনরোল করা হয়েছে!' : 'Successfully moved to Enrolled!', 'success');
}

// =============================================
// SHARED: Enroll Tab Switching & Search
// (Used by both public and admin enrollment modals)
// =============================================
function switchEnrollTab(tab, btn) {
    if (!btn) return;
    btn.parentElement.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    document.getElementById('enroll-tab-enrolled').style.display = tab === 'enrolled' ? 'block' : 'none';
    document.getElementById('enroll-tab-interested').style.display = tab === 'interested' ? 'block' : 'none';
    const searchInput = document.getElementById('enroll-search-input');
    if (searchInput) searchInput.value = '';
    document.querySelectorAll('.enroll-list-container > div').forEach(d => d.style.display = '');
}

function filterEnrollList(query) {
    if (!query) { document.querySelectorAll('.enroll-list-container > div').forEach(d => d.style.display = ''); return; }
    const q = query.toLowerCase();
    document.querySelectorAll('.enroll-list-container > div').forEach(d => {
        const text = d.textContent.toLowerCase();
        d.style.display = text.includes(q) ? '' : 'none';
    });
}

// =============================================
// SHARED: Toggle password visibility
// =============================================
function toggleLoginPass(inputId, icon) {
    const input = document.getElementById(inputId);
    if (!input || !icon) return;
    if (input.type === 'password') { input.type = 'text'; icon.classList.remove('fa-eye-slash'); icon.classList.add('fa-eye'); }
    else { input.type = 'password'; icon.classList.remove('fa-eye'); icon.classList.add('fa-eye-slash'); }
}

// =============================================
// PUBLIC PAGE RENDERERS
// =============================================
function renderHome() {
    const upcoming = trainings.filter(t => t.status === 'upcoming').slice(0, 3);
    const ongoing = trainings.filter(t => t.status === 'ongoing').slice(0, 3);
    const testingList = testings.slice(0, 3);
    const statsToShow = [
        { n: siteStats.trainings ?? trainings.length ?? 0, l: t('home_stats_trainings'), icon: 'fa-chalkboard-teacher', color: 'var(--primary)' },
        { n: siteStats.trainees ?? trainees.length ?? 0, l: t('home_stats_trainees'), icon: 'fa-user-graduate', color: 'var(--accent)' },
        { n: siteStats.testings ?? testings.length ?? 0, l: t('home_stats_tests'), icon: 'fa-flask', color: 'var(--success)' },
        { n: siteStats.facilities ?? facilities.length ?? 0, l: t('home_stats_facilities'), icon: 'fa-school', color: 'var(--warning)' }
    ];
    const statsHTML = statsToShow.map(s => `<div class="stat-card text-center"><div class="w-12 h-12 rounded-lg mx-auto mb-3 flex items-center justify-center" style="background:${s.color}15"><i class="fas ${s.icon} text-lg" style="color:${s.color}"></i></div><div class="text-2xl font-bold" style="color:${s.color}">${s.n}</div><div class="text-xs text-gray-500 mt-1">${s.l}</div></div>`).join('');

    let sliderHTML = '';
    if (sliders.length === 0) {
        sliderHTML = `<div class="slide active"><img src="https://picsum.photos/seed/pwdta/1200/400.jpg" alt="Default"><div class="slide-overlay"><div class="max-w-lg"><h1 class="text-3xl md:text-5xl font-bold text-white mb-4">${currentLang === 'bn' ? 'পিডব্লিউডি প্রশিক্ষণ একাডেমি' : 'PWD Training Academy'}</h1><p class="text-white/70 mb-6 text-sm">${currentLang === 'bn' ? 'জাতির অবকাঠামোর জন্য সক্ষমতা বিনির্মাণ' : "Building Capacity for Nation's Infrastructure"}</p></div></div></div>`;
    } else {
        sliderHTML = sliders.map((s, i) => `<div class="slide ${i === 0 ? 'active' : ''}"><img src="${escAttr(s.img)}" alt="${escAttr(s.title || '')}"><div class="slide-overlay"><div class="max-w-lg">${s.title ? `<h1 class="text-3xl md:text-5xl font-bold text-white mb-4 leading-tight">${escAttr(s.title)}</h1>` : ''}${s.subtitle ? `<p class="text-white/70 mb-6 text-sm">${escAttr(s.subtitle)}</p>` : ''}<div class="flex gap-3">${s.btnText ? `<button class="btn-accent" onclick="navigate('${escAttr(s.btnLink || 'trainings')}')">${escAttr(s.btnText)}</button>` : ''}<button class="btn-outline" style="color:#fff;border-color:rgba(255,255,255,.4)" onclick="navigate('trainings')">${t('home_explore')}</button></div></div></div></div>`).join('');
    }
    let dotsHTML = sliders.length > 1 ? sliders.map((_, i) => `<button class="slider-dot ${i === 0 ? 'active' : ''}" onclick="goSlide(${i})"></button>`).join('') : '';

    return `<div class="slider-container mb-10">${sliderHTML}${dotsHTML ? `<div style="position:absolute;bottom:24px;left:50%;transform:translateX(-50%);display:flex;gap:6px;z-index:10">${dotsHTML}</div>` : ''}${sliders.length > 1 ? `<button onclick="prevSlide()" style="position:absolute;left:16px;top:50%;transform:translateY(-50%);background:rgba(255,255,255,.9);border:none;color:var(--primary);width:40px;height:40px;border-radius:50%;cursor:pointer;z-index:10"><i class="fas fa-chevron-left"></i></button><button onclick="nextSlide()" style="position:absolute;right:16px;top:50%;transform:translateY(-50%);background:rgba(255,255,255,.9);border:none;color:var(--primary);width:40px;height:40px;border-radius:50%;cursor:pointer;z-index:10"><i class="fas fa-chevron-right"></i></button>` : ''}</div>

<div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-12">${statsHTML}</div>

<div class="mb-12"><div class="flex items-center justify-between mb-6"><h2 class="text-xl font-bold">${t('home_programs_title')}</h2><div class="flex gap-1"><button class="tab-btn active" onclick="filterPrograms('all',this)">${t('home_programs_all')}</button><button class="tab-btn" onclick="filterPrograms('training',this)">${t('home_programs_training')}</button><button class="tab-btn" onclick="filterPrograms('testing',this)">${t('home_programs_testing')}</button></div></div><div class="grid md:grid-cols-2 lg:grid-cols-3 gap-4" id="programs-list">${ongoing.map(t_item => renderProgramCard(t_item, 'training')).join('')}${upcoming.map(t_item => renderProgramCard(t_item, 'training')).join('')}${testingList.map(t_item => renderProgramCard(t_item, 'testing')).join('')}</div><div class="text-center mt-6"><button class="btn-outline" onclick="navigate('trainings')">${t('home_view_all')}</button></div></div>

 ${renderMiniCalendar()}

 ${galleryItems.length > 0 ? `<div class="mb-12"><h2 class="text-xl font-bold mb-6">${t('home_gallery_title')}</h2><div class="grid grid-cols-2 md:grid-cols-4 gap-4">${galleryItems.slice(0, 4).map((g, gi) => `<div class="rounded-lg overflow-hidden cursor-pointer group" onclick="openLightbox('${escAttr(g.img)}')"><img src="${escAttr(g.img)}" class="w-full h-48 object-cover group-hover:scale-105 transition duration-300"></div>`).join('')}</div><div class="text-center mt-4"><button class="btn-outline" onclick="navigate('photogallery')">${t('home_view_all_gallery')}</button></div></div>` : ''}

<div class="mb-12"><h2 class="text-xl font-bold mb-6">${t('home_location_title')}</h2><div class="rounded-lg overflow-hidden" style="border:1px solid var(--border)"><iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3652.2637350037844!2d90.37907431498192!3d23.73939698458857!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x3755b9004a4cfb75%3A0x2cf43dd7d1a2f3c2!2sSher-e-Bangla%20Nagar%2C%20Dhaka!5e0!3m2!1sen!2sbd!4v1680000000000" width="100%" height="350" style="border:0" allowfullscreen loading="lazy"></iframe></div></div>

<div class="p-8 rounded-xl" style="background:linear-gradient(135deg,var(--primary),var(--primary-light));color:#fff"><div class="flex flex-col md:flex-row items-center justify-between gap-4"><div><h3 class="text-lg font-bold mb-2"><i class="fas fa-calendar-alt mr-2 text-cyan-300"></i>${t('home_stay_updated')}</h3><p class="text-sm opacity-70">${t('home_stay_updated_desc')}</p></div><div class="flex gap-3"><button class="btn-accent" onclick="navigate('trainings')">${t('home_view_calendar')}</button><button class="btn-outline" style="color:#fff;border-color:rgba(255,255,255,.4)" onclick="navigate('register')">${t('home_register')}</button></div></div></div>`;
}
// =============================================
// PROGRAM CARD RENDERER (Properly Closed)
// =============================================
function renderProgramCard(item, type) {
    const isTraining = type === 'training';
    const isOngoing = isTraining && item.status === 'ongoing';
    const isUpcoming = isTraining && item.status === 'upcoming';
    const isCompleted = isTraining && item.status === 'completed';
    const imgSrc = item.img ? escAttr(item.img) : getDefaultThumbSVG(type === 'testing' ? 'equipment' : 'training');
    const bn = currentLang === 'bn';

    const programId = item.id ?? 0;
    const stats = getProgramStats(programId);

    const statsHTML = `<div class="flex items-center gap-2 mb-2 mt-1">
        <button type="button" onclick="viewPublicProgramEnrollments(${programId},'${type}')" class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] font-semibold transition-all hover:scale-105 active:scale-95 cursor-pointer" style="background:#ecfdf5;color:#059669;border:1px solid #a7f3d0" title="${bn ? 'নিবন্ধিত প্রশিক্ষণার্থী দেখুন' : 'View Enrolled Trainees'}">
            <i class="fas fa-user-check text-[10px]"></i><span>${stats.enrolledCount}</span><span class="hidden sm:inline">${bn ? 'নিবন্ধিত' : 'Enrolled'}</span>
        </button>
        <button type="button" onclick="viewPublicProgramEnrollments(${programId},'${type}')" class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] font-semibold transition-all hover:scale-105 active:scale-95 cursor-pointer" style="background:#fef2f2;color:#dc2626;border:1px solid #fecaca" title="${bn ? 'আগ্রহী প্রশিক্ষণার্থী দেখুন' : 'View Interested Trainees'}">
            <i class="far fa-heart text-[10px]"></i><span>${stats.interestedCount}</span><span class="hidden sm:inline">${bn ? 'আগ্রহী' : 'Interested'}</span>
        </button>
    </div>`;

    let actionButtons = '';
    if (isOngoing) actionButtons = `<button class="btn-primary btn-sm flex-1" onclick="openEnrollModal(${item.id ?? 0},'${type}')"><i class="fas fa-user-plus mr-1"></i>${t('home_enroll_now')}</button>`;
    else if (isUpcoming) actionButtons = `<button class="btn-outline btn-sm flex-1" onclick="registerInterest(${item.id ?? 0})"><i class="far fa-heart mr-1"></i>${t('interest_btn')}</button>`;
    else if (isCompleted) actionButtons = `<span class="text-xs text-gray-400 flex items-center justify-center gap-1 w-full"><i class="fas fa-check-circle text-green-500"></i>${bn ? 'সম্পন্ন' : 'Completed'}</span>`;
    else if (type === 'testing') actionButtons = `<button class="btn-primary btn-sm flex-1" onclick="openEnrollModal(${item.id ?? 0},'${type}')"><i class="fas fa-user-plus mr-1"></i>${bn ? 'নিবন্ধন' : 'Enroll'}</button><button class="btn-outline btn-sm flex-1" onclick="registerInterest(${item.id ?? 0})"><i class="far fa-heart mr-1"></i>${t('interest_btn')}</button>`;

    return `<div class="program-card" data-type="${type}" data-status="${isTraining ? (item.status || '') : 'testing'}"><div class="card"><img src="${imgSrc}" class="w-full h-40 object-cover" alt="${escAttr(item.title)}" onerror="handleImgError(this,'${type === 'testing' ? 'equipment' : 'training'}','')"><div class="p-4"><div class="flex items-center gap-2 mb-2"><span class="badge ${isTraining ? (item.status === 'ongoing' ? 'badge-success' : item.status === 'upcoming' ? 'badge-info' : 'badge-warning') : 'badge-info'}">${isTraining ? escAttr(item.status) : escAttr(item.testType)}</span><span class="badge badge-warning">${isTraining ? escAttr(item.category) : escAttr(item.turnaround)}</span></div><h3 class="font-semibold text-sm mb-1">${escAttr(item.title)}</h3>${statsHTML}<p class="text-xs text-gray-500 leading-relaxed mb-3 line-clamp-2">${escAttr(item.desc || '')}</p><div class="flex items-center text-xs text-gray-400 mb-3"><span>${isTraining ? (item.start || '') : escAttr(item.turnaround || '')}</span></div><div class="flex gap-2">${actionButtons}</div></div></div></div>`;
}

// =============================================
// PUBLIC: View Program Enrollment & Interest
// =============================================
function viewPublicProgramEnrollments(programId, type) {
    const item = type === 'training'
        ? trainings.find(t => t.id === programId)
        : testings.find(t => t.id === programId);
    if (!item) { showToast('Program not found', 'error'); return; }

    const bn = currentLang === 'bn';
    const enrolledList = getProgramEnrolledList(programId);
    const interestedList = getProgramInterestedList(programId);
    const modalImgSrc = item.img ? escAttr(item.img) : getDefaultThumbSVG(type === 'testing' ? 'equipment' : 'training');

    const profileCard = (entry, index, listType) => {
        const initial = (entry.name || 'U').charAt(0).toUpperCase();
        const colors = ['#059669', '#0d6efd', '#7c3aed', '#d97706', '#dc2626', '#0891b2'];
        const color = colors[index % colors.length];
        const borderColor = listType === 'enrolled' ? '#059669' : '#dc2626';
        const dateStr = entry.date ? new Date(entry.date).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' }) : '-';
        const timeStr = entry.date ? new Date(entry.date).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' }) : '';
        const statusBadge = listType === 'enrolled'
            ? `<span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[9px] font-bold bg-green-100 text-green-700"><i class="fas fa-user-check text-[8px]"></i>${bn ? 'নিবন্ধিত' : 'Enrolled'}</span>`
            : `<span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[9px] font-bold bg-red-100 text-red-600"><i class="far fa-heart text-[8px]"></i>${bn ? 'আগ্রহী' : 'Interested'}</span>`;
        const safeEmail = escAttr(entry.email || '');

        return `<div class="flex items-start gap-3 p-3 rounded-xl border-l-4 transition-all hover:shadow-md cursor-pointer group" style="border-left-color:${borderColor}; background:var(--card); border-top:1px solid var(--border); border-right:1px solid var(--border); border-bottom:1px solid var(--border)" onclick="viewTraineeProfile('${safeEmail}', ${programId}, '${type}', '${listType}')">
            <div class="w-12 h-12 rounded-full flex items-center justify-center shrink-0 text-base font-bold text-white shadow-md" style="background:linear-gradient(135deg,${color},${color}cc)">${initial}</div>
            <div class="flex-1 min-w-0">
                <div class="flex items-center justify-between gap-2 mb-1"><span class="font-semibold text-sm text-gray-800 truncate">${escAttr(entry.name || '-')}</span>${statusBadge}</div>
                ${entry.designation ? `<div class="text-xs text-gray-600 flex items-center gap-1.5 mb-0.5"><i class="fas fa-briefcase text-[9px] text-gray-400 w-3 text-center"></i><span class="truncate">${escAttr(entry.designation)}</span></div>` : ''}
                ${entry.org ? `<div class="text-xs text-gray-500 flex items-center gap-1.5 mb-1.5"><i class="fas fa-building text-[9px] text-gray-400 w-3 text-center"></i><span class="truncate">${escAttr(entry.org)}</span></div>` : ''}
                <div class="flex flex-wrap items-center gap-2 mt-1">
                    ${entry.email ? `<span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-[10px] font-medium text-blue-700 bg-blue-50"><i class="fas fa-envelope text-[8px]"></i><span class="truncate">${escAttr(entry.email)}</span></span>` : ''}
                    ${entry.phone ? `<span class="inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-[10px] font-medium text-green-700 bg-green-50"><i class="fas fa-phone text-[8px]"></i>${escAttr(entry.phone)}</span>` : ''}
                </div>
            </div>
            <div class="flex flex-col items-end justify-between h-full shrink-0 mt-1">
                <div class="text-[10px] text-gray-400 text-right leading-tight"><div>${dateStr}</div>${timeStr ? `<div class="text-[9px]">${timeStr}</div>` : ''}</div>
                <i class="fas fa-chevron-right text-[10px] text-gray-300 group-hover:text-gray-500 transition mt-2"></i>
            </div>
        </div>`;
    };

    const enrolledHTML = enrolledList.length > 0
        ? enrolledList.map((e, i) => profileCard(e, i, 'enrolled')).join('')
        : `<div class="text-center py-10"><div class="w-20 h-20 rounded-full mx-auto mb-4 flex items-center justify-center" style="background:#ecfdf5"><i class="fas fa-user-slash text-3xl text-green-300"></i></div><p class="text-sm font-medium text-gray-500">${bn ? 'কোনো নিবন্ধিত প্রশিক্ষণার্থী নেই' : 'No enrolled trainees yet'}</p></div>`;

    const interestedHTML = interestedList.length > 0
        ? interestedList.map((e, i) => profileCard(e, i, 'interested')).join('')
        : `<div class="text-center py-10"><div class="w-20 h-20 rounded-full mx-auto mb-4 flex items-center justify-center" style="background:#fef2f2"><i class="far fa-heart text-3xl text-red-300"></i></div><p class="text-sm font-medium text-gray-500">${bn ? 'কোনো আগ্রহী প্রশিক্ষণার্থী নেই' : 'No interested trainees yet'}</p></div>`;

    openModal(`
        <div class="relative">
            <div class="relative h-32 overflow-hidden rounded-t-xl">
                <img src="${modalImgSrc}" class="w-full h-full object-cover" alt="${escAttr(item.title)}" onerror="handleImgError(this,'${type === 'testing' ? 'equipment' : 'training'}','')">
                <div class="absolute inset-0" style="background:linear-gradient(to top, rgba(0,0,0,0.7), rgba(0,0,0,0.1))"></div>
                <button onclick="closeModal()" class="absolute top-3 right-3 w-8 h-8 rounded-full bg-black/30 backdrop-blur-sm text-white flex items-center justify-center hover:bg-black/50 transition cursor-pointer"><i class="fas fa-times text-sm"></i></button>
                <div class="absolute bottom-3 left-4 right-12">
                    <div class="flex items-center gap-2 mb-1">
                        <span class="badge ${type === 'training' ? 'badge-info' : 'badge-warning'}" style="font-size:9px">${type === 'training' ? (bn ? 'প্রশিক্ষণ' : 'Training') : (bn ? 'পরীক্ষা' : 'Testing')}</span>
                        ${type === 'training' && item.status ? `<span class="badge ${item.status === 'ongoing' ? 'badge-success' : item.status === 'upcoming' ? 'badge-info' : 'badge-warning'}" style="font-size:9px">${escAttr(item.status)}</span>` : ''}
                    </div>
                    <h3 class="font-bold text-white text-base leading-tight truncate">${escAttr(item.title)}</h3>
                </div>
            </div>
            <div class="flex items-center gap-4 px-4 py-2.5 border-b" style="border-color:var(--border);background:var(--card)">
                ${item.start ? `<div class="flex items-center gap-1.5 text-xs text-gray-600"><i class="far fa-calendar-alt text-blue-500"></i>${escAttr(item.start)}${item.end ? ` — ${escAttr(item.end)}` : ''}</div>` : ''}
            </div>
        </div>
        <div class="p-5">
            <div class="grid grid-cols-2 gap-3 mb-5">
                <div class="p-4 rounded-xl text-center cursor-pointer transition-all hover:scale-[1.02] active:scale-[0.98] shadow-sm" style="background:linear-gradient(135deg,#ecfdf5,#d1fae5);border:1.5px solid #6ee7b7" onclick="switchEnrollTab('enrolled',document.querySelector('#enroll-tab-btn-enrolled'))">
                    <div class="w-10 h-10 rounded-full mx-auto mb-2 flex items-center justify-center" style="background:#05966920"><i class="fas fa-user-check text-green-600"></i></div>
                    <div class="text-2xl font-bold text-green-700">${enrolledList.length}</div>
                    <div class="text-[10px] text-green-600 mt-0.5 font-semibold">${bn ? 'নিবন্ধিত' : 'Enrolled'}</div>
                </div>
                <div class="p-4 rounded-xl text-center cursor-pointer transition-all hover:scale-[1.02] active:scale-[0.98] shadow-sm" style="background:linear-gradient(135deg,#fef2f2,#fecaca);border:1.5px solid #fca5a5" onclick="switchEnrollTab('interested',document.querySelector('#enroll-tab-btn-interested'))">
                    <div class="w-10 h-10 rounded-full mx-auto mb-2 flex items-center justify-center" style="background:#dc262620"><i class="fas fa-heart text-red-500"></i></div>
                    <div class="text-2xl font-bold text-red-700">${interestedList.length}</div>
                    <div class="text-[10px] text-red-600 mt-0.5 font-semibold">${bn ? 'আগ্রহী' : 'Interested'}</div>
                </div>
            </div>
            <div class="mb-4 relative">
                <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-xs"></i>
                <input type="text" id="enroll-search-input" placeholder="${bn ? 'নাম, পদবি বা ইমেইল দিয়ে খুঁজুন...' : 'Search by name, designation or email...'}" class="w-full pl-9 pr-4 py-2 rounded-lg border text-sm focus:ring-2 focus:ring-blue-400 focus:border-blue-400 transition" style="border-color:var(--border)" oninput="filterEnrollList(this.value)">
            </div>
            <div class="flex gap-1 mb-4" style="border-bottom:2px solid var(--border)">
                <button id="enroll-tab-btn-enrolled" class="tab-btn active" onclick="switchEnrollTab('enrolled',this)"><i class="fas fa-user-check mr-1 text-green-500"></i>${bn ? 'নিবন্ধিত' : 'Enrolled'} (${enrolledList.length})</button>
                <button id="enroll-tab-btn-interested" class="tab-btn" onclick="switchEnrollTab('interested',this)"><i class="fas fa-heart mr-1 text-red-400"></i>${bn ? 'আগ্রহী' : 'Interested'} (${interestedList.length})</button>
            </div>
            <div class="text-xs text-gray-400 mb-2 flex items-center gap-1"><i class="fas fa-info-circle"></i> ${bn ? 'বিস্তারিত দেখতে প্রোফাইলে ক্লিক করুন' : 'Click on a profile to view details'}</div>
            <div id="enroll-tab-enrolled" class="space-y-2 max-h-80 overflow-y-auto enroll-list-container">${enrolledHTML}</div>
            <div id="enroll-tab-interested" class="space-y-2 max-h-80 overflow-y-auto enroll-list-container" style="display:none">${interestedHTML}</div>
        </div>
    `);
}

// =============================================
// PUBLIC: View Detailed Trainee Profile
// =============================================
function viewTraineeProfile(userEmail, programId, programType, listType) {
    const bn = currentLang === 'bn';
    const safeEmail = escAttr(userEmail);

    const currentList = listType === 'enrolled' ? getProgramEnrolledList(programId) : getProgramInterestedList(programId);
    const currentEntry = currentList.find(e => e.email === userEmail);
    if (!currentEntry) { showToast('Profile data not found', 'error'); return; }

    const allEngagements = getTraineeAllEngagements(userEmail);
    const initial = (currentEntry.name || 'U').charAt(0).toUpperCase();
    const colors = ['#059669', '#0d6efd', '#7c3aed', '#d97706', '#dc2626', '#0891b2'];
    const color = colors[(currentEntry.name || 'A').charCodeAt(0) % colors.length];

    const dateStr = currentEntry.date ? new Date(currentEntry.date).toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' }) : '-';
    const timeStr = currentEntry.date ? new Date(currentEntry.date).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' }) : '';

    const renderEngagementItem = (eng, type) => {
        const isEnrolled = type === 'enrolled';
        return `<div class="flex items-center gap-3 p-2.5 rounded-lg" style="background:var(--bg); border:1px solid var(--border)">
            <div class="w-8 h-8 rounded-lg flex items-center justify-center shrink-0" style="background:${isEnrolled ? '#ecfdf5' : '#fef2f2'}">
                <i class="fas ${isEnrolled ? 'fa-user-check text-green-600' : 'fa-heart text-red-500'} text-xs"></i>
            </div>
            <div class="flex-1 min-w-0">
                <div class="text-xs font-semibold text-gray-800 truncate">${escAttr(eng.programTitle)}</div>
                <div class="flex items-center gap-2 mt-0.5">
                    <span class="badge ${eng.programType === 'training' ? 'badge-info' : 'badge-warning'}" style="font-size:8px">${eng.programType === 'training' ? (bn ? 'প্রশিক্ষণ' : 'Training') : (bn ? 'পরীক্ষা' : 'Testing')}</span>
                </div>
            </div>
        </div>`;
    };

    const enrolledListHTML = allEngagements.enrolled.length > 0
        ? allEngagements.enrolled.map(e => renderEngagementItem(e, 'enrolled')).join('')
        : `<p class="text-xs text-gray-400 text-center py-2">${bn ? 'অন্য কোনো কোর্সে নিবন্ধিত নন' : 'Not enrolled in other courses'}</p>`;

    const interestedListHTML = allEngagements.interested.length > 0
        ? allEngagements.interested.map(e => renderEngagementItem(e, 'interested')).join('')
        : `<p class="text-xs text-gray-400 text-center py-2">${bn ? 'অন্য কোনো কোর্সে আগ্রহী নন' : 'Not interested in other courses'}</p>`;

    openModal(`
        <div class="p-5 border-b" style="border-color:var(--border)">
            <div class="flex items-center gap-3 mb-5">
                <button onclick="viewPublicProgramEnrollments(${programId},'${programType}')" class="w-8 h-8 rounded-lg flex items-center justify-center hover:bg-gray-100 transition cursor-pointer" style="border:1px solid var(--border); background:var(--card)"><i class="fas fa-arrow-left text-xs"></i></button>
                <h3 class="font-semibold text-base">${bn ? 'প্রশিক্ষণার্থী প্রোফাইল' : 'Trainee Profile'}</h3>
            </div>
            <div class="flex flex-col items-center text-center">
                <div class="w-20 h-20 rounded-full flex items-center justify-center text-2xl font-bold text-white shadow-lg mb-3" style="background:linear-gradient(135deg,${color},${color}cc)">${initial}</div>
                <h2 class="text-lg font-bold text-gray-800">${escAttr(currentEntry.name || '-')}</h2>
                ${currentEntry.designation ? `<div class="text-sm text-gray-600 mt-1 flex items-center gap-1.5"><i class="fas fa-briefcase text-gray-400 text-xs"></i>${escAttr(currentEntry.designation)}</div>` : ''}
                ${currentEntry.org ? `<div class="text-sm text-gray-500 mt-0.5 flex items-center gap-1.5"><i class="fas fa-building text-gray-400 text-xs"></i>${escAttr(currentEntry.org)}</div>` : ''}
            </div>
        </div>
        <div class="p-5 space-y-5">
            <div>
                <h4 class="text-xs font-bold text-gray-500 uppercase tracking-wider mb-3 flex items-center gap-2"><i class="fas fa-address-card text-blue-500"></i> ${bn ? 'যোগাযোগের তথ্য' : 'Contact Information'}</h4>
                <div class="grid grid-cols-1 gap-2">
                    ${currentEntry.email ? `<div class="flex items-center gap-3 p-3 rounded-lg" style="background:var(--bg); border:1px solid var(--border)"><div class="w-9 h-9 rounded-lg flex items-center justify-center bg-blue-100 shrink-0"><i class="fas fa-envelope text-blue-600 text-sm"></i></div><div class="min-w-0"><div class="text-[10px] text-gray-400">${bn ? 'ইমেইল' : 'Email'}</div><a href="mailto:${safeEmail}" class="text-sm font-medium text-blue-600 hover:underline truncate block">${safeEmail}</a></div></div>` : ''}
                    ${currentEntry.phone ? `<div class="flex items-center gap-3 p-3 rounded-lg" style="background:var(--bg); border:1px solid var(--border)"><div class="w-9 h-9 rounded-lg flex items-center justify-center bg-green-100 shrink-0"><i class="fas fa-phone text-green-600 text-sm"></i></div><div class="min-w-0"><div class="text-[10px] text-gray-400">${bn ? 'ফোন' : 'Phone'}</div><a href="tel:${escAttr(currentEntry.phone)}" class="text-sm font-medium text-green-600 hover:underline">${escAttr(currentEntry.phone)}</a></div></div>` : ''}
                    <div class="flex items-center gap-3 p-3 rounded-lg" style="background:var(--bg); border:1px solid var(--border)">
                        <div class="w-9 h-9 rounded-lg flex items-center justify-center bg-purple-100 shrink-0"><i class="fas fa-clock text-purple-600 text-sm"></i></div>
                        <div class="min-w-0"><div class="text-[10px] text-gray-400">${listType === 'enrolled' ? (bn ? 'নিবন্ধনের তারিখ' : 'Enrolled Date') : (bn ? 'আগ্রহ দেখানোর তারিখ' : 'Interested Date')}</div><div class="text-sm font-medium text-gray-800">${dateStr} ${timeStr}</div></div>
                    </div>
                </div>
            </div>
            <div>
                <h4 class="text-xs font-bold text-gray-500 uppercase tracking-wider mb-3 flex items-center gap-2"><i class="fas fa-history text-orange-500"></i> ${bn ? 'অন্যান্য এনগেজমেন্ট' : 'Other Engagements'}</h4>
                <div class="mb-3">
                    <div class="text-xs font-semibold text-green-700 mb-2 flex items-center gap-1"><i class="fas fa-user-check text-[10px]"></i> ${bn ? 'নিবন্ধিত কোর্সসমূহ' : 'Enrolled Courses'} (${allEngagements.enrolled.length})</div>
                    <div class="space-y-1.5">${enrolledListHTML}</div>
                </div>
                <div>
                    <div class="text-xs font-semibold text-red-600 mb-2 flex items-center gap-1"><i class="far fa-heart text-[10px]"></i> ${bn ? 'আগ্রহী কোর্সসমূহ' : 'Interested Courses'} (${allEngagements.interested.length})</div>
                    <div class="space-y-1.5">${interestedListHTML}</div>
                </div>
            </div>
        </div>
    `);
}

function registerInterest(id) {
    if (!currentUser) {
        showToast(currentLang === 'bn' ? 'আগ্রহ নিবন্ধন করতে লগইন করুন' : 'Please login to register interest', 'error');
        navigate('login');
        return;
    }
    addUserCourse(id, 'interested');
    addProgramInterest(id, currentUser);
    showToast(t('interest_registered'), 'success');
    renderPage();
}

function filterPrograms(type, btn) {
    document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    document.querySelectorAll('.program-card').forEach(c => {
        c.style.display = (type === 'all' || c.dataset.type === type) ? 'block' : 'none';
    });
}
function renderMiniCalendar() {
    const now = new Date();
    const year = window.calendarYear ?? now.getFullYear();
    const month = window.calendarMonth ?? now.getMonth();
    const monthNames = currentLang === 'bn' ? ["জানুয়ারি", "ফেব্রুয়ারি", "মার্চ", "এপ্রিল", "মে", "জুন", "জুলাই", "আগস্ট", "সেপ্টেম্বর", "অক্টোবর", "নভেম্বর", "ডিসেম্বর"] : ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    const dayNames = currentLang === 'bn' ? ['সোম', 'মঙ্গল', 'বুধ', 'বৃহঃ', 'শুক্র', 'শনি', 'রবি'] : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
    const firstDayOfMonth = new Date(year, month, 1);
    const daysInMonth = new Date(year, month + 1, 0).getDate();
    let startDay = firstDayOfMonth.getDay();
    let offset = (startDay + 6) % 7;
    const todayDate = now.getDate(), todayMonth = now.getMonth(), todayYear = now.getFullYear();
    const events = {};
    trainings.forEach(tr => {
        if (tr.start) {
            let d;
            if (typeof tr.start === 'string' && tr.start.includes('-')) {
                const parts = tr.start.split('-');
                d = new Date(parseInt(parts[0]), parseInt(parts[1]) - 1, parseInt(parts[2]));
            } else { d = new Date(tr.start); }
            if (!isNaN(d.getTime()) && d.getMonth() === month && d.getFullYear() === year) {
                const day = d.getDate();
                if (!events[day]) events[day] = [];
                events[day].push(tr.title);
            }
        }
    });
    let calendarDays = '';
    for (let i = 0; i < offset; i++) calendarDays += `<div class="calendar-day" style="background:transparent;cursor:default;"></div>`;
    for (let day = 1; day <= daysInMonth; day++) {
        const hasEvent = events[day];
        const isToday = (day === todayDate && month === todayMonth && year === todayYear);
        let clickAttr = hasEvent ? `data-cal-event="${escAttr(events[day][0])}" onclick="showToast(this.dataset.calEvent,'info')"` : '';
        calendarDays += `<div class="calendar-day ${hasEvent ? 'has-event' : ''} ${isToday ? 'today' : ''}" ${clickAttr}>${day}</div>`;
    }
    let eventListHTML = '';
    const eventDays = Object.keys(events).sort((a, b) => a - b);
    if (eventDays.length > 0) {
        eventListHTML = `<div class="mt-4 space-y-2">${eventDays.map(day => events[day].map(ev => `<div class="flex items-center gap-3 text-xs p-2 rounded" style="background:var(--primary-glow)"><div class="w-7 h-7 rounded flex items-center justify-center shrink-0 font-bold text-white" style="background:var(--primary);font-size:10px">${day}</div><div class="font-medium" style="color:var(--primary)">${escAttr(ev)}</div></div>`).join('')).join('')}</div>`;
    } else {
        eventListHTML = `<div class="text-center text-xs text-gray-400 mt-4">${t('calendar_no_events')}</div>`;
    }
    const prevMonth = month === 0 ? 11 : month - 1, prevYear = month === 0 ? year - 1 : year;
    const nextMonth = month === 11 ? 0 : month + 1, nextYear = month === 11 ? year + 1 : year;
    const isCurrentMonth = (month === todayMonth && year === todayYear);
    return `<div class="mb-12"><div class="flex items-center justify-between mb-4"><h2 class="text-xl font-bold">${t('calendar_title')}</h2><button class="btn-outline btn-sm" onclick="openYearCalendarModal()">${t('calendar_view_full')}</button></div><div class="card p-5"><div class="flex items-center justify-between mb-4"><button onclick="window.calendarMonth=${prevMonth};window.calendarYear=${prevYear};refreshCalendar()" class="w-8 h-8 rounded-lg flex items-center justify-center hover:bg-gray-100 transition" style="border:1px solid var(--border);background:var(--card)"><i class="fas fa-chevron-left text-xs"></i></button><div class="text-center"><div class="font-semibold">${monthNames[month]} ${year}</div>${!isCurrentMonth ? `<button onclick="window.calendarMonth=${todayMonth};window.calendarYear=${todayYear};refreshCalendar()" class="text-xs text-cyan-600 hover:underline mt-1">${currentLang === 'bn' ? 'আজ যান' : 'Go to Today'}</button>` : ''}</div><button onclick="window.calendarMonth=${nextMonth};window.calendarYear=${nextYear};refreshCalendar()" class="w-8 h-8 rounded-lg flex items-center justify-center hover:bg-gray-100 transition" style="border:1px solid var(--border);background:var(--card)"><i class="fas fa-chevron-right text-xs"></i></button></div><div class="calendar-grid">${dayNames.map(d => `<div class="calendar-day-name">${d}</div>`).join('')}${calendarDays}</div>${eventListHTML}</div></div>`;
}

function refreshCalendar() { if (currentPage === 'home') renderPage(); }

function openYearCalendarModal() {
    const year = window.calendarYear ?? new Date().getFullYear();
    const monthNames = currentLang === 'bn' ? ["জানুয়ারি", "ফেব্রুয়ারি", "মার্চ", "এপ্রিল", "মে", "জুন", "জুলাই", "আগস্ট", "সেপ্টেম্বর", "অক্টোবর", "নভেম্বর", "ডিসেম্বর"] : ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    const byMonth = {};
    trainings.forEach(tr => {
        if (tr.start) {
            let d;
            if (typeof tr.start === 'string' && tr.start.includes('-')) { const parts = tr.start.split('-'); d = new Date(parseInt(parts[0]), parseInt(parts[1]) - 1, parseInt(parts[2])); } else { d = new Date(tr.start); }
            if (!isNaN(d.getTime()) && d.getFullYear() === year) { const m = d.getMonth(); if (!byMonth[m]) byMonth[m] = []; byMonth[m].push(tr); }
        }
    });
    const content = Object.keys(byMonth).sort().map(m => `<div class="mb-4"><h4 class="font-semibold text-sm mb-2" style="color:var(--primary)">${monthNames[m]}</h4><div class="space-y-2">${byMonth[m].map(tr => `<div class="flex items-center gap-3 text-xs p-2 rounded" style="background:var(--bg)"><div style="min-width:60px">${escAttr(tr.start)}</div><div class="font-medium">${escAttr(tr.title)}</div></div>`).join('')}</div></div>`).join('') || `<div class="text-center text-gray-400 py-8">${t('trainings_no_trainings')}</div>`;
    openModal(`<div class="p-5 border-b flex items-center justify-between" style="border-color:var(--border)"><h3 class="font-semibold">${t('calendar_year_view')} ${year}</h3><button onclick="closeModal()" class="text-gray-400 hover:text-gray-600 cursor-pointer"><i class="fas fa-times"></i></button></div><div class="p-5 max-h-96 overflow-y-auto">${content}</div>`);
}

function renderVision() {
    return pageHeader(t('about_vision_title'), t('nav_about'), `<div class="grid md:grid-cols-2 gap-6"><div class="p-6 rounded-xl" style="background:var(--primary-glow);border-left:4px solid var(--primary)"><div class="w-10 h-10 rounded-lg flex items-center justify-center mb-4" style="background:var(--primary)"><i class="fas fa-eye text-white"></i></div><h3 class="text-lg font-bold mb-3">${t('about_vision_title')}</h3><p class="text-sm text-gray-600 leading-relaxed">${t('about_vision_text')}</p></div><div class="p-6 rounded-xl" style="background:var(--accent-glow);border-left:4px solid var(--accent)"><div class="w-10 h-10 rounded-lg flex items-center justify-center mb-4" style="background:var(--accent)"><i class="fas fa-bullseye text-white"></i></div><h3 class="text-lg font-bold mb-3">${t('about_mission_title')}</h3><ul class="text-sm text-gray-600 leading-relaxed space-y-2"><li class="flex items-start gap-2"><i class="fas fa-check-circle mt-1 text-green-500 text-xs"></i>${t('about_mission_1')}</li><li class="flex items-start gap-2"><i class="fas fa-check-circle mt-1 text-green-500 text-xs"></i>${t('about_mission_2')}</li><li class="flex items-start gap-2"><i class="fas fa-check-circle mt-1 text-green-500 text-xs"></i>${t('about_mission_3')}</li><li class="flex items-start gap-2"><i class="fas fa-check-circle mt-1 text-green-500 text-xs"></i>${t('about_mission_4')}</li></ul></div></div>`);
}

function renderManagement() {
    return pageHeader(t('about_management_title'), t('nav_about'), `<div class="management-wrapper">${officers.sort((a, b) => (a.display_order || 0) - (b.display_order || 0)).map(o => {
        const imgSrc = o.img ? escAttr(o.img) : getDefaultPersonSVG(o.name);
        return `<div class="management-card"><div class="management-image"><img src="${imgSrc}" alt="${escAttr(o.name || '')}" onerror="handleImgError(this,'person','')"></div><div class="management-content"><h2 class="management-name">${escAttr(o.name || '')}</h2><div class="management-designation">${escAttr(o.designation || '')}</div>${o.office ? `<div class="management-office">${escAttr(o.office)}</div>` : ''}${o.phone ? `<div class="management-line"><i class="fas fa-phone-alt"></i>${escAttr(o.phone)}</div>` : ''}${o.mobile ? `<div class="management-line"><i class="fas fa-mobile-alt"></i>${escAttr(o.mobile)}</div>` : ''}${o.email ? `<div class="management-line"><i class="fas fa-envelope"></i>${escAttr(o.email)}</div>` : ''}</div></div>`;
    }).join('')}</div><style>.management-wrapper{display:flex;flex-direction:column;gap:16px}.management-card{display:flex;align-items:center;gap:18px;padding:18px;background:#fff;border-radius:18px;border:1px solid rgba(0,0,0,0.06);box-shadow:0 5px 18px rgba(0,0,0,0.06);transition:.3s}.management-card:hover{transform:translateY(-3px);box-shadow:0 10px 24px rgba(0,45,94,0.12)}.management-image{flex-shrink:0}.management-image img{width:95px;height:95px;border-radius:16px;object-fit:cover;border:3px solid #fff;box-shadow:0 4px 12px rgba(0,0,0,0.10)}.management-content{flex:1;min-width:0}.management-name{font-size:20px;font-weight:700;color:#003366;margin-bottom:5px}.management-designation{font-size:15px;font-weight:600;color:#0d6efd;margin-bottom:4px}.management-office{font-size:13px;color:#666;margin-bottom:10px}.management-line{display:flex;align-items:center;gap:8px;font-size:13px;color:#444;margin-bottom:6px}.management-line i{width:16px;color:#0d6efd;flex-shrink:0}@media(max-width:768px){.management-card{align-items:flex-start;padding:16px;gap:14px}.management-image img{width:75px;height:75px;border-radius:14px}.management-name{font-size:17px}}</style>`);
}

function renderOrganogram() {
    const organogramList = [
        { icon: 'fas fa-user-tie', title: 'Chief Engineer', office: 'Public Works Department (PWD)' },
        { icon: 'fas fa-user-cog', title: 'Additional Chief Engineer (Est. & Co)', office: 'Public Works Department (PWD)' },
        { icon: 'fas fa-building', title: 'Director / Superintending Engineer', office: 'PWD Training Academy and Testing Laboratory, Dhaka' },
        { icon: 'fas fa-hard-hat', title: 'Senior Instructor / Executive Engineer (Civil)', office: 'PWD Training Academy and Testing Laboratory, Dhaka' },
        { icon: 'fas fa-hard-hat', title: 'Senior Instructor / Executive Engineer (Civil)', office: 'PWD Training Academy and Testing Laboratory, Dhaka' },
        { icon: 'fas fa-bolt', title: 'Senior Instructor / Executive Engineer (E/M)', office: 'PWD Training Academy and Testing Laboratory, Dhaka' }
    ];
    return pageHeader(t('about_organogram_title'), t('nav_about'), `<div class="space-y-4">${organogramList.map(item => `<div class="card p-5 flex items-start gap-4"><div class="w-14 h-14 rounded-xl bg-blue-600 text-white flex items-center justify-center text-xl shrink-0"><i class="${item.icon}"></i></div><div class="flex-1"><h3 class="font-semibold text-base leading-snug">${item.title}</h3><p class="text-sm text-gray-500 mt-1">${item.office}</p></div></div>`).join('')}</div>`);
}

function renderCampus() {
    const items = [{ title: t('about_campus_main_building'), image: 'https://demo.shelltechnologiesbd.com/pwdta/uploads/main-building.jpg' }, { title: t('about_campus_training_hall'), image: 'https://demo.shelltechnologiesbd.com/pwdta/uploads/training-hall.jpg' }, { title: t('about_campus_computer_lab'), image: 'https://demo.shelltechnologiesbd.com/pwdta/uploads/computer-lab.jpg' }, { title: t('about_campus_library'), image: 'https://demo.shelltechnologiesbd.com/pwdta/uploads/library.jpg' }, { title: t('about_campus_residential'), image: 'https://demo.shelltechnologiesbd.com/pwdta/uploads/residential.jpg' }, { title: t('about_campus_testing_lab'), image: 'https://demo.shelltechnologiesbd.com/pwdta/uploads/testing-lab.jpg' }];
    return pageHeader(t('about_campus_title'), t('nav_about'), `<div class="grid md:grid-cols-2 lg:grid-cols-3 gap-4">${items.map(i => `<div class="card overflow-hidden cursor-pointer" onclick="openLightbox('${escAttr(i.image)}')"><img src="${escAttr(i.image)}" class="w-full h-48 object-cover" onerror="this.src='https://demo.shelltechnologiesbd.com/pwdta/uploads/no-image.jpg'"><div class="p-4"><h4 class="font-semibold text-sm">${escAttr(i.title)}</h4></div></div>`).join('')}</div>`);
}

function renderOfficers() {
    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];
        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">${e.img ? `<img src="${escAttr(e.img)}" class="w-full h-full object-cover" alt="${escAttr(e.name)}" onerror="this.style.display='none';this.nextElementSibling.style.display='flex'"><div class="w-full h-full items-center justify-center text-lg font-bold text-white" style="background:${color};display:none">${initial}</div>` : `<div class="w-full h-full flex items-center justify-center text-lg font-bold text-white" style="background:${color}">${initial}</div>`}</div><div class="flex-1 min-w-0"><h4 class="font-semibold text-sm">${escAttr(e.name || '-')}</h4><p class="text-xs text-gray-500">${escAttr(e.designation || '')}</p><p class="text-xs text-gray-400">${escAttr(e.department || '')}</p></div><div class="flex gap-3 text-gray-400 shrink-0">${e.email ? `<a href="mailto:${escAttr(e.email)}" class="hover:text-blue-500 transition" title="${escAttr(e.email)}"><i class="fas fa-envelope text-sm"></i></a>` : ''}${e.phone ? `<a href="tel:${escAttr(e.phone)}" class="hover:text-green-500 transition" title="${escAttr(e.phone)}"><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}`);
}

function renderClassroom() { return renderFacilityPage('classroom'); }
function renderComputerLab() { return renderFacilityPage('computerlab'); }
function renderLibrary() { return renderFacilityPage('library'); }
function renderResidential() { return renderFacilityPage('residential'); }
function renderPlayground() { return renderFacilityPage('playground'); }
function renderGymnasium() { return renderFacilityPage('gymnasium'); }
function renderSwimmingPool() { return renderFacilityPage('swimmingpool'); }
function renderTestingLabFacility() { return renderFacilityPage('testinglab'); }

function renderFacilityPage(type) {
    const fac = facilities.find(f => f.type === type);
    const typeTitles = { classroom: currentLang === 'bn' ? 'ক্লাসরুম' : 'Classroom', computerlab: currentLang === 'bn' ? 'কম্পিউটার ল্যাব' : 'Computer Lab', library: currentLang === 'bn' ? 'লাইব্রেরি' : 'Library', residential: currentLang === 'bn' ? 'আবাসিক' : 'Residential', playground: currentLang === 'bn' ? 'খেলার মাঠ' : 'Playground', gymnasium: currentLang === 'bn' ? 'জিমনেসিয়াম' : 'Gymnasium', swimmingpool: currentLang === 'bn' ? 'সুইমিং পুল' : 'Swimming Pool', testinglab: currentLang === 'bn' ? 'পরীক্ষাগার' : 'Testing Lab' };
    if (!fac) return pageHeader(typeTitles[type] || type, t('nav_facilities'), `<div class="card p-12 text-center"><i class="fas fa-database text-4xl text-gray-300 mb-4"></i><p class="text-gray-500 mb-4">${currentLang === 'bn' ? 'তথ্য যোগ হয়নি।' : 'No data found. Add from Admin Panel.'}</p><button class="btn-primary btn-sm mt-2" onclick="showAdminPanel()"><i class="fas fa-cog mr-2"></i>${currentLang === 'bn' ? 'অ্যাডমিন' : 'Go to Admin'}</button></div>`);
    const title = fac.title || typeTitles[type] || type;
    const desc = fac.desc || '';
    const img = fac.img || `https://picsum.photos/seed/${type}/700/500.jpg`;
    const cap = fac.capacity || '-';
    const area = fac.area ? `${fac.area} sq.ft` : null;
    const features = fac.features ? fac.features.split(',').filter(f => f.trim()) : [];
    return pageHeader(title, t('nav_facilities'), `<div class="grid md:grid-cols-2 gap-6"><div class="rounded-lg overflow-hidden" style="border:1px solid var(--border)"><img src="${escAttr(img)}" class="w-full h-72 object-cover" alt="${escAttr(title)}" onerror="this.src='https://picsum.photos/seed/${type}/700/500.jpg'"></div><div class="flex flex-col justify-center"><h3 class="text-lg font-bold mb-4">${t('facility_overview')}</h3><p class="text-sm text-gray-600 leading-relaxed mb-6">${escAttr(desc)}</p><div class="grid grid-cols-2 gap-3 mb-6">${cap && cap !== '-' ? `<div class="p-4 rounded-lg" style="background:var(--bg)"><div class="text-xl font-bold" style="color:var(--primary)">${cap}</div><div class="text-xs text-gray-500">${t('facility_capacity')}</div></div>` : ''}${area ? `<div class="p-4 rounded-lg" style="background:var(--bg)"><div class="text-xl font-bold" style="color:var(--accent)">${area}</div><div class="text-xs text-gray-500">Area</div></div>` : ''}</div>${features.length > 0 ? `<h4 class="font-semibold text-sm mb-3">Features</h4><div class="grid grid-cols-2 gap-2">${features.map(f => `<div class="flex items-center gap-2 text-xs text-gray-600"><i class="fas fa-check-circle text-green-500"></i>${escAttr(f.trim())}</div>`).join('')}</div>` : ''}</div></div>`);
}

function renderPhotoGallery() {
    return pageHeader(t('media_photo_gallery'), t('nav_media'), galleryItems.length > 0 ? `<div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">${galleryItems.map((g, i) => `<div class="rounded-lg overflow-hidden cursor-pointer group" style="border:1px solid var(--border)" onclick="openLightbox('${escAttr(g.img)}')"><img src="${escAttr(g.img)}" class="w-full h-48 object-cover group-hover:scale-105 transition duration-300">${g.title ? `<div class="p-2 text-xs text-gray-500">${escAttr(g.title)}</div>` : ''}</div>`).join('')}</div>` : `<div class="card p-12 text-center text-gray-400"><i class="fas fa-image text-4xl mb-4"></i><p>${t('media_no_photos')}</p></div>`);
}

function getEmbedUrl(url) {
    if (!url) return '';
    let match = url.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([\w-]+)/);
    if (match) return `https://www.youtube.com/embed/${match[1]}?autoplay=1`;
    match = url.match(/vimeo\.com\/(\d+)/);
    if (match) return `https://player.vimeo.com/video/${match[1]}?autoplay=1`;
    return url;
}

function openVideoModal(url) {
    if (!url) { showToast('Video URL not found', 'error'); return; }
    const embedUrl = getEmbedUrl(url);
    const isDirect = embedUrl.match(/\.(mp4|webm|ogg)$/i);
    let html = isDirect ? `<video controls autoplay style="width:100%;max-height:70vh;border-radius:8px;outline:none"><source src="${escAttr(embedUrl)}" type="video/mp4"></video>` : `<iframe src="${escAttr(embedUrl)}" style="width:100%;height:450px;border:none;border-radius:8px" allow="autoplay;fullscreen" allowfullscreen></iframe>`;
    openModal(`<div class="p-4 border-b flex items-center justify-between" style="border-color:var(--border)"><h3 class="font-semibold">Video Player</h3><button onclick="closeModal()" class="text-gray-400 hover:text-gray-600 cursor-pointer"><i class="fas fa-times"></i></button></div><div class="p-4" style="background:#000;border-radius:0 0 12px 12px">${html}</div>`);
}

function renderVideoGallery() {
    return pageHeader(t('media_video_gallery'), t('nav_media'), videoItems.length > 0 ? `<div class="grid md:grid-cols-2 lg:grid-cols-3 gap-6">${videoItems.map((v, vi) => {
        let thumb = v.thumb || 'https://picsum.photos/seed/vid/400/250.jpg';
        if (!v.thumb && v.url) { const m = v.url.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([\w-]+)/); if (m) thumb = `https://img.youtube.com/vi/${m[1]}/hqdefault.jpg`; }
        return `<div class="card overflow-hidden cursor-pointer group" onclick="openVideoModal('${escAttr(v.url || '')}')"><div class="relative"><img src="${escAttr(thumb)}" class="w-full h-48 object-cover group-hover:scale-105 transition duration-300" onerror="this.src='https://picsum.photos/seed/vid/400/250.jpg'"><div class="absolute inset-0 bg-black/40 flex items-center justify-center group-hover:bg-black/50 transition"><div class="w-16 h-16 rounded-full bg-white/90 flex items-center justify-center shadow-lg group-hover:scale-110 transition"><i class="fas fa-play text-xl" style="color:var(--primary);margin-left:3px"></i></div></div>${v.category ? `<span class="badge badge-info absolute top-3 left-3">${escAttr(v.category)}</span>` : ''}</div><div class="p-4"><h4 class="font-semibold text-sm mb-1">${escAttr(v.title)}</h4></div></div>`;
    }).join('')}</div>` : `<div class="card p-12 text-center text-gray-400"><i class="fas fa-video text-4xl mb-4"></i><p>${t('media_no_videos')}</p></div>`);
}

function renderMaterialTest() {
    return pageHeader(t('testing_material_test'), t('nav_testinglab'), `<div class="card p-6 mb-6"><p class="text-sm text-gray-600">${t('testing_desc')}</p></div><div class="grid md:grid-cols-2 gap-4">${testings.map(t_item => `<div class="card p-5"><div class="flex items-start gap-4"><div class="w-10 h-10 rounded-lg flex items-center justify-center shrink-0" style="background:var(--primary-glow)"><i class="fas fa-flask" style="color:var(--primary)"></i></div><div><h4 class="font-semibold text-sm mb-1">${escAttr(t_item.title)}</h4><p class="text-xs text-gray-500 mb-2">${escAttr(t_item.desc || '')}</p><div class="flex gap-2"><span class="badge badge-info">${escAttr(t_item.testType)}</span></div></div></div></div>`).join('')}</div>`);
}

function renderEquipmentPage() {
    return pageHeader(t('testing_equipment_list'), t('nav_testinglab'), equipment.length > 0 ? `<div class="grid md:grid-cols-2 lg:grid-cols-4 gap-4">${equipment.map(e => {
        const eqImg = e.img ? escAttr(e.img) : getDefaultThumbSVG('equipment');
        return `<div class="card overflow-hidden"><img src="${eqImg}" class="w-full h-36 object-cover" onerror="handleImgError(this,'equipment','')"><div class="p-4"><h4 class="font-semibold text-sm mb-2">${escAttr(e.name)}</h4><div class="text-xs text-gray-500 space-y-1"><div><span class="font-medium">${t('testing_capacity')}</span> ${escAttr(e.capacity || '-')}</div><div><span class="font-medium">${t('testing_standard')}</span> ${escAttr(e.standard || '-')}</div></div></div></div>`;
    }).join('')}</div>` : `<div class="card p-12 text-center text-gray-400">${t('testing_no_equipment')}</div>`);
}

function renderTestingReport() {
    return pageHeader(t('testing_report_title'), t('nav_testinglab'), `<div class="card p-6 mb-6"><p class="text-sm text-gray-600">${t('testing_report_desc')}</p></div><div class="space-y-3"><div class="card p-4 flex items-center justify-between"><div class="flex items-center gap-4"><div class="w-10 h-10 rounded-lg flex items-center justify-center" style="background:var(--danger-light)"><i class="fas fa-file-pdf text-red-500"></i></div><div><div class="font-medium text-sm">${t('testing_sample_report')}</div><div class="text-xs text-gray-400">PDF | 1.2 MB</div></div></div><button class="btn-primary btn-sm"><i class="fas fa-download"></i></button></div></div>`);
}

function renderTrainings() {
    return pageHeader(t('trainings_title'), t('nav_trainings'), `<div class="flex justify-between items-center mb-6"><div class="flex gap-1"><button class="tab-btn active" onclick="filterTraining('all',this)">${t('trainings_all')}</button><button class="tab-btn" onclick="filterTraining('upcoming',this)">${t('trainings_upcoming')}</button><button class="tab-btn" onclick="filterTraining('ongoing',this)">${t('trainings_ongoing')}</button><button class="tab-btn" onclick="filterTraining('completed',this)">${t('trainings_completed')}</button></div></div><div class="grid md:grid-cols-2 lg:grid-cols-3 gap-4" id="training-full-list">${trainings.length > 0 ? trainings.map(t_item => renderProgramCard(t_item, 'training')).join('') : `<div class="col-span-3 card p-12 text-center text-gray-400"><i class="fas fa-chalkboard-teacher text-4xl mb-4"></i><p>${t('trainings_no_trainings')}</p></div>`}</div>`);
}

function filterTraining(status, btn) {
    btn.parentElement.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    document.querySelectorAll('#training-full-list .program-card').forEach(c => {
        const cardStatus = c.dataset.status || '';
        c.style.display = (status === 'all' || cardStatus === status) ? 'block' : 'none';
    });
}

function renderTesting() {
    return pageHeader(t('testing_services_title'), t('nav_testing'), `<div class="grid md:grid-cols-2 lg:grid-cols-3 gap-4">${testings.length > 0 ? testings.map(t_item => renderProgramCard(t_item, 'testing')).join('') : `<div class="col-span-3 card p-12 text-center text-gray-400"><i class="fas fa-flask text-4xl mb-4"></i><p>${t('testing_services_no_services')}</p></div>`}</div>`);
}

function renderNotices() {
    return pageHeader(t('notices_title'), t('nav_notices'), `<div class="flex gap-1 mb-6"><button class="tab-btn active" onclick="filterNotices('all',this)">${t('notices_all')}</button><button class="tab-btn" onclick="filterNotices('important',this)">${t('notices_important')}</button><button class="tab-btn" onclick="filterNotices('new',this)">${t('notices_new')}</button></div><div class="space-y-3" id="notice-list">${notices.length > 0 ? notices.map(n => renderNoticeItem(n)).join('') : `<div class="card p-12 text-center text-gray-400"><i class="fas fa-bullhorn text-4xl mb-4"></i><p>${t('notices_no_notices')}</p></div>`}</div>`);
}

function renderNoticeItem(n) {
    return `<div class="card p-5 notice-item cursor-pointer" onclick="openNoticeModal(${n.id ?? 0})" data-type="${n.type}"><div class="flex items-start justify-between gap-4"><div class="flex items-start gap-4"><div class="w-10 h-10 rounded-lg flex items-center justify-center shrink-0" style="background:${n.type === 'important' ? 'var(--danger-light)' : n.type === 'new' ? 'var(--info-light)' : 'var(--bg)'}"><i class="fas ${n.type === 'important' ? 'fa-exclamation-triangle text-red-500' : n.type === 'new' ? 'fa-bell text-blue-500' : 'fa-info-circle text-gray-400'}"></i></div><div><div class="flex items-center gap-2 mb-1"><span class="badge ${n.type === 'important' ? 'badge-danger' : n.type === 'new' ? 'badge-info' : 'badge-warning'}">${escAttr(n.type)}</span></div><h4 class="font-semibold text-sm mb-1">${escAttr(n.title)}</h4><p class="text-xs text-gray-500 line-clamp-1">${escAttr(n.content || '')}</p></div></div><div class="text-xs text-gray-400 shrink-0">${n.date || ''}</div></div></div>`;
}

function openNoticeModal(id) {
    const notice = notices.find(n => n.id === id);
    if (!notice) return;
    openModal(`<div class="p-5 border-b flex items-center justify-between" style="border-color:var(--border)"><h3 class="font-semibold text-lg">${escAttr(notice.title)}</h3><button onclick="closeModal()" class="text-gray-400 hover:text-gray-600 cursor-pointer"><i class="fas fa-times"></i></button></div><div class="p-5"><div class="flex items-center gap-2 mb-4"><span class="badge ${notice.type === 'important' ? 'badge-danger' : notice.type === 'new' ? 'badge-info' : 'badge-warning'}">${escAttr(notice.type)}</span><span class="text-sm text-gray-500">${notice.date || ''}</span></div><div class="text-sm text-gray-700 leading-relaxed">${escAttr(notice.content || '')}</div></div>`);
}

function filterNotices(type, btn) {
    btn.parentElement.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    document.querySelectorAll('.notice-item').forEach(n => { n.style.display = (type === 'all' || n.dataset.type === type) ? 'block' : 'none'; });
}

function renderContact() {
    return pageHeader(t('contact_title'), t('nav_contact'), `<div class="grid md:grid-cols-2 gap-6"><div class="card p-6"><h3 class="font-bold mb-4">${t('contact_send_message')}</h3><form onsubmit="submitContact(event)"><div class="space-y-4"><div><label>${t('contact_full_name')}</label><input type="text" required></div><div><label>${t('contact_email')}</label><input type="email" required></div><div><label>${t('contact_subject')}</label><select required><option value="">Select</option><option>${t('contact_training_inquiry')}</option><option>${t('contact_testing_inquiry')}</option><option>${t('contact_general_inquiry')}</option></select></div><div><label>${t('contact_message')}</label><textarea rows="4" required></textarea></div><button type="submit" class="btn-primary w-full"><i class="fas fa-paper-plane mr-2"></i>${t('contact_send')}</button></div></form></div><div><div class="card p-6 mb-6"><h3 class="font-bold mb-4">${t('contact_info_title')}</h3><div class="space-y-4"><div class="flex items-start gap-4"><div class="w-10 h-10 rounded-lg flex items-center justify-center shrink-0" style="background:var(--primary-glow)"><i class="fas fa-map-marker-alt" style="color:var(--primary)"></i></div><div><div class="font-medium text-sm">${t('contact_address_label')}</div><div class="text-xs text-gray-500">${t('contact_address_value')}</div></div></div><div class="flex items-start gap-4"><div class="w-10 h-10 rounded-lg flex items-center justify-center shrink-0" style="background:var(--primary-glow)"><i class="fas fa-phone" style="color:var(--primary)"></i></div><div><div class="font-medium text-sm">${t('contact_phone_label')}</div><div class="text-xs text-gray-500">${t('contact_phone_value')}</div></div></div><div class="flex items-start gap-4"><div class="w-10 h-10 rounded-lg flex items-center justify-center shrink-0" style="background:var(--primary-glow)"><i class="fas fa-envelope" style="color:var(--primary)"></i></div><div><div class="font-medium text-sm">${t('contact_email_label')}</div><div class="text-xs text-gray-500">${t('contact_email_value')}</div></div></div></div></div><div class="rounded-lg overflow-hidden" style="border:1px solid var(--border)"><iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3652.2637350037844!2d90.37907431498192!3d23.73939698458857!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x3755b9004a4cfb75%3A0x2cf43dd7d1a2f3c2!2sSher-e-Bangla%20Nagar%2C%20Dhaka!5e0!3m2!1sen!2sbd!4v1680000000000" width="100%" height="250" style="border:0" allowfullscreen loading="lazy"></iframe></div></div></div>`);
}

async function submitContact(e) { e.preventDefault(); showToast(t('contact_message_sent'), 'success'); e.target.reset(); }

function renderVerify() {
    return pageHeader(t('verify_title'), t('nav_verify'), `<div class="max-w-lg mx-auto"><div class="card p-8 text-center"><div class="flex justify-center gap-2 mb-6 border-b" style="border-color:var(--border)"><button class="tab-btn active" onclick="switchVerifyTab('cert',this)">${t('verify_cert_tab')}</button><button class="tab-btn" onclick="switchVerifyTab('test',this)">${t('verify_test_tab')}</button></div><div id="verify-cert-content"><div class="w-16 h-16 rounded-lg mx-auto mb-4 flex items-center justify-center" style="background:var(--accent-glow)"><i class="fas fa-certificate text-3xl" style="color:var(--accent)"></i></div><h3 class="font-bold mb-2">${t('verify_cert_title')}</h3><p class="text-sm text-gray-500 mb-6">${t('verify_cert_desc')}</p><form onsubmit="verifyCert(event)"><div class="mb-4"><label>${t('verify_cert_number')}</label><input type="text" required placeholder="${t('verify_placeholder')}" id="cert-input"></div><button type="submit" class="btn-primary w-full"><i class="fas fa-search mr-2"></i>${t('verify_btn')}</button></form><div id="cert-result" class="mt-6"></div></div><div id="verify-test-content" style="display:none"><div class="w-16 h-16 rounded-lg mx-auto mb-4 flex items-center justify-center" style="background:var(--warning-light)"><i class="fas fa-flask text-3xl" style="color:var(--warning)"></i></div><h3 class="font-bold mb-2">${t('verify_test_title')}</h3><p class="text-sm text-gray-500 mb-6">${t('verify_test_desc')}</p><form onsubmit="verifyTest(event)"><div class="mb-4"><label>${t('verify_test_id')}</label><input type="text" required placeholder="${t('verify_test_placeholder')}" id="test-input"></div><button type="submit" class="btn-primary w-full"><i class="fas fa-search mr-2"></i>${t('verify_btn')}</button></form><div id="test-result" class="mt-6"></div></div></div></div>`);
}

function switchVerifyTab(tab, btn) {
    document.querySelectorAll('#page-content .tab-btn').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    document.getElementById('verify-cert-content').style.display = tab === 'cert' ? 'block' : 'none';
    document.getElementById('verify-test-content').style.display = tab === 'test' ? 'block' : 'none';
}

function verifyCert(e) {
    e.preventDefault();
    const num = document.getElementById('cert-input').value;
    document.getElementById('cert-result').innerHTML = `<div class="p-5 rounded-lg text-left" style="border:2px solid var(--success);background:var(--success-light)"><div class="flex items-center gap-2 mb-3"><i class="fas fa-check-circle text-green-600"></i><span class="font-bold text-green-700 text-sm">${t('verify_verified')}</span></div><div class="space-y-2 text-sm"><div><span class="text-gray-600">${t('verify_cert_no')}</span> <span class="font-medium">${escAttr(num)}</span></div><div><span class="text-gray-600">${t('verify_status')}</span> <span class="badge badge-success">${t('verify_valid')}</span></div></div></div>`;
}

function verifyTest(e) {
    e.preventDefault();
    const id = document.getElementById('test-input').value;
    document.getElementById('test-result').innerHTML = `<div class="p-5 rounded-lg text-left" style="border:2px solid var(--success);background:var(--success-light)"><div class="flex items-center gap-2 mb-3"><i class="fas fa-check-circle text-green-600"></i><span class="font-bold text-green-700 text-sm">${t('verify_verified')}</span></div><div class="space-y-2 text-sm"><div><span class="text-gray-600">${t('verify_test_id')}</span> <span class="font-medium">${escAttr(id)}</span></div><div><span class="text-gray-600">${t('verify_status')}</span> <span class="badge badge-success">${t('verify_valid')}</span></div></div></div>`;
}

// =============================================
// LOGIN PAGE
// =============================================
function renderLogin() {
    const bn = currentLang === 'bn';
    return `<div class="max-w-md mx-auto"><div class="card p-8 shadow-xl border border-gray-100"><div class="text-center mb-8"><div class="w-20 h-20 rounded-full mx-auto mb-4 flex items-center justify-center shadow-lg" style="background: linear-gradient(135deg, var(--primary), var(--primary-light))"><i class="fas fa-shield-alt text-3xl text-white"></i></div><h2 class="text-2xl font-bold text-gray-800">${t('login_welcome')}</h2><p class="text-sm text-gray-500 mt-1">${t('login_subtitle')}</p></div><div id="login-error" class="hidden mb-4 p-3 rounded-lg text-sm text-red-700 bg-red-50 border border-red-200 flex items-center gap-2"><i class="fas fa-exclamation-circle"></i><span id="login-error-msg"></span></div><form onsubmit="doLogin(event)"><div class="space-y-5"><div><label class="block text-sm font-medium text-gray-700 mb-1">${t('login_email')}</label><div class="relative"><i class="fas fa-envelope absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i><input type="email" id="login-email" required class="w-full pl-10 pr-4 py-2.5 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition text-sm" placeholder="your.name@pwd.gov.bd"></div></div><div><div class="flex items-center justify-between mb-1"><label class="block text-sm font-medium text-gray-700">${t('login_password')}</label><a class="text-xs font-medium cursor-pointer hover:underline" style="color:var(--primary)" onclick="handleForgotPassword()">${bn ? 'পাসওয়ার্ড ভুলে গেছেন?' : 'Forgot Password?'}</a></div><div class="relative"><i class="fas fa-lock absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i><input type="password" id="login-pass" required minlength="6" class="w-full pl-10 pr-10 py-2.5 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition text-sm" placeholder="••••••••"><i class="fas fa-eye-slash absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 cursor-pointer hover:text-gray-600 transition" onclick="toggleLoginPass('login-pass', this)"></i></div></div><div class="flex items-center justify-between"><label class="flex items-center text-sm text-gray-600 cursor-pointer"><input type="checkbox" id="login-remember" class="mr-2 rounded border-gray-300 text-blue-600 shadow-sm">${bn ? 'আমাকে মনে রাখুন' : 'Remember me'}</label></div><button type="submit" id="login-btn" class="btn-primary w-full flex items-center justify-center py-2.5 text-base font-semibold shadow-md hover:shadow-lg transition"><span id="login-btn-text"><i class="fas fa-sign-in-alt mr-2"></i>${t('login_btn')}</span><span id="login-btn-loader" class="hidden"><i class="fas fa-circle-notch fa-spin mr-2"></i>${bn ? 'প্রবেশ হচ্ছে...' : 'Logging in...'}</span></button></div></form><div class="mt-6 text-center text-sm text-gray-500">${t('login_no_account')} <a class="font-semibold cursor-pointer hover:underline" style="color:var(--primary)" onclick="navigate('register')">${t('login_register')}</a></div><div class="mt-4 text-center border-t pt-4 border-gray-100"><a class="text-xs text-gray-400 cursor-pointer hover:text-blue-500 hover:underline transition" onclick="prefillAdminLogin()"><i class="fas fa-lock mr-1"></i>${t('login_admin_access')}</a></div></div></div>`;
}

function handleForgotPassword() {
    const bn = currentLang === 'bn';
    openModal(`<div class="p-5 border-b flex items-center justify-between" style="border-color:var(--border)"><h3 class="font-semibold text-lg">${bn ? 'পাসওয়ার্ড পুনরুদ্ধার' : 'Reset Password'}</h3><button onclick="closeModal()" class="text-gray-400 hover:text-gray-600 cursor-pointer"><i class="fas fa-times"></i></button></div><div class="p-6"><div class="w-16 h-16 rounded-full mx-auto mb-4 flex items-center justify-center" style="background:var(--warning-light)"><i class="fas fa-key text-2xl" style="color:var(--warning)"></i></div><p class="text-sm text-gray-600 mb-5 text-center">${bn ? 'আপনার নিবন্ধিত ইমেইল ঠিকানা দিন, আমরা পাসওয়ার্ড রিসেট লিঙ্ক পাঠাবো।' : 'Enter your registered email address and we will send you a password reset link.'}</p><form onsubmit="submitForgotPassword(event)"><div class="mb-4"><label class="block text-sm font-medium text-gray-700 mb-1">${t('login_email')}</label><input type="email" id="forgot-email" required placeholder="your.name@pwd.gov.bd" class="w-full px-4 py-2.5 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition text-sm"></div><button type="submit" class="btn-primary w-full py-2.5 text-sm font-semibold"><i class="fas fa-paper-plane mr-2"></i>${bn ? 'রিসেট লিঙ্ক পাঠান' : 'Send Reset Link'}</button></form></div>`);
}

function submitForgotPassword(e) {
    e.preventDefault();
    const email = document.getElementById('forgot-email').value;
    closeModal();
    showToast(currentLang === 'bn' ? `যদি "${email}" এ অ্যাকাউন্ট থাকে, পাসওয়ার্ড রিসেট লিঙ্ক পাঠানো হয়েছে` : `If an account exists with "${email}", a reset link has been sent`, 'success');
}

async function doLogin(e) {
    e.preventDefault();
    const btn = document.getElementById('login-btn');
    const btnText = document.getElementById('login-btn-text');
    const btnLoader = document.getElementById('login-btn-loader');
    const errorDiv = document.getElementById('login-error');
    const errorMsg = document.getElementById('login-error-msg');
    const email = document.getElementById('login-email').value.trim();
    const pass = document.getElementById('login-pass').value;
    const remember = document.getElementById('login-remember')?.checked;
    errorDiv.classList.add('hidden');
    errorMsg.innerText = '';
    btn.disabled = true;
    btnText.classList.add('hidden');
    btnLoader.classList.remove('hidden');
    try {
        const res = await api('login', 'POST', { email, password: pass });
        if (res.success) {
            currentUser = res.user;
            if (remember) { localStorage.setItem('pwdta_remember', 'true'); localStorage.setItem('pwdta_email', email); }
            else { localStorage.removeItem('pwdta_remember'); localStorage.removeItem('pwdta_email'); }
            updateLoginButton();
            if (currentUser.role === 'admin') {
                if (typeof showAdminPanel === 'function') showAdminPanel();
                else navigate('dashboard');
            }
            else { showToast(t('login_success'), 'success'); navigate('dashboard'); }
        } else {
            const errMsg = res.message || t('login_invalid');
            errorMsg.innerText = errMsg;
            errorDiv.classList.remove('hidden');
            showToast(errMsg, 'error');
        }
    } catch (err) {
        errorMsg.innerText = currentLang === 'bn' ? 'নেটওয়ার্ক ত্রুটি। আবার চেষ্টা করুন।' : 'Network error. Please try again.';
        errorDiv.classList.remove('hidden');
    } finally {
        btn.disabled = false;
        btnText.classList.remove('hidden');
        btnLoader.classList.add('hidden');
    }
}

function prefillAdminLogin() {
    const emailEl = document.getElementById('login-email');
    const passEl = document.getElementById('login-pass');
    if (emailEl) emailEl.value = 'admin@pwd.training.gov.bd';
    if (passEl) passEl.value = 'admin123';
    if (passEl) passEl.focus();
    showToast(currentLang === 'bn' ? 'অ্যাডমিন তথ্য পূরণ হয়েছে' : 'Admin credentials filled', 'info');
}

// =============================================
// REGISTER PAGE
// =============================================
function renderRegister() {
    const bn = currentLang === 'bn';

    // কম্প্যাক্ট ও শার্প ইনপুট স্টাইল
    const labelClass = "block text-[12px] font-semibold text-gray-700 mb-1 font-sans";
    const inputClass = "w-full px-3.5 py-2.5 text-[14px] text-gray-900 bg-gray-50 border border-gray-250 rounded-lg focus:bg-white focus:outline-none focus:border-indigo-600 focus:ring-2 focus:ring-indigo-100 transition-all duration-150 placeholder-gray-400 shadow-sm";
    const selectClass = "w-full px-3.5 py-2.5 text-[14px] text-gray-900 bg-gray-50 border border-gray-250 rounded-lg focus:bg-white focus:outline-none focus:border-indigo-600 focus:ring-2 focus:ring-indigo-100 transition-all duration-150 text-gray-700 appearance-none cursor-pointer shadow-sm";

    return `
    <div class="max-w-lg mx-auto my-6 px-4">
        <!-- Compact Premium Card -->
        <div class="bg-white-100 rounded-xl shadow-[0_8px_30px_rgb(0,0,0,0.04)] border border-blue-100 p-6 sm:p-8">
            
            <!-- Header Section (Sleek & Tight) -->
            <div class="text-center mb-6">
                <div class="w-12 h-12 rounded-xl mx-auto mb-2.5 flex items-center justify-center bg-indigo-50 text-indigo-600">
                    <i class="fas fa-user-plus text-lg"></i>
                </div>
                <h2 class="text-xl font-bold text-gray-900 tracking-tight">${t('register_create_account')}</h2>
            </div>

            <form onsubmit="doRegister(event)" class="space-y-4">
                
                <!-- Full Name & Phone Number -->
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div>
                        <label class="${labelClass}">${t('register_full_name')}</label>
                        <input type="text" id="reg-name" required class="${inputClass}" placeholder="${bn ? 'পুরো নাম' : 'Full name'}">
                    </div>
                    <div>
                        <label class="${labelClass}">${t('register_phone')}</label>
                        <input type="tel" id="reg-phone" required class="${inputClass}" placeholder="+880 XXXXX-XXXXXX">
                    </div>
                </div>

                <!-- Email Field (Compact Notification) -->
                <div>
                    <label class="${labelClass}">${t('register_email')}</label>
                    <input type="email" id="reg-email" required pattern="^[a-zA-Z0-9._%+\\-]+@pwd\\.gov\\.bd$" title="${bn ? 'শুধুমাত্র @pwd.gov.bd গ্রহণযোগ্য' : 'Only @pwd.gov.bd accepted'}" class="${inputClass}" placeholder="name@pwd.gov.bd">
                    <p class="text-[11px] mt-1 text-indigo-600 font-medium flex items-center gap-1">
                        <i class="fas fa-info-circle"></i> ${bn ? 'শুধুমাত্র অফিসিয়াল @pwd.gov.bd ইমেইল গ্রহণযোগ্য' : 'Only official @pwd.gov.bd emails accepted'}
                    </p>
                </div>

                <!-- Organization & Designation -->
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div class="relative">
                        <label class="${labelClass}">${t('register_organization')}</label>
                        <select id="reg-org" required class="${selectClass}">
                            <option value="" disabled selected class="text-gray-400">${bn ? 'প্রতিষ্ঠান নির্বাচন' : 'Select Organization'}</option>
                            <option value="PWD">PWD</option>
                            <option value="PWD Training Academy">PWD Training Academy</option>
                        </select>
                        <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-3.5 pt-5 text-gray-400">
                            <i class="fas fa-chevron-down text-[10px]"></i>
                        </div>
                    </div>
                    
                    <div class="relative">
                        <label class="${labelClass}">${t('register_designation')}</label>
                        <select id="reg-desig" required class="${selectClass}">
                            <option value="" disabled selected class="text-gray-400">${bn ? 'পদবি নির্বাচন' : 'Select Designation'}</option>
                            <optgroup label="${bn ? 'ক্যাডার' : 'Cadre'}" class="font-semibold bg-white text-gray-800">
                                <option value="Assistant Engineer">AE</option>
                                <option value="Assistant Architect">Asst. Architect</option>
                            </optgroup>
                            <optgroup label="${bn ? 'নন-ক্যাডার' : 'Non-Cadre'}" class="font-semibold bg-white text-gray-800">
                                <option value="Sub-Assistant Engineer">SAE</option>
                                <option value="Draftsman">Draftsman</option>
                                <option value="Surveyor">Surveyor</option>
                                <option value="Computer Operator">Computer Operator</option>
                            </optgroup>
                            <optgroup label="${bn ? 'সহকারী' : 'Support'}" class="font-semibold bg-white text-gray-800">
                                <option value="Office Assistant">Office Assistant</option>
                                <option value="Office Sohayok">MLSS</option>
                            </optgroup>
                            <option value="Other">${bn ? 'অন্যান্য' : 'Other'}</option>
                        </select>
                        <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-3.5 pt-5 text-gray-400">
                            <i class="fas fa-chevron-down text-[10px]"></i>
                        </div>
                    </div>
                </div>

                <!-- Password & Confirm Password -->
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div>
                        <label class="${labelClass}">${t('register_password')}</label>
                        <div class="relative">
                            <input type="password" id="reg-pass" required minlength="6" class="${inputClass} pr-10" placeholder="••••••••">
                            <i class="fas fa-eye-slash text-gray-400 hover:text-indigo-600 transition-colors absolute right-3.5 top-1/2 -translate-y-1/2 text-sm cursor-pointer" onclick="toggleLoginPass('reg-pass', this)"></i>
                        </div>
                    </div>
                    <div>
                        <label class="${labelClass}">${bn ? 'কনফার্ম পাসওয়ার্ড' : 'Confirm Password'}</label>
                        <div class="relative">
                            <input type="password" id="reg-confirm-pass" required minlength="6" class="${inputClass} pr-10" placeholder="••••••••">
                            <i class="fas fa-eye-slash text-gray-400 hover:text-indigo-600 transition-colors absolute right-3.5 top-1/2 -translate-y-1/2 text-sm cursor-pointer" onclick="toggleLoginPass('reg-confirm-pass', this)"></i>
                        </div>
                    </div>
                </div>

                <!-- Solid Compact Submit Button -->
                <div class="pt-2">
                    <button type="submit" class="w-full bg-gray-900 hover:bg-black text-white font-semibold py-3 px-4 rounded-lg shadow-sm transition-all duration-150 flex items-center justify-center gap-2 text-[15px]">
                        <span>${t('register_create_btn')}</span>
                        <i class="fas fa-arrow-right text-[11px]"></i>
                    </button>
                </div>
            </form>

            <!-- Footer Link -->
            <div class="mt-5 text-center text-[13px] text-gray-500 border-t border-gray-100 pt-4">
                ${t('register_have_account')} 
                <a class="font-semibold text-indigo-600 hover:text-indigo-700 transition-colors cursor-pointer ml-0.5" onclick="navigate('login')">
                    ${t('register_login_link')}
                </a>
            </div>
            
        </div>
    </div>`;
}

async function doRegister(e) {
    e.preventDefault();
    const emailInput = document.getElementById('reg-email').value.trim();
    const passInput = document.getElementById('reg-pass').value;
    const confirmPass = document.getElementById('reg-confirm-pass').value;
    const bn = currentLang === 'bn';
    if (!emailInput.endsWith('@pwd.gov.bd')) { showToast(bn ? 'শুধুমাত্র অথরাইজড ইমেইল গ্রহণযোগ্য!' : 'Only authorized emails accepted!', 'error'); return; }
    if (passInput !== confirmPass) { showToast(bn ? 'পাসওয়ার্ড মিলেনি!' : 'Passwords do not match!', 'error'); return; }
    if (passInput.length < 6) { showToast(bn ? 'পাসওয়ার্ড কমপক্ষে ৬ অক্ষর হতে হবে!' : 'Password must be at least 6 characters!', 'error'); return; }
    const payload = { name: document.getElementById('reg-name').value, email: emailInput, password: passInput, phone: document.getElementById('reg-phone').value, org: document.getElementById('reg-org').value, designation: document.getElementById('reg-desig').value };
    const res = await api('register', 'POST', payload);
    if (res.success) { showToast(t('register_success'), 'success'); navigate('login'); }
    else showToast(res.error || t('register_failed'), 'error');
}

// =============================================
// USER DASHBOARD
// =============================================
function renderUserDashboard() {
    if (!currentUser) return renderLogin();
    const bn = currentLang === 'bn';
    const initial = (currentUser.name || 'U').charAt(0).toUpperCase();
    const gradientColors = ['#312E81', '#06B6D4', '#059669', '#D97706', '#DC2626'];
    const color = gradientColors[(currentUser.id || 0) % gradientColors.length];

    const userCourses = getUserCourses();
    const interestedIds = userCourses.filter(c => c.status === 'interested').map(c => c.trainingId);
    const enrolledIds = userCourses.filter(c => c.status === 'enrolled').map(c => c.trainingId);
    const completedIds = userCourses.filter(c => c.status === 'completed').map(c => c.trainingId);
    const interestedTrainings = trainings.filter(tr => interestedIds.includes(tr.id));
    const enrolledTrainings = trainings.filter(tr => enrolledIds.includes(tr.id));
    const completedTrainings = trainings.filter(tr => completedIds.includes(tr.id));

    return `<div class="space-y-6">
        <div class="card p-6 shadow-lg border-0" style="background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);">
            <div class="flex flex-col md:flex-row items-center gap-6">
                <div class="relative"><div class="w-20 h-20 rounded-full flex items-center justify-center text-3xl font-bold text-white shadow-xl" style="background: linear-gradient(135deg, ${color}, ${color}cc)">${initial}</div><div class="absolute bottom-0 right-0 w-6 h-6 bg-green-500 rounded-full border-2 border-white flex items-center justify-center"><i class="fas fa-check text-white text-[8px]"></i></div></div>
                <div class="flex-1 text-center md:text-left"><h2 class="text-2xl font-bold text-gray-800">${escAttr(currentUser.name)}</h2><p class="text-sm text-gray-600 mt-1"><i class="fas fa-briefcase mr-1"></i>${escAttr(currentUser.designation || 'N/A')}</p><div class="flex flex-col md:flex-row gap-2 md:gap-6 mt-2 text-xs text-gray-500"><span><i class="fas fa-building mr-1"></i>${escAttr(currentUser.org || currentUser.organization || 'N/A')}</span><span><i class="fas fa-envelope mr-1"></i>${escAttr(currentUser.email || 'N/A')}</span></div></div>
                <div class="flex flex-col gap-2"><button class="btn-outline btn-sm" onclick="openEditProfileModal()"><i class="fas fa-user-edit mr-1"></i> ${bn ? 'প্রোফাইল' : 'Profile'}</button><button class="btn-danger btn-sm" onclick="doLogout()"><i class="fas fa-sign-out-alt mr-1"></i> ${t('dashboard_logout')}</button></div>
            </div>
        </div>
        <div class="grid grid-cols-3 gap-4">
            <div class="card p-4 text-center transform hover:scale-105 transition border-l-4 border-blue-500"><div class="text-2xl font-bold text-blue-700">${enrolledTrainings.length}</div><div class="text-xs text-gray-500 mt-1">${bn ? 'চলমান কোর্স' : 'Enrolled'}</div></div>
            <div class="card p-4 text-center transform hover:scale-105 transition border-l-4 border-green-500"><div class="text-2xl font-bold text-green-700">${interestedTrainings.length}</div><div class="text-xs text-gray-500 mt-1">${bn ? 'আগ্রহী কোর্স' : 'Interested'}</div></div>
            <div class="card p-4 text-center transform hover:scale-105 transition border-l-4 border-purple-500"><div class="text-2xl font-bold text-purple-700">${completedTrainings.length}</div><div class="text-xs text-gray-500 mt-1">${bn ? 'সম্পন্ন কোর্স' : 'Completed'}</div></div>
        </div>
        <div class="card p-6 shadow-sm">
            <div class="flex items-center justify-between mb-5 border-b pb-3" style="border-color: var(--border)"><h3 class="font-semibold text-gray-800 flex items-center gap-2"><i class="fas fa-graduation-cap text-blue-600"></i> ${bn ? 'আমার কোর্সসমূহ' : 'My Courses'}</h3><div class="flex gap-1"><button class="tab-btn active" onclick="filterDashCourse('enrolled', this)">${bn ? 'চলমান' : 'Enrolled'}</button><button class="tab-btn" onclick="filterDashCourse('interested', this)">${bn ? 'আগ্রহী' : 'Interested'}</button><button class="tab-btn" onclick="filterDashCourse('completed', this)">${bn ? 'সম্পন্ন' : 'Completed'}</button></div></div>
            <div id="dash-course-list">${renderDashCourseItems('enrolled', enrolledTrainings, interestedTrainings, completedTrainings)}</div>
        </div>
    </div>`;
}

function renderDashCourseItems(type, enrolledList, interestedList, completedList) {
    const bn = currentLang === 'bn';
    let list = type === 'enrolled' ? enrolledList : type === 'interested' ? interestedList : completedList;
    if (list.length === 0) {
        return `<div class="text-center py-10"><div class="w-20 h-20 rounded-full mx-auto mb-4 flex items-center justify-center bg-gray-50"><i class="fas fa-folder-open text-3xl text-gray-300"></i></div><p class="text-sm font-medium text-gray-500">${type === 'enrolled' ? (bn ? 'কোনো চলমান কোর্সে এনরোল করেননি' : 'Not enrolled in any courses') : type === 'interested' ? (bn ? 'কোনো আসন্ন কোর্সে আগ্রহ দেখাননি' : 'No interested courses') : (bn ? 'কোনো কোর্স সম্পন্ন হয়নি' : 'No completed courses')}</p><button onclick="navigate('trainings')" class="btn-outline btn-sm mt-4">${bn ? 'কোর্স খুঁজুন' : 'Browse Courses'}</button></div>`;
    }
    return list.map(tr => `<div class="flex items-center gap-4 p-4 rounded-xl border border-gray-100 hover:shadow-md transition-all group mb-3"><div class="w-12 h-12 rounded-xl flex items-center justify-center shrink-0 bg-blue-50 group-hover:bg-blue-100 transition"><i class="fas fa-book-reader text-blue-600"></i></div><div class="flex-1 min-w-0"><h4 class="font-semibold text-sm text-gray-800 truncate">${escAttr(tr.title)}</h4><div class="flex items-center gap-3 mt-1 text-xs text-gray-500"><span class="flex items-center gap-1"><i class="far fa-calendar-alt"></i> ${tr.start || 'N/A'}</span><span class="badge ${type === 'enrolled' ? 'badge-success' : type === 'interested' ? 'badge-info' : 'badge-warning'}" style="font-size:10px">${type === 'enrolled' ? (bn ? 'চলমান' : 'Ongoing') : type === 'interested' ? (bn ? 'আগ্রহী' : 'Interested') : (bn ? 'সম্পন্ন' : 'Completed')}</span></div></div>${type === 'enrolled' ? `<button class="btn-primary btn-sm shrink-0" onclick="markCourseCompleted(${tr.id})"><i class="fas fa-check mr-1"></i> ${bn ? 'সম্পন্ন' : 'Complete'}</button>` : ''}</div>`).join('');
}

function filterDashCourse(type, btn) {
    btn.parentElement.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    const userCourses = getUserCourses();
    const interestedIds = userCourses.filter(c => c.status === 'interested').map(c => c.trainingId);
    const enrolledIds = userCourses.filter(c => c.status === 'enrolled').map(c => c.trainingId);
    const completedIds = userCourses.filter(c => c.status === 'completed').map(c => c.trainingId);
    document.getElementById('dash-course-list').innerHTML = renderDashCourseItems(type, trainings.filter(tr => enrolledIds.includes(tr.id)), trainings.filter(tr => interestedIds.includes(tr.id)), trainings.filter(tr => completedIds.includes(tr.id)));
}

function markCourseCompleted(trainingId) {
    addUserCourse(trainingId, 'completed');
    showToast(currentLang === 'bn' ? 'কোর্সটি সম্পন্ন হিসেবে চিহ্নিত করা হয়েছে!' : 'Course marked as completed!', 'success');
    renderPage();
}

function doLogout() {
    currentUser = null;
    updateLoginButton();
    navigate('login');
    showToast(currentLang === 'bn' ? 'সফলভাবে লগআউট হয়েছে' : 'Logged out successfully', 'success');
}

function openEditProfileModal() {
    if (!currentUser) return;
    const bn = currentLang === 'bn';
    openModal(`<div class="p-5 border-b flex items-center justify-between" style="border-color:var(--border)"><h3 class="font-semibold text-lg">${bn ? 'প্রোফাইল এডিট করুন' : 'Edit Profile'}</h3><button onclick="closeModal()" class="text-gray-400 hover:text-gray-600 cursor-pointer"><i class="fas fa-times"></i></button></div><div class="p-6"><div class="space-y-4"><div><label class="block text-sm font-medium text-gray-700 mb-1">${bn ? 'পুরো নাম' : 'Full Name'}</label><input type="text" id="edit-name" value="${escAttr(currentUser.name || '')}" class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 transition text-sm"></div><div><label class="block text-sm font-medium text-gray-700 mb-1">${bn ? 'ফোন নম্বর' : 'Phone'}</label><input type="tel" id="edit-phone" value="${escAttr(currentUser.phone || '')}" class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 transition text-sm"></div><div><label class="block text-sm font-medium text-gray-700 mb-1">${bn ? 'পদবি' : 'Designation'}</label><input type="text" id="edit-desig" value="${escAttr(currentUser.designation || '')}" class="w-full px-4 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 transition text-sm"></div><div class="pt-2"><button onclick="saveProfile()" class="btn-primary w-full py-2.5 text-sm font-semibold"><i class="fas fa-save mr-2"></i>${bn ? 'সেভ করুন' : 'Save Changes'}</button></div></div></div>`);
}

async function saveProfile() {
    const bn = currentLang === 'bn';
    const name = document.getElementById('edit-name')?.value.trim();
    const phone = document.getElementById('edit-phone')?.value.trim();
    const desig = document.getElementById('edit-desig')?.value.trim();
    if (!name) { showToast(bn ? 'নাম দিতে হবে' : 'Name is required', 'error'); return; }
    currentUser.name = name;
    currentUser.phone = phone;
    currentUser.designation = desig;
    closeModal();
    showToast(bn ? 'প্রোফাইল আপডেট হয়েছে!' : 'Profile updated successfully!', 'success');
    renderPage();
}

function openEnrollModal(id, type) {
    window._currentEnrollId = id;
    if (!currentUser) { showToast(currentLang === 'bn' ? 'ভর্তির আবেদন করতে লগইন করুন' : 'Please login to enroll', 'error'); navigate('login'); return; }
    const item = type === 'training' ? trainings.find(tr => tr.id === id) : testings.find(tr => tr.id === id);
    if (!item) { showToast(currentLang === 'bn' ? 'আইটেম পাওয়া যায়নি' : 'Item not found', 'error'); return; }
    const bn = currentLang === 'bn';
    openModal(`<div class="p-5 border-b flex items-center justify-between" style="border-color:var(--border)"><h3 class="font-semibold">${t('enroll_title')}</h3><button onclick="closeModal()" class="text-gray-400 hover:text-gray-600 cursor-pointer"><i class="fas fa-times"></i></button></div><div class="p-5"><div class="flex items-center gap-4 mb-5 p-4 rounded-lg" style="background:var(--bg)">${item.img ? `<img src="${escAttr(item.img)}" class="w-14 h-14 rounded-lg object-cover">` : ''}<div><h4 class="font-semibold text-sm">${escAttr(item.title)}</h4><span class="badge badge-info mt-1">${escAttr(item.category || item.testType || '')}</span></div></div><form onsubmit="submitEnroll(event)"><div class="space-y-4"><div class="grid grid-cols-2 gap-4"><div><label>${t('register_full_name')}</label><input type="text" required value="${escAttr(currentUser.name || '')}"></div><div><label>${t('register_phone')}</label><input type="tel" required value="${escAttr(currentUser.phone || '')}"></div></div><div><label>${t('register_email')}</label><input type="email" required value="${escAttr(currentUser.email || '')}"></div><div><label>${t('register_organization')}</label><input type="text" required value="${escAttr(currentUser.org || '')}"></div><button type="submit" class="btn-primary w-full"><i class="fas fa-check mr-2"></i>${t('enroll_submit')}</button></div></form></div>`);
}

function submitEnroll(e) {
    e.preventDefault();
    if (window._currentEnrollId) {
        addUserCourse(window._currentEnrollId, 'enrolled');
        if (currentUser) addProgramEnrollment(window._currentEnrollId, currentUser);
        window._currentEnrollId = null;
    }
    closeModal();
    showToast(t('enroll_success'), 'success');
    renderPage();
}