<?php
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PWD Training Academy</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&family=Space+Grotesk:wght@400;500;600;700&family=Noto+Sans+Bengali:wght@400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
:root{--primary:#312E81;--primary-light:#4338CA;--primary-dark:#1E1B4B;--primary-glow:rgba(49,46,129,0.08);--accent:#06B6D4;--accent-light:#22D3EE;--accent-glow:rgba(6,182,212,0.1);--bg:#F9FAFB;--bg-alt:#F3F4F6;--card:#FFFFFF;--text:#111827;--text-secondary:#6B7280;--muted:#9CA3AF;--border:#E5E7EB;--border-light:#F3F4F6;--danger:#DC2626;--danger-light:#FEE2E2;--success:#059669;--success-light:#D1FAE5;--info:#2563EB;--info-light:#DBEAFE;--warning:#D97706;--warning-light:#FEF3C7;--radius:8px;--radius-lg:12px;--radius-full:9999px;--shadow-sm:0 0 0 1px var(--border);--shadow-md:0 0 0 1px var(--border),0 2px 8px rgba(0,0,0,0.04);--shadow-lg:0 0 0 1px var(--border),0 4px 16px rgba(0,0,0,0.06);--shadow-xl:0 0 0 1px var(--border),0 8px 32px rgba(0,0,0,0.08)}
body.dark-mode{--bg:#0F172A;--bg-alt:#1E293B;--card:#1F2937;--text:#F3F4F6;--text-secondary:#9CA3AF;--border:#374151;--border-light:#374151}
*{margin:0;padding:0;box-sizing:border-box;scroll-behavior:smooth}
body{font-family:'Inter',sans-serif;background:var(--bg);color:var(--text);overflow-x:hidden;line-height:1.6;-webkit-font-smoothing:antialiased;transition:background .3s,color .3s}
body.lang-bn{font-family:'Noto Sans Bengali',sans-serif}
h1,h2,h3,h4,h5{font-family:'Space Grotesk',sans-serif;letter-spacing:-0.02em;line-height:1.2}
body.lang-bn h1,body.lang-bn h2,body.lang-bn h3,body.lang-bn h4,body.lang-bn h5{font-family:'Noto Sans Bengali',sans-serif}
.btn-accent{background:var(--accent);color:#fff;padding:10px 24px;border-radius:var(--radius);border:none;cursor:pointer;font-family:'Inter';font-weight:600;font-size:13px;transition:all .2s}
.btn-accent:hover{background:var(--accent-light);box-shadow:0 0 0 3px var(--accent-glow)}
.btn-outline{background:transparent;color:var(--primary);padding:10px 24px;border-radius:var(--radius);border:1.5px solid var(--primary);cursor:pointer;font-family:'Inter';font-weight:600;font-size:13px;transition:all .2s}
.btn-outline:hover{background:var(--primary);color:#fff}
.btn-sm{padding:6px 16px;font-size:12px}
.btn-danger{background:var(--danger);color:#fff;padding:6px 16px;border-radius:var(--radius);border:none;cursor:pointer;font-family:'Inter';font-weight:500;font-size:12px;transition:all .2s}
.btn-danger:hover{opacity:.9}
.card{background:var(--card);border-radius:var(--radius-lg);box-shadow:var(--shadow-sm);border:1px solid var(--border);transition:all .2s;overflow:hidden}
.card:hover{box-shadow:var(--shadow-md);border-color:var(--muted)}
input,select,textarea{font-family:'Inter';border:1px solid var(--border);border-radius:var(--radius);padding:10px 14px;font-size:13px;width:100%;transition:all .2s;background:#fff;color:var(--text)}
body.dark-mode input,body.dark-mode select,body.dark-mode textarea{background:var(--bg-alt);border-color:var(--border);color:var(--text)}
body.lang-bn input,body.lang-bn select,body.lang-bn textarea{font-family:'Noto Sans Bengali',sans-serif}
input:focus,select:focus,textarea:focus{outline:none;border-color:var(--primary);box-shadow:0 0 0 3px var(--primary-glow)}
label{font-size:12px;font-weight:600;color:var(--text-secondary);margin-bottom:4px;display:block;letter-spacing:.01em}
.nav-link{position:relative;color:var(--text-secondary);padding:8px 16px;font-size:14px;font-weight:500;transition:all .2s;cursor:pointer;text-decoration:none;border-radius:var(--radius)}
.nav-link:hover,.nav-link.active{color:var(--primary);background:var(--primary-glow)}
.dropdown{position:relative}
.dropdown-menu{position:absolute;top:calc(100% + 4px);left:0;background:var(--card);border-radius:var(--radius);box-shadow:var(--shadow-lg);min-width:220px;padding:4px;opacity:0;visibility:hidden;transition:all .2s;z-index:100;border:1px solid var(--border)}
.dropdown:hover .dropdown-menu{opacity:1;visibility:visible}
.dropdown-item{padding:8px 12px;font-size:13px;color:var(--text-secondary);cursor:pointer;transition:all .15s;display:flex;align-items:center;gap:10px;border-radius:6px;font-weight:500}
.dropdown-item:hover{background:var(--bg-alt);color:var(--primary)}
.dropdown-item i{width:16px;text-align:center;font-size:12px;opacity:.5}
.slider-container{position:relative;overflow:hidden;border-radius:var(--radius-lg);height:500px}
.slide{position:absolute;inset:0;opacity:0;transition:opacity .8s}.slide.active{opacity:1}
.slide img{width:100%;height:100%;object-fit:cover}
.slide-overlay{position:absolute;inset:0;background:linear-gradient(to right,rgba(49,46,129,0.85) 0%,rgba(49,46,129,0.4) 60%,transparent 100%);display:flex;align-items:center;padding:0 80px}
.notice-ticker{background:var(--primary-dark);color:#fff;padding:8px 0;overflow:hidden}
.ticker-wrap{display:flex;animation:ticker 35s linear infinite}
.ticker-item{white-space:nowrap;padding:0 40px;font-size:13px}
@keyframes ticker{0%{transform:translateX(0)}100%{transform:translateX(-50%)}}
.badge{display:inline-flex;align-items:center;gap:4px;padding:3px 10px;border-radius:var(--radius-full);font-size:11px;font-weight:600;letter-spacing:.02em}
.badge-success{background:var(--success-light);color:var(--success)}.badge-warning{background:var(--warning-light);color:var(--warning)}.badge-info{background:var(--info-light);color:var(--info)}.badge-danger{background:var(--danger-light);color:var(--danger)}
.modal-overlay{position:fixed;inset:0;background:rgba(0,0,0,0.4);backdrop-filter:blur(4px);z-index:1000;display:flex;align-items:center;justify-content:center;opacity:0;visibility:hidden;transition:all .2s}
.modal-overlay.show{opacity:1;visibility:visible}
.modal-content{background:var(--card);border-radius:var(--radius-lg);max-width:600px;width:90%;max-height:85vh;overflow-y:auto;transform:scale(.95);transition:all .2s;box-shadow:var(--shadow-xl)}
.modal-overlay.show .modal-content{transform:scale(1)}
.toast{position:fixed;top:20px;right:20px;z-index:2000;padding:12px 20px;border-radius:var(--radius);color:#fff;font-size:13px;font-weight:500;transform:translateX(120%);transition:transform .3s;box-shadow:var(--shadow-lg)}
.toast.show{transform:translateX(0)}.toast-success{background:var(--success)}.toast-error{background:var(--danger)}.toast-info{background:var(--info)}
.admin-sidebar{width:240px;background:var(--card);min-height:100vh;position:fixed;left:0;top:0;z-index:50;transition:transform .2s;overflow-y:auto;border-right:1px solid var(--border)}
.admin-main{margin-left:240px;min-height:100vh;background:var(--bg)}
.admin-nav-item{padding:10px 20px;color:var(--text-secondary);font-size:13px;font-weight:500;cursor:pointer;transition:all .15s;display:flex;align-items:center;gap:12px;border-left:3px solid transparent;margin:1px 8px;border-radius:0 6px 6px 0}
.admin-nav-item:hover{background:var(--bg-alt)}
.admin-nav-item.active{background:var(--primary-glow);color:var(--primary);border-left-color:var(--primary);font-weight:600}
.admin-nav-item i{width:18px;text-align:center;font-size:14px}
.admin-card{background:var(--card);border-radius:var(--radius-lg);padding:20px;box-shadow:var(--shadow-sm);border:1px solid var(--border)}
.admin-table{width:100%;border-collapse:collapse;font-size:13px}
.admin-table th{background:var(--bg-alt);padding:10px 14px;text-align:left;font-weight:600;color:var(--text-secondary);font-size:11px;text-transform:uppercase;letter-spacing:.05em;border-bottom:1px solid var(--border)}
.admin-table td{padding:12px 14px;border-bottom:1px solid var(--border-light);vertical-align:middle}
.admin-table tbody tr:hover td{background:var(--bg)}.admin-table tr:last-child td{border-bottom:none}
.stat-card{background:var(--card);border-radius:var(--radius-lg);padding:20px;box-shadow:var(--shadow-sm);border:1px solid var(--border);transition:all .2s}
.stat-card:hover{box-shadow:var(--shadow-md)}
.tab-btn{padding:8px 16px;border:none;background:transparent;cursor:pointer;font-family:'Inter';font-size:13px;font-weight:500;color:var(--muted);border-bottom:2px solid transparent;transition:all .15s}
.tab-btn.active{color:var(--primary);border-bottom-color:var(--primary);font-weight:600}
.progress-bar{height:6px;background:var(--border);border-radius:var(--radius-full);overflow:hidden}
.progress-fill{height:100%;border-radius:var(--radius-full);transition:width .6s;background:var(--success)}
.program-card{
    display:flex;
}

.program-card .card{
    position:relative;
    width:100%;
    height:100%;
    display:flex;
    flex-direction:column;
}

.program-card .p-4{
    flex:1;
    display:flex;
    flex-direction:column;
}

.program-card .flex.gap-2{
    margin-top:auto;
}

.program-card .card::before{
    content:'';
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:3px;
    background:linear-gradient(90deg,var(--primary),var(--accent));
    opacity:0;
    transition:opacity .2s;
}

.program-card:hover .card::before{
    opacity:1;
}

.btn-primary{
    background:var(--primary);
    color:#fff;
    padding:10px 24px;
    border-radius:var(--radius);
    border:none;
    cursor:pointer;
    font-family:'Inter';
    font-weight:600;
    font-size:13px;
    transition:all .2s;
}

.btn-primary:hover{
    background:var(--primary-light);
    box-shadow:0 0 0 3px var(--primary-glow);
}
.lightbox{position:fixed;inset:0;background:rgba(0,0,0,0.9);z-index:2000;display:flex;align-items:center;justify-content:center;opacity:0;visibility:hidden;transition:all .2s}
.lightbox.show{opacity:1;visibility:visible}
.fade-in{animation:fadeIn .4s ease}
@keyframes fadeIn{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}
.slider-dot{width:8px;height:8px;border-radius:50%;background:rgba(255,255,255,0.4);cursor:pointer;transition:all .2s;border:none}
.slider-dot.active{background:var(--accent);box-shadow:0 0 0 2px rgba(6,182,212,0.3)}
#loading-screen{position:fixed;inset:0;background:var(--bg);z-index:9999;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:16px;transition:opacity .3s}
.loader{border:4px solid var(--border);border-top:4px solid var(--primary);border-radius:50%;width:40px;height:40px;animation:spin 1s linear infinite}
@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}

/* Calendar Styles */
/* Calendar Styles Update */
.calendar-grid {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 4px;
    text-align: center;
    font-size: 12px;
}

.calendar-day {
    padding: 8px 4px;
    border-radius: 4px;
    background: var(--bg);
    min-height: 36px; /* Ensures box shape even if empty */
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: background 0.2s;
}

.calendar-day:hover:not([style*="transparent"]) {
    background: var(--bg-alt);
}

.calendar-day.has-event {
    background: var(--primary);
    color: #fff;
    font-weight: 600;
    box-shadow: 0 2px 4px rgba(49,46,129,0.2);
}

.calendar-day.today.has-event {
    background: var(--primary);
    color: #fff;
    font-weight: 600;
    box-shadow: 0 2px 4px rgba(49,46,129,0.2), inset 0 0 0 2px var(--accent);
}

.calendar-day-name {
    font-size: 10px;
    color: var(--muted);
    font-weight: 600;
    padding: 4px;
}

/* ===== FORM LAYOUT CLASSES ===== */
.form-group{margin-bottom:16px}
.form-group label{font-size:12px;font-weight:600;color:var(--text-secondary);margin-bottom:4px;display:block;letter-spacing:.01em}
.form-group input,.form-group select,.form-group textarea{font-family:'Inter',sans-serif;border:1px solid var(--border);border-radius:var(--radius);padding:10px 14px;font-size:13px;width:100%;transition:all .2s;background:#fff;color:var(--text)}
body.dark-mode .form-group input,body.dark-mode .form-group select,body.dark-mode .form-group textarea{background:var(--bg-alt);border-color:var(--border);color:var(--text)}
body.lang-bn .form-group input,body.lang-bn .form-group select,body.lang-bn .form-group textarea{font-family:'Noto Sans Bengali',sans-serif}
.form-group input:focus,.form-group select:focus,.form-group textarea:focus{outline:none;border-color:var(--primary);box-shadow:0 0 0 3px var(--primary-glow)}
.form-group input[type="file"]{padding:8px 10px;font-size:12px;cursor:pointer}
.form-row{display:grid;grid-template-columns:1fr 1fr;gap:16px}
@media(max-width:500px){.form-row{grid-template-columns:1fr;gap:0}}

.lang-switch-btn {
  position: relative;
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 14px;
  border-radius: var(--radius);
  border: 1.5px solid var(--border);
  background: var(--card);
  cursor: pointer;
  font-family: 'Inter', sans-serif;
  font-weight: 600;
  font-size: 12px;
  color: var(--text);
  transition: all 0.2s;
  white-space: nowrap;
}
.lang-switch-btn:hover {
  border-color: var(--primary);
  background: var(--primary-glow);
  color: var(--primary);
}
.lang-switch-btn i {
  font-size: 14px;
}
.lang-badge {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 22px;
  height: 22px;
  border-radius: 50%;
  background: var(--primary);
  color: #fff;
  font-size: 10px;
  font-weight: 700;
}

/* Enhanced Form Styles */
.form-group { margin-bottom: 16px; }
.form-group label { display: block; margin-bottom: 6px; font-weight: 600; font-size: 12px; color: var(--text-secondary); }
.form-group input, .form-group select, .form-group textarea { width: 100%; }
.form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
.file-upload-zone {
  border: 2px dashed var(--border);
  border-radius: var(--radius-lg);
  padding: 24px;
  text-align: center;
  cursor: pointer;
  transition: all 0.2s;
  background: var(--bg);
}
.file-upload-zone:hover {
  border-color: var(--primary);
  background: var(--primary-glow);
}
.file-upload-zone i { font-size: 32px; color: var(--primary); margin-bottom: 8px; }

@media(max-width:768px){.slider-container{height:300px}.slide-overlay{padding:0 24px}.admin-sidebar{transform:translateX(-100%)}.admin-sidebar.open{transform:translateX(0)}.admin-main{margin-left:0}}
::-webkit-scrollbar{width:6px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:var(--border);border-radius:3px}::-webkit-scrollbar-thumb:hover{background:var(--muted)}
::selection{background:var(--primary);color:#fff}:focus-visible{outline:2px solid var(--primary);outline-offset:2px}
</style>
</head>
<body>

<!-- Loading Screen -->
<div id="loading-screen">
  <div style="width:60px;height:60px;background:var(--primary);border-radius:12px;display:flex;align-items:center;justify-content:center;margin-bottom:8px">
    <i class="fas fa-university text-white text-2xl"></i>
  </div>
  <div class="loader"></div>
  <div class="text-sm text-gray-500" data-i18n="loading">Loading Academy Data...</div>
</div>

<div id="toast" class="toast"></div>

<div id="lightbox" class="lightbox" onclick="closeLightbox()">
  <img id="lightbox-img" src="" style="max-width:90%;max-height:90%;border-radius:8px">
</div>

<!-- ========== PUBLIC SITE ========== -->
<div id="public-site">

  <header style="background:var(--card);border-bottom:1px solid var(--border);position:sticky;top:0;z-index:90">
    <div class="max-w-7xl mx-auto px-4 flex items-center justify-between h-16">
      <div class="flex items-center gap-3 cursor-pointer" onclick="navigate('home')">
    <img src="PWDTA-logo.png" alt="PWDTA" style="height:45px;filter:drop-shadow(0 3px 6px rgba(0,0,0,0.3))">
</div>
      
      <!-- Action Buttons: Theme + Language Switch -->
      <div class="flex items-center gap-2">
        <!-- Language Switch Button -->
        <button onclick="toggleLanguage()" class="lang-switch-btn" id="lang-switch-btn" title="Switch Language / ভাষা পরিবর্তন">
          <i class="fas fa-language"></i>
          <span id="lang-label">EN</span>
        </button>
        
        <!-- Theme Toggle -->
        <button onclick="toggleTheme()" class="p-2 rounded-full hover:bg-gray-200 transition" style="background:none;border:1px solid var(--border)">
          <i id="theme-icon" class="fas fa-moon text-gray-600"></i>
        </button>
      </div>
      
      <nav class="hidden lg:flex items-center gap-1" id="main-nav">
        <a class="nav-link active" onclick="navigate('home')" data-page="home" data-i18n="nav_home">Home</a>
        <div class="dropdown">
          <a class="nav-link" data-page="about" data-i18n="nav_about">About <i class="fas fa-chevron-down ml-1" style="font-size:10px"></i></a>
          <div class="dropdown-menu">
            <a class="dropdown-item" onclick="navigate('vision')"><i class="fas fa-eye"></i><span data-i18n="nav_vision">Vision & Mission</span></a>
            <a class="dropdown-item" onclick="navigate('management')"><i class="fas fa-users"></i><span data-i18n="nav_management">Management</span></a>
            <a class="dropdown-item" onclick="navigate('organogram')"><i class="fas fa-sitemap"></i><span data-i18n="nav_organogram">Organogram</span></a>
            <a class="dropdown-item" onclick="navigate('campus')"><i class="fas fa-school"></i><span data-i18n="nav_campus">Campus</span></a>
            <a class="dropdown-item" onclick="navigate('officers')"><i class="fas fa-id-badge"></i><span data-i18n="nav_officers">Officers</span></a>
          </div>
        </div>
        <div class="dropdown">
  <a class="nav-link" data-page="facilities" data-i18n="nav_facilities">
    Facilities 
    <i class="fas fa-chevron-down ml-1" style="font-size:10px"></i>
  </a>

  <div class="dropdown-menu">
    <a class="dropdown-item" onclick="navigate('classroom')">
      <i class="fas fa-chalkboard-teacher"></i>
      <span data-i18n="nav_classroom">Classroom</span>
    </a>

    <a class="dropdown-item" onclick="navigate('computerlab')">
      <i class="fas fa-desktop"></i>
      <span data-i18n="nav_computerlab">Computer Lab</span>
    </a>

    <a class="dropdown-item" onclick="navigate('library')">
      <i class="fas fa-book-reader"></i>
      <span data-i18n="nav_library">Library</span>
    </a>

    <a class="dropdown-item" onclick="navigate('residential')">
      <i class="fas fa-bed"></i>
      <span data-i18n="nav_residential">Residential</span>
    </a>

    <a class="dropdown-item" onclick="navigate('playground')">
      <i class="fas fa-futbol"></i>
      <span data-i18n="nav_playground">Playground</span>
    </a>

    <a class="dropdown-item" onclick="navigate('gymnasium')">
      <i class="fas fa-dumbbell"></i>
      <span data-i18n="nav_gymnasium">Gymnasium</span>
    </a>

    <a class="dropdown-item" onclick="navigate('swimmingpool')">
      <i class="fas fa-swimmer"></i>
      <span data-i18n="nav_swimmingpool">Swimming Pool</span>
    </a>

    <a class="dropdown-item" onclick="navigate('testinglab')">
      <i class="fas fa-flask"></i>
      <span data-i18n="nav_testinglab">Testing Laboratory</span>
    </a>
  </div>
</div>
        <div class="dropdown">
          <a class="nav-link" data-page="media" data-i18n="nav_media">Media <i class="fas fa-chevron-down ml-1" style="font-size:10px"></i></a>
          <div class="dropdown-menu">
            <a class="dropdown-item" onclick="navigate('photogallery')"><i class="fas fa-image"></i><span data-i18n="nav_photos">Photos</span></a>
            <a class="dropdown-item" onclick="navigate('videogallery')"><i class="fas fa-video"></i><span data-i18n="nav_videos">Videos</span></a>
          </div>
        </div>
        <div class="dropdown">
          <a class="nav-link" data-page="testinglab" data-i18n="nav_lab">Lab <i class="fas fa-chevron-down ml-1" style="font-size:10px"></i></a>
          <div class="dropdown-menu">
            <a class="dropdown-item" onclick="navigate('materialtest')"><i class="fas fa-flask"></i><span data-i18n="nav_materialtest">Material Test</span></a>
            <a class="dropdown-item" onclick="navigate('equipment')"><i class="fas fa-tools"></i><span data-i18n="nav_equipment">Equipment</span></a>
            <a class="dropdown-item" onclick="navigate('testingreport')"><i class="fas fa-file-alt"></i><span data-i18n="nav_reports">Reports</span></a>
          </div>
        </div>
        <a class="nav-link" onclick="navigate('trainings')" data-page="trainings" data-i18n="nav_trainings">Trainings</a>
        <a class="nav-link" onclick="navigate('testing')" data-page="testing" data-i18n="nav_testing">Testing</a>
        <a class="nav-link" onclick="navigate('notices')" data-page="notices" data-i18n="nav_notices">Notices</a>
        <a class="nav-link" onclick="navigate('contact')" data-page="contact" data-i18n="nav_contact">Contact</a>
        <a class="nav-link" onclick="navigate('verify')" data-page="verify" data-i18n="nav_verify">Verify</a>
      </nav>
      <div class="flex items-center gap-3">
        <button class="btn-primary btn-sm hidden sm:block" onclick="navigate('login')" id="header-login-btn" data-i18n="nav_login">Login</button>
        <button class="lg:hidden" style="background:none;border:none;cursor:pointer;color:var(--text);font-size:20px" onclick="toggleMobileNav()"><i class="fas fa-bars"></i></button>
      </div>
    </div>
    
    <!-- Mobile Navigation with i18n -->
    <div id="mobile-nav" class="lg:hidden hidden" style="background:var(--card);border-top:1px solid var(--border);padding:16px">
      <div class="flex flex-col gap-1">
        <a class="py-2 px-3 rounded-lg text-sm cursor-pointer hover:bg-gray-50" onclick="navigate('home');toggleMobileNav()" data-i18n="mobile_home">Home</a>
        <a class="py-2 px-3 rounded-lg text-sm cursor-pointer hover:bg-gray-50" onclick="navigate('vision');toggleMobileNav()" data-i18n="mobile_about">About Us</a>
        <a class="py-2 px-3 rounded-lg text-sm cursor-pointer hover:bg-gray-50" onclick="navigate('classroom');toggleMobileNav()" data-i18n="mobile_facilities">Facilities</a>
        <a class="py-2 px-3 rounded-lg text-sm cursor-pointer hover:bg-gray-50" onclick="navigate('photogallery');toggleMobileNav()" data-i18n="mobile_media">Media</a>
        <a class="py-2 px-3 rounded-lg text-sm cursor-pointer hover:bg-gray-50" onclick="navigate('materialtest');toggleMobileNav()" data-i18n="mobile_lab">Testing Lab</a>
        <a class="py-2 px-3 rounded-lg text-sm cursor-pointer hover:bg-gray-50" onclick="navigate('trainings');toggleMobileNav()" data-i18n="mobile_trainings">Trainings</a>
        <a class="py-2 px-3 rounded-lg text-sm cursor-pointer hover:bg-gray-50" onclick="navigate('testing');toggleMobileNav()" data-i18n="mobile_testing">Testing</a>
        <a class="py-2 px-3 rounded-lg text-sm cursor-pointer hover:bg-gray-50" onclick="navigate('notices');toggleMobileNav()" data-i18n="mobile_notices">Notices</a>
        <a class="py-2 px-3 rounded-lg text-sm cursor-pointer hover:bg-gray-50" onclick="navigate('contact');toggleMobileNav()" data-i18n="mobile_contact">Contact</a>
        <button class="btn-primary btn-sm mt-2" onclick="navigate('login');toggleMobileNav()" data-i18n="mobile_login">Login</button>
      </div>
    </div>
  </header>

  <!-- Notice Ticker (dynamic) -->
  <div class="notice-ticker">
    <div class="max-w-7xl mx-auto px-4 flex items-center gap-4">
      <span style="background:var(--accent);color:#fff;padding:2px 10px;border-radius:4px;font-size:11px;font-weight:700;letter-spacing:.05em" data-i18n="notice_label">NOTICE</span>
      <div style="overflow:hidden;flex:1">
        <div class="ticker-wrap" id="ticker-wrap">
          <span class="ticker-item" data-i18n="notice_loading">Loading notices...</span>
        </div>
      </div>
    </div>
  </div>

  <main id="page-content" class="max-w-7xl mx-auto px-4 py-8"></main>

  <footer style="background:var(--primary-dark);color:#fff;margin-top:60px">
    <div class="max-w-7xl mx-auto px-4 py-12 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8">
      <div>
        <div class="flex items-center gap-3 mb-4">
          <div style="width:36px;height:36px;background:var(--accent);border-radius:8px;display:flex;align-items:center;justify-content:center"><i class="fas fa-graduation-cap text-white"></i></div>
          <div class="font-bold" data-i18n="footer_title">PWD Training Academy</div>
        </div>
        <p class="text-sm opacity-60 leading-relaxed" data-i18n="footer_desc">Premier training institution under Public Works Department for civil engineering and construction management.</p>
      </div>
      <div>
        <h4 class="font-bold mb-4 text-sm" data-i18n="footer_quick_links">Quick Links</h4>
        <div class="flex flex-col gap-2">
          <a class="text-sm opacity-60 hover:opacity-100 hover:text-cyan-400 cursor-pointer" onclick="navigate('home')" data-i18n="footer_home">Home</a>
          <a class="text-sm opacity-60 hover:opacity-100 hover:text-cyan-400 cursor-pointer" onclick="navigate('trainings')" data-i18n="footer_trainings">Trainings</a>
          <a class="text-sm opacity-60 hover:opacity-100 hover:text-cyan-400 cursor-pointer" onclick="navigate('testing')" data-i18n="footer_testing">Testing</a>
          <a class="text-sm opacity-60 hover:opacity-100 hover:text-cyan-400 cursor-pointer" onclick="navigate('notices')" data-i18n="footer_notices">Notices</a>
        </div>
      </div>
      <div>
        <h4 class="font-bold mb-4 text-sm" data-i18n="footer_contact">Contact</h4>
        <div class="flex flex-col gap-3 text-sm opacity-60">
          <div class="flex items-start gap-3"><i class="fas fa-map-marker-alt mt-1 text-cyan-400"></i><span data-i18n="footer_address">PWD, Sher-e-Bangla Nagar, Dhaka-1207</span></div>
          <div class="flex items-center gap-3"><i class="fas fa-phone text-cyan-400"></i><span data-i18n="footer_phone">+880-2-8181234</span></div>
          <div class="flex items-center gap-3"><i class="fas fa-envelope text-cyan-400"></i><span data-i18n="footer_email">info@pwd.training.gov.bd</span></div>
        </div>
      </div>
      <div>
        <h4 class="font-bold mb-4 text-sm" data-i18n="footer_connect">Connect</h4>
        <div class="flex gap-2 mb-4">
          <a class="w-9 h-9 rounded-lg bg-white/10 flex items-center justify-center hover:bg-cyan-500 transition cursor-pointer"><i class="fab fa-facebook-f text-sm"></i></a>
          <a class="w-9 h-9 rounded-lg bg-white/10 flex items-center justify-center hover:bg-cyan-500 transition cursor-pointer"><i class="fab fa-youtube text-sm"></i></a>
        </div>
      </div>
    </div>
    <div style="border-top:1px solid rgba(255,255,255,.1)" class="max-w-7xl mx-auto px-4 py-4 text-center text-xs opacity-40" data-i18n="footer_copyright">&copy; 2026 PWD Training Academy. All rights reserved.</div>
  </footer>
</div>

<!-- ========== ADMIN PANEL ========== -->
<div id="admin-panel" style="display:none">
  <aside class="admin-sidebar" id="admin-sidebar">
    <div class="p-4 border-b border-gray-200">
      <div class="flex items-center gap-3">
        <div style="width:32px;height:32px;background:var(--primary);border-radius:8px;display:flex;align-items:center;justify-content:center"><i class="fas fa-shield-alt text-white text-sm"></i></div>
        <div><div class="font-bold text-sm" style="color:var(--primary)" data-i18n="admin_panel_title">Admin Panel</div><div class="text-xs text-gray-400" data-i18n="admin_panel_subtitle">PWD Training</div></div>
      </div>
    </div>
    <nav class="py-2">
      <div class="px-4 pb-1 text-xs text-gray-400 uppercase tracking-wider font-semibold" data-i18n="admin_main">Main</div>
      <div class="admin-nav-item active" onclick="adminNav('dashboard',this)"><i class="fas fa-tachometer-alt"></i><span data-i18n="admin_dashboard">Dashboard</span></div>
      <div class="px-4 pb-1 pt-3 text-xs text-gray-400 uppercase tracking-wider font-semibold" data-i18n="admin_management">Management</div>
      <div class="admin-nav-item" onclick="adminNav('admin-trainings',this)"><i class="fas fa-chalkboard-teacher"></i><span data-i18n="admin_trainings">Trainings</span></div>
      <div class="admin-nav-item" onclick="adminNav('admin-testings',this)"><i class="fas fa-flask"></i><span data-i18n="admin_testings">Testing</span></div>
      <div class="admin-nav-item" onclick="adminNav('admin-notices',this)"><i class="fas fa-bullhorn"></i><span data-i18n="admin_notices">Notices</span></div>
      <div class="admin-nav-item" onclick="adminNav('admin-officers',this)"><i class="fas fa-users"></i><span data-i18n="admin_officers">Officers</span></div>
      <div class="admin-nav-item" onclick="adminNav('admin-employees',this)">
    <i class="fas fa-id-card"></i>
    <span data-i18n="admin_employees">Employees</span>
</div>
      <div class="admin-nav-item" onclick="adminNav('admin-trainees',this)"><i class="fas fa-user-graduate"></i><span data-i18n="admin_trainees">Trainees</span></div>
      <div class="px-4 pb-1 pt-3 text-xs text-gray-400 uppercase tracking-wider font-semibold" data-i18n="admin_resources">Resources</div>
      <div class="admin-nav-item" onclick="adminNav('admin-equipment',this)"><i class="fas fa-tools"></i><span data-i18n="admin_equipment">Equipment</span></div>
      <div class="admin-nav-item" onclick="adminNav('admin-gallery',this)"><i class="fas fa-image"></i><span data-i18n="admin_gallery">Gallery</span></div>
      <div class="admin-nav-item" onclick="adminNav('admin-videos',this)"><i class="fas fa-video"></i><span data-i18n="admin_videos">Videos</span></div>
      <div class="admin-nav-item" onclick="adminNav('admin-facilities',this)"><i class="fas fa-school"></i><span data-i18n="admin_facilities">Facilities</span></div>
      <div class="admin-nav-item" onclick="adminNav('admin-sliders',this)"><i class="fas fa-images"></i><span data-i18n="admin_sliders">Sliders</span></div>
      <div class="px-4 pb-1 pt-3 text-xs text-gray-400 uppercase tracking-wider font-semibold" data-i18n="admin_system">System</div>
      <div class="admin-nav-item" onclick="adminNav('admin-settings',this)"><i class="fas fa-cog"></i><span data-i18n="admin_settings">Settings</span></div>
      <div class="admin-nav-item" onclick="adminNav('admin-reports',this)"><i class="fas fa-chart-bar"></i><span data-i18n="admin_reports">Reports</span></div>
    </nav>
    <div class="p-4 mt-auto border-t border-gray-200">
      <div class="flex items-center gap-3 mb-3">
        <div class="w-8 h-8 rounded-lg bg-cyan-500 flex items-center justify-center text-xs font-bold text-white">A</div>
        <div><div class="text-sm font-medium" id="admin-user-name">Admin</div><div class="text-xs text-gray-400" data-i18n="admin_role">Super Admin</div></div>
      </div>
      <button class="w-full text-left text-xs text-red-500 hover:text-red-600 flex items-center gap-2 cursor-pointer" onclick="logoutAdmin()"><i class="fas fa-sign-out-alt"></i><span data-i18n="admin_logout">Logout</span></button>
      <button class="w-full text-left text-xs text-gray-400 hover:text-gray-600 flex items-center gap-2 cursor-pointer mt-1" onclick="goToPublic()"><i class="fas fa-external-link-alt"></i><span data-i18n="admin_view_site">View Site</span></button>
    </div>
  </aside>
  <div class="admin-main">
    <header class="bg-white px-6 py-3 flex items-center justify-between sticky top-0 z-40" style="border-bottom:1px solid var(--border)">
      <div class="flex items-center gap-4">
        <button class="md:hidden" style="background:none;border:none;cursor:pointer;color:var(--text);font-size:18px" onclick="document.getElementById('admin-sidebar').classList.toggle('open')"><i class="fas fa-bars"></i></button>
        <h2 class="text-base font-semibold" id="admin-page-title">Dashboard</h2>
      </div>
      <div class="flex items-center gap-3">
        <button onclick="toggleLanguage()" class="lang-switch-btn" title="Switch Language / ভাষা পরিবর্তন">
          <i class="fas fa-language"></i>
          <span id="admin-lang-label">EN</span>
        </button>
        <button onclick="toggleTheme()" class="p-2 rounded-full hover:bg-gray-200 transition" style="background:none;border:1px solid var(--border)"><i class="fas fa-moon text-gray-600"></i></button>
        <span class="text-xs text-gray-400"><i class="far fa-clock mr-1"></i><span id="admin-time"></span></span>
      </div>
    </header>
    <div id="admin-content" class="p-6"></div>
  </div>
</div>

<!-- Modal -->
<div id="modal-overlay" class="modal-overlay" onclick="if(event.target===this)closeModal()">
  <div class="modal-content" id="modal-content"></div>
</div>

<script>// =============================================
// LANGUAGE SYSTEM (E2B/B2E) - COMPLETE TRANSLATIONS
// =============================================
let currentLang = 'en';

const translations = {
  'nav_home': { en: 'Home', bn: 'হোম' },
  'nav_about': { en: 'About', bn: 'সম্পর্কে' },
  'nav_vision': { en: 'Vision & Mission', bn: 'দর্শন ও লক্ষ্য' },
  'nav_management': { en: 'Management', bn: 'ব্যবস্থাপনা' },
  'nav_organogram': { en: 'Organogram', bn: 'সাংগঠনিক চার্ট' },
  'nav_campus': { en: 'Campus', bn: 'ক্যাম্পাস' },
  'nav_officers': { en: 'Officers', bn: 'কর্মকর্তাগণ' },
  'nav_facilities': { en: 'Facilities', bn: 'সুবিধাসমূহ' },
  'nav_classroom': { en: 'Classroom', bn: 'ক্লাসরুম' },
  'nav_computerlab': { en: 'Computer Lab', bn: 'কম্পিউটার ল্যাব' },
  'nav_library': { en: 'Library', bn: 'লাইব্রেরি' },
  'nav_residential': { en: 'Residential', bn: 'আবাসিক' },
  'nav_playground': { en: 'Playground', bn: 'খেলার মাঠ' },
  'nav_gymnasium': { en: 'Gymnasium', bn: 'জিমনেসিয়াম' },
  'nav_swimmingpool': { en: 'Swimming Pool', bn: 'সুইমিং পুল' },
  'nav_testinglab': { en: 'Testing Laboratory', bn: 'পরীক্ষাগার' },
  'nav_media': { en: 'Media', bn: 'মিডিয়া' },
  'nav_photos': { en: 'Photos', bn: 'ফটো' },
  'nav_videos': { en: 'Videos', bn: 'ভিডিও' },
  'nav_lab': { en: 'Lab', bn: 'ল্যাব' },
  'nav_materialtest': { en: 'Material Test', bn: 'উপকরণ পরীক্ষা' },
  'nav_equipment': { en: 'Equipment', bn: 'যন্ত্রপাতি' },
  'nav_reports': { en: 'Reports', bn: 'রিপোর্ট' },
  'nav_trainings': { en: 'Trainings', bn: 'প্রশিক্ষণ' },
  'nav_testing': { en: 'Testing', bn: 'পরীক্ষা' },
  'nav_notices': { en: 'Notices', bn: 'নোটিশ' },
  'nav_contact': { en: 'Contact', bn: 'যোগাযোগ' },
  'nav_verify': { en: 'Verify', bn: 'যাচাই' },
  'nav_login': { en: 'Login', bn: 'লগইন' },
  'mobile_home': { en: 'Home', bn: 'হোম' },
  'mobile_about': { en: 'About Us', bn: 'আমাদের সম্পর্কে' },
  'mobile_facilities': { en: 'Facilities', bn: 'সুবিধাসমূহ' },
  'mobile_media': { en: 'Media', bn: 'মিডিয়া' },
  'mobile_lab': { en: 'Testing Lab', bn: 'পরীক্ষাগার' },
  'mobile_trainings': { en: 'Trainings', bn: 'প্রশিক্ষণ' },
  'mobile_testing': { en: 'Testing', bn: 'পরীক্ষা' },
  'mobile_notices': { en: 'Notices', bn: 'নোটিশ' },
  'mobile_contact': { en: 'Contact', bn: 'যোগাযোগ' },
  'mobile_login': { en: 'Login', bn: 'লগইন' },
  'notice_label': { en: 'NOTICE', bn: 'নোটিশ' },
  'notice_loading': { en: 'Loading notices...', bn: 'নোটিশ লোড হচ্ছে...' },
  'notice_no_notices': { en: 'No notices available', bn: 'কোনো নোটিশ নেই' },
  'footer_title': { en: 'PWD Training Academy', bn: 'পিডব্লিউডি প্রশিক্ষণ একাডেমি' },
  'footer_desc': { en: 'Premier training institution under Public Works Department for civil engineering and construction management.', bn: 'গণপূর্ত অধিদপ্তরের অধীনে সিভিল ইঞ্জিনিয়ারিং ও নির্মাণ ব্যবস্থাপনায় প্রধান প্রশিক্ষণ প্রতিষ্ঠান।' },
  'footer_quick_links': { en: 'Quick Links', bn: 'দ্রুত লিঙ্ক' },
  'footer_home': { en: 'Home', bn: 'হোম' },
  'footer_trainings': { en: 'Trainings', bn: 'প্রশিক্ষণ' },
  'footer_testing': { en: 'Testing', bn: 'পরীক্ষা' },
  'footer_notices': { en: 'Notices', bn: 'নোটিশ' },
  'footer_contact': { en: 'Contact', bn: 'যোগাযোগ' },
  'footer_address': { en: 'PWD, Sher-e-Bangla Nagar,Dhaka-1207', bn: 'পিডব্লিউডি, শের-ই-বাংলা নগর,<br>ঢাকা-১২০৭' },
  'footer_phone': { en: '+880-2-8181234', bn: '+৮৮০-২-৮১৮১২৩৪' },
  'footer_email': { en: 'info@pwd.training.gov.bd', bn: 'info@pwd.training.gov.bd' },
  'footer_connect': { en: 'Connect', bn: 'সংযুক্ত হন' },
  'footer_copyright': { en: '© 2026 PWD Training Academy. All rights reserved.', bn: '© ২০২৬ পিডব্লিউডি প্রশিক্ষণ একাডেমি। সর্বস্বত্ব সংরক্ষিত।' },
  'loading': { en: 'Loading Academy Data...', bn: 'একাডেমি ডাটা লোড হচ্ছে...' },
  'home_stats_trainings': { en: 'Trainings', bn: 'প্রশিক্ষণ' },
  'home_stats_trainees': { en: 'Trainees', bn: 'প্রশিক্ষণার্থী' },
  'home_stats_tests': { en: 'Tests Available', bn: 'উপলব্ধ পরীক্ষা' },
  'home_stats_facilities': { en: 'Facilities', bn: 'সুবিধাসমূহ' },
  'home_programs_title': { en: 'Available Programs', bn: 'উপলব্ধ প্রোগ্রাম' },
  'home_programs_all': { en: 'All', bn: 'সব' },
  'home_programs_training': { en: 'Trainings', bn: 'প্রশিক্ষণ' },
  'home_programs_testing': { en: 'Testing', bn: 'পরীক্ষা' },
  'home_view_all': { en: 'View All Programs', bn: 'সব প্রোগ্রাম দেখুন' },
  'home_gallery_title': { en: 'Photo Gallery', bn: 'ফটো গ্যালারি' },
  'home_view_all_gallery': { en: 'View All', bn: 'সব দেখুন' },
  'home_location_title': { en: 'Our Location', bn: 'আমাদের অবস্থান' },
  'home_stay_updated': { en: 'Stay Updated', bn: 'আপডেট থাকুন' },
  'home_stay_updated_desc': { en: 'Register your interest and get notified when new courses are announced.', bn: 'আপনার আগ্রহ নিবন্ধন করুন এবং নতুন কোর্স ঘোষণার সাথে সাথে জানতে পারবেন।' },
  'home_view_calendar': { en: 'View Calendar', bn: 'ক্যালেন্ডার দেখুন' },
  'home_register': { en: 'Register', bn: 'নিবন্ধন করুন' },
  'home_explore': { en: 'Explore', bn: 'অন্বেষণ করুন' },
  'home_enroll_now': { en: 'Enroll Now', bn: 'এখনই ভর্তি হন' },
  'calendar_title': { en: 'Course Calendar', bn: 'কোর্স ক্যালেন্ডার' },
  'calendar_view_full': { en: 'View Full Calendar', bn: 'সম্পূর্ণ ক্যালেন্ডার দেখুন' },
  'calendar_no_events': { en: 'No courses scheduled this month.', bn: 'এই মাসে কোনো কোর্স নেই।' },
  'calendar_year_view': { en: 'Yearly Schedule', bn: 'বাৎসরিক সময়সূচি' },
  'verify_title': { en: 'Verification', bn: 'যাচাইকরণ' },
  'verify_cert_tab': { en: 'Certificate', bn: 'সার্টিফিকেট' },
  'verify_test_tab': { en: 'Test Report', bn: 'টেস্ট রিপোর্ট' },
  'verify_cert_title': { en: 'Certificate Verification', bn: 'সার্টিফিকেট যাচাই' },
  'verify_test_title': { en: 'Test Report Verification', bn: 'টেস্ট রিপোর্ট যাচাই' },
  'verify_cert_desc': { en: 'Enter your certificate number to verify authenticity.', bn: 'সার্টিফিকেটের সত্যতা যাচাই করতে নম্বর দিন।' },
  'verify_test_desc': { en: 'Enter test report ID to verify test results.', bn: 'টেস্ট রিপোর্ট যাচাই করতে আইডি দিন।' },
  'verify_cert_number': { en: 'Certificate Number', bn: 'সার্টিফিকেট নম্বর' },
  'verify_test_id': { en: 'Test Report ID', bn: 'টেস্ট রিপোর্ট আইডি' },
  'verify_placeholder': { en: 'e.g., PWD-2026-00123', bn: 'যেমন: PWD-2026-00123' },
  'verify_test_placeholder': { en: 'e.g., TR-2026-001', bn: 'যেমন: TR-2026-001' },
  'verify_btn': { en: 'Verify', bn: 'যাচাই করুন' },
  'verify_verified': { en: 'Verified', bn: 'যাচাই হয়েছে' },
  'verify_valid': { en: 'VALID', bn: 'বৈধ' },
  'verify_cert_no': { en: 'Certificate No:', bn: 'সার্টিফিকেট নম্বর:' },
  'verify_status': { en: 'Status:', bn: 'অবস্থা:' },
  'interest_btn': { en: 'Interested', bn: 'আগ্রহী' },
  'interest_registered': { en: 'Interest registered successfully!', bn: 'আপনার আগ্রহ নিবন্ধিত হয়েছে!' },
  'about_vision_title': { en: 'Our Vision', bn: 'আমাদের দর্শন' },
  'about_vision_text': { en: 'To be the premier center of excellence in engineering training and capacity building, contributing to sustainable infrastructure development in Bangladesh.', bn: 'বাংলাদেশে টেকসই অবকাঠামো উন্নয়নে অবদান রাখতে ইঞ্জিনিয়ারিং প্রশিক্ষণ ও সক্ষমতা বৃদ্ধিতে শীর্ষস্থানীয় কেন্দ্র হওয়া।' },
  'about_mission_title': { en: 'Our Mission', bn: 'আমাদের লক্ষ্য' },
  'about_mission_1': { en: 'Provide quality training aligned with industry needs', bn: 'শিল্পের চাহিদার সাথে সামঞ্জস্যপূর্ণ মানসম্মত প্রশিক্ষণ প্রদান করা' },
  'about_mission_2': { en: 'Enhance technical competencies of PWD staff', bn: 'পিডব্লিউডি কর্মীদের কারিকারি দক্ষতা বৃদ্ধি করা' },
  'about_mission_3': { en: 'Maintain state-of-the-art laboratory facilities', bn: 'আধুনিক ল্যাবরেটরি সুবিধা বজায় রাখা' },
  'about_mission_4': { en: 'Promote research and innovation', bn: 'গবেষণা ও উদ্ভাবন প্রচার করা' },
  'about_management_title': { en: 'Management', bn: 'ব্যবস্থাপনা' },
  'about_organogram_title': { en: 'Organogram', bn: 'সাংগঠনিক চার্ট' },
  'about_campus_title': { en: 'Our Campus', bn: 'আমাদের ক্যাম্পাস' },
  'about_campus_main_building': { en: 'Main Building', bn: 'প্রধান ভবন' },
  'about_campus_training_hall': { en: 'Training Hall', bn: 'প্রশিক্ষণ হল' },
  'about_campus_computer_lab': { en: 'Computer Lab', bn: 'কম্পিউটার ল্যাব' },
  'about_campus_library': { en: 'Library', bn: 'লাইব্রেরি' },
  'about_campus_residential': { en: 'Residential Block', bn: 'আবাসিক ব্লক' },
  'about_campus_testing_lab': { en: 'Testing Laboratory', bn: 'পরীক্ষাগার' },
  'about_officers_title': { en: 'List of Officers', bn: 'কর্মকর্তাদের তালিকা' },
  'about_officers_photo': { en: 'Photo', bn: 'ফটো' },
  'about_officers_name': { en: 'Name', bn: 'নাম' },
  'about_officers_designation': { en: 'Designation', bn: 'পদবি' },
  'about_officers_phone': { en: 'Phone', bn: 'ফোন' },
  'about_officers_email': { en: 'Email', bn: 'ইমেইল' },
  'facility_overview': { en: 'Overview', bn: 'সংক্ষেপ' },
  'facility_capacity': { en: 'Capacity', bn: 'ধারণক্ষমতা' },
  'facility_climate_control': { en: 'Climate Control', bn: 'তাপমাত্রা নিয়ন্ত্রণ' },
  'facility_classroom_desc': { en: 'Well-equipped air-conditioned classrooms with modern audio-visual aids, multimedia projectors, whiteboards, and comfortable seating for up to 40 participants.', bn: 'আধুনিক অডিও-ভিসুয়াল সহায়ক, মাল্টিমিডিয়া প্রজেক্টর, হোয়াইটবোর্ড এবং ৪০ জন অংশগ্রহণকারীর জন্য আরামদায়ক আসনসহ সুসজ্জিত এয়ারকন্ডিশনড ক্লাসরুম।' },
  'facility_computerlab_desc': { en: 'State-of-the-art computer laboratory with 40+ workstations, high-speed internet, latest engineering software.', bn: '৪০+ ওয়ার্কস্টেশন, হাই-স্পিড ইন্টারনেট, সর্বাধুনিক কম্পিউটার ল্যাবরেটরি।' },
  'facility_library_desc': { en: 'Extensive library with over 5,000 books on civil engineering, construction management, material testing.', bn: 'সিভিল ইঞ্জিনিয়ারিং, নির্মাণ ব্যবস্থাপনা, উপকরণ পরীক্ষা বিষয়ক ৫,০০০+ বইসহ বিশাল লাইব্রেরি।' },
  'facility_residential_desc': { en: 'Comfortable residential facilities for outstation trainees.', bn: 'দূরবর্তী প্রশিক্ষণার্থীদের জন্য আরামদায়ক আবাসিক সুবিধা।' },
  'media_photo_gallery': { en: 'Photo Gallery', bn: 'ফটো গ্যালারি' },
  'media_video_gallery': { en: 'Video Gallery', bn: 'ভিডিও গ্যালারি' },
  'media_no_photos': { en: 'No gallery items yet.', bn: 'এখনও কোনো গ্যালারি আইটেম নেই।' },
  'media_no_videos': { en: 'No videos yet.', bn: 'এখনও কোনো ভিডিও নেই।' },
  'testing_material_test': { en: 'Material Test', bn: 'উপকরণ পরীক্ষা' },
  'testing_desc': { en: 'Our testing laboratory offers comprehensive material testing services for construction quality assurance.', bn: 'আমাদের পরীক্ষাগার নির্মাণ গুণমান নিশ্চিতকরণের জন্য ব্যাপক উপকরণ পরীক্ষা সেবা প্রদান করে।' },
  'testing_equipment_list': { en: 'List of Equipment', bn: 'যন্ত্রপাতির তালিকা' },
  'testing_no_equipment': { en: 'No equipment listed.', bn: 'কোনো যন্ত্রপাতি তালিকাভুক্ত নেই।' },
  'testing_capacity': { en: 'Capacity:', bn: 'ধারণক্ষমতা:' },
  'testing_standard': { en: 'Standard:', bn: 'মান:' },
  'testing_report_title': { en: 'Testing Report', bn: 'পরীক্ষার রিপোর্ট' },
  'testing_report_desc': { en: 'Download previous testing reports in PDF format.', bn: 'PDF ফরম্যাটে পূর্ববর্তী পরীক্ষার রিপোর্ট ডাউনলোড করুন।' },
  'testing_sample_report': { en: 'Sample Report - Concrete Test', bn: 'নমুনা রিপোর্ট - কংক্রিট পরীক্ষা' },
  'trainings_title': { en: 'Available Trainings', bn: 'উপলব্ধ প্রশিক্ষণ' },
  'trainings_all': { en: 'All', bn: 'সব' },
  'trainings_upcoming': { en: 'Upcoming', bn: 'আসন্ন' },
  'trainings_ongoing': { en: 'Ongoing', bn: 'চলমান' },
  'trainings_completed': { en: 'Completed', bn: 'সম্পন্ন' },
  'trainings_no_trainings': { en: 'No trainings available yet.', bn: 'এখনও কোনো প্রশিক্ষণ উপলব্ধ নেই।' },
  'trainings_upcoming_courses': { en: 'Upcoming Courses', bn: 'আসন্ন কোর্স' },
  'testing_services_title': { en: 'Available Testing Services', bn: 'উপলব্ধ পরীক্ষা সেবা' },
  'testing_services_no_services': { en: 'No testing services available yet.', bn: 'এখনও কোনো পরীক্ষা সেবা উপলব্ধ নেই।' },
  'notices_title': { en: 'Notice Board', bn: 'নোটিশ বোর্ড' },
  'notices_all': { en: 'All', bn: 'সব' },
  'notices_important': { en: 'Important', bn: 'গুরুত্বপূর্ণ' },
  'notices_new': { en: 'New', bn: 'নতুন' },
  'notices_no_notices': { en: 'No notices available.', bn: 'কোনো নোটিশ নেই।' },
  'contact_title': { en: 'Contact Us', bn: 'যোগাযোগ করুন' },
  'contact_send_message': { en: 'Send us a Message', bn: 'আমাদের বার্তা পাঠান' },
  'contact_full_name': { en: 'Full Name', bn: 'পুরো নাম' },
  'contact_email': { en: 'Email Address', bn: 'ইমেইল ঠিকানা' },
  'contact_subject': { en: 'Subject', bn: 'বিষয়' },
  'contact_message': { en: 'Message', bn: 'বার্তা' },
  'admin_employees': { en: 'Employees', bn: 'কর্মকর্তাগণ' },
'nav_employees': { en: 'Employees', bn: 'কর্মকর্তাগণ' },
  'contact_send': { en: 'Send Message', bn: 'বার্তা পাঠান' },
  'contact_info_title': { en: 'Contact Information', bn: 'যোগাযোগের তথ্য' },
  'contact_address_label': { en: 'Address', bn: 'ঠিকানা' },
  'contact_address_value': { en: 'PWD Training Academy, Sher-e-Bangla Nagar, Dhaka-1207', bn: 'পিডব্লিউডি প্রশিক্ষণ একাডেমি, শের-ই-বাংলা নগর, ঢাকা-১২০৭' },
  'contact_phone_label': { en: 'Phone', bn: 'ফোন' },
  'contact_phone_value': { en: '+880-2-8181234', bn: '+৮৮০-২-৮১৮১২৩৪' },
  'contact_email_label': { en: 'Email', bn: 'ইমেইল' },
  'contact_email_value': { en: 'info@pwd.training.gov.bd', bn: 'info@pwd.training.gov.bd' },
  'contact_training_inquiry': { en: 'Training Inquiry', bn: 'প্রশিক্ষণ জিজ্ঞাসা' },
  'contact_testing_inquiry': { en: 'Testing Inquiry', bn: 'পরীক্ষা জিজ্ঞাসা' },
  'contact_general_inquiry': { en: 'General Inquiry', bn: 'সাধারণ জিজ্ঞাসা' },
  'contact_message_sent': { en: 'Message sent successfully!', bn: 'বার্তা সফলভাবে পাঠানো হয়েছে!' },
  'login_welcome': { en: 'Welcome Back', bn: 'স্বাগতম' },
  'login_subtitle': { en: 'Login to your account', bn: 'আপনার অ্যাকাউন্টে লগইন করুন' },
  'login_email': { en: 'Email', bn: 'ইমেইল' },
  'login_password': { en: 'Password', bn: 'পাসওয়ার্ড' },
  'login_btn': { en: 'Login', bn: 'লগইন' },
  'login_no_account': { en: "Don't have an account?", bn: 'অ্যাকাউন্ট নেই?' },
  'login_register': { en: 'Register', bn: 'নিবন্ধন করুন' },
  'login_admin_access': { en: 'Admin Access', bn: 'অ্যাডমিন অ্যাক্সেস' },
  'login_success': { en: 'Login successful!', bn: 'লগইন সফল!' },
  'login_invalid': { en: 'Invalid credentials', bn: 'অবৈধ তথ্য' },
  'register_create_account': { en: 'Create Account', bn: 'অ্যাকাউন্ট তৈরি করুন' },
  'register_full_name': { en: 'Full Name', bn: 'পুরো নাম' },
  'register_phone': { en: 'Phone', bn: 'ফোন' },
  'register_email': { en: 'Email', bn: 'ইমেইল' },
  'register_organization': { en: 'Organization', bn: 'প্রতিষ্ঠান' },
  'register_designation': { en: 'Designation', bn: 'পদবি' },
  'register_password': { en: 'Password', bn: 'পাসওয়ার্ড' },
  'register_create_btn': { en: 'Create Account', bn: 'অ্যাকাউন্ট তৈরি করুন' },
  'register_have_account': { en: 'Already have an account?', bn: 'ইতিমধ্যে অ্যাকাউন্ট আছে?' },
  'register_login_link': { en: 'Login', bn: 'লগইন' },
  'register_success': { en: 'Registration successful! Please login.', bn: 'নিবন্ধন সফল! অনুগ্রহ করে লগইন করুন।' },
  'register_failed': { en: 'Registration failed. Please try again.', bn: 'নিবন্ধন ব্যর্থ হয়েছে। আবার চেষ্টা করুন।' },
  'enroll_submit': { en: 'Submit Enrollment', bn: 'ভর্তির আবেদন জমা দিন' },
  'enroll_title': { en: 'Course Enrollment', bn: 'কোর্সে ভর্তি' },
  'enroll_success': { en: 'Enrollment submitted successfully!', bn: 'ভর্তির আবেদন সফলভাবে জমা পড়েছে!' },
  'dashboard_welcome': { en: 'Welcome,', bn: 'স্বাগতম,' },
  'dashboard_completed': { en: 'Completed', bn: 'সম্পন্ন' },
  'dashboard_interested': { en: 'Interested', bn: 'আগ্রহী' },
  'dashboard_progress': { en: 'Progress', bn: 'অগ্রগতি' },
  'dashboard_certificates': { en: 'Certificates', bn: 'সার্টিফিকেট' },
  'dashboard_available_trainings': { en: 'Available Trainings', bn: 'উপলব্ধ প্রশিক্ষণ' },
  'dashboard_enroll': { en: 'Enroll', bn: 'ভর্তি হন' },
  'dashboard_logout': { en: 'Logout', bn: 'লগআউট' },
  'dashboard_no_upcoming': { en: 'No upcoming trainings at this time.', bn: 'এই মুহূর্তে কোনো আসন্ন প্রশিক্ষণ নেই।' },
  'admin_panel_title': { en: 'Admin Panel', bn: 'অ্যাডমিন প্যানেল' },
  'admin_panel_subtitle': { en: 'PWD Training', bn: 'পিডব্লিউডি প্রশিক্ষণ' },
  'admin_main': { en: 'Main', bn: 'প্রধান' },
  'admin_dashboard': { en: 'Dashboard', bn: 'ড্যাশবোর্ড' },
  'admin_add_new': { en: 'Add New', bn: 'নতুন যোগ করুন' },
  'admin_actions': { en: 'Actions', bn: 'ক্রিয়াকলাপ' },
  'admin_edit': { en: 'Edit', bn: 'সম্পাদনা' },
  'admin_delete': { en: 'Delete', bn: 'মুছুন' },
  'admin_save': { en: 'Save', bn: 'সংরক্ষণ করুন' },
  'admin_update': { en: 'Update', bn: 'আপডেট করুন' },
  'admin_cancel': { en: 'Cancel', bn: 'বাতিল করুন' },
  'admin_deleted': { en: 'Deleted successfully!', bn: 'সফলভাবে মুছে ফেলা হয়েছে!' },
  'admin_created': { en: 'Created successfully!', bn: 'সফলভাবে তৈরি হয়েছে!' },
  'admin_updated': { en: 'Updated successfully!', bn: 'সফলভাবে আপডেট হয়েছে!' },
  'settings_saved': { en: 'Settings saved!', bn: 'সেটিংস সংরক্ষিত হয়েছে!' },
  'admin_trainings': { en: 'Trainings', bn: 'প্রশিক্ষণ' },
  'admin_testings': { en: 'Testing', bn: 'পরীক্ষা' },
  'admin_notices': { en: 'Notices', bn: 'নোটিশ' },
  'admin_officers': { en: 'Officers', bn: 'কর্মকর্তাগণ' },
  'admin_trainees': { en: 'Trainees', bn: 'প্রশিক্ষণার্থী' },
  'admin_equipment': { en: 'Equipment', bn: 'যন্ত্রপাতি' },
  'admin_gallery': { en: 'Gallery', bn: 'গ্যালারি' },
  'admin_videos': { en: 'Videos', bn: 'ভিডিও' },
  'admin_facilities': { en: 'Facilities', bn: 'সুবিধাসমূহ' },
  'admin_sliders': { en: 'Sliders', bn: 'স্লাইডার' },
  'admin_settings': { en: 'Settings', bn: 'সেটিংস' },
  'admin_reports': { en: 'Reports', bn: 'রিপোর্ট' },
  'admin_management': { en: 'Management', bn: 'ব্যবস্থাপনা' },
  'admin_resources': { en: 'Resources', bn: 'সম্পদ' },
  'admin_system': { en: 'System', bn: 'সিস্টেম' },
  'admin_role': { en: 'Super Admin', bn: 'সুপার অ্যাডমিন' },
  'admin_logout': { en: 'Logout', bn: 'লগআউট' },
  'admin_view_site': { en: 'View Site', bn: 'সাইট দেখুন' },
  'toast_logged_out': { en: 'Logged out', bn: 'লগআউট হয়েছে' },
  'admin_confirm_delete': { en: 'Are you sure you want to delete this item?', bn: 'আপনি কি নিশ্চিত এই আইটেমটি মুছতে চান?' },
  'admin_operation_failed': { en: 'Operation failed. Please try again.', bn: 'অপারেশন ব্যর্থ হয়েছে। আবার চেষ্টা করুন।' },
  'admin_no_records': { en: 'No records found.', bn: 'কোনো রেকর্ড পাওয়া যায়নি।' },
  'settings_title': { en: 'Academy Settings', bn: 'একাডেমি সেটিংস' },
  'settings_academy_name': { en: 'Academy Name', bn: 'একাডেমির নাম' },
  'settings_academy_address': { en: 'Address', bn: 'ঠিকানা' },
  'settings_academy_phone': { en: 'Phone', bn: 'ফোন' },
  'settings_academy_email': { en: 'Email', bn: 'ইমেইল' },
  'settings_save': { en: 'Save Settings', bn: 'সেটিংস সংরক্ষণ করুন' },
  'reports_training_summary': { en: 'Training Summary Report', bn: 'প্রশিক্ষণ সারাংশ রিপোর্ট' },
  'reports_generate': { en: 'Generate Report', bn: 'রিপোর্ট তৈরি করুন' },
  'reports_export_pdf': { en: 'Export as PDF', bn: 'PDF হিসেবে রপ্তানি করুন' },
  'reports_export_excel': { en: 'Export as Excel', bn: 'Excel হিসেবে রপ্তানি করুন' },
};

function toggleLanguage() {
  currentLang = currentLang === 'en' ? 'bn' : 'en';
  if (currentLang === 'bn') document.body.classList.add('lang-bn');
  else document.body.classList.remove('lang-bn');
  const publicLabel = document.getElementById('lang-label');
  const adminLabel = document.getElementById('admin-lang-label');
  if (publicLabel) publicLabel.textContent = currentLang === 'en' ? 'EN' : 'বাং';
  if (adminLabel) adminLabel.textContent = currentLang === 'en' ? 'EN' : 'বাং';
  applyTranslations();
  renderPage();
  localStorage.setItem('preferred_lang', currentLang);
  showToast(currentLang === 'en' ? 'Switched to English' : 'বাংলায় পরিবর্তিত হয়েছে', 'info');
}

function applyTranslations() {
  document.querySelectorAll('[data-i18n]').forEach(el => {
    const key = el.getAttribute('data-i18n');
    if (translations[key] && translations[key][currentLang]) {
      el.textContent = translations[key][currentLang];
    }
  });
}

function t(key) {
  return (translations[key] && translations[key][currentLang]) || key;
}

// ===== DEFAULT SVG IMAGE HELPERS =====
function getDefaultImg(type, label) {
    const icons = {
        training: '<path d="M20 15 L40 25 L20 35 L0 25Z" fill="#4338CA" opacity="0.9"/><rect x="5" y="30" width="30" height="2" rx="1" fill="#06B6D4" opacity="0.6"/><rect x="8" y="44" width="24" height="2" rx="1" fill="#6366F1" opacity="0.4"/><rect x="8" y="49" width="18" height="2" rx="1" fill="#6366F1" opacity="0.3"/>',
        facility: '<rect x="5" y="22" width="50" height="36" rx="3" fill="#4338CA" opacity="0.8"/><rect x="15" y="12" width="30" height="10" rx="2" fill="#06B6D4" opacity="0.8"/><rect x="19" y="30" width="9" height="12" rx="1" fill="#fff" opacity="0.7"/><rect x="33" y="30" width="9" height="12" rx="1" fill="#fff" opacity="0.7"/><rect x="23" y="50" width="14" height="8" rx="1" fill="#06B6D4" opacity="0.7"/>',
        equipment: '<circle cx="30" cy="30" r="20" fill="none" stroke="#4338CA" stroke-width="3" opacity="0.8"/><circle cx="30" cy="30" r="9" fill="#06B6D4" opacity="0.9"/><line x1="30" y1="7" x2="30" y2="3" stroke="#4338CA" stroke-width="2.5" opacity="0.6"/><line x1="30" y1="57" x2="30" y2="53" stroke="#4338CA" stroke-width="2.5" opacity="0.6"/><line x1="7" y1="30" x2="3" y2="30" stroke="#4338CA" stroke-width="2.5" opacity="0.6"/><line x1="57" y1="30" x2="53" y2="30" stroke="#4338CA" stroke-width="2.5" opacity="0.6"/>',
        gallery: '<rect x="5" y="15" width="50" height="40" rx="4" fill="#4338CA" opacity="0.8"/><circle cx="20" cy="28" r="6" fill="#06B6D4" opacity="0.8"/><polyline points="5,52 22,36 34,46 42,38 55,52" fill="#06B6D4" opacity="0.5"/>',
        slider: '<rect x="2" y="10" width="56" height="40" rx="4" fill="#4338CA" opacity="0.7"/><polygon points="25,22 25,38 40,30" fill="#06B6D4" opacity="0.9"/><rect x="10" y="54" width="8" height="3" rx="1.5" fill="#06B6D4" opacity="0.5"/><rect x="22" y="54" width="8" height="3" rx="1.5" fill="#4338CA" opacity="0.5"/><rect x="34" y="54" width="8" height="3" rx="1.5" fill="#4338CA" opacity="0.5"/>',
        default: '<rect x="10" y="5" width="40" height="50" rx="4" fill="#4338CA" opacity="0.7"/><rect x="16" y="12" width="28" height="20" rx="2" fill="#06B6D4" opacity="0.6"/><rect x="16" y="37" width="28" height="2" rx="1" fill="#fff" opacity="0.3"/><rect x="16" y="42" width="20" height="2" rx="1" fill="#fff" opacity="0.2"/>'
    };
    const icon = icons[type] || icons.default;
    const text = label ? `<text x="30" y="58" font-family="Arial,Helvetica,sans-serif" font-size="4.5" fill="#9CA3AF" text-anchor="middle" letter-spacing="0.5">${label}</text>` : '';
    return `data:image/svg+xml,${encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" width="400" height="300" viewBox="0 0 60 60"><rect fill="#1E1B4B" width="60" height="60"/>${icon}${text}</svg>`)}`;
}

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

// Image onerror fallback handler
function handleImgError(el, type, label) {
    el.onerror = null; // prevent infinite loop
    el.src = getDefaultImg(type || 'default', label || '');
}

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

// ===== FIX #1: API calls with timeout =====
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) url += `&id=${data.id}`;
    if (method === 'GET' && data && data.id) url += `&id=${data.id}`;
    if (method === 'GET' && data && data.slug) url += `&slug=${data.slug}`;

    // Add timeout so requests can't hang forever
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 8000);
    opts.signal = controller.signal;

    try {
        const res = await fetch(url, opts);
        clearTimeout(timeoutId);
        return await res.json();
    } catch(e) {
        clearTimeout(timeoutId);
        return {error: "Network Error"};
    }
}

// ===== SEED DEFAULT DATA IMMEDIATELY — calendar always works =====
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 _nextM = _now.getMonth() + 1;
const _nm = String(_nextM > 11 ? 1 : _nextM + 1).padStart(2, '0');
const _ny = _nextM > 11 ? _y + 1 : _y;

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 and best practices for highway engineers.' },
    { id: 2, title: 'Concrete Quality Control', start: `${_y}-${_m}-15`, end: `${_y}-${_m}-20`, category: 'Workshop', status: 'upcoming', desc: 'Compressive strength testing, mix design, and quality assurance.' },
    { id: 3, title: 'Bridge Design Workshop', start: `${_y}-${_m}-22`, end: `${_y}-${_m}-25`, category: 'Workshop', status: 'upcoming', desc: 'Modern bridge engineering and load analysis techniques.' },
    { id: 4, title: 'Project Management Fundamentals', start: `${_ny}-${_nm}-05`, end: `${_ny}-${_nm}-10`, category: 'Certificate Program', status: 'upcoming', desc: 'PMP certification preparation and project planning.' },
    { id: 5, title: 'Soil Investigation Techniques', start: `${_y}-${_m}-08`, end: `${_y}-${_m}-12`, category: 'Short Course', status: 'upcoming', desc: 'Boring, sampling, and laboratory testing of soils.' }
];

let testings = [
    { id: 1, title: 'Concrete Compression Test', testType: 'Concrete', turnaround: '3', desc: 'Compressive strength test of concrete cylinders and cubes.' },
    { id: 2, title: 'Soil Bearing Capacity', testType: 'Soil', turnaround: '5', desc: 'Bearing capacity analysis for foundation design.' },
    { id: 3, title: 'Steel Tensile Test', testType: 'Steel', turnaround: '2', desc: 'Tensile strength and elongation testing of reinforcement.' }
];

let notices = [
    { id: 1, title: 'Admission Notice - July 2025', content: 'Applications are invited for upcoming training programs. Please apply through the enrollment form.', date: `${_y}-${_m}-${_d}`, type: 'new', category: 'Training' },
    { id: 2, title: 'Holiday Notice', content: 'Office will remain closed on public holidays as per government calendar.', 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 = {};

async function loadAllData() {
    try {
        const [t, te, n, o, e, tr, g, v, f, sl, emp, st] = await Promise.all([
            api('trainings'), api('testings'), api('notices'), api('officers'),
            api('equipment'), api('trainees'), api('gallery'), api('videos'),
            api('facilities'), api('sliders'), api('employees'), api('stats')
        ]);
        
        if (Array.isArray(t) && t.length > 0) trainings = t;
        if (Array.isArray(te) && te.length > 0) testings = te;
        if (Array.isArray(n) && n.length > 0) notices = n;
        if (Array.isArray(o) && o.length > 0) officers = o;
        equipment = Array.isArray(e) ? e : [];
        trainees = Array.isArray(tr) ? tr : [];
        galleryItems = Array.isArray(g) ? g : [];
        videoItems = Array.isArray(v) ? v : [];
        facilities = Array.isArray(f) ? f : [];
        sliders = Array.isArray(sl) ? sl : [];
        employees = Array.isArray(emp) ? emp : [];
        siteStats = (st && !st.error) ? st : {};
    } catch(e) {
        console.error('Data load error:', e);
    }
}

async function refreshEntity(entity) {
    const data = await api(entity);
    if (!data.error) {
        if (entity === 'trainings') { if (Array.isArray(data) && data.length > 0) trainings = data; }
        else if (entity === 'testings') { if (Array.isArray(data) && data.length > 0) testings = data; }
        else if (entity === 'notices') { if (Array.isArray(data) && data.length > 0) notices = data; }
        else if (entity === 'officers') { if (Array.isArray(data) && data.length > 0) officers = data; }
        else if (entity === 'equipment') equipment = Array.isArray(data) ? data : [];
        else if (entity === 'trainees') trainees = Array.isArray(data) ? data : [];
        else if (entity === 'gallery') galleryItems = Array.isArray(data) ? data : [];
        else if (entity === 'videos') videoItems = Array.isArray(data) ? data : [];
        else if (entity === 'facilities') facilities = Array.isArray(data) ? data : [];
        else if (entity === 'sliders') sliders = Array.isArray(data) ? data : [];
        else if (entity === 'employees') employees = Array.isArray(data) ? data : [];
    }
}

// =============================================
// UI HELPERS
// =============================================
function showToast(msg, type='success') {
    const toastEl = document.getElementById('toast');
    toastEl.className = `toast toast-${type} show`;
    toastEl.textContent = msg;
    setTimeout(() => toastEl.classList.remove('show'), 3000);
}
function openModal(html) {
    document.getElementById('modal-content').innerHTML = html;
    document.getElementById('modal-overlay').classList.add('show');
    setTimeout(() => applyTranslations(), 50);
}
function closeModal() { document.getElementById('modal-overlay').classList.remove('show'); }
function openLightbox(src) { document.getElementById('lightbox-img').src = src; document.getElementById('lightbox').classList.add('show'); }
function closeLightbox() { document.getElementById('lightbox').classList.remove('show'); }
function toggleMobileNav() { document.getElementById('mobile-nav').classList.toggle('hidden'); }
function toggleTheme() {
    document.body.classList.toggle('dark-mode');
    const icon = document.getElementById('theme-icon');
    icon.classList.toggle('fa-moon'); icon.classList.toggle('fa-sun');
}
function pageHeader(title, breadcrumb, content) {
    return `<div class="mb-8"><div class="flex items-center gap-2 text-xs text-gray-400 mb-3"><a class="cursor-pointer hover:text-gray-600" onclick="navigate('home')">${t('nav_home')}</a><i class="fas fa-chevron-right" style="font-size:8px"></i><span>${breadcrumb}</span></div><h1 class="text-2xl font-bold">${title}</h1></div>${content}`;
}

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

function navigate(page) {
    currentPage = page;
    document.querySelectorAll('.nav-link').forEach(l => {
        l.classList.remove('active');
        if (l.dataset.page === page || (l.dataset.page && page.startsWith(l.dataset.page))) l.classList.add('active');
    });
    renderPage();
    document.getElementById('mobile-nav').classList.add('hidden');
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

function renderPage() {
    const c = document.getElementById('page-content');
    const renders = {
        home: renderHome, vision: renderVision, management: renderManagement, organogram: renderOrganogram,
        campus: renderCampus, officers: renderOfficers, classroom: renderClassroom, computerlab: renderComputerLab,
        library: renderLibrary, residential: renderResidential, playground: renderPlayground,
        gymnasium: renderGymnasium, swimmingpool: renderSwimmingPool, testinglab: renderTestingLabFacility,
        photogallery: renderPhotoGallery, videogallery: renderVideoGallery, materialtest: renderMaterialTest,
        equipment: renderEquipmentPage, testingreport: renderTestingReport, trainings: renderTrainings,
        testing: renderTesting, notices: renderNotices, contact: renderContact, verify: renderVerify,
        login: renderLogin, register: renderRegister, dashboard: renderUserDashboard
    };
    const fn = renders[currentPage] || renderHome;
    c.innerHTML = '<div class="fade-in">' + fn() + '</div>';
    setTimeout(() => applyTranslations(), 50);
    if (currentPage === 'home') initSlider();
    if (currentPage === 'dashboard') initUserCharts();
}

// =============================================
// NOTICE TICKER
// =============================================
function updateTicker() {
    const wrap = document.getElementById('ticker-wrap');
    if (!notices.length) { wrap.innerHTML = `<span class="ticker-item">${t('notice_no_notices')}</span>`; return; }
    const items = notices.map(n => `<span class="ticker-item">📢 ${n.title} ${n.type === 'important' ? '⚠️' : ''}</span>`).join('');
    wrap.innerHTML = items + items;
}

// =============================================
// SLIDER
// =============================================
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 + sliders.length) % Math.max(sliders.length, 1); updateSlider(); }
function goSlide(i) { sliderIndex = i; updateSlider(); }

// =============================================
// PUBLIC PAGE RENDERERS
// =============================================

// ===== FIX #2: renderHome() - stats code moved OUTSIDE template literal =====
function renderHome() {
    const upcoming = trainings.filter(t => t.status === 'upcoming').slice(0, 3);
    const ongoing = trainings.filter(t => t.status === 'ongoing');
    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="${s.img}" alt="${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">${s.title}</h1>` : ''}
                        ${s.subtitle ? `<p class="text-white/70 mb-6 text-sm">${s.subtitle}</p>` : ''}
                        <div class="flex gap-3">
                            ${s.btnText ? `<button class="btn-accent" onclick="navigate('${s.btnLink || 'trainings'}')">${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 `
    <!-- Slider -->
    <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>

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

    <!-- Available Programs -->
    <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>

    <!-- Course Calendar (AFTER View All button) -->
    ${renderMiniCalendar()}

    <!-- Photo Gallery -->
    ${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 => `<div class="rounded-lg overflow-hidden cursor-pointer group" onclick="openLightbox('${g.img}')"><img src="${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>` : ''}

    <!-- Map -->
    <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>

    <!-- Stay Updated CTA -->
    <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>`;
}

// Mini Calendar
function renderMiniCalendar() {
    const now = new Date();
    const year = window.calendarYear;
    const month = window.calendarMonth;

    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; // Monday=0

    const todayDate = now.getDate();
    const todayMonth = now.getMonth();
    const todayYear = now.getFullYear();

    // FIX: Parse dates safely without timezone issues
    const events = {};
    if (trainings && trainings.length > 0) {
        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 titleAttr = '';
        if (hasEvent) {
            titleAttr = `title="${events[day].join(', ')}"`;
        }

        // FIX: Escape single quotes in event names for onclick
        let clickHandler = '';
        if (hasEvent) {
            const safeName = events[day][0].replace(/'/g, "\\'");
            clickHandler = `onclick="showToast('${safeName}', 'info')"`;
        }

        calendarDays += `<div class="calendar-day ${hasEvent ? 'has-event' : ''} ${isToday ? 'today' : ''}" ${titleAttr} ${clickHandler}>${day}</div>`;
    }

    // Event list for this month
    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 => {
            return 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)">${ev}</div>
                </div>
            `).join('');
        }).join('')}</div>`;
    } else {
        eventListHTML = `<div class="text-center text-xs text-gray-400 mt-4">${t('calendar_no_events')}</div>`;
    }

    // Month navigation
    const prevMonth = month === 0 ? 11 : month - 1;
    const prevYear = month === 0 ? year - 1 : year;
    const nextMonth = month === 11 ? 0 : month + 1;
    const 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="calendarMonth=${prevMonth};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="calendarMonth=${todayMonth};calendarYear=${todayYear};refreshCalendar()" class="text-xs text-cyan-600 hover:underline mt-1">${currentLang==='bn'?'আজ যান':'Go to Today'}</button>` : ''}
                </div>
                <button onclick="calendarMonth=${nextMonth};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;
    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">${tr.start}</div><div class="font-medium">${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 renderProgramCard(item, type) {
    const isTraining = type === 'training';
    const isUpcoming = isTraining && item.status === 'upcoming';
    const imgSrc = item.img || getDefaultImg(type === 'testing' ? 'equipment' : 'training');
    return `<div class="program-card" data-type="${type}"><div class="card">
        <img src="${imgSrc}" class="w-full h-40 object-cover" alt="${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 ? item.status : item.testType}</span>
                <span class="badge badge-warning">${isTraining ? item.category : item.turnaround}</span>
            </div>
            <h3 class="font-semibold text-sm mb-2" style="color:var(--text)">${item.title}</h3>
            <p class="text-xs text-gray-500 leading-relaxed mb-3 line-clamp-2">${item.desc || ''}</p>
            <div class="flex items-center text-xs text-gray-400 mb-3">
                <span>${isTraining ? (item.start || '') : item.turnaround}</span>
            </div>
            <div class="flex gap-2">
                <button class="btn-primary btn-sm flex-1" onclick="openEnrollModal(${item.id},'${type}')"><i class="fas fa-user-plus mr-1"></i>${t('home_enroll_now')}</button>
                ${isUpcoming ? `<button class="btn-outline btn-sm" onclick="registerInterest(${item.id})" title="${t('interest_btn')}"><i class="far fa-heart"></i></button>` : ''}
            </div>
        </div>
    </div></div>`;
}

function registerInterest(id) { showToast(t('interest_registered'), 'success'); }

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 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 - b.display_order)
    .map(o => `
                <div class="management-card">
                    <div class="management-image">
                        <img 
                            src="${o.img || getDefaultAvatar(o.name)}"
                            alt="${o.name}"
                            onerror="handleImgError(this,'default',''); this.style.objectFit='cover';"
                        >
                    </div>
                    <div class="management-content">
                        <h2 class="management-name">${o.name || ''}</h2>
                        <div class="management-designation">${o.designation || ''}</div>
                        ${o.office ? `<div class="management-office">${o.office}</div>` : ''}
                        ${o.phone ? `<div class="management-line"><i class="fas fa-phone-alt"></i>${o.phone}</div>` : ''}
                        ${o.mobile ? `<div class="management-line"><i class="fas fa-mobile-alt"></i>${o.mobile}</div>` : ''}
                        ${o.email ? `<div class="management-line"><i class="fas fa-envelope"></i>${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:0.3s ease}
            .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;line-height:1.3}
            .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;word-break:break-word}
            .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}
                .management-designation{font-size:14px}
                .management-office,.management-line{font-size:12px}
            }
        </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 campusItems = [
        {
            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">

            ${campusItems.map(item => `

                <div class="card overflow-hidden cursor-pointer"
                     onclick="openLightbox('${item.image}')">

                    <img src="${item.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">
                            ${item.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="${e.img}" class="w-full h-full object-cover" alt="${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">${e.name || '-'}</h4>
                        <p class="text-xs text-gray-500">${e.designation || ''}</p>
                        <p class="text-xs text-gray-400">${e.department || ''}</p>
                    </div>
                    <div class="flex gap-3 text-gray-400 shrink-0">
                        ${e.email ? `<a href="mailto:${e.email}" class="hover:text-blue-500 transition" title="${e.email}"><i class="fas fa-envelope text-sm"></i></a>` : ''}
                        ${e.phone ? `<a href="tel:${e.phone}" class="hover:text-green-500 transition" title="${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}
        `
    );
}

// ===== FIX #3: Remove duplicate declarations, single renderFacilityPage =====
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'); }

// ===== FIX #4: renderFacilityPage - fixed duplicate args, removed undefined 'titles' =====
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 for this facility. Please add it 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 || (currentLang==='bn'?'বিস্তারিত শীঘ্রই পাওয়া যাবে।':'No description available.');
    const img = fac.img || `https://picsum.photos/seed/${type}/700/500.jpg`;
    const cap = fac.capacity || '-';
    const area = fac.area ? `${fac.area} ${currentLang==='bn'?'বর্গফুট':'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="${img}" class="w-full h-72 object-cover" alt="${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">${desc}</p>
            <div class="grid grid-cols-2 gap-3 mb-6">
                ${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">${currentLang==='bn'?'আয়তন':'Area'}</div></div>` : ''}
            </div>
            ${features.length > 0 ? `
            <h4 class="font-semibold text-sm mb-3">${currentLang==='bn'?'বৈশিষ্ট্য':'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>${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 => `<div class="rounded-lg overflow-hidden cursor-pointer group" style="border:1px solid var(--border)" onclick="openLightbox('${g.img}')"><img src="${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">${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>`);
}
// ===== VIDEO EMBED HELPER =====
function getEmbedUrl(url) {
    if (!url) return '';
    // YouTube: youtube.com/watch?v=xxx বা youtu.be/xxx
    let match = url.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([\w-]+)/);
    if (match) return `https://www.youtube.com/embed/${match[1]}?autoplay=1`;
    // Vimeo: vimeo.com/xxx
    match = url.match(/vimeo\.com\/(\d+)/);
    if (match) return `https://player.vimeo.com/video/${match[1]}?autoplay=1`;
    // Direct video file (.mp4, .webm, .ogg)
    return url;
}

// ===== VIDEO PLAYER MODAL =====
function openVideoModal(url) {
    if (!url) {
        showToast(currentLang === 'bn' ? 'ভিডিও URL পাওয়া যায়নি' : 'Video URL not found', 'error');
        return;
    }
    
    const embedUrl = getEmbedUrl(url);
    const isDirectVideo = embedUrl.match(/\.(mp4|webm|ogg)$/i);
    
    let mediaHTML = '';
    if (isDirectVideo) {
        mediaHTML = `<video controls autoplay style="width:100%;max-height:70vh;border-radius:8px;outline:none"><source src="${embedUrl}" type="video/mp4">Your browser does not support the video tag.</video>`;
    } else {
        mediaHTML = `<iframe src="${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">${currentLang === 'bn' ? 'ভিডিও প্লেয়ার' : '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">
            ${mediaHTML}
        </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 => {
        // Generate thumbnail from YouTube/Vimeo URL if not provided
        let thumb = v.thumb || 'https://picsum.photos/seed/vid/400/250.jpg';
        if (!v.thumb && v.url) {
            const ytMatch = v.url.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([\w-]+)/);
            if (ytMatch) thumb = `https://img.youtube.com/vi/${ytMatch[1]}/hqdefault.jpg`;
        }
        
        return `<div class="card overflow-hidden cursor-pointer group" onclick="openVideoModal('${v.url || ''}')">
            <div class="relative">
                <img src="${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">${v.category}</span>` : ''}
            </div>
            <div class="p-4">
                <h4 class="font-semibold text-sm mb-1">${v.title}</h4>
                <p class="text-xs text-gray-400 truncate">${v.url || ''}</p>
            </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">${t_item.title}</h4><p class="text-xs text-gray-500 mb-2">${t_item.desc || ''}</p><div class="flex gap-2"><span class="badge badge-info">${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 => `<div class="card overflow-hidden"><img src="${e.img || 'https://via.placeholder.com/300x200'}" class="w-full h-36 object-cover"><div class="p-4"><h4 class="font-semibold text-sm mb-2">${e.name}</h4><div class="text-xs text-gray-500 space-y-1"><div><span class="font-medium">${t('testing_capacity')}</span> ${e.capacity}</div><div><span class="font-medium">${t('testing_standard')}</span> ${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>
    ${trainings.filter(t_item => t_item.status === 'upcoming').length > 0 ? `
    <div class="p-6 rounded-xl mt-8" style="background:linear-gradient(135deg,var(--primary),var(--primary-light));color:#fff">
        <h3 class="font-bold mb-2"><i class="fas fa-calendar-check mr-2 text-cyan-300"></i>${t('trainings_upcoming_courses')}</h3>
        <div class="grid md:grid-cols-3 gap-4 mt-4">${trainings.filter(t_item => t_item.status === 'upcoming').map(t_item => `<div class="bg-white/10 rounded-lg p-4"><div class="text-xs opacity-60">${t_item.start || ''}</div><div class="font-medium text-sm mt-1">${t_item.title}</div><div class="text-xs mt-1 text-cyan-300">${t_item.category || ''}</div></div>`).join('')}</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 badge = c.querySelector('.badge');
        const show = status === 'all' || (badge && badge.textContent.trim().toLowerCase() === status);
        c.style.display = show ? '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" id="testing-full-list">
        ${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})" data-type="${n.type}" data-cat="${n.category || ''}">
        <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'}">${n.type}</span>${n.category ? `<span class="badge badge-success">${n.category}</span>` : ''}</div>
                    <h4 class="font-semibold text-sm mb-1">${n.title}</h4>
                    <p class="text-xs text-gray-500 line-clamp-1">${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">${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'}">${notice.type}</span><span class="text-sm text-gray-500">${notice.date || ''}</span></div><p class="text-sm text-gray-700 leading-relaxed">${notice.content || ''}</p></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 placeholder="${currentLang==='bn'?'আপনার নাম':'Enter your name'}"></div><div><label>${t('contact_email')}</label><input type="email" required placeholder="${currentLang==='bn'?'আপনার ইমেইল':'Enter your email'}"></div><div><label>${t('contact_subject')}</label><select required><option value="">${currentLang==='bn'?'বিষয় নির্বাচন করুন':'Select subject'}</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 placeholder="${currentLang==='bn'?'আপনার বার্তা লিখুন...':'Write your message...'}"></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();
}

// =============================================
// VERIFY PAGE
// =============================================
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">${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">${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 / REGISTER
// =============================================
function renderLogin() {
    return `<div class="max-w-md mx-auto"><div class="card p-8"><div class="text-center mb-6"><div class="w-14 h-14 rounded-lg mx-auto mb-3 flex items-center justify-center" style="background:var(--primary)"><i class="fas fa-user text-xl text-white"></i></div><h2 class="text-xl font-bold">${t('login_welcome')}</h2><p class="text-xs text-gray-500 mt-1">${t('login_subtitle')}</p></div><form onsubmit="doLogin(event)"><div class="space-y-4"><div><label>${t('login_email')}</label><input type="email" id="login-email" required placeholder="${currentLang==='bn'?'ইমেইল দিন':'Enter email'}"></div><div><label>${t('login_password')}</label><input type="password" id="login-pass" required placeholder="${currentLang==='bn'?'পাসওয়ার্ড দিন':'Enter password'}"></div><button type="submit" class="btn-primary w-full"><i class="fas fa-sign-in-alt mr-2"></i>${t('login_btn')}</button></div></form><div class="mt-5 text-center text-sm text-gray-500">${t('login_no_account')} <a class="font-semibold cursor-pointer" style="color:var(--primary)" onclick="navigate('register')">${t('login_register')}</a></div><div class="mt-4 text-center"><a class="text-xs text-gray-400 cursor-pointer hover:underline" onclick="prefillAdminLogin()"><i class="fas fa-lock mr-1"></i>${t('login_admin_access')}</a></div></div></div>`;
}

async function doLogin(e) {
    e.preventDefault();
    const email = document.getElementById('login-email').value;
    const pass = document.getElementById('login-pass').value;
    const res = await api('login', 'POST', { email, password: pass });
    if (res.success) {
        currentUser = res.user;
        if (currentUser.role === 'admin') {
            showAdminPanel();
        } else {
            showToast(t('login_success'), 'success');
            updateLoginButton();
            navigate('dashboard');
        }
    } else {
        showToast(res.message || t('login_invalid'), 'error');
    }
}

function renderRegister() {
    return `<div class="max-w-lg mx-auto"><div class="card p-8"><div class="text-center mb-6"><div class="w-14 h-14 rounded-lg mx-auto mb-3 flex items-center justify-center" style="background:var(--accent)"><i class="fas fa-user-plus text-xl text-white"></i></div><h2 class="text-xl font-bold">${t('register_create_account')}</h2></div><form onsubmit="doRegister(event)"><div class="grid grid-cols-2 gap-4"><div><label>${t('register_full_name')}</label><input type="text" id="reg-name" required placeholder="${currentLang==='bn'?'পুরো নাম':'Full name'}"></div><div><label>${t('register_phone')}</label><input type="tel" id="reg-phone" required placeholder="+880XXXXXXXXXX"></div></div><div class="space-y-4 mt-4"><div><label>${t('register_email')}</label><input type="email" id="reg-email" required placeholder="${currentLang==='bn'?'ইমেইল':'Enter email'}"></div><div class="grid grid-cols-2 gap-4"><div><label>${t('register_organization')}</label><input type="text" id="reg-org" required placeholder="${currentLang==='bn'?'যেমন: PWD':'e.g., PWD'}"></div><div><label>${t('register_designation')}</label><input type="text" id="reg-desig" required placeholder="${currentLang==='bn'?'যেমন: SAE':'e.g., SAE'}"></div></div><div><label>${t('register_password')}</label><input type="password" id="reg-pass" required placeholder="${currentLang==='bn'?'পাসওয়ার্ড তৈরি করুন':'Create password'}" minlength="6"></div><button type="submit" class="btn-primary w-full"><i class="fas fa-user-plus mr-2"></i>${t('register_create_btn')}</button></div></form><div class="mt-5 text-center text-sm text-gray-500">${t('register_have_account')} <a class="font-semibold cursor-pointer" style="color:var(--primary)" onclick="navigate('login')">${t('register_login_link')}</a></div></div></div>`;
}

async function doRegister(e) {
    e.preventDefault();
    const payload = {
        name: document.getElementById('reg-name').value,
        email: document.getElementById('reg-email').value,
        password: document.getElementById('reg-pass').value,
        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');
    }
}

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');
    }
}

// =============================================
// USER DASHBOARD
// =============================================
function renderUserDashboard() {
    if (!currentUser) return renderLogin();
    return `<div class="flex items-center justify-between mb-6"><div><h2 class="text-xl font-bold">${t('dashboard_welcome')} ${currentUser.name}</h2><p class="text-sm text-gray-500">${currentUser.designation || ''} | ${currentUser.org || ''}</p></div><button class="btn-danger btn-sm" onclick="currentUser=null;updateLoginButton();navigate('login')"><i class="fas fa-sign-out-alt mr-1"></i>${t('dashboard_logout')}</button></div><div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8"><div class="card p-5 text-center"><div class="text-2xl font-bold" style="color:var(--primary)">0</div><div class="text-xs text-gray-500 mt-1">${t('dashboard_completed')}</div></div><div class="card p-5 text-center"><div class="text-2xl font-bold" style="color:var(--accent)">0</div><div class="text-xs text-gray-500 mt-1">${t('dashboard_interested')}</div></div><div class="card p-5 text-center"><div class="text-2xl font-bold" style="color:var(--primary)">0%</div><div class="text-xs text-gray-500 mt-1">${t('dashboard_progress')}</div></div><div class="card p-5 text-center"><div class="text-2xl font-bold" style="color:var(--accent)">0</div><div class="text-xs text-gray-500 mt-1">${t('dashboard_certificates')}</div></div></div><div class="card p-6"><h3 class="font-semibold mb-4 text-sm">${t('dashboard_available_trainings')}</h3><div class="grid md:grid-cols-2 gap-4">${trainings.filter(tr=>tr.status==='upcoming').slice(0,4).map(tr=>`<div class="p-4 rounded-lg flex items-center gap-4" style="border:1px solid var(--border)"><div class="flex-1"><div class="font-medium text-sm">${tr.title}</div><div class="text-xs text-gray-500">${tr.start || ''}</div></div><button class="btn-primary btn-sm" onclick="openEnrollModal(${tr.id},'training')">${t('dashboard_enroll')}</button></div>`).join('')||`<p class="text-sm text-gray-400">${t('dashboard_no_upcoming')}</p>`}</div></div>`;
}

function initUserCharts() {}

// =============================================
// ENROLLMENT MODAL
// =============================================
function openEnrollModal(id, type) {
    const item = type === 'training' ? trainings.find(tr => tr.id === id) : testings.find(tr => tr.id === id);
    if (!item) return;
    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="${item.img}" class="w-14 h-14 rounded-lg object-cover">` : ''}
                <div>
                    <h4 class="font-semibold text-sm">${item.title}</h4>
                    <span class="badge badge-info mt-1">${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 placeholder="${currentLang === 'bn' ? 'আপনার নাম' : 'Your name'}"></div>
                        <div><label>${t('register_phone')}</label><input type="tel" required placeholder="+880XXXXXXXXXX"></div>
                    </div>
                    <div><label>${t('register_email')}</label><input type="email" required placeholder="${currentLang === 'bn' ? 'আপনার ইমেইল' : 'Your email'}"></div>
                    <div><label>${t('register_organization')}</label><input type="text" required placeholder="${currentLang === 'bn' ? 'আপনার প্রতিষ্ঠান' : 'Your org'}"></div>
                    <div>
                        <label class="block mb-1">${currentLang === 'bn' ? 'কর্তৃপক্ষের অনুমোদন পত্র' : 'Authority Approval Letter'} <span class="text-red-500">*</span></label>
                        <div class="relative group">
                            <input type="file" name="approval_doc" id="file-upload" class="opacity-0 absolute inset-0 w-full h-full cursor-pointer z-10" accept=".pdf,.jpg,.jpeg,.png" required
                                onchange="document.getElementById('file-name-display').innerText = this.files[0] ? this.files[0].name : '${currentLang === 'bn' ? 'কোনো ফাইল নেই' : 'No file chosen'}'">
                            <div class="flex items-center justify-center gap-4 p-5 border-2 border-dashed rounded-lg transition-all group-hover:border-primary group-hover:bg-indigo-50" style="border-color:var(--border);background:var(--bg)">
                                <div class="w-12 h-12 rounded-full flex items-center justify-center shrink-0" style="background:var(--primary-glow)">
                                    <i class="fas fa-cloud-upload-alt text-xl" style="color:var(--primary)"></i>
                                </div>
                                <div class="text-left">
                                    <div class="text-sm font-semibold" style="color:var(--primary)">
                                        <span id="file-name-display">${currentLang === 'bn' ? 'ফাইল আপলোড করতে ক্লিক করুন' : 'Click to upload file'}</span>
                                    </div>
                                    <div class="text-xs text-gray-400 mt-0.5">PDF, JPG, PNG (Max 5MB)</div>
                                </div>
                            </div>
                        </div>
                    </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(); closeModal(); showToast(t('enroll_success'), 'success'); }

// =============================================
// ADMIN PANEL
// =============================================
function showAdminPanel() {
    // ===== SECURITY CHECK: Must be logged in as admin =====
    if (!currentUser || currentUser.role !== 'admin') {
        // Not logged in - go to login page and pre-fill admin email
        navigate('login');
        showToast(currentLang === 'bn' ? 'অ্যাডমিন হিসেবে লগইন করুন' : 'Please login as admin', 'info');
        setTimeout(() => {
            const emailInput = document.getElementById('login-email');
            if (emailInput) emailInput.value = 'admin@pwd.gov.bd';
            const passInput = document.getElementById('login-pass');
            if (passInput) passInput.focus();
        }, 200);
        return;
    }
    // ===== END SECURITY CHECK =====
    
    document.getElementById('admin-panel').style.display = 'block';
    document.getElementById('public-site').style.display = 'none';
    const adminTitle = document.getElementById('admin-page-title');
    if (adminTitle) adminTitle.textContent = t('admin_dashboard');
    adminNav('dashboard', document.querySelector('.admin-nav-item.active'));
}
function prefillAdminLogin() {
    const emailInput = document.getElementById('login-email');
    const passInput = document.getElementById('login-pass');
    if (emailInput) emailInput.value = 'admin@pwd.gov.bd';
    if (passInput) passInput.focus();
    showToast(currentLang === 'bn' ? 'অ্যাডমিন পাসওয়ার্ড দিন' : 'Enter admin password', 'info');
}

function goToPublic() {
    document.getElementById('admin-panel').style.display = 'none';
    document.getElementById('public-site').style.display = 'block';
    navigate('home');
}

function logoutAdmin() {
    currentUser = null;
    updateLoginButton();
    goToPublic();
    showToast(t('toast_logged_out'), 'info');
}

function adminNav(page, el) {
    currentAdminPage = page;
    document.querySelectorAll('.admin-nav-item').forEach(n => n.classList.remove('active'));
    if (el) el.classList.add('active');
    const titles = {
        dashboard: t('admin_dashboard'),
        'admin-trainings': t('admin_trainings'),
        'admin-testings': t('admin_testings'),
        'admin-notices': t('admin_notices'),
        'admin-officers': t('admin_officers'),
        'admin-employees': t('admin_employees'),
        'admin-trainees': t('admin_trainees'),
        'admin-equipment': t('admin_equipment'),
        'admin-gallery': t('admin_gallery'),
        'admin-videos': t('admin_videos'),
        'admin-facilities': t('admin_facilities'),
        'admin-sliders': t('admin_sliders'),
        'admin-settings': t('admin_settings'),
        'admin-reports': t('admin_reports')
    };
    document.getElementById('admin-page-title').textContent = titles[page] || t('admin_dashboard');
    renderAdminPage();
    document.getElementById('admin-sidebar').classList.remove('open');
}

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

// =============================================
// ADMIN DASHBOARD
// =============================================
function adminDashboard() {
    return `<div class="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        ${[
            {n:siteStats.trainings||trainings.length||0,l:t('admin_trainings'),c:'var(--primary)',i:'fa-chalkboard-teacher'},
            {n:siteStats.testings||testings.length||0,l:t('admin_testings'),c:'var(--accent)',i:'fa-flask'},
            {n:siteStats.notices||notices.length||0,l:t('admin_notices'),c:'var(--info)',i:'fa-bullhorn'},
            {n:siteStats.trainees||trainees.length||0,l:t('admin_trainees'),c:'var(--warning)',i:'fa-user-graduate'}
        ].map(s=>`<div class="stat-card"><div class="flex items-center justify-between"><div><div class="text-xs text-gray-500">${s.l}</div><div class="text-2xl font-bold mt-1" style="color:${s.c}">${s.n}</div></div><div class="w-10 h-10 rounded-lg flex items-center justify-center" style="background:${s.c}15"><i class="fas ${s.i}" style="color:${s.c}"></i></div></div></div>`).join('')}
    </div>
    <div class="grid lg:grid-cols-2 gap-6">
        <div class="admin-card"><h3 class="font-semibold mb-4 text-sm">${currentLang==='bn'?'নিবন্ধন ওভারভিউ':'Registrations Overview'}</h3><canvas id="adminYearChart" height="220"></canvas></div>
        <div class="admin-card"><h3 class="font-semibold mb-4 text-sm">${currentLang==='bn'?'বিভাগ অনুযায়ী':'By Category'}</h3><canvas id="adminCatChart" height="220"></canvas></div>
    </div>
    <div class="grid lg:grid-cols-3 gap-4 mt-6">
        <div class="admin-card"><h3 class="font-semibold mb-3 text-sm">${currentLang==='bn'?'সাম্প্রতিক ভর্তি':'Recent Enrollments'}</h3><div class="space-y-2">${trainees.slice(0,5).map(t=>`<div class="flex items-center gap-3 p-2 rounded" style="background:var(--bg)"><div class="w-8 h-8 rounded-full bg-indigo-100 flex items-center justify-center text-xs font-bold text-indigo-600">${(t.name||'U')[0]}</div><div class="flex-1 min-w-0"><div class="text-sm font-medium truncate">${t.name||'-'}</div><div class="text-xs text-gray-400">${t.org||''}</div></div></div>`).join('')||'<p class="text-xs text-gray-400">No enrollments yet</p>'}</div></div>
        <div class="admin-card"><h3 class="font-semibold mb-3 text-sm">${currentLang==='bn'?'সাম্প্রতিক নোটিশ':'Recent Notices'}</h3><div class="space-y-2">${notices.slice(0,5).map(n=>`<div class="flex items-center gap-3 p-2 rounded" style="background:var(--bg)"><div class="w-8 h-8 rounded-full flex items-center justify-center" style="background:${n.type==='important'?'var(--danger-light)':n.type==='new'?'var(--info-light)':'var(--warning-light)'}"><i class="fas ${n.type==='important'?'fa-exclamation-triangle text-red-500':n.type==='new'?'fa-bell text-blue-500':'fa-info-circle text-yellow-500'} text-xs"></i></div><div class="flex-1 min-w-0"><div class="text-sm font-medium truncate">${n.title}</div><div class="text-xs text-gray-400">${n.date||''}</div></div></div>`).join('')||'<p class="text-xs text-gray-400">No notices</p>'}</div></div>
        <div class="admin-card"><h3 class="font-semibold mb-3 text-sm">${currentLang==='bn'?'দ্রুত অ্যাকশন':'Quick Actions'}</h3><div class="space-y-2"><button class="w-full text-left p-3 rounded-lg text-sm hover:bg-gray-50 transition flex items-center gap-3" style="border:1px solid var(--border)" onclick="openAdminForm('trainings')"><i class="fas fa-plus text-green-500"></i>${t('admin_add_new')} Training</button><button class="w-full text-left p-3 rounded-lg text-sm hover:bg-gray-50 transition flex items-center gap-3" style="border:1px solid var(--border)" onclick="openAdminForm('notices')"><i class="fas fa-bullhorn text-blue-500"></i>${t('admin_add_new')} Notice</button><button class="w-full text-left p-3 rounded-lg text-sm hover:bg-gray-50 transition flex items-center gap-3" style="border:1px solid var(--border)" onclick="openAdminForm('officers')"><i class="fas fa-user-plus text-purple-500"></i>${t('admin_add_new')} Officer</button></div></div>
    </div>`;
}

function initAdminCharts() {
    setTimeout(() => {
        const yc = document.getElementById('adminYearChart');
        if (yc) {
            try {
                new Chart(yc, {
                    type:'bar',
                    data:{
                        labels:['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
                        datasets:[
                            {label:currentLang==='bn'?'প্রশিক্ষণ':'Trainings',data:[3,2,4,3,5,4,0,0,0,0,0,0],backgroundColor:'#312E81',borderRadius:4},
                            {label:currentLang==='bn'?'সার্টিফিকেট':'Certificates',data:[12,8,15,10,18,14,0,0,0,0,0,0],backgroundColor:'#06B6D4',borderRadius:4}
                        ]
                    },
                    options:{plugins:{legend:{position:'bottom'}},scales:{y:{beginAtZero:true}}}
                });
            } catch(e) { console.error('Chart error:', e); }
        }
        const cc = document.getElementById('adminCatChart');
        if (cc) {
            try {
                const cats = {};
                trainings.forEach(tr => { cats[tr.category] = (cats[tr.category]||0)+1; });
                const catLabels = Object.keys(cats);
                const catData = Object.values(cats);
                if (catLabels.length === 0) { catLabels.push('No Data'); catData.push(1); }
                new Chart(cc, {
                    type:'doughnut',
                    data:{labels:catLabels,datasets:[{data:catData,backgroundColor:['#312E81','#06B6D4','#F59E0B','#DC2626','#059669']}]},
                    options:{plugins:{legend:{position:'right'}},cutout:'60%'}
                });
                        } catch(e) { console.error('Chart error:', e); }
        }
    }, 100);
}

// =============================================
// GENERIC CRUD LIST
// =============================================
function adminCrudList(entity, title, columns) {
    let data = [];
    if (entity === 'trainings') data = trainings;
    else if (entity === 'testings') data = testings;
    else if (entity === 'notices') data = notices;
    else if (entity === 'officers') data = officers;
    else if (entity === 'employees') data = employees;
    else if (entity === 'trainees') data = trainees;
    else if (entity === 'equipment') data = equipment;
    else if (entity === 'gallery') data = galleryItems;
    else if (entity === 'videos') data = videoItems;
    else if (entity === 'facilities') data = facilities;
    else if (entity === 'sliders') data = sliders;

    const ths = columns.map(c => `<th>${c}</th>`).join('');
    const rows = data.map(item => {
        let tds = getAdminRowCells(item, entity);
        return `<tr>${tds}<td><div class="flex gap-1">
            <button class="btn-primary btn-sm" onclick="openAdminForm('${entity}',${item.id})"><i class="fas fa-edit"></i> ${t('admin_edit')}</button>
            <button class="btn-danger btn-sm" onclick="adminDelete('${entity}',${item.id})"><i class="fas fa-trash"></i> ${t('admin_delete')}</button>
        </div></td></tr>`;
    }).join('');

    return `<div class="flex justify-between items-center mb-6">
        <h3 class="font-bold text-lg">${title}</h3>
        <button class="btn-primary" onclick="openAdminForm('${entity}')"><i class="fas fa-plus mr-2"></i>${t('admin_add_new')}</button>
    </div>
    <div class="admin-card overflow-x-auto">
        <table class="admin-table">
            <thead><tr>${ths}<th>${t('admin_actions')}</th></tr></thead>
            <tbody>${rows || `<tr><td colspan="${columns.length+1}" class="text-center py-8 text-gray-400">${t('admin_no_records')}</td></tr>`}</tbody>
        </table>
    </div>`;
}

function getAdminRowCells(item, entity) {
    if (entity === 'trainings')
        return `<td class="font-medium">${item.title}</td><td><span class="badge badge-info">${item.category||'-'}</span></td><td class="text-xs">${item.start || '-'}</td><td><span class="badge ${item.status==='ongoing'?'badge-success':item.status==='upcoming'?'badge-info':'badge-warning'}">${item.status||'-'}</span></td>`;
    if (entity === 'testings')
        return `<td class="font-medium">${item.title}</td><td><span class="badge badge-info">${item.testType||'-'}</span></td><td class="text-xs">${item.turnaround || '-'}</td>`;
    if (entity === 'notices')
        return `<td class="font-medium">${item.title}</td><td class="text-xs">${item.date || '-'}</td><td><span class="badge ${item.type==='important'?'badge-danger':item.type==='new'?'badge-info':'badge-warning'}">${item.type||'-'}</span></td>`;
    if (entity === 'officers')
        return `<td><img src="${item.img || 'https://via.placeholder.com/40'}" class="w-10 h-10 rounded-full object-cover"></td><td class="font-medium">${item.name}</td><td>${item.designation||'-'}</td><td class="text-xs">${item.email || '-'}</td>`;
    if (entity === 'employees')
    return `<td><div class="w-10 h-10 rounded-full overflow-hidden border" style="border-color:var(--border)">${item.img ? `<img src="${item.img}" class="w-full h-full object-cover">` : `<div class="w-full h-full flex items-center justify-center text-xs font-bold text-white" style="background:var(--primary)">${(item.name||'U')[0]}</div>`}</div></td><td class="font-medium">${item.name||'-'}</td><td>${item.designation||'-'}</td><td class="text-xs">${item.department||'-'}</td>`;
    if (entity === 'trainees')
        return `<td class="font-medium">${item.name||'-'}</td><td class="text-xs">${item.email || '-'}</td><td class="text-xs">${item.org || '-'}</td>`;
    if (entity === 'equipment')
        return `<td class="font-medium">${item.name||'-'}</td><td class="text-xs">${item.capacity || '-'}</td><td class="text-xs">${item.standard || '-'}</td>`;
    if (entity === 'gallery')
        return `<td class="font-medium">${item.title || '-'}</td><td><span class="badge badge-info">${item.category || '-'}</span></td>`;
    if (entity === 'videos')
        return `<td class="font-medium">${item.title||'-'}</td><td class="text-xs text-blue-600">${item.url ? '<i class="fas fa-link"></i> Link' : '-'}</td>`;
    if (entity === 'facilities')
        return `<td><span class="badge badge-info">${item.type || '-'}</span></td><td class="font-medium">${item.title || item.type || '-'}</td>`;
    if (entity === 'sliders')
        return `<td class="font-medium">${item.title || '-'}</td><td class="text-xs">${item.subtitle || '-'}</td>`;
    return '<td>-</td>';
}

// =============================================
// ADMIN FORM BUILDER
// =============================================
function openAdminForm(entity, id = null) {
    let data = [];
    if (entity==='trainings') data=trainings;
    else if (entity==='testings') data=testings;
    else if (entity==='notices') data=notices;
    else if (entity==='officers') data=officers;
    else if (entity==='trainees') data=trainees;
    else if (entity==='equipment') data=equipment;
    else if (entity==='gallery') data=galleryItems;
    else if (entity==='videos') data=videoItems;
    else if (entity==='facilities') data=facilities;
    else if (entity==='sliders') data=sliders;

    // ===== FIX #1: Proper ID comparison (string vs number) =====
    const numericId = (id !== null && id !== 'null' && id !== 0) ? parseInt(id) : null;
    const item = numericId ? data.find(d => parseInt(d.id) === numericId) : null;
    
    // Debug log (remove after confirming fix)
    console.log('openAdminForm:', { entity, id, numericId, itemFound: !!item });
    if (numericId && !item) {
        console.log('Available IDs:', data.map(d => ({ id: d.id, type: typeof d.id })));
    }
    
    const isEdit = !!item;
    const bn = currentLang === 'bn';
    const title = isEdit 
        ? `${t('admin_edit')} ${entity}` 
        : `${t('admin_add_new')} ${entity}`;

    let fields = '';

    const imgField = (val) => `
        <div class="form-group">
            <label>${bn?'ছবি / Image':'Image'}</label>
            <input type="file" id="af-img-file" accept="image/*" onchange="previewAdminImage(this)">
            <div id="img-preview-box" class="mt-2 ${val ? '' : 'hidden'}">
                <img id="img-preview-tag" src="${val||''}" class="w-24 h-24 object-cover rounded border">
            </div>
            <input type="hidden" id="af-img" value="${val||''}">
        </div>`;

    if (entity === 'trainings') {
        fields = `
            <div class="form-group">
                <label>${bn?'শিরোনাম / Title':'Title'} <span class="text-red-500">*</span></label>
                <input type="text" id="af-title" required value="${isEdit ? (item.title||'') : ''}" placeholder="${bn?'প্রশিক্ষণের নাম':'Training Title'}">
            </div>
            <div class="form-group">
                <label>${bn?'বিবরণ / Description':'Description'}</label>
                <textarea id="af-desc" rows="3" placeholder="${bn?'বিস্তারিত বিবরণ':'Detailed description'}">${isEdit ? (item.desc||'') : ''}</textarea>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>${bn?'বিভাগ / Category':'Category'}</label>
                    <select id="af-category">
                        <option value="Short Course" ${isEdit && item.category==='Short Course'?'selected':''}>Short Course</option>
                        <option value="Workshop" ${isEdit && item.category==='Workshop'?'selected':''}>Workshop</option>
                        <option value="Certificate Program" ${isEdit && item.category==='Certificate Program'?'selected':''}>Certificate Program</option>
                        <option value="Seminar" ${isEdit && item.category==='Seminar'?'selected':''}>Seminar</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>${bn?'অবস্থা / Status':'Status'}</label>
                    <select id="af-status">
                        <option value="upcoming" ${isEdit && item.status==='upcoming'?'selected':''}>Upcoming</option>
                        <option value="ongoing" ${isEdit && item.status==='ongoing'?'selected':''}>Ongoing</option>
                        <option value="completed" ${isEdit && item.status==='completed'?'selected':''}>Completed</option>
                    </select>
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>${bn?'শুরুর তারিখ / Start Date':'Start Date'}</label>
                    <input type="date" id="af-start" value="${isEdit ? (item.start||'') : ''}">
                </div>
                <div class="form-group">
                    <label>${bn?'শেষ তারিখ / End Date':'End Date'}</label>
                    <input type="date" id="af-end" value="${isEdit ? (item.end||'') : ''}">
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>${bn?'সর্বোচ্চ অংশগ্রহণকারী / Max Participants':'Max Participants'}</label>
                    <input type="number" id="af-capacity" value="${isEdit ? (item.capacity||30) : 30}" placeholder="30">
                </div>
                <div class="form-group">
                    <label>${bn?'স্থান / Venue':'Venue'}</label>
                    <input type="text" id="af-venue" value="${isEdit ? (item.venue||'') : ''}" placeholder="${bn?'প্রশিক্ষণ স্থান':'Training venue'}">
                </div>
            </div>
            ${imgField(isEdit ? (item.img||'') : '')}`;
    }
    else if (entity === 'testings') {
        fields = `
            <div class="form-group">
                <label>${bn?'শিরোনাম / Test Name':'Test Name'} <span class="text-red-500">*</span></label>
                <input type="text" id="af-title" required value="${isEdit ? (item.title||'') : ''}" placeholder="${bn?'পরীক্ষার নাম':'Test Service Name'}">
            </div>
            <div class="form-group">
                <label>${bn?'বিবরণ / Description':'Description'}</label>
                <textarea id="af-desc" rows="3" placeholder="${bn?'পরীক্ষা সেবার বিবরণ':'Description'}">${isEdit ? (item.desc||'') : ''}</textarea>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>${bn?'পরীক্ষার ধরন / Test Type':'Test Type'}</label>
                    <select id="af-testType">
                        <option value="Concrete" ${isEdit && item.testType==='Concrete'?'selected':''}>Concrete</option>
                        <option value="Soil" ${isEdit && item.testType==='Soil'?'selected':''}>Soil</option>
                        <option value="Steel" ${isEdit && item.testType==='Steel'?'selected':''}>Steel</option>
                        <option value="Water" ${isEdit && item.testType==='Water'?'selected':''}>Water</option>
                        <option value="Bitumen" ${isEdit && item.testType==='Bitumen'?'selected':''}>Bitumen</option>
                        <option value="Aggregate" ${isEdit && item.testType==='Aggregate'?'selected':''}>Aggregate</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>${bn?'সময়সীমা (দিন) / Turnaround':'Turnaround (Days)'}</label>
                    <input type="number" id="af-turnaround" value="${isEdit ? (item.turnaround||3) : 3}" placeholder="3">
                </div>
            </div>
            <div class="form-group">
                <label>${bn?'মান / Standard':'Standard'}</label>
                <select id="af-standard">
                    <option value="BDS" ${isEdit && item.standard==='BDS'?'selected':''}>BDS</option>
                    <option value="ASTM" ${isEdit && item.standard==='ASTM'?'selected':''}>ASTM</option>
                    <option value="IS" ${isEdit && item.standard==='IS'?'selected':''}>IS</option>
                    <option value="AASHTO" ${isEdit && item.standard==='AASHTO'?'selected':''}>AASHTO</option>
                </select>
            </div>
            ${imgField(isEdit ? (item.img||'') : '')}`;
    }
    else if (entity === 'notices') {
        fields = `
            <div class="form-group">
                <label>${bn?'শিরোনাম / Notice Title':'Notice Title'} <span class="text-red-500">*</span></label>
                <input type="text" id="af-title" required value="${isEdit ? (item.title||'') : ''}" placeholder="${bn?'নোটিশের শিরোনাম':'Notice Title'}">
            </div>
            <div class="form-group">
                <label>${bn?'বিষয়বস্তু / Content':'Content'}</label>
                <textarea id="af-content" rows="5" required placeholder="${bn?'সম্পূর্ণ বিষয়বস্তু':'Full notice content'}">${isEdit ? (item.content||'') : ''}</textarea>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>${bn?'তারিখ / Date':'Date'}</label>
                    <input type="date" id="af-date" value="${isEdit ? (item.date||'') : ''}">
                </div>
                <div class="form-group">
                    <label>${bn?'ধরন / Type':'Type'}</label>
                    <select id="af-type">
                        <option value="general" ${isEdit && item.type==='general'?'selected':''}>General</option>
                        <option value="important" ${isEdit && item.type==='important'?'selected':''}>Important</option>
                        <option value="new" ${isEdit && item.type==='new'?'selected':''}>New</option>
                        <option value="urgent" ${isEdit && item.type==='urgent'?'selected':''}>Urgent</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label>${bn?'বিভাগ / Category':'Category'}</label>
                <select id="af-category">
                    <option value="" ${isEdit && !item.category?'selected':''}>${bn?'নির্বাচন করুন':'Select'}</option>
                    <option value="Training" ${isEdit && item.category==='Training'?'selected':''}>Training</option>
                    <option value="Exam" ${isEdit && item.category==='Exam'?'selected':''}>Exam</option>
                    <option value="Holiday" ${isEdit && item.category==='Holiday'?'selected':''}>Holiday</option>
                    <option value="Event" ${isEdit && item.category==='Event'?'selected':''}>Event</option>
                </select>
            </div>`;
    }
    else if (entity === 'officers') {
        fields = `
            <div class="form-row">
                <div class="form-group">
                    <label>${bn?'নাম / Full Name':'Full Name'} <span class="text-red-500">*</span></label>
                    <input type="text" id="af-name" required value="${isEdit ? (item.name||'') : ''}" placeholder="${bn?'পুরো নাম':'Full Name'}">
                </div>
                <div class="form-group">
                    <label>${bn?'পদবি / Designation':'Designation'} <span class="text-red-500">*</span></label>
                    <input type="text" id="af-designation" required value="${isEdit ? (item.designation||'') : ''}" placeholder="${bn?'পদবি':'Designation'}">
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>${bn?'ইমেইল / Email':'Email'}</label>
                    <input type="email" id="af-email" value="${isEdit ? (item.email||'') : ''}" placeholder="email@example.com">
                </div>
                <div class="form-group">
                    <label>${bn?'ফোন / Phone':'Phone'}</label>
                    <input type="tel" id="af-phone" value="${isEdit ? (item.phone||'') : ''}" placeholder="+880XXXXXXXXXX">
                </div>
            </div>
            <div class="form-group">
                <label>${bn?'বিভাগ / Department':'Department'}</label>
                <input type="text" id="af-department" value="${isEdit ? (item.department||'') : ''}" placeholder="${bn?'বিভাগ':'Department'}">
            </div>
            ${imgField(isEdit ? (item.img||'') : '')}`;
    }
    else if (entity === 'trainees') {
        fields = `
            <div class="form-row">
                <div class="form-group">
                    <label>${bn?'নাম / Name':'Name'} <span class="text-red-500">*</span></label>
                    <input type="text" id="af-name" required value="${isEdit ? (item.name||'') : ''}" placeholder="${bn?'নাম':'Name'}">
                </div>
                <div class="form-group">
                    <label>${bn?'ইমেইল / Email':'Email'} <span class="text-red-500">*</span></label>
                    <input type="email" id="af-email" required value="${isEdit ? (item.email||'') : ''}" placeholder="email@example.com">
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>${bn?'ফোন / Phone':'Phone'}</label>
                    <input type="tel" id="af-phone" value="${isEdit ? (item.phone||'') : ''}" placeholder="+880XXXXXXXXXX">
                </div>
                <div class="form-group">
                    <label>${bn?'প্রতিষ্ঠান / Organization':'Organization'}</label>
                    <input type="text" id="af-org" value="${isEdit ? (item.org||'') : ''}" placeholder="${bn?'প্রতিষ্ঠান':'Organization'}">
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>${bn?'পদবি / Designation':'Designation'}</label>
                    <input type="text" id="af-designation" value="${isEdit ? (item.designation||'') : ''}" placeholder="${bn?'পদবি':'Designation'}">
                </div>
                <div class="form-group">
                    <label>${bn?'ভর্তি হওয়া প্রশিক্ষণ / Training':'Enrolled Training'}</label>
                    <input type="text" id="af-training" value="${isEdit ? (item.training||'') : ''}" placeholder="${bn?'প্রশিক্ষণের নাম':'Training Name'}">
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>${bn?'অবস্থা / Status':'Status'}</label>
                    <select id="af-status">
                        <option value="enrolled" ${isEdit && item.status==='enrolled'?'selected':''}>Enrolled</option>
                        <option value="active" ${isEdit && item.status==='active'?'selected':''}>Active</option>
                        <option value="completed" ${isEdit && item.status==='completed'?'selected':''}>Completed</option>
                        <option value="dropped" ${isEdit && item.status==='dropped'?'selected':''}>Dropped</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>${bn?'ভর্তির তারিখ / Date':'Enrollment Date'}</label>
                    <input type="date" id="af-date" value="${isEdit ? (item.date||'') : ''}">
                </div>
            </div>`;
    }
    else if (entity === 'equipment') {
        fields = `
            <div class="form-group">
                <label>${bn?'যন্ত্রের নাম / Equipment Name':'Equipment Name'} <span class="text-red-500">*</span></label>
                <input type="text" id="af-name" required value="${isEdit ? (item.name||'') : ''}" placeholder="${bn?'যন্ত্রের নাম':'Equipment Name'}">
            </div>
            <div class="form-group">
                <label>${bn?'বিবরণ / Description':'Description'}</label>
                <textarea id="af-desc" rows="3" placeholder="${bn?'বিবরণ':'Description'}">${isEdit ? (item.desc||'') : ''}</textarea>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>${bn?'ধারণক্ষমতা / Capacity':'Capacity'}</label>
                    <input type="text" id="af-capacity" value="${isEdit ? (item.capacity||'') : ''}" placeholder="${bn?'যেমন: 2000 kN':'e.g., 2000 kN'}">
                </div>
                <div class="form-group">
                    <label>${bn?'মান / Standard':'Standard'}</label>
                    <select id="af-standard">
                        <option value="BDS" ${isEdit && item.standard==='BDS'?'selected':''}>BDS</option>
                        <option value="ASTM" ${isEdit && item.standard==='ASTM'?'selected':''}>ASTM</option>
                        <option value="IS" ${isEdit && item.standard==='IS'?'selected':''}>IS</option>
                        <option value="AASHTO" ${isEdit && item.standard==='AASHTO'?'selected':''}>AASHTO</option>
                    </select>
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>${bn?'মডেল / Model':'Model'}</label>
                    <input type="text" id="af-model" value="${isEdit ? (item.model||'') : ''}" placeholder="${bn?'মডেল নম্বর':'Model Number'}">
                </div>
                <div class="form-group">
                    <label>${bn?'সিরিয়াল / Serial No.':'Serial No.'}</label>
                    <input type="text" id="af-serial" value="${isEdit ? (item.serial||'') : ''}" placeholder="${bn?'সিরিয়াল নম্বর':'Serial Number'}">
                </div>
            </div>
            ${imgField(isEdit ? (item.img||'') : '')}`;
    }
    else if (entity === 'gallery') {
        fields = `
            <div class="form-group">
                <label>${bn?'শিরোনাম / Title':'Title'}</label>
                <input type="text" id="af-title" value="${isEdit ? (item.title||'') : ''}" placeholder="${bn?'ছবির শিরোনাম':'Image Title'}">
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>${bn?'বিভাগ / Category':'Category'}</label>
                    <select id="af-category">
                        <option value="Event" ${isEdit && item.category==='Event'?'selected':''}>Event</option>
                        <option value="Training" ${isEdit && item.category==='Training'?'selected':''}>Training</option>
                        <option value="Campus" ${isEdit && item.category==='Campus'?'selected':''}>Campus</option>
                        <option value="Lab" ${isEdit && item.category==='Lab'?'selected':''}>Lab</option>
                        <option value="Ceremony" ${isEdit && item.category==='Ceremony'?'selected':''}>Ceremony</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>${bn?'তারিখ / Date':'Date'}</label>
                    <input type="date" id="af-date" value="${isEdit ? (item.date||'') : ''}">
                </div>
            </div>
            ${imgField(isEdit ? (item.img||'') : '')}`;
    }
    else if (entity === 'videos') {
        fields = `
            <div class="form-group">
                <label>${bn?'শিরোনাম / Video Title':'Video Title'} <span class="text-red-500">*</span></label>
                <input type="text" id="af-title" required value="${isEdit ? (item.title||'') : ''}" placeholder="${bn?'ভিডিওর শিরোনাম':'Video Title'}">
            </div>
            <div class="form-group">
                <label>${bn?'বিবরণ / Description':'Description'}</label>
                <textarea id="af-desc" rows="3" placeholder="${bn?'ভিডিওর বিবরণ':'Description'}">${isEdit ? (item.desc||'') : ''}</textarea>
            </div>
            <div class="form-group">
                <label>YouTube / Vimeo URL</label>
                <input type="url" id="af-url" required value="${isEdit ? (item.url||'') : ''}" placeholder="https://www.youtube.com/watch?v=...">
            </div>
            <div class="form-group">
                <label>${bn?'থাম্বনেইল / Thumbnail URL':'Thumbnail URL'}</label>
                <input type="url" id="af-thumb" value="${isEdit ? (item.thumb||'') : ''}" placeholder="${bn?'থাম্বনেইল URL':'Thumbnail URL'}">
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>${bn?'বিভাগ / Category':'Category'}</label>
                    <select id="af-category">
                        <option value="Training" ${isEdit && item.category==='Training'?'selected':''}>Training</option>
                        <option value="Event" ${isEdit && item.category==='Event'?'selected':''}>Event</option>
                        <option value="Tour" ${isEdit && item.category==='Tour'?'selected':''}>Campus Tour</option>
                        <option value="Interview" ${isEdit && item.category==='Interview'?'selected':''}>Interview</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>${bn?'সময়কাল (মিনিট) / Duration':'Duration (min)'}</label>
                    <input type="number" id="af-duration" value="${isEdit ? (item.duration||0) : 0}" placeholder="0">
                </div>
            </div>`;
    }
    else if (entity === 'facilities') {
        fields = `
            <div class="form-group">
                <label>${bn?'সুবিধার ধরন / Facility Type':'Facility Type'} <span class="text-red-500">*</span></label>
                <select id="af-type" required>
                    <option value="">-- ${bn?'নির্বাচন করুন':'Select Type'} --</option>
                    <option value="classroom" ${isEdit && item.type==='classroom'?'selected':''}>Classroom</option>
                    <option value="computerlab" ${isEdit && item.type==='computerlab'?'selected':''}>Computer Lab</option>
                    <option value="library" ${isEdit && item.type==='library'?'selected':''}>Library</option>
                    <option value="residential" ${isEdit && item.type==='residential'?'selected':''}>Residential</option>
                    <option value="playground" ${isEdit && item.type==='playground'?'selected':''}>Playground</option>
                    <option value="gymnasium" ${isEdit && item.type==='gymnasium'?'selected':''}>Gymnasium</option>
                    <option value="swimmingpool" ${isEdit && item.type==='swimmingpool'?'selected':''}>Swimming Pool</option>
                    <option value="testinglab" ${isEdit && item.type==='testinglab'?'selected':''}>Testing Lab</option>
                </select>
            </div>
            <div class="form-group">
                <label>${bn?'শিরোনাম / Title':'Title'}</label>
                <input type="text" id="af-title" value="${isEdit ? (item.title||'') : ''}" placeholder="${bn?'সুবিধার নাম':'Facility Title'}">
            </div>
            <div class="form-group">
                <label>${bn?'বিবরণ / Description':'Description'}</label>
                <textarea id="af-desc" rows="4" placeholder="${bn?'বিস্তারিত বিবরণ':'Detailed description'}">${isEdit ? (item.desc||'') : ''}</textarea>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>${bn?'ধারণক্ষমতা / Capacity':'Capacity'}</label>
                    <input type="number" id="af-capacity" value="${isEdit ? (item.capacity||0) : 0}" placeholder="0">
                </div>
                <div class="form-group">
                    <label>${bn?'আয়তন (বর্গফুট) / Area (sq.ft)':'Area (sq.ft)'}</label>
                    <input type="number" id="af-area" value="${isEdit ? (item.area||0) : 0}" placeholder="0">
                </div>
            </div>
            <div class="form-group">
                <label>${bn?'বৈশিষ্ট্য / Features':'Features (comma separated)'}</label>
                <textarea id="af-features" rows="3" placeholder="${bn?'কমা দিয়ে আলাদা করুন':'Separate with comma'}">${isEdit ? (item.features||'') : ''}</textarea>
            </div>
            ${imgField(isEdit ? (item.img||'') : '')}`;
    }
    else if (entity === 'sliders') {
        fields = `
            <div class="form-group">
                <label>${bn?'শিরোনাম / Title':'Title'}</label>
                <input type="text" id="af-title" value="${isEdit ? (item.title||'') : ''}" placeholder="${bn?'স্লাইডার শিরোনাম':'Slider Title'}">
            </div>
            <div class="form-group">
                <label>${bn?'উপশিরোনাম / Subtitle':'Subtitle'}</label>
                <input type="text" id="af-subtitle" value="${isEdit ? (item.subtitle||'') : ''}" placeholder="${bn?'উপশিরোনাম':'Subtitle'}">
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>${bn?'বাটন টেক্সট / Button Text':'Button Text'}</label>
                    <input type="text" id="af-btnText" value="${isEdit ? (item.btnText||'') : ''}" placeholder="${bn?'যেমন: View Courses':'e.g., View Courses'}">
                </div>
                <div class="form-group">
                    <label>${bn?'বাটন লিংক / Button Link':'Button Link'}</label>
                    <input type="text" id="af-btnLink" value="${isEdit ? (item.btnLink||'') : ''}" placeholder="${bn?'যেমন: trainings':'e.g., trainings'}">
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>${bn?'সাজানো / Order':'Order'}</label>
                    <input type="number" id="af-order" value="${isEdit ? (item.order||0) : 0}" placeholder="0">
                </div>
                <div class="form-group">
                    <label>${bn?'সক্রিয় / Active':'Active'}</label>
                    <select id="af-active">
                        <option value="1" ${isEdit && item.active!=0?'selected':''}>Yes</option>
                        <option value="0" ${isEdit && item.active===0?'selected':''}>No</option>
                    </select>
                </div>
            </div>
            ${imgField(isEdit ? (item.img||'') : '')}`;
    }
       else if (entity === 'employees') {
        fields = `
            <div class="form-row">
                <div class="form-group">
                    <label>${bn?'নাম / Name':'Name'} <span class="text-red-500">*</span></label>
                    <input type="text" id="af-name" required value="${isEdit ? (item.name||'') : ''}" placeholder="${bn?'পুরো নাম':'Full Name'}">
                </div>
                <div class="form-group">
                    <label>${bn?'পদবি / Designation':'Designation'} <span class="text-red-500">*</span></label>
                    <input type="text" id="af-designation" required value="${isEdit ? (item.designation||'') : ''}" placeholder="${bn?'পদবি':'Designation'}">
                </div>
            </div>
            <div class="form-group">
                <label>${bn?'বিভাগ / Department':'Department'}</label>
                <select id="af-department">
                    <option value="Civil Division" ${isEdit && item.department==='Civil Division'?'selected':''}>Civil Division</option>
                    <option value="Architecture Division" ${isEdit && item.department==='Architecture Division'?'selected':''}>Architecture Division</option>
                    <option value="Electrical & Mechanical" ${isEdit && item.department==='Electrical & Mechanical'?'selected':''}>Electrical & Mechanical</option>
                    <option value="Training Section" ${isEdit && item.department==='Training Section'?'selected':''}>Training Section</option>
                    <option value="Administration" ${isEdit && item.department==='Administration'?'selected':''}>Administration</option>
                    <option value="Testing Laboratory" ${isEdit && item.department==='Testing Laboratory'?'selected':''}>Testing Laboratory</option>
                    <option value="Other" ${isEdit && item.department==='Other'?'selected':''}>Other</option>
                </select>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>${bn?'ইমেইল / Email':'Email'}</label>
                    <input type="email" id="af-email" value="${isEdit ? (item.email||'') : ''}" placeholder="email@pwd.gov.bd">
                </div>
                <div class="form-group">
                    <label>${bn?'ফোন / Phone':'Phone'}</label>
                    <input type="tel" id="af-phone" value="${isEdit ? (item.phone||'') : ''}" placeholder="+880XXXXXXXXXX">
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>${bn?'যোগদানের তারিখ / Join Date':'Join Date'}</label>
                    <input type="date" id="af-joinDate" value="${isEdit ? (item.joinDate||'') : ''}">
                </div>
                <div class="form-group">
                    <label>${bn?'সক্রিয় / Active':'Active'}</label>
                    <select id="af-active">
                        <option value="1" ${isEdit && item.active!=0?'selected':''}>${bn?'হ্যাঁ':'Yes'}</option>
                        <option value="0" ${isEdit && item.active===0?'selected':''}>${bn?'না':'No'}</option>
                    </select>
                </div>
            </div>
            ${imgField(isEdit ? (item.img||'') : '')}`;
    }
        else if (entity === 'employees') {
        fields = `
            <div class="form-row">
                <div class="form-group">
                    <label>${bn?'নাম / Name':'Name'} <span class="text-red-500">*</span></label>
                    <input type="text" id="af-name" required value="${isEdit ? (item.name||'') : ''}" placeholder="${bn?'পুরো নাম':'Full Name'}">
                </div>
                <div class="form-group">
                    <label>${bn?'পদবি / Designation':'Designation'} <span class="text-red-500">*</span></label>
                    <input type="text" id="af-designation" required value="${isEdit ? (item.designation||'') : ''}" placeholder="${bn?'পদবি':'Designation'}">
                </div>
            </div>
            <div class="form-group">
                <label>${bn?'বিভাগ / Department':'Department'}</label>
                <select id="af-department">
                    <option value="Civil Division" ${isEdit && item.department==='Civil Division'?'selected':''}>Civil Division</option>
                    <option value="Architecture Division" ${isEdit && item.department==='Architecture Division'?'selected':''}>Architecture Division</option>
                    <option value="Electrical & Mechanical" ${isEdit && item.department==='Electrical & Mechanical'?'selected':''}>Electrical & Mechanical</option>
                    <option value="Training Section" ${isEdit && item.department==='Training Section'?'selected':''}>Training Section</option>
                    <option value="Administration" ${isEdit && item.department==='Administration'?'selected':''}>Administration</option>
                    <option value="Testing Laboratory" ${isEdit && item.department==='Testing Laboratory'?'selected':''}>Testing Laboratory</option>
                    <option value="Other" ${isEdit && item.department==='Other'?'selected':''}>Other</option>
                </select>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>${bn?'ইমেইল / Email':'Email'}</label>
                    <input type="email" id="af-email" value="${isEdit ? (item.email||'') : ''}" placeholder="email@pwd.gov.bd">
                </div>
                <div class="form-group">
                    <label>${bn?'ফোন / Phone':'Phone'}</label>
                    <input type="tel" id="af-phone" value="${isEdit ? (item.phone||'') : ''}" placeholder="+880XXXXXXXXXX">
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>${bn?'যোগদানের তারিখ / Join Date':'Join Date'}</label>
                    <input type="date" id="af-joinDate" value="${isEdit ? (item.joinDate||'') : ''}">
                </div>
                <div class="form-group">
                    <label>${bn?'সক্রিয় / Active':'Active'}</label>
                    <select id="af-active">
                        <option value="1" ${isEdit && item.active!=0?'selected':''}>${bn?'হ্যাঁ':'Yes'}</option>
                        <option value="0" ${isEdit && item.active===0?'selected':''}>${bn?'না':'No'}</option>
                    </select>
                </div>
            </div>
            ${imgField(isEdit ? (item.img||'') : '')}`;
    }
       else if (entity === 'employees') {
        fields = `
            <div class="form-row">
                <div class="form-group">
                    <label>${bn?'নাম / Name':'Name'} <span class="text-red-500">*</span></label>
                    <input type="text" id="af-name" required value="${isEdit ? (item.name||'') : ''}" placeholder="${bn?'পুরো নাম':'Full Name'}">
                </div>
                <div class="form-group">
                    <label>${bn?'পদবি / Designation':'Designation'} <span class="text-red-500">*</span></label>
                    <input type="text" id="af-designation" required value="${isEdit ? (item.designation||'') : ''}" placeholder="${bn?'পদবি':'Designation'}">
                </div>
            </div>
            <div class="form-group">
                <label>${bn?'বিভাগ / Department':'Department'}</label>
                <select id="af-department">
                    <option value="Civil Division" ${isEdit && item.department==='Civil Division'?'selected':''}>Civil Division</option>
                    <option value="Architecture Division" ${isEdit && item.department==='Architecture Division'?'selected':''}>Architecture Division</option>
                    <option value="Electrical & Mechanical" ${isEdit && item.department==='Electrical & Mechanical'?'selected':''}>Electrical & Mechanical</option>
                    <option value="Training Section" ${isEdit && item.department==='Training Section'?'selected':''}>Training Section</option>
                    <option value="Administration" ${isEdit && item.department==='Administration'?'selected':''}>Administration</option>
                    <option value="Testing Laboratory" ${isEdit && item.department==='Testing Laboratory'?'selected':''}>Testing Laboratory</option>
                    <option value="Other" ${isEdit && item.department==='Other'?'selected':''}>Other</option>
                </select>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>${bn?'ইমেইল / Email':'Email'}</label>
                    <input type="email" id="af-email" value="${isEdit ? (item.email||'') : ''}" placeholder="email@pwd.gov.bd">
                </div>
                <div class="form-group">
                    <label>${bn?'ফোন / Phone':'Phone'}</label>
                    <input type="tel" id="af-phone" value="${isEdit ? (item.phone||'') : ''}" placeholder="+880XXXXXXXXXX">
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>${bn?'যোগদানের তারিখ / Join Date':'Join Date'}</label>
                    <input type="date" id="af-joinDate" value="${isEdit ? (item.joinDate||'') : ''}">
                </div>
                <div class="form-group">
                    <label>${bn?'সক্রিয় / Active':'Active'}</label>
                    <select id="af-active">
                        <option value="1" ${isEdit && item.active!=0?'selected':''}>${bn?'হ্যাঁ':'Yes'}</option>
                        <option value="0" ${isEdit && item.active===0?'selected':''}>${bn?'না':'No'}</option>
                    </select>
                </div>
            </div>
            ${imgField(isEdit ? (item.img||'') : '')}`;
    }
    else {
        fields = `<div class="form-group"><p style="color:var(--muted)">${bn?'ফর্ম উপলব্ধ নেই':'Form not available'}</p></div>`;
    }

    // ===== FIX #2: Proper ID passing to submitAdminForm =====
    const submitId = numericId ? numericId : 0;
    
    // Show edit indicator in modal
    const editIndicator = isEdit ? `
        <div class="flex items-center gap-2 px-4 py-2 rounded-lg mb-4" style="background:var(--info-light);border:1px solid var(--info)">
            <i class="fas fa-info-circle text-blue-500"></i>
            <span class="text-xs font-medium" style="color:var(--info)">Editing existing record #${numericId}</span>
        </div>
    ` : '';

    openModal(`
        <div class="p-5 border-b flex items-center justify-between" style="border-color:var(--border)">
            <h3 class="font-semibold">${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">
            ${editIndicator}
            <form onsubmit="submitAdminForm(event,'${entity}',${submitId})">
                ${fields}
                <div class="flex gap-3 mt-6">
                    <button type="submit" class="btn-primary flex-1">
                        <i class="fas fa-${isEdit ? 'save' : 'plus'} mr-2"></i>${isEdit ? t('admin_update') : t('admin_save')}
                    </button>
                    <button type="button" onclick="closeModal()" class="btn-outline flex-1">${t('admin_cancel')}</button>
                </div>
            </form>
        </div>
    `);
}

async function submitAdminForm(e, entity, id) {
    e.preventDefault();
    
    // ===== FIX: Proper ID handling =====
    const editId = (id && id !== 0) ? parseInt(id) : null;
    
    // Use FormData for file upload support
    const formData = new FormData();
    
    // Get the file input
    const fileInput = e.target.querySelector('#af-img-file');
    const hasNewFile = fileInput && fileInput.files && fileInput.files.length > 0;
    
    // If there's a new file, append it
    if (hasNewFile) {
        formData.append('img', fileInput.files[0]);
    } else {
        // Keep existing image path from hidden field
        const hiddenImg = document.getElementById('af-img');
        if (hiddenImg && hiddenImg.value) {
            const val = hiddenImg.value;
            if (!val.startsWith('data:')) {
                formData.append('img', val);
            }
        }
    }
    
    // Collect all other fields
    const inputs = e.target.querySelectorAll('input, textarea, select');
    inputs.forEach(input => {
        if (input.id && input.id.startsWith('af-') && input.type !== 'file' && input.id !== 'af-img') {
            const key = input.id.replace('af-', '');
            formData.append(key, input.value);
        }
    });
    
    // ===== FIX: Only append id if actually editing =====
    if (editId) {
        formData.append('id', editId);
    }

    // Send as FormData
    try {
        const url = `${API}?entity=${entity}`;
        const res = await fetch(url, {
            method: 'POST',
            body: formData
        });
        const result = await res.json();
        
        if (result.success !== false && !result.error) {
            showToast(editId ? t('admin_updated') : t('admin_created'), 'success');
            closeModal();
            await refreshEntity(entity);
            renderAdminPage();
            if (entity === 'notices') updateTicker();
        } else {
            showToast(result.error || result.message || t('admin_operation_failed'), 'error');
        }
    } catch(err) {
        console.error('Submit error:', err);
        showToast(t('admin_operation_failed'), 'error');
    }
}

async function adminDelete(entity, id) {
    if (!confirm(t('admin_confirm_delete'))) return;
    const res = await api(entity, 'DELETE', { id });
    if (res.success !== false && !res.error) {
        showToast(t('admin_deleted'), 'success');
        await refreshEntity(entity);
        renderAdminPage();
        if (entity === 'notices') updateTicker();
    } else {
        showToast(res.error || t('admin_operation_failed'), 'error');
    }
}

// =============================================
// ADMIN SETTINGS & REPORTS
// =============================================
function adminSettings() {
    return `<div class="admin-card max-w-2xl">
        <h3 class="font-semibold mb-6">${t('settings_title')}</h3>
        <form onsubmit="saveSettings(event)" class="space-y-5">
            <div class="form-group"><label>${t('settings_academy_name')}</label><input type="text" id="set-name" value="${currentLang==='bn'?'পিডব্লিউডি প্রশিক্ষণ একাডেমি':'PWD Training Academy'}"></div>
            <div class="form-group"><label>${t('settings_academy_address')}</label><input type="text" id="set-address" value="${currentLang==='bn'?'শের-ই-বাংলা নগর, ঢাকা-১২০৭':'Sher-e-Bangla Nagar, Dhaka-1207'}"></div>
            <div class="form-row">
                <div class="form-group"><label>${t('settings_academy_phone')}</label><input type="tel" id="set-phone" value="+880-2-8181234"></div>
                <div class="form-group"><label>${t('settings_academy_email')}</label><input type="email" id="set-email" value="info@pwd.training.gov.bd"></div>
            </div>
            <div class="form-group"><label>${currentLang==='bn'?'ওয়েবসাইটের বিবরণ / Site Description':'Site Description'}</label><textarea id="set-desc" rows="3">${currentLang==='bn'?'গণপূর্ত অধিদপ্তরের অধীনে সিভিল ইঞ্জিনিয়ারিং প্রশিক্ষণ প্রতিষ্ঠান':'Premier training institution under Public Works Department'}</textarea></div>
            <button type="submit" class="btn-primary"><i class="fas fa-save mr-2"></i>${t('settings_save')}</button>
        </form>
    </div>`;
}

async function saveSettings(e) {
    e.preventDefault();
    showToast(t('settings_saved'), 'success');
}

function adminReports() {
    const bn = currentLang === 'bn';
    return `<div class="admin-card">
        <h3 class="font-semibold mb-4 text-sm">${t('reports_training_summary')}</h3>
        <div class="grid md:grid-cols-2 gap-4 mb-6">
            <div class="p-4 rounded-lg" style="background:var(--bg);border:1px solid var(--border)"><div class="text-sm text-gray-500 mb-1">${bn?'মোট প্রশিক্ষণ':'Total Trainings'}</div><div class="text-2xl font-bold" style="color:var(--primary)">${trainings.length}</div></div>
            <div class="p-4 rounded-lg" style="background:var(--bg);border:1px solid var(--border)"><div class="text-sm text-gray-500 mb-1">${bn?'মোট প্রশিক্ষণার্থী':'Total Trainees'}</div><div class="text-2xl font-bold" style="color:var(--accent)">${trainees.length}</div></div>
        </div>
        <div class="mb-4">
            <label class="block text-sm font-medium mb-2">${bn?'রিপোর্টের ধরন নির্বাচন করুন':'Select Report Type'}</label>
            <select class="w-full max-w-md"><option>${bn?'প্রশিক্ষণ সারাংশ':'Training Summary'}</option><option>${bn?'প্রশিক্ষণার্থী তালিকা':'Trainee List'}</option><option>${bn?'আর্থিক রিপোর্ট':'Financial Report'}</option><option>${bn?'সুবিধার ব্যবহার':'Facility Usage'}</option></select>
        </div>
        <div class="flex gap-3">
            <button class="btn-primary" onclick="showToast('${bn?'রিপোর্ট তৈরি হচ্ছে...':'Generating report...'}', 'info')"><i class="fas fa-file-alt mr-2"></i>${t('reports_generate')}</button>
            <button class="btn-outline" onclick="showToast('${bn?'PDF ডাউনলোড হচ্ছে...':'Downloading PDF...'}', 'info')"><i class="fas fa-file-pdf mr-2"></i>${t('reports_export_pdf')}</button>
            <button class="btn-outline" onclick="showToast('${bn?'Excel ডাউনলোড হচ্ছে...':'Downloading Excel...'}', 'info')"><i class="fas fa-file-excel mr-2"></i>${t('reports_export_excel')}</button>
        </div>
        <div class="mt-6 pt-6" style="border-top:1px solid var(--border)">
            <h4 class="font-semibold text-sm mb-3">${bn?'দ্রুত পরিসংখ্যান':'Quick Statistics'}</h4>
            <div class="overflow-x-auto">
                <table class="admin-table">
                    <thead><tr><th>${bn?'বিভাগ':'Category'}</th><th>${bn?'মোট':'Total'}</th><th>${bn?'সক্রিয়':'Active'}</th><th>${bn?'সম্পন্ন':'Completed'}</th></tr></thead>
                    <tbody>
                        <tr><td>${bn?'প্রশিক্ষণ':'Trainings'}</td><td class="font-medium">${trainings.length}</td><td class="text-green-600">${trainings.filter(t=>t.status==='ongoing').length}</td><td class="text-gray-500">${trainings.filter(t=>t.status==='completed').length}</td></tr>
                        <tr><td>${bn?'পরীক্ষা':'Tests'}</td><td class="font-medium">${testings.length}</td><td class="text-green-600">${testings.length}</td><td class="text-gray-500">-</td></tr>
                        <tr><td>${bn?'প্রশিক্ষণার্থী':'Trainees'}</td><td class="font-medium">${trainees.length}</td><td class="text-green-600">${trainees.filter(t=>t.status==='active'||t.status==='enrolled').length}</td><td class="text-gray-500">${trainees.filter(t=>t.status==='completed').length}</td></tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>`;
}

// =============================================
// IMAGE PREVIEW HANDLER
// =============================================
function previewAdminImage(input) {
    const file = input.files[0];
    if (!file) return;
    if (!file.type.startsWith('image/')) {
        showToast(currentLang === 'bn' ? 'শুধুমাত্র ছবি ফাইল আপলোড করুন' : 'Please select an image file', 'error');
        input.value = '';
        return;
    }
    if (file.size > 5 * 1024 * 1024) {
        showToast(currentLang === 'bn' ? 'ফাইলের আকার 5MB এর বেশি হতে পারবে না' : 'File size must be less than 5MB', 'error');
        input.value = '';
        return;
    }
    const reader = new FileReader();
    reader.onload = function(e) {
        const base64 = e.target.result;
        const previewBox = document.getElementById('img-preview-box');
        const previewTag = document.getElementById('img-preview-tag');
        const hiddenInput = document.getElementById('af-img');
        if (previewBox && previewTag && hiddenInput) {
            previewBox.classList.remove('hidden');
            previewTag.src = base64;
            hiddenInput.value = base64;
        }
    };
    reader.readAsDataURL(file);
}

// Check if facility type already exists
async function checkFacilityType(type) {
    const warning = document.getElementById('facility-type-warning');
    if (!type || type === '') {
        if (warning) warning.classList.add('hidden');
        return;
    }
    
    // Check in local data
    const exists = facilities.find(f => f.type === type);
    if (exists) {
        if (warning) warning.classList.remove('hidden');
    } else {
        if (warning) warning.classList.add('hidden');
    }
}

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

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

    // FIX: Mock Data BEFORE renderPage() so calendar can see it
    if (typeof trainings === 'undefined' || trainings.length === 0) {
        const today = new Date();
        const y = today.getFullYear();
        const m = String(today.getMonth() + 1).padStart(2, '0');
        const d = String(today.getDate()).padStart(2, '0');
        
        // Events spread across current and next month
        const nextMonth = today.getMonth() + 1;
        const nextMonthYear = nextMonth > 11 ? today.getFullYear() + 1 : today.getFullYear();
        const nextMonthNum = nextMonth > 11 ? 1 : nextMonth + 1;
        const nm = String(nextMonthNum).padStart(2, '0');

        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: 'Concrete testing and QC' },
            { 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: `${y}-${nm}-05`, end: `${y}-${nm}-10`, category: 'Certificate Program', status: 'upcoming', desc: 'PMP certification prep' },
            { id: 5, title: 'Soil Investigation', start: `${y}-${m}-08`, end: `${y}-${m}-12`, category: 'Short Course', status: 'upcoming', desc: 'Soil testing techniques' }
        ];
    }
    // Employees seed data — API তে ডাটা না থাকলেও কাজ করবে
if (typeof employees === 'undefined' || employees.length === 0) {
    employees = [
        {
            id: 1,
            name: 'Md. Shahidul Islam',
            designation: 'Superintending Engineer',
            department: 'Civil Division',
            email: 'shahidul@pwd.gov.bd',
            phone: '+8801711111111',
            img: ''
        },
        {
            id: 2,
            name: 'Md. Rafiqul Hasan',
            designation: 'Executive Engineer',
            department: 'Architecture Division',
            email: 'rafiq@pwd.gov.bd',
            phone: '+8801722222222',
            img: ''
        },
        {
            id: 3,
            name: 'Md. Mizanur Rahman',
            designation: 'Executive Engineer (E/M)',
            department: 'Electrical & Mechanical',
            email: 'mizan@pwd.gov.bd',
            phone: '+8801733333333',
            img: ''
        },
        {
            id: 4,
            name: 'Ms. Nasreen Akhter',
            designation: 'Assistant Engineer',
            department: 'Civil Division',
            email: 'nasreen@pwd.gov.bd',
            phone: '+8801744444444',
            img: ''
        },
        {
            id: 5,
            name: 'Md. Kamal Hossain',
            designation: 'Senior Instructor',
            department: 'Training Section',
            email: 'kamal@pwd.gov.bd',
            phone: '+8801755555555',
            img: ''
        }
    ];
}

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

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

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

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

// ===== START THE APP =====
init();
</script>
</body>
</html>