<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Admin Dashboard - EE Micro LMS</title>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <script src="https://cdn.jsdelivr.net/npm/tinymce@6/tinymce.min.js" referrerpolicy="origin"></script>
  <script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    
    body { 
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; 
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      min-height: 100vh;
    }

    /* Navbar Styling */
    .navbar {
      background: rgba(255,255,255,0.95);
      padding: 15px 0;
      backdrop-filter: blur(10px);
      box-shadow: 0 2px 10px rgba(0,0,0,0.1);
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      z-index: 100;
    }
    
    .navbar-content {
      max-width: 1400px;
      margin: 0 auto;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 20px;
    }
    
    .logo {
      font-size: 1.5em;
      font-weight: bold;
      color: #667eea;
    }
    
    .user-info {
      display: flex;
      align-items: center;
      gap: 15px;
    }
    
    .btn {
      padding: 8px 16px;
      border: none;
      border-radius: 6px;
      text-decoration: none;
      font-size: 14px;
      cursor: pointer;
      transition: all 0.3s;
      display: inline-block;
    }
    
    .btn-primary {
      background: #667eea;
      color: white;
    }
    
    .btn-secondary {
      background: #6c757d;
      color: white;
    }
    
    .btn:hover {
      transform: translateY(-1px);
      box-shadow: 0 2px 5px rgba(0,0,0,0.2);
    }

    /* Main Layout */
    .admin-container {
      display: flex;
      margin-top: 70px;
      min-height: calc(100vh - 70px);
    }

    /* Sidebar Styling */
    .sidebar {
      width: 260px;
      background: rgba(255,255,255,0.1);
      backdrop-filter: blur(10px);
      padding: 20px;
      position: fixed;
      height: calc(100vh - 70px);
      overflow-y: auto;
      border-right: 1px solid rgba(255,255,255,0.2);
    }

    .sidebar h2 {
      color: white;
      font-size: 1.2em;
      margin-bottom: 20px;
      padding-bottom: 10px;
      border-bottom: 2px solid rgba(255,255,255,0.3);
    }

    .sidebar ul {
      list-style: none;
    }

    .sidebar li {
      margin-bottom: 8px;
    }

    .admin-nav {
      display: block;
      padding: 12px 16px;
      color: rgba(255,255,255,0.9);
      text-decoration: none;
      border-radius: 10px;
      transition: all 0.3s;
      cursor: pointer;
    }

    .admin-nav:hover {
      background: rgba(255,255,255,0.2);
      color: white;
    }

    .admin-nav.active {
      background: rgba(255,255,255,0.25);
      color: white;
      font-weight: 600;
    }

    .admin-nav i {
      margin-right: 10px;
      width: 20px;
      text-align: center;
    }

    /* Submenu styles */
    .nav-item-with-submenu {
      position: relative;
    }

    .nav-item-with-submenu > .admin-nav {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .nav-item-with-submenu > .admin-nav .submenu-arrow {
      transition: transform 0.3s;
      font-size: 12px;
    }

    .nav-item-with-submenu.open > .admin-nav .submenu-arrow {
      transform: rotate(180deg);
    }

    .submenu {
      max-height: 0;
      overflow: hidden;
      transition: max-height 0.3s ease-out;
      padding-left: 20px;
    }

    .nav-item-with-submenu.open .submenu {
      max-height: 500px;
    }

    .submenu li {
      margin-bottom: 4px;
    }

    .submenu .admin-nav {
      padding: 10px 16px;
      font-size: 0.95em;
      background: rgba(255,255,255,0.05);
    }

    .submenu .admin-nav:hover {
      background: rgba(255,255,255,0.15);
    }

    .submenu .admin-nav.active {
      background: rgba(255,255,255,0.2);
    }

    /* Content Area */
    .content-area {
      flex: 1;
      margin-left: 260px;
      padding: 30px;
    }

    .section-header {
      background: rgba(255,255,255,0.1);
      padding: 25px;
      border-radius: 15px;
      margin-bottom: 30px;
      backdrop-filter: blur(10px);
    }

    .section-header h1 {
      color: white;
      font-size: 2em;
      margin-bottom: 8px;
    }

    .section-header p {
      color: rgba(255,255,255,0.9);
    }

    /* Cards */
    .card {
      background: rgba(255,255,255,0.95);
      padding: 20px;
      border-radius: 15px;
      box-shadow: 0 5px 15px rgba(0,0,0,0.1);
      backdrop-filter: blur(10px);
      margin-bottom: 20px;
    }

    .card h3 {
      color: #333;
      margin-bottom: 15px;
      font-size: 1.2em;
    }

    /* Form Elements */
    input[type="text"],
    input[type="email"],
    input[type="number"],
    input[type="file"],
    textarea,
    select {
      width: 100%;
      padding: 10px;
      border: 1px solid #ddd;
      border-radius: 8px;
      font-family: inherit;
      margin-bottom: 15px;
    }

    textarea {
      resize: vertical;
      min-height: 100px;
    }

    label {
      display: block;
      margin-bottom: 5px;
      color: #333;
      font-weight: 500;
    }

    /* Table Styling */
    table {
      width: 100%;
      border-collapse: collapse;
      background: white;
      border-radius: 10px;
      overflow: hidden;
    }

    th {
      background: #667eea;
      color: white;
      padding: 12px;
      text-align: left;
    }

    td {
      padding: 12px;
      border-bottom: 1px solid #eee;
    }

    tr:last-child td {
      border-bottom: none;
    }

    /* Switch Toggle */
    .switch { position: relative; display: inline-block; width: 60px; height: 34px; }
    .switch input { opacity: 0; width: 0; height: 0; }
    .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; transition: .4s; border-radius: 34px; }
    .slider:before { position: absolute; content: ""; height: 26px; width: 26px; left: 4px; bottom: 4px; background-color: white; transition: .4s; border-radius: 50%; }
    input:checked + .slider { background-color: #667eea; }
    input:checked + .slider:before { transform: translateX(26px); }

    /* Status Badges */
    .status-badge {
      display: inline-block;
      padding: 5px 12px;
      border-radius: 20px;
      font-size: 12px;
      font-weight: 600;
    }

    .status-active { background: #d1edff; color: #0066cc; }
    .status-admin { background: #ffe6cc; color: #cc6600; }
    .status-online { background: #d1f4e0; color: #00994d; }

    /* Grid Layouts */
    .grid {
      display: grid;
      gap: 20px;
    }

    .grid-2 { grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); }
    .grid-3 { grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); }
    .grid-4 { grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); }

    /* Metric Cards */
    .metric-card {
      background: rgba(255,255,255,0.95);
      padding: 20px;
      border-radius: 15px;
      box-shadow: 0 5px 15px rgba(0,0,0,0.1);
      display: flex;
      align-items: center;
      gap: 15px;
    }

    .metric-icon {
      width: 50px;
      height: 50px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24px;
    }

    .metric-icon.blue { background: #e0e7ff; color: #667eea; }
    .metric-icon.green { background: #d1f4e0; color: #00994d; }
    .metric-icon.yellow { background: #fff3cd; color: #cc9900; }
    .metric-icon.purple { background: #f3e8ff; color: #9333ea; }

    .metric-info h4 {
      color: #666;
      font-size: 0.9em;
      font-weight: 500;
    }

    .metric-info p {
      color: #333;
      font-size: 1.8em;
      font-weight: bold;
      margin-top: 5px;
    }

    /* Toast Notifications */
    .toast {
      position: fixed;
      top: 90px;
      right: 20px;
      z-index: 1000;
      padding: 15px 20px;
      border-radius: 10px;
      color: white;
      font-weight: 500;
      opacity: 0;
      transform: translateX(100%);
      transition: all 0.3s ease;
      box-shadow: 0 5px 15px rgba(0,0,0,0.2);
    }

    .toast.show {
      opacity: 1;
      transform: translateX(0);
    }

    .toast.success { background: linear-gradient(135deg, #10b981, #059669); }
    .toast.error { background: linear-gradient(135deg, #ef4444, #dc2626); }
    .toast.info { background: linear-gradient(135deg, #667eea, #764ba2); }
    .toast.warning { background: linear-gradient(135deg, #f59e0b, #d97706); }

    /* Content Tree */
    .content-tree { border-left: 2px solid rgba(255,255,255,0.3); margin-left: 20px; padding-left: 20px; }
    .course-node { background-color: #eff6ff; border-left: 4px solid #667eea; padding: 10px; margin-bottom: 10px; border-radius: 8px; transition: all 0.2s; }
    .course-node:hover { box-shadow: 0 2px 8px rgba(102, 126, 234, 0.2); }
    .topics-container { border-left: 2px solid #e5e7eb; padding-left: 16px; margin-left: 12px; margin-top: 10px; }
    .topic-node { background-color: #fffbeb; border-left: 4px solid #f59e0b; padding: 8px; margin-bottom: 8px; border-radius: 6px; transition: all 0.2s; }
    .topic-node:hover { box-shadow: 0 2px 6px rgba(245, 158, 11, 0.2); }
    
    /* Drag and Drop */
    .sortable-ghost { opacity: 0.4; background: #f3f4f6; }
    .sortable-drag { opacity: 0.8; cursor: move !important; }
    .cursor-move { cursor: move; }
    .fa-grip-vertical:hover { color: #667eea; }

    /* Modals */
    .modal {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0,0,0,0.5);
      display: none;
      align-items: center;
      justify-content: center;
      z-index: 9999;
    }
    
    .modal.active {
      display: flex;
    }
    
    .modal-content {
      background: white;
      padding: 30px;
      border-radius: 15px;
      max-width: 600px;
      width: 90%;
      max-height: 90vh;
      overflow-y: auto;
      box-shadow: 0 10px 40px rgba(0,0,0,0.3);
    }
    
    .modal-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      padding-bottom: 15px;
      border-bottom: 2px solid #e5e7eb;
    }
    
    .modal-header h2 {
      color: #333;
      font-size: 1.5em;
      margin: 0;
    }
    
    .modal-close {
      background: none;
      border: none;
      font-size: 24px;
      color: #999;
      cursor: pointer;
      padding: 0;
      width: 30px;
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
      transition: all 0.2s;
    }
    
    .modal-close:hover {
      background: #f3f4f6;
      color: #333;
    }
    
    .modal-body {
      margin-bottom: 20px;
    }
    
    .form-group {
      margin-bottom: 20px;
    }
    
    .form-group label {
      display: block;
      margin-bottom: 8px;
      color: #333;
      font-weight: 600;
      font-size: 14px;
    }
    
    .form-group input[type="text"],
    .form-group textarea {
      width: 100%;
      padding: 10px 12px;
      border: 2px solid #e5e7eb;
      border-radius: 8px;
      font-size: 14px;
      transition: border-color 0.2s;
    }
    
    .form-group input[type="text"]:focus,
    .form-group textarea:focus {
      outline: none;
      border-color: #667eea;
    }
    
    .form-group .help-text {
      font-size: 12px;
      color: #6b7280;
      margin-top: 5px;
    }
    
    .checkbox-group {
      max-height: 300px;
      overflow-y: auto;
      border: 2px solid #e5e7eb;
      border-radius: 8px;
      padding: 10px;
    }
    
    .checkbox-item {
      display: flex;
      align-items: center;
      padding: 8px;
      border-radius: 6px;
      transition: background 0.2s;
    }
    
    .checkbox-item:hover {
      background: #f9fafb;
    }
    
    .checkbox-item input[type="checkbox"] {
      margin-right: 10px;
      width: 18px;
      height: 18px;
      cursor: pointer;
    }
    
    .checkbox-item label {
      margin: 0;
      cursor: pointer;
      font-weight: 400;
      font-family: monospace;
      font-size: 13px;
    }
    
    .modal-footer {
      display: flex;
      gap: 10px;
      justify-content: flex-end;
      padding-top: 15px;
      border-top: 2px solid #e5e7eb;
    }
    
    .btn-modal {
      padding: 10px 20px;
      border: none;
      border-radius: 8px;
      font-size: 14px;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.2s;
    }
    
    .btn-modal-primary {
      background: #667eea;
      color: white;
    }
    
    .btn-modal-primary:hover {
      background: #5568d3;
    }
    
    .btn-modal-secondary {
      background: #e5e7eb;
      color: #374151;
    }
    
    .btn-modal-secondary:hover {
      background: #d1d5db;
    }

    /* Old modal styles */
    .modal-old {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.6);
      display: flex;
      align-items: center;
      justify-content: center;
      z-index: 1000;
      backdrop-filter: blur(4px);
    }

    .modal-content {
      background: white;
      border-radius: 15px;
      width: 90%;
      max-height: 90vh;
      overflow-y: auto;
      box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
      animation: modalSlideIn 0.3s ease;
    }

    @keyframes modalSlideIn {
      from {
        transform: translateY(-50px);
        opacity: 0;
      }
      to {
        transform: translateY(0);
        opacity: 1;
      }
    }

    .modal-header {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      padding: 20px 25px;
      border-radius: 15px 15px 0 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .modal-header h2 {
      margin: 0;
      font-size: 1.5em;
    }

    .close-modal {
      background: rgba(255, 255, 255, 0.2);
      border: none;
      color: white;
      font-size: 28px;
      cursor: pointer;
      width: 35px;
      height: 35px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.3s;
    }

    .close-modal:hover {
      background: rgba(255, 255, 255, 0.3);
      transform: rotate(90deg);
    }

    .modal-body {
      padding: 25px;
    }

    /* Form Controls */
    .form-group {
      margin-bottom: 20px;
    }

    .form-group label {
      display: block;
      font-weight: 600;
      color: #374151;
      margin-bottom: 8px;
    }

    .form-control {
      width: 100%;
      padding: 10px 15px;
      border: 2px solid #e5e7eb;
      border-radius: 8px;
      font-size: 14px;
      transition: all 0.3s;
    }

    .form-control:focus {
      outline: none;
      border-color: #667eea;
      box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    }

    .grid {
      display: grid;
      gap: 20px;
    }

    .grid-cols-2 {
      grid-template-columns: repeat(2, 1fr);
    }

    .gap-4 {
      gap: 16px;
    }

    /* Icon Buttons */
    .icon-btn {
      background: #667eea;
      color: white;
      border: none;
      padding: 8px 12px;
      border-radius: 6px;
      cursor: pointer;
      transition: all 0.3s;
      font-size: 14px;
    }

    .icon-btn:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
    }

    .icon-btn-danger {
      background: #ef4444;
    }

    .icon-btn-danger:hover {
      box-shadow: 0 4px 12px rgba(239, 68, 68, 0.4);
    }

    /* Button variants */
    .btn-danger {
      background: #ef4444;
      color: white;
    }

    .btn-danger:hover {
      background: #dc2626;
    }

    /* Search Input */
    .search-input {
      padding: 10px 15px;
      border: 2px solid #e5e7eb;
      border-radius: 8px;
      font-size: 14px;
      transition: all 0.3s;
    }

    .search-input:focus {
      outline: none;
      border-color: #667eea;
      box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    }

    /* Table Responsive */
    .table-responsive {
      overflow-x: auto;
    }

    .data-table {
      width: 100%;
      border-collapse: collapse;
    }

    .data-table th {
      background: #f9fafb;
      color: #374151;
      font-weight: 600;
      padding: 12px;
      text-align: left;
      border-bottom: 2px solid #e5e7eb;
    }

    .data-table td {
      padding: 12px;
      border-bottom: 1px solid #f3f4f6;
    }

    .data-table tbody tr:hover {
      background: #f9fafb;
    }

    /* Hidden utility */
    .hidden { display: none !important; }

    /* Visual Builder Styles */
    .block-palette .block-btn {
      width: 100%;
      padding: 15px 10px;
      margin-bottom: 10px;
      background: white;
      border: 2px solid #dee2e6;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.3s;
      font-size: 13px;
      text-align: center;
    }

    .block-palette .block-btn:hover {
      border-color: #667eea;
      background: #f8f9ff;
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
    }

    .block-palette .block-btn span {
      font-size: 24px;
      display: block;
      margin-bottom: 5px;
    }

    .content-block {
      position: relative;
      margin: 15px;
      padding: 20px;
      border: 2px solid #dee2e6;
      border-radius: 8px;
      background: white;
      transition: all 0.3s;
    }

    .content-block:hover {
      border-color: #667eea;
      box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
    }

    .content-block.selected {
      border-color: #667eea;
      background: #f8f9ff;
    }

    .block-controls {
      position: absolute;
      top: 10px;
      right: 10px;
      display: none;
      gap: 5px;
    }

    .content-block:hover .block-controls {
      display: flex;
    }

    .block-control-btn {
      padding: 5px 10px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 12px;
      transition: all 0.2s;
    }

    .block-control-btn.up { background: #3b82f6; color: white; }
    .block-control-btn.down { background: #3b82f6; color: white; }
    .block-control-btn.edit { background: #fbbf24; color: #000; }
    .block-control-btn.delete { background: #ef4444; color: white; }

    .block-control-btn:hover {
      transform: scale(1.1);
    }

    .property-input {
      width: 100%;
      padding: 8px;
      margin-bottom: 15px;
      border: 1px solid #dee2e6;
      border-radius: 4px;
      font-size: 14px;
    }

    .property-label {
      display: block;
      margin-bottom: 5px;
      font-weight: 600;
      font-size: 13px;
      color: #374151;
    }

    .color-picker-wrapper {
      display: flex;
      gap: 10px;
      align-items: center;
    }

    .color-picker-wrapper input[type="color"] {
      width: 60px;
      height: 40px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }

    /* TinyMCE Light Mode Override */
    .tox .tox-edit-area__iframe {
      background-color: #ffffff !important;
    }
    
    .tox-tinymce {
      border: 1px solid #ccc !important;
    }
    
    .tox .tox-editor-header {
      background-color: #f0f0f0 !important;
      border-bottom: 1px solid #ccc !important;
    }
    
    .tox .tox-toolbar,
    .tox .tox-toolbar__overflow,
    .tox .tox-toolbar__primary {
      background-color: #f0f0f0 !important;
    }
    
    .tox .tox-menubar,
    .tox .tox-statusbar {
      background-color: #f0f0f0 !important;
    }
  </style>
</head>
<body>
  <!-- Navbar -->
  <nav class="navbar">
    <div class="navbar-content">
      <div class="logo">🎓 EE Micro LMS - Admin</div>
      <div class="user-info">
        <span>Welcome, <strong>{{ Auth::user()->name }}</strong></span>
        <span class="status-badge status-admin">Admin</span>
        <a href="{{ route('dashboard') }}" class="btn btn-primary">Student Dashboard</a>
        <form method="POST" action="{{ route('logout') }}" style="display: inline;">
          @csrf
          <button type="submit" class="btn btn-secondary">Logout</button>
        </form>
      </div>
    </div>
  </nav>

  <div class="admin-container">
    <!-- Sidebar -->
    <div class="sidebar">
      <h2>📊 Admin Menu</h2>
      <ul>
        <li>
          <a href="#" class="admin-nav active" data-section="dashboard">
            <i class="fas fa-chart-bar"></i>Dashboard
          </a>
        </li>
        <li>
          <a href="#" class="admin-nav" data-section="users">
            <i class="fas fa-users"></i>Users
          </a>
        </li>
        <li>
          <a href="#" class="admin-nav" data-section="courses">
            <i class="fas fa-graduation-cap"></i>Courses
          </a>
        </li>
        <li class="nav-item-with-submenu">
          <a href="#" class="admin-nav" onclick="toggleSubmenu(event, this)">
            <span><i class="fas fa-user-shield"></i>Roles & Permissions</span>
            <i class="fas fa-chevron-down submenu-arrow"></i>
          </a>
          <ul class="submenu">
            <li>
              <a href="#" class="admin-nav" data-section="roles">
                <i class="fas fa-user-tag"></i>Roles
              </a>
            </li>
            <li>
              <a href="#" class="admin-nav" data-section="permissions">
                <i class="fas fa-lock"></i>Permissions
              </a>
            </li>
            <li>
              <a href="#" class="admin-nav" data-section="manage-user-roles">
                <i class="fas fa-user-shield"></i>Manage User Roles
              </a>
            </li>
          </ul>
        </li>
        <li>
          <a href="#" class="admin-nav" data-section="access-code">
            <i class="fas fa-key"></i>Access Codes
          </a>
        </li>
        <li>
          <a href="#" class="admin-nav" data-section="certificates">
            <i class="fas fa-certificate"></i>Certificates
          </a>
        </li>
        <li>
          <a href="#" class="admin-nav" data-section="badges">
            <i class="fas fa-trophy"></i>Badges
          </a>
        </li>
        <li>
          <a href="#" class="admin-nav" data-section="penalties">
            <i class="fas fa-exclamation-triangle"></i>Penalty Cards
          </a>
        </li>
        <li>
          <a href="#" class="admin-nav" data-section="pages">
            <i class="fas fa-file-alt"></i>Custom Pages
          </a>
        </li>
        <li>
          <a href="#" class="admin-nav" data-section="settings">
            <i class="fas fa-cog"></i>Settings
          </a>
        </li>
      </ul>
    </div>

    <!-- Main Content -->
    <div class="content-area" id="admin-app">
      <!-- Admin gate -->
      <div id="admin-gate" class="hidden">
        <div class="bg-white p-8 rounded-lg shadow text-center">
          <i class="fas fa-lock text-4xl text-red-500 mb-4"></i>
          <h2 class="text-2xl font-bold mb-2">Access Restricted</h2>
          <p class="text-gray-600">This dashboard is for administrators only.</p>
          <a href="{{ route('login') }}" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded mt-4 inline-block">
            Go to Login
          </a>
        </div>
      </div>

      <!-- Access Code Section -->
      <div id="access-code-section" class="hidden">
        <div class="section-header">
          <h1>🔑 Access Code Management</h1>
          <p>Control registration access with unique codes</p>
        </div>
        
        <div class="card">
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
            <div>
              <h3 style="margin-bottom: 5px;">🔐 Registration Requirement</h3>
              <p style="font-size: 13px; color: #666; margin: 0;">When ON, users must enter a valid access code to register</p>
            </div>
            <label class="switch">
              <input type="checkbox" id="access-code-toggle">
              <span class="slider"></span>
            </label>
          </div>
        </div>

        <div class="card">
          <h3>✨ Generate Access Codes</h3>
          <form id="generate-code-form" style="display: flex; gap: 15px; align-items: end; margin-bottom: 15px;">
            <div style="flex: 1;">
              <label>Quantity</label>
              <input type="number" id="code-count" min="1" max="100" value="1">
            </div>
            <div style="flex: 1;">
              <label>Type</label>
              <select id="code-type">
                <option value="single">Single-use</option>
                <option value="bulk">Bulk</option>
              </select>
            </div>
            <button type="submit" class="btn btn-primary" style="margin-bottom: 15px;">
              <i class="fas fa-plus"></i> Generate
            </button>
          </form>
          <div id="code-generation-result" style="color: #10b981; font-size: 13px;"></div>
        </div>

        <div class="card">
          <h3>🗑️ Clear Expired Codes</h3>
          <p style="font-size: 13px; color: #666; margin-bottom: 15px;">
            Manually remove ALL expired access codes immediately. The system also clears codes automatically after 7 days of expiration.
          </p>
          <button id="clear-expired-btn" class="btn btn-danger" onclick="clearExpiredAccessCodes()">
            <i class="fas fa-trash-alt"></i> Clear All Expired Codes Now
          </button>
          <div id="clear-result" style="margin-top: 10px; font-size: 13px;"></div>
        </div>

        <div class="card" style="overflow-x: auto;">
          <h3>📋 Active Access Codes</h3>
          <table>
            <thead>
              <tr>
                <th>Code</th>
                <th>Status</th>
                <th>Expires</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody id="access-codes-table">
              <tr>
                <td colspan="4" style="text-align: center; padding: 20px; color: #999;">No codes found</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- Certificates Section -->
      <div id="certificates-section" class="hidden">
        <div class="section-header">
          <h1>🎓 Certificate Template Builder</h1>
          <p>Create and manage certificate templates for courses and lessons</p>
        </div>

        <div style="background: white; padding: 40px; border-radius: 15px; box-shadow: 0 5px 15px rgba(0,0,0,0.1);">
          <iframe 
            src="/admin/certificates-builder" 
            style="width: 100%; height: calc(100vh - 300px); border: none; border-radius: 10px;"
            title="Certificate Template Builder">
          </iframe>
        </div>
      </div>

      <!-- Badges Section -->
      <div id="badges-section" class="hidden">
        <div class="section-header">
          <h1>🏆 Badge Management</h1>
          <p>Manage achievement badges and track student gamification progress</p>
        </div>

        <!-- Badge Statistics -->
        <div class="grid grid-4" style="margin-bottom: 30px;">
          <div class="metric-card">
            <div class="metric-icon purple">
              <i class="fas fa-trophy"></i>
            </div>
            <div class="metric-content">
              <h3 id="total-badges-count">0</h3>
              <p>Total Badges</p>
            </div>
          </div>
          <div class="metric-card">
            <div class="metric-icon blue">
              <i class="fas fa-award"></i>
            </div>
            <div class="metric-content">
              <h3 id="active-badges-count">0</h3>
              <p>Active Badges</p>
            </div>
          </div>
          <div class="metric-card">
            <div class="metric-icon green">
              <i class="fas fa-star"></i>
            </div>
            <div class="metric-content">
              <h3 id="total-points-count">0</h3>
              <p>Total Points</p>
            </div>
          </div>
          <div class="metric-card">
            <div class="metric-icon orange">
              <i class="fas fa-users"></i>
            </div>
            <div class="metric-content">
              <h3 id="badges-earned-count">0</h3>
              <p>Badges Earned</p>
            </div>
          </div>
        </div>

        <!-- Badge Management Tabs -->
        <div style="background: white; padding: 30px; border-radius: 15px; box-shadow: 0 5px 15px rgba(0,0,0,0.1); margin-bottom: 30px;">
          <div style="display: flex; gap: 15px; margin-bottom: 30px; border-bottom: 2px solid #f0f0f0;">
            <button class="badge-tab active" data-tab="all-badges" style="padding: 12px 24px; background: none; border: none; border-bottom: 3px solid #667eea; color: #667eea; font-weight: 600; cursor: pointer;">
              All Badges
            </button>
            <button class="badge-tab" data-tab="create-badge" style="padding: 12px 24px; background: none; border: none; border-bottom: 3px solid transparent; color: #666; cursor: pointer;">
              Create Badge
            </button>
            <button class="badge-tab" data-tab="leaderboard" style="padding: 12px 24px; background: none; border: none; border-bottom: 3px solid transparent; color: #666; cursor: pointer;">
              Leaderboard
            </button>
          </div>

          <!-- All Badges Tab -->
          <div id="all-badges-tab" class="badge-tab-content">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
              <div>
                <h2 style="font-size: 1.5em; color: #333; margin-bottom: 5px;">Badge Library</h2>
                <p style="color: #666;">Manage all achievement badges in your system</p>
              </div>
              <div style="display: flex; gap: 10px;">
                <select id="badge-category-filter" style="padding: 8px 16px; border: 1px solid #ddd; border-radius: 8px; cursor: pointer;">
                  <option value="all">All Categories</option>
                  <option value="course">Course</option>
                  <option value="lesson">Lesson</option>
                  <option value="quiz">Quiz</option>
                  <option value="speed">Speed</option>
                  <option value="special">Special</option>
                  <option value="ee_specific">EE Specific</option>
                </select>
                <select id="badge-status-filter" style="padding: 8px 16px; border: 1px solid #ddd; border-radius: 8px; cursor: pointer;">
                  <option value="all">All Status</option>
                  <option value="active">Active</option>
                  <option value="inactive">Inactive</option>
                </select>
              </div>
            </div>

            <!-- Badges Grid -->
            <div id="badges-grid" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 20px;">
              <!-- Badges will be loaded here -->
            </div>
          </div>

          <!-- Create Badge Tab -->
          <div id="create-badge-tab" class="badge-tab-content hidden">
            <h2 style="font-size: 1.5em; color: #333; margin-bottom: 20px;">Create New Badge</h2>
            
            <form id="create-badge-form" style="max-width: 600px;">
              <div style="margin-bottom: 20px;">
                <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">Badge Name</label>
                <input type="text" id="badge-name" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 8px;">
              </div>

              <div style="margin-bottom: 20px;">
                <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">Description</label>
                <textarea id="badge-description" required rows="3" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 8px;"></textarea>
              </div>

              <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px;">
                <div>
                  <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">Icon (emoji)</label>
                  <input type="text" id="badge-icon" required placeholder="🏆" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 8px;">
                </div>
                <div>
                  <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">Color</label>
                  <input type="color" id="badge-color" value="#667eea" style="width: 100%; padding: 5px; border: 1px solid #ddd; border-radius: 8px; height: 45px;">
                </div>
              </div>

              <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px;">
                <div>
                  <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">Category</label>
                  <select id="badge-category" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 8px;">
                    <option value="">Select Category</option>
                    <option value="course">Course</option>
                    <option value="lesson">Lesson</option>
                    <option value="quiz">Quiz</option>
                    <option value="speed">Speed</option>
                    <option value="special">Special</option>
                    <option value="ee_specific">EE Specific</option>
                  </select>
                </div>
                <div>
                  <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">Points</label>
                  <input type="number" id="badge-points" required min="0" value="10" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 8px;">
                </div>
              </div>

              <div style="margin-bottom: 20px;">
                <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">Criteria Type</label>
                <select id="badge-criteria-type" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 8px;">
                  <option value="">Select Criteria Type</option>
                  <option value="course_completion">Course Completion</option>
                  <option value="course_count">Course Count</option>
                  <option value="quiz_score">Quiz Score</option>
                  <option value="perfect_score">Perfect Score</option>
                  <option value="speed_completion">Speed Completion</option>
                  <option value="streak">Streak</option>
                  <option value="lesson_count">Lesson Count</option>
                </select>
              </div>

              <div id="criteria-value-field" style="margin-bottom: 20px; display: none;">
                <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">Required Value</label>
                <input type="number" id="badge-criteria-value" min="1" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 8px;">
                <small style="color: #666; display: block; margin-top: 5px;">For course_count, quiz_score, lesson_count, etc.</small>
              </div>

              <div style="margin-bottom: 20px;">
                <label style="display: flex; align-items: center; cursor: pointer;">
                  <input type="checkbox" id="badge-active" checked style="margin-right: 10px; width: 20px; height: 20px;">
                  <span style="font-weight: 600; color: #333;">Active (Award to students)</span>
                </label>
              </div>

              <button type="submit" style="width: 100%; padding: 14px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; border-radius: 8px; font-size: 16px; font-weight: 600; cursor: pointer; transition: transform 0.2s;">
                <i class="fas fa-plus-circle" style="margin-right: 8px;"></i>Create Badge
              </button>
            </form>
          </div>

          <!-- Leaderboard Tab -->
          <div id="leaderboard-tab" class="badge-tab-content hidden">
            <h2 style="font-size: 1.5em; color: #333; margin-bottom: 20px;">Student Leaderboard</h2>
            <p style="color: #666; margin-bottom: 30px;">Top students by badge points earned</p>

            <div id="leaderboard-list" style="background: #f8f9fa; border-radius: 12px; padding: 20px;">
              <!-- Leaderboard will be loaded here -->
            </div>
          </div>
        </div>
      </div>

      <!-- Penalties Section -->
      <div id="penalties-section" class="hidden">
        <div class="section-header">
          <h1>⚠️ Penalty Card Management</h1>
          <p>Manage yellow and red card penalties for student inactivity</p>
        </div>

        <!-- Penalty Statistics -->
        <div class="grid grid-4" style="margin-bottom: 30px;">
          <div class="metric-card">
            <div class="metric-icon orange">
              <i class="fas fa-exclamation-triangle"></i>
            </div>
            <div class="metric-content">
              <h3 id="total-penalty-cards">0</h3>
              <p>Total Cards Issued</p>
            </div>
          </div>
          <div class="metric-card">
            <div class="metric-icon yellow" style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);">
              <i class="fas fa-exclamation-circle"></i>
            </div>
            <div class="metric-content">
              <h3 id="yellow-cards-count">0</h3>
              <p>Yellow Cards</p>
            </div>
          </div>
          <div class="metric-card">
            <div class="metric-icon red" style="background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);">
              <i class="fas fa-ban"></i>
            </div>
            <div class="metric-content">
              <h3 id="red-cards-count">0</h3>
              <p>Red Cards</p>
            </div>
          </div>
          <div class="metric-card">
            <div class="metric-icon purple">
              <i class="fas fa-coins"></i>
            </div>
            <div class="metric-content">
              <h3 id="total-points-deducted">0</h3>
              <p>Points Deducted</p>
            </div>
          </div>
        </div>

        <!-- Penalty Management Tabs -->
        <div style="background: white; padding: 30px; border-radius: 15px; box-shadow: 0 5px 15px rgba(0,0,0,0.1); margin-bottom: 30px;">
          <div style="display: flex; gap: 15px; margin-bottom: 30px; border-bottom: 2px solid #f0f0f0;">
            <button class="penalty-tab active" data-penalty-tab="penalty-rules" style="padding: 12px 24px; background: none; border: none; border-bottom: 3px solid #667eea; color: #667eea; font-weight: 600; cursor: pointer;">
              Penalty Rules
            </button>
            <button class="penalty-tab" data-penalty-tab="issued-cards" style="padding: 12px 24px; background: none; border: none; border-bottom: 3px solid transparent; color: #666; cursor: pointer;">
              Issued Cards
            </button>
            <button class="penalty-tab" data-penalty-tab="create-rule" style="padding: 12px 24px; background: none; border: none; border-bottom: 3px solid transparent; color: #666; cursor: pointer;">
              Create Rule
            </button>
            <button class="penalty-tab" data-penalty-tab="penalty-stats" style="padding: 12px 24px; background: none; border: none; border-bottom: 3px solid transparent; color: #666; cursor: pointer;">
              Statistics
            </button>
          </div>

          <!-- Penalty Rules Tab -->
          <div id="penalty-rules-tab" class="penalty-tab-content">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
              <div>
                <h2 style="font-size: 1.5em; color: #333; margin-bottom: 5px;">Penalty Rules</h2>
                <p style="color: #666;">Configure automatic penalty rules and thresholds</p>
              </div>
              <button id="run-penalty-check-btn" onclick="runPenaltyCheck()" style="padding: 10px 20px; background: #667eea; color: white; border: none; border-radius: 8px; cursor: pointer; font-weight: 600;">
                <i class="fas fa-play-circle" style="margin-right: 8px;"></i>Run Check Now
              </button>
            </div>

            <!-- Rules List -->
            <div id="penalty-rules-list" style="display: flex; flex-direction: column; gap: 15px;">
              <!-- Rules will be loaded here -->
            </div>
          </div>

          <!-- Issued Cards Tab -->
          <div id="issued-cards-tab" class="penalty-tab-content hidden">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
              <div>
                <h2 style="font-size: 1.5em; color: #333; margin-bottom: 5px;">Issued Penalty Cards</h2>
                <p style="color: #666;">View and manage all penalty cards issued to students</p>
              </div>
              <div style="display: flex; gap: 10px;">
                <select id="filter-card-type" style="padding: 8px 16px; border: 1px solid #ddd; border-radius: 8px;">
                  <option value="all">All Cards</option>
                  <option value="yellow">Yellow Cards</option>
                  <option value="red">Red Cards</option>
                </select>
                <select id="filter-card-status" style="padding: 8px 16px; border: 1px solid #ddd; border-radius: 8px;">
                  <option value="all">All Status</option>
                  <option value="active">Active Only</option>
                  <option value="revoked">Revoked</option>
                </select>
              </div>
            </div>

            <!-- Cards Table -->
            <div style="overflow-x: auto;">
              <table id="issued-cards-table" style="width: 100%; border-collapse: collapse;">
                <thead>
                  <tr style="background: #f9fafb; border-bottom: 2px solid #e5e7eb;">
                    <th style="padding: 12px; text-align: left; font-weight: 600; color: #374151;">Card</th>
                    <th style="padding: 12px; text-align: left; font-weight: 600; color: #374151;">Student</th>
                    <th style="padding: 12px; text-align: left; font-weight: 600; color: #374151;">Reason</th>
                    <th style="padding: 12px; text-align: left; font-weight: 600; color: #374151;">Points</th>
                    <th style="padding: 12px; text-align: left; font-weight: 600; color: #374151;">Issued</th>
                    <th style="padding: 12px; text-align: left; font-weight: 600; color: #374151;">Status</th>
                    <th style="padding: 12px; text-align: left; font-weight: 600; color: #374151;">Actions</th>
                  </tr>
                </thead>
                <tbody id="issued-cards-tbody">
                  <!-- Cards will be loaded here -->
                </tbody>
              </table>
            </div>
          </div>

          <!-- Create Rule Tab -->
          <div id="create-rule-tab" class="penalty-tab-content hidden">
            <h2 style="font-size: 1.5em; color: #333; margin-bottom: 20px;">Create Penalty Rule</h2>
            
            <form id="create-penalty-rule-form" style="max-width: 700px;">
              <div style="margin-bottom: 20px;">
                <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">Rule Name</label>
                <input type="text" id="penalty-rule-name" required placeholder="e.g., 5-Day Inactivity Yellow Card" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 8px;">
              </div>

              <div style="margin-bottom: 20px;">
                <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">Description</label>
                <textarea id="penalty-rule-description" rows="2" placeholder="Detailed explanation of when this rule applies" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 8px;"></textarea>
              </div>

              <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px;">
                <div>
                  <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">Card Type</label>
                  <select id="penalty-card-type" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 8px;">
                    <option value="">Select Card Type</option>
                    <option value="yellow">⚠️ Yellow Card (Warning)</option>
                    <option value="red">🚫 Red Card (Severe)</option>
                  </select>
                </div>
                <div>
                  <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">Trigger Type</label>
                  <select id="penalty-trigger-type" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 8px;">
                    <option value="">Select Trigger</option>
                    <option value="inactivity_days">Inactivity (Days)</option>
                    <option value="missed_deadline">Missed Deadlines</option>
                    <option value="failed_quiz">Failed Quizzes</option>
                    <option value="custom">Custom Trigger</option>
                  </select>
                </div>
              </div>

              <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px;">
                <div>
                  <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">Threshold Value</label>
                  <input type="number" id="penalty-threshold-value" required min="1" placeholder="e.g., 3 for 3 days" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 8px;">
                  <small style="color: #666; display: block; margin-top: 5px;">Number of days, deadlines, or occurrences</small>
                </div>
                <div>
                  <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">Points to Deduct</label>
                  <input type="number" id="penalty-points-deduction" required min="0" placeholder="e.g., 5" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 8px;">
                  <small style="color: #666; display: block; margin-top: 5px;">Badge points to remove</small>
                </div>
              </div>

              <div style="margin-bottom: 20px; padding: 15px; background: #f0f9ff; border: 1px solid #bae6fd; border-radius: 8px;">
                <h4 style="font-size: 14px; font-weight: 600; color: #0369a1; margin-bottom: 10px;">
                  <i class="fas fa-arrow-up" style="margin-right: 6px;"></i>Escalation Settings (Yellow Card Only)
                </h4>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                  <div>
                    <label style="display: block; margin-bottom: 6px; font-weight: 600; color: #333; font-size: 13px;">Escalation Days</label>
                    <input type="number" id="penalty-escalation-days" min="1" placeholder="e.g., 7" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 6px;">
                    <small style="color: #666; display: block; margin-top: 4px; font-size: 11px;">Days before yellow → red</small>
                  </div>
                  <div>
                    <label style="display: block; margin-bottom: 6px; font-weight: 600; color: #333; font-size: 13px;">Additional Points</label>
                    <input type="number" id="penalty-escalation-points" min="0" placeholder="e.g., 10" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 6px;">
                    <small style="color: #666; display: block; margin-top: 4px; font-size: 11px;">Extra points deducted on escalation</small>
                  </div>
                </div>
              </div>

              <div style="margin-bottom: 20px;">
                <label style="display: flex; align-items: center; cursor: pointer;">
                  <input type="checkbox" id="penalty-rule-active" checked style="margin-right: 10px; width: 20px; height: 20px;">
                  <span style="font-weight: 600; color: #333;">Active (Enable this rule immediately)</span>
                </label>
              </div>

              <button type="submit" style="width: 100%; padding: 14px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; border-radius: 8px; font-size: 16px; font-weight: 600; cursor: pointer; transition: transform 0.2s;">
                <i class="fas fa-plus-circle" style="margin-right: 8px;"></i>Create Penalty Rule
              </button>
            </form>
          </div>

          <!-- Statistics Tab -->
          <div id="penalty-stats-tab" class="penalty-tab-content hidden">
            <h2 style="font-size: 1.5em; color: #333; margin-bottom: 20px;">Penalty System Statistics</h2>
            
            <div id="detailed-penalty-stats" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px;">
              <!-- Detailed stats will be loaded here -->
            </div>

            <div style="margin-top: 30px;">
              <h3 style="font-size: 1.2em; color: #333; margin-bottom: 15px;">Recent Activity</h3>
              <div id="recent-penalty-activity" style="background: #f9fafb; border-radius: 12px; padding: 20px;">
                <!-- Recent activity will be loaded here -->
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Dashboard Section -->
      <div id="dashboard-section">
        <div class="section-header">
          <h1>📊 Dashboard Overview</h1>
          <p>Welcome back! Here's what's happening with your LMS.</p>
        </div>

        <!-- Key Metrics Cards -->
        <div class="grid grid-4" style="margin-bottom: 30px;">
          <div class="metric-card">
            <div class="metric-icon blue">
              <i class="fas fa-users"></i>
            </div>
            <div class="metric-info">
              <h4>Total Users</h4>
              <p id="total-users">0</p>
            </div>
          </div>

          <div class="metric-card">
            <div class="metric-icon green">
              <i class="fas fa-graduation-cap"></i>
            </div>
            <div class="metric-info">
              <h4>Active Courses</h4>
              <p id="active-courses">0</p>
            </div>
          </div>

          <div class="metric-card">
            <div class="metric-icon yellow">
              <i class="fas fa-chart-line"></i>
            </div>
            <div class="metric-info">
              <h4>Completions</h4>
              <p id="completed-users">0</p>
            </div>
          </div>

          <div class="metric-card">
            <div class="metric-icon purple">
              <i class="fas fa-trophy"></i>
            </div>
            <div class="metric-info">
              <h4>Avg. Score</h4>
              <p id="avg-score">0%</p>
            </div>
          </div>
        </div>

        <!-- Charts Row -->
        <div class="grid grid-2" style="margin-bottom: 30px;">
          <!-- User Registration Trend -->
          <div class="card">
            <h3>📈 User Growth</h3>
            <div style="height: 250px;">
              <canvas id="user-growth-chart"></canvas>
            </div>
          </div>

          <!-- Course Completion Rates -->
          <div class="card">
            <h3>🎯 Course Performance</h3>
            <div style="height: 250px;">
              <canvas id="course-performance-chart"></canvas>
            </div>
          </div>
        </div>

        <!-- Recent Activity & Quick Actions -->
        <div class="grid grid-3">
          <!-- Recent Activity -->
          <div class="card">
            <h3>📖 Recent Activity</h3>
            <div id="recent-activity">
              <div style="display: flex; align-items: center; margin-bottom: 12px; color: #666;">
                <i class="fas fa-user-plus" style="color: #10b981; margin-right: 12px; width: 20px;"></i>
                <span style="font-size: 14px;">New user registered</span>
              </div>
              <div style="display: flex; align-items: center; margin-bottom: 12px; color: #666;">
                <i class="fas fa-graduation-cap" style="color: #667eea; margin-right: 12px; width: 20px;"></i>
                <span style="font-size: 14px;">Course completed</span>
              </div>
              <div style="display: flex; align-items: center; color: #666;">
                <i class="fas fa-cog" style="color: #f59e0b; margin-right: 12px; width: 20px;"></i>
                <span style="font-size: 14px;">Settings updated</span>
              </div>
            </div>
          </div>

          <!-- Quick Actions -->
          <div class="card">
            <h3>⚡ Quick Actions</h3>
            <div style="display: flex; flex-direction: column; gap: 10px;">
              <button onclick="navigateToSection('courses')" style="width: 100%; text-align: left; padding: 12px; background: rgba(102, 126, 234, 0.1); border: 1px solid rgba(102, 126, 234, 0.3); border-radius: 8px; cursor: pointer; display: flex; align-items: center; transition: all 0.3s;">
                <i class="fas fa-plus-circle" style="color: #667eea; margin-right: 10px;"></i>
                <span style="font-size: 14px; font-weight: 500;">Create New Course</span>
              </button>
              <button onclick="navigateToSection('users')" style="width: 100%; text-align: left; padding: 12px; background: rgba(16, 185, 129, 0.1); border: 1px solid rgba(16, 185, 129, 0.3); border-radius: 8px; cursor: pointer; display: flex; align-items: center; transition: all 0.3s;">
                <i class="fas fa-user-plus" style="color: #10b981; margin-right: 10px;"></i>
                <span style="font-size: 14px; font-weight: 500;">View All Users</span>
              </button>
              <button onclick="navigateToSection('settings')" style="width: 100%; text-align: left; padding: 12px; background: rgba(245, 158, 11, 0.1); border: 1px solid rgba(245, 158, 11, 0.3); border-radius: 8px; cursor: pointer; display: flex; align-items: center; transition: all 0.3s;">
                <i class="fas fa-cog" style="color: #f59e0b; margin-right: 10px;"></i>
                <span style="font-size: 14px; font-weight: 500;">System Settings</span>
              </button>
            </div>
          </div>

          <!-- System Status -->
          <div class="card">
            <h3>🔧 System Status</h3>
            <div style="display: flex; flex-direction: column; gap: 12px;">
              <div style="display: flex; justify-content: space-between; align-items: center;">
                <span style="font-size: 14px; color: #666;">Database</span>
                <span class="status-badge status-online">Online</span>
              </div>
              <div style="display: flex; justify-content: space-between; align-items: center;">
                <span style="font-size: 14px; color: #666;">File Storage</span>
                <span class="status-badge status-online">Online</span>
              </div>
              <div style="display: flex; justify-content: space-between; align-items: center;">
                <span style="font-size: 14px; color: #666;">Email Service</span>
                <span style="background: #fff3cd; color: #cc9900; padding: 4px 10px; border-radius: 12px; font-size: 11px; font-weight: 600;">Maintenance</span>
              </div>
              <div style="display: flex; justify-content: space-between; align-items: center;">
                <span style="font-size: 14px; color: #666;">Last Backup</span>
                <span style="font-size: 12px; color: #999;">2 hours ago</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Roles Section -->
      <div id="roles-section" class="hidden">
        <div class="section-header">
          <h1>🏷️ Role Management</h1>
          <p>Create and manage user roles</p>
        </div>
        
        <div class="card">
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h3>All Roles</h3>
            <button onclick="showCreateRoleModal()" class="btn btn-primary">
              <i class="fas fa-plus"></i> Create Role
            </button>
          </div>
          
          <div style="overflow-x: auto;">
            <table>
              <thead>
                <tr>
                  <th>Role Name</th>
                  <th>Guard</th>
                  <th>Permissions Count</th>
                  <th>Users Count</th>
                  <th>Created</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody id="roles-table-body">
                <tr>
                  <td colspan="6" style="text-align: center; padding: 20px; color: #999;">
                    <i class="fas fa-spinner fa-spin"></i> Loading roles...
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- Permissions Section -->
      <div id="permissions-section" class="hidden">
        <div class="section-header">
          <h1>🔐 Permission Management</h1>
          <p>Manage system permissions and assign them to roles</p>
        </div>
        
        <div class="card">
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h3>All Permissions</h3>
            <button onclick="showCreatePermissionModal()" class="btn btn-primary">
              <i class="fas fa-plus"></i> Create Permission
            </button>
          </div>
          
          <div style="overflow-x: auto;">
            <table>
              <thead>
                <tr>
                  <th>Permission Name</th>
                  <th>Guard</th>
                  <th>Assigned to Roles</th>
                  <th>Created</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody id="permissions-table-body">
                <tr>
                  <td colspan="5" style="text-align: center; padding: 20px; color: #999;">
                    <i class="fas fa-spinner fa-spin"></i> Loading permissions...
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

  <!-- Manage User Roles Section -->
  <div id="manage-user-roles-section" class="hidden">
        <div class="section-header">
          <h1>🛡️ Manage User Roles</h1>
          <p>Upgrade or downgrade users to Admin, Tutor, or User roles</p>
        </div>
        <div class="card" style="overflow-x: auto;">
          <table>
            <thead>
              <tr>
                <th>Name</th>
                <th>Email</th>
                <th>Roles</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody id="manage-user-roles-table-body">
              <tr>
                <td colspan="4" style="text-align: center; padding: 20px; color: #999;">
                  <i class="fas fa-spinner fa-spin"></i> Loading users...
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- Custom Pages Section -->
      <div id="pages-section" class="hidden">
        <div class="section-header">
          <h1>📄 Custom Pages Management</h1>
          <p>Create and manage custom pages for your LMS</p>
        </div>

        <div class="card">
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h3 style="margin: 0;">📋 All Pages</h3>
            <button onclick="openPageModal()" class="btn btn-primary">
              <i class="fas fa-plus"></i> Create New Page
            </button>
          </div>

          <div id="pages-table-container">
            <table style="width: 100%; border-collapse: collapse;">
              <thead>
                <tr style="background: #f8f9fa; border-bottom: 2px solid #dee2e6;">
                  <th style="padding: 12px; text-align: left;">Title</th>
                  <th style="padding: 12px; text-align: left;">Slug</th>
                  <th style="padding: 12px; text-align: center;">Status</th>
                  <th style="padding: 12px; text-align: left;">Created</th>
                  <th style="padding: 12px; text-align: left;">Author</th>
                  <th style="padding: 12px; text-align: center;">Actions</th>
                </tr>
              </thead>
              <tbody id="pages-table-body">
                <tr>
                  <td colspan="6" style="padding: 20px; text-align: center; color: #6c757d;">
                    <i class="fas fa-spinner fa-spin"></i> Loading pages...
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- Settings Section -->
      <div id="settings-section" class="hidden">
        <div class="section-header">
          <h1>⚙️ Site Settings</h1>
          <p>Configure your site branding, theme, SEO, and more</p>
        </div>

        <!-- Tabs Navigation -->
        <div style="display: flex; gap: 10px; margin-bottom: 20px; border-bottom: 2px solid rgba(255,255,255,0.2); padding-bottom: 10px; flex-wrap: wrap;">
          <button class="settings-tab-btn active" data-tab="general-settings-tab" style="background: rgba(255,255,255,0.2); color: white; border: none; padding: 10px 20px; border-radius: 6px 6px 0 0; cursor: pointer; font-weight: 600; transition: all 0.3s;">
            <i class="fas fa-cog"></i> General
          </button>
          <button class="settings-tab-btn" data-tab="branding-settings-tab" style="background: transparent; color: rgba(255,255,255,0.7); border: none; padding: 10px 20px; border-radius: 6px 6px 0 0; cursor: pointer; font-weight: 600; transition: all 0.3s;">
            <i class="fas fa-palette"></i> Branding
          </button>
          <button class="settings-tab-btn" data-tab="theme-settings-tab" style="background: transparent; color: rgba(255,255,255,0.7); border: none; padding: 10px 20px; border-radius: 6px 6px 0 0; cursor: pointer; font-weight: 600; transition: all 0.3s;">
            <i class="fas fa-paint-brush"></i> Theme
          </button>
          <button class="settings-tab-btn" data-tab="seo-settings-tab" style="background: transparent; color: rgba(255,255,255,0.7); border: none; padding: 10px 20px; border-radius: 6px 6px 0 0; cursor: pointer; font-weight: 600; transition: all 0.3s;">
            <i class="fas fa-search"></i> SEO
          </button>
          <button class="settings-tab-btn" data-tab="social-settings-tab" style="background: transparent; color: rgba(255,255,255,0.7); border: none; padding: 10px 20px; border-radius: 6px 6px 0 0; cursor: pointer; font-weight: 600; transition: all 0.3s;">
            <i class="fas fa-share-alt"></i> Social
          </button>
          <button class="settings-tab-btn" data-tab="notifications-settings-tab" style="background: transparent; color: rgba(255,255,255,0.7); border: none; padding: 10px 20px; border-radius: 6px 6px 0 0; cursor: pointer; font-weight: 600; transition: all 0.3s;">
            <i class="fas fa-bell"></i> Notifications
          </button>
        </div>

        <!-- General Settings Tab -->
        <div id="general-settings-tab" class="settings-tab-content">
          <div class="card">
            <h3>🏢 General Information</h3>
            <div class="grid grid-cols-1 gap-6">
              <div>
                <label class="block text-gray-700 mb-2 font-semibold">Site Name *</label>
                <input type="text" id="site_name" class="w-full p-3 border rounded" placeholder="EE Micro LMS">
                <p class="text-xs text-gray-500 mt-1">The name of your site (appears in header and browser title)</p>
              </div>
              <div>
                <label class="block text-gray-700 mb-2 font-semibold">Site Description / Tagline</label>
                <textarea id="site_description" class="w-full p-3 border rounded" rows="2" placeholder="Learn and Grow with Our Courses"></textarea>
                <p class="text-xs text-gray-500 mt-1">A brief description or slogan for your site</p>
              </div>
              <div>
                <label class="block text-gray-700 mb-2 font-semibold">Copyright Text</label>
                <input type="text" id="copyright_text" class="w-full p-3 border rounded" placeholder="EE Micro LMS. All rights reserved.">
                <p class="text-xs text-gray-500 mt-1">Footer copyright text (current year will be added automatically)</p>
                <p class="text-xs text-blue-600 mt-1"><i class="fas fa-info-circle"></i> Example: © 2025 EE Micro LMS. All rights reserved.</p>
              </div>
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label class="block text-gray-700 mb-2 font-semibold">Contact Email</label>
                  <input type="email" id="contact_email" class="w-full p-3 border rounded" placeholder="support@eelms.com">
                  <p class="text-xs text-gray-500 mt-1">Main contact email address</p>
                </div>
                <div>
                  <label class="block text-gray-700 mb-2 font-semibold">Contact Phone</label>
                  <input type="text" id="contact_phone" class="w-full p-3 border rounded" placeholder="+1 (555) 123-4567">
                  <p class="text-xs text-gray-500 mt-1">Contact phone number</p>
                </div>
              </div>
            </div>
            <div style="margin-top: 20px; padding-top: 20px; border-top: 1px solid #e5e7eb;">
              <button onclick="saveSettings('general')" class="btn btn-primary">
                <i class="fas fa-save"></i> Save General Settings
              </button>
            </div>
          </div>
        </div>

        <!-- Branding Settings Tab -->
        <div id="branding-settings-tab" class="settings-tab-content hidden">
          <div class="card">
            <h3>🎨 Branding & Logos</h3>
            <div class="grid grid-cols-1 gap-6">
              <div>
                <label class="block text-gray-700 mb-2 font-semibold">Site Logo</label>
                <div style="display: flex; align-items: center; gap: 15px;">
                  <img id="logo_preview" src="" alt="Logo" style="max-width: 200px; max-height: 80px; border: 2px solid #e5e7eb; border-radius: 8px; padding: 10px; background: white; display: none;">
                  <div>
                    <input type="file" id="logo_upload" accept="image/*" style="display: none;" onchange="handleImageUpload('logo_path', this)">
                    <button onclick="document.getElementById('logo_upload').click()" class="btn btn-secondary">
                      <i class="fas fa-upload"></i> Upload Logo
                    </button>
                    <p class="text-xs text-gray-500 mt-2">Recommended: PNG with transparent background, max 200x80px</p>
                  </div>
                </div>
                <input type="hidden" id="logo_path">
              </div>
              <div>
                <label class="block text-gray-700 mb-2 font-semibold">Favicon</label>
                <div style="display: flex; align-items: center; gap: 15px;">
                  <img id="favicon_preview" src="" alt="Favicon" style="width: 32px; height: 32px; border: 2px solid #e5e7eb; border-radius: 4px; background: white; display: none;">
                  <div>
                    <input type="file" id="favicon_upload" accept="image/x-icon,image/png,image/svg+xml" style="display: none;" onchange="handleImageUpload('favicon_path', this)">
                    <button onclick="document.getElementById('favicon_upload').click()" class="btn btn-secondary">
                      <i class="fas fa-upload"></i> Upload Favicon
                    </button>
                    <p class="text-xs text-gray-500 mt-2">Recommended: .ico or .png, 32x32 or 64x64px</p>
                  </div>
                </div>
                <input type="hidden" id="favicon_path">
              </div>
              <div>
                <label class="block text-gray-700 mb-2 font-semibold">Dark Mode Logo (Optional)</label>
                <div style="display: flex; align-items: center; gap: 15px;">
                  <img id="logo_dark_preview" src="" alt="Dark Logo" style="max-width: 200px; max-height: 80px; border: 2px solid #e5e7eb; border-radius: 8px; padding: 10px; background: #1f2937; display: none;">
                  <div>
                    <input type="file" id="logo_dark_upload" accept="image/*" style="display: none;" onchange="handleImageUpload('logo_dark_path', this)">
                    <button onclick="document.getElementById('logo_dark_upload').click()" class="btn btn-secondary">
                      <i class="fas fa-upload"></i> Upload Dark Logo
                    </button>
                    <p class="text-xs text-gray-500 mt-2">Logo variant for dark backgrounds</p>
                  </div>
                </div>
                <input type="hidden" id="logo_dark_path">
              </div>
            </div>
            <div style="margin-top: 20px; padding-top: 20px; border-top: 1px solid #e5e7eb;">
              <button onclick="saveSettings('branding')" class="btn btn-primary">
                <i class="fas fa-save"></i> Save Branding Settings
              </button>
            </div>
          </div>
        </div>

        <!-- Theme Settings Tab -->
        <div id="theme-settings-tab" class="settings-tab-content hidden">
          <div class="card">
            <h3>🎨 Color Scheme</h3>
            <p class="text-sm text-gray-600 mb-4">Customize your site's color palette. Changes will apply across the entire site.</p>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label class="block text-gray-700 mb-2 font-semibold">Primary Color</label>
                <div style="display: flex; gap: 10px; align-items: center;">
                  <input type="color" id="primary_color" class="w-20 h-12 border rounded cursor-pointer" value="#667eea">
                  <input type="text" id="primary_color_hex" class="flex-1 p-3 border rounded font-mono" value="#667eea" onchange="document.getElementById('primary_color').value = this.value">
                </div>
                <p class="text-xs text-gray-500 mt-1">Main brand color (buttons, links, accents)</p>
                <div style="margin-top: 8px; padding: 15px; border-radius: 6px; background: var(--primary-color, #667eea); color: white; text-align: center; font-weight: 600;">
                  Preview: Button Example
                </div>
              </div>
              <div>
                <label class="block text-gray-700 mb-2 font-semibold">Secondary Color</label>
                <div style="display: flex; gap: 10px; align-items: center;">
                  <input type="color" id="secondary_color" class="w-20 h-12 border rounded cursor-pointer" value="#764ba2">
                  <input type="text" id="secondary_color_hex" class="flex-1 p-3 border rounded font-mono" value="#764ba2" onchange="document.getElementById('secondary_color').value = this.value">
                </div>
                <p class="text-xs text-gray-500 mt-1">Secondary brand color (gradients, highlights)</p>
                <div style="margin-top: 8px; padding: 15px; border-radius: 6px; background: var(--secondary-color, #764ba2); color: white; text-align: center; font-weight: 600;">
                  Preview: Accent Example
                </div>
              </div>
              <div>
                <label class="block text-gray-700 mb-2 font-semibold">Success Color</label>
                <div style="display: flex; gap: 10px; align-items: center;">
                  <input type="color" id="success_color" class="w-20 h-12 border rounded cursor-pointer" value="#10b981">
                  <input type="text" id="success_color_hex" class="flex-1 p-3 border rounded font-mono" value="#10b981" onchange="document.getElementById('success_color').value = this.value">
                </div>
                <p class="text-xs text-gray-500 mt-1">Success state color (green)</p>
              </div>
              <div>
                <label class="block text-gray-700 mb-2 font-semibold">Danger Color</label>
                <div style="display: flex; gap: 10px; align-items: center;">
                  <input type="color" id="danger_color" class="w-20 h-12 border rounded cursor-pointer" value="#ef4444">
                  <input type="text" id="danger_color_hex" class="flex-1 p-3 border rounded font-mono" value="#ef4444" onchange="document.getElementById('danger_color').value = this.value">
                </div>
                <p class="text-xs text-gray-500 mt-1">Danger/error state color (red)</p>
              </div>
              <div>
                <label class="block text-gray-700 mb-2 font-semibold">Warning Color</label>
                <div style="display: flex; gap: 10px; align-items: center;">
                  <input type="color" id="warning_color" class="w-20 h-12 border rounded cursor-pointer" value="#f59e0b">
                  <input type="text" id="warning_color_hex" class="flex-1 p-3 border rounded font-mono" value="#f59e0b" onchange="document.getElementById('warning_color').value = this.value">
                </div>
                <p class="text-xs text-gray-500 mt-1">Warning state color (orange/yellow)</p>
              </div>
              <div>
                <label class="block text-gray-700 mb-2 font-semibold">Info Color</label>
                <div style="display: flex; gap: 10px; align-items: center;">
                  <input type="color" id="info_color" class="w-20 h-12 border rounded cursor-pointer" value="#3b82f6">
                  <input type="text" id="info_color_hex" class="flex-1 p-3 border rounded font-mono" value="#3b82f6" onchange="document.getElementById('info_color').value = this.value">
                </div>
                <p class="text-xs text-gray-500 mt-1">Info state color (blue)</p>
              </div>
            </div>
            <div style="margin-top: 20px; padding-top: 20px; border-top: 1px solid #e5e7eb; display: flex; gap: 10px;">
              <button onclick="saveSettings('theme')" class="btn btn-primary">
                <i class="fas fa-save"></i> Save Theme Settings
              </button>
              <button onclick="resetThemeColors()" class="btn btn-secondary">
                <i class="fas fa-undo"></i> Reset to Default
              </button>
            </div>
          </div>
        </div>

        <!-- SEO Settings Tab -->
        <div id="seo-settings-tab" class="settings-tab-content hidden">
          <div class="card">
            <h3>🔍 SEO & Meta Tags</h3>
            <p class="text-sm text-gray-600 mb-4">Optimize your site for search engines and social media sharing.</p>
            <div class="grid grid-cols-1 gap-6">
              <div>
                <label class="block text-gray-700 mb-2 font-semibold">Meta Title</label>
                <input type="text" id="meta_title" class="w-full p-3 border rounded" placeholder="EE Micro LMS - Online Learning Platform" maxlength="60">
                <p class="text-xs text-gray-500 mt-1">Default page title for SEO (max 60 characters)</p>
              </div>
              <div>
                <label class="block text-gray-700 mb-2 font-semibold">Meta Description</label>
                <textarea id="meta_description" class="w-full p-3 border rounded" rows="3" placeholder="Join thousands of learners..." maxlength="160"></textarea>
                <p class="text-xs text-gray-500 mt-1">Default meta description for search engines (155-160 characters recommended)</p>
              </div>
              <div>
                <label class="block text-gray-700 mb-2 font-semibold">Meta Keywords</label>
                <textarea id="meta_keywords" class="w-full p-3 border rounded" rows="2" placeholder="online learning, courses, education, LMS"></textarea>
                <p class="text-xs text-gray-500 mt-1">Comma-separated keywords for SEO</p>
              </div>
              <div>
                <label class="block text-gray-700 mb-2 font-semibold">Open Graph Image</label>
                <div style="display: flex; align-items: center; gap: 15px;">
                  <img id="og_image_preview" src="" alt="OG Image" style="max-width: 300px; max-height: 150px; border: 2px solid #e5e7eb; border-radius: 8px; display: none;">
                  <div>
                    <input type="file" id="og_image_upload" accept="image/*" style="display: none;" onchange="handleImageUpload('og_image', this)">
                    <button onclick="document.getElementById('og_image_upload').click()" class="btn btn-secondary">
                      <i class="fas fa-upload"></i> Upload OG Image
                    </button>
                    <p class="text-xs text-gray-500 mt-2">Image for social media sharing (1200x630px recommended)</p>
                  </div>
                </div>
                <input type="hidden" id="og_image">
              </div>
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label class="block text-gray-700 mb-2 font-semibold">Google Analytics ID</label>
                  <input type="text" id="google_analytics_id" class="w-full p-3 border rounded" placeholder="UA-XXXXXXXXX-X or G-XXXXXXXXXX">
                  <p class="text-xs text-gray-500 mt-1">Google Analytics tracking ID</p>
                </div>
                <div>
                  <label class="block text-gray-700 mb-2 font-semibold">Google Site Verification</label>
                  <input type="text" id="google_site_verification" class="w-full p-3 border rounded" placeholder="verification code">
                  <p class="text-xs text-gray-500 mt-1">Google Search Console verification</p>
                </div>
              </div>
            </div>
            <div style="margin-top: 20px; padding-top: 20px; border-top: 1px solid #e5e7eb;">
              <button onclick="saveSettings('seo')" class="btn btn-primary">
                <i class="fas fa-save"></i> Save SEO Settings
              </button>
            </div>
          </div>
        </div>

        <!-- Social Settings Tab -->
        <div id="social-settings-tab" class="settings-tab-content hidden">
          <div class="card">
            <h3>🌐 Social Media Links</h3>
            <p class="text-sm text-gray-600 mb-4">Add your social media profiles to display in the footer.</p>
            <div class="grid grid-cols-1 gap-6">
              <div>
                <label class="block text-gray-700 mb-2 font-semibold"><i class="fab fa-facebook" style="color: #1877f2;"></i> Facebook URL</label>
                <input type="url" id="facebook_url" class="w-full p-3 border rounded" placeholder="https://facebook.com/yourpage">
              </div>
              <div>
                <label class="block text-gray-700 mb-2 font-semibold"><i class="fab fa-twitter" style="color: #1da1f2;"></i> Twitter / X URL</label>
                <input type="url" id="twitter_url" class="w-full p-3 border rounded" placeholder="https://twitter.com/yourprofile">
              </div>
              <div>
                <label class="block text-gray-700 mb-2 font-semibold"><i class="fab fa-linkedin" style="color: #0a66c2;"></i> LinkedIn URL</label>
                <input type="url" id="linkedin_url" class="w-full p-3 border rounded" placeholder="https://linkedin.com/company/yourcompany">
              </div>
              <div>
                <label class="block text-gray-700 mb-2 font-semibold"><i class="fab fa-instagram" style="color: #e4405f;"></i> Instagram URL</label>
                <input type="url" id="instagram_url" class="w-full p-3 border rounded" placeholder="https://instagram.com/yourprofile">
              </div>
              <div>
                <label class="block text-gray-700 mb-2 font-semibold"><i class="fab fa-youtube" style="color: #ff0000;"></i> YouTube URL</label>
                <input type="url" id="youtube_url" class="w-full p-3 border rounded" placeholder="https://youtube.com/c/yourchannel">
              </div>
            </div>
            <div style="margin-top: 20px; padding-top: 20px; border-top: 1px solid #e5e7eb;">
              <button onclick="saveSettings('social')" class="btn btn-primary">
                <i class="fas fa-save"></i> Save Social Links
              </button>
            </div>
          </div>
        </div>

        <!-- Notifications Settings Tab -->
        <div id="notifications-settings-tab" class="settings-tab-content hidden">
          <iframe src="{{ route('admin.settings.notifications') }}" style="width: 100%; height: calc(100vh - 200px); border: none; border-radius: 8px;"></iframe>
        </div>
      </div>

      <!-- Users Section -->
      <div id="users-section" class="hidden">
        <div class="section-header" style="display: flex; justify-content: space-between; align-items: center;">
          <div>
            <h1>👥 User Management</h1>
            <p>View and manage all registered users</p>
          </div>
          <button id="refresh-users" class="btn btn-primary">
            <i class="fas fa-sync"></i> Refresh
          </button>
        </div>
        <div class="card" style="overflow-x: auto;">
          <table>
            <thead>
              <tr>
                <th>User</th>
                <th>Roles</th>
                <th>Progress</th>
                <th>Quiz Score</th>
                <th>Last Activity</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody id="users-table-body">
              <tr>
                <td colspan="6" style="text-align: center; padding: 20px; color: #999;">
                  <i class="fas fa-spinner fa-spin"></i> Loading users...
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- Courses Section -->
      <div id="courses-section" class="hidden">
        <div class="section-header">
          <h1>📚 Course Management</h1>
          <p>Create and manage learning courses, lessons, and topics</p>
        </div>

        <!-- Tabs Navigation -->
        <div style="display: flex; gap: 10px; margin-bottom: 20px; border-bottom: 2px solid rgba(255,255,255,0.2); padding-bottom: 10px;">
          <button class="tab-btn active" data-tab="courses-list" style="background: rgba(255,255,255,0.2); color: white; border: none; padding: 10px 20px; border-radius: 6px 6px 0 0; cursor: pointer; font-weight: 600; transition: all 0.3s;">
            <i class="fas fa-graduation-cap"></i> All Courses
          </button>
          <button class="tab-btn" data-tab="lessons-topics" style="background: transparent; color: rgba(255,255,255,0.7); border: none; padding: 10px 20px; border-radius: 6px 6px 0 0; cursor: pointer; font-weight: 600; transition: all 0.3s;">
            <i class="fas fa-book-open"></i> Lessons & Topics
          </button>
        </div>

        <!-- Tab Content: All Courses -->
        <div id="courses-list-tab" class="tab-content">
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h3 style="color: white; margin: 0;">📚 All Courses</h3>
            <button id="add-course-btn" class="btn btn-primary">
              <i class="fas fa-plus"></i> Add New Course
            </button>
          </div>

          <!-- Courses Table -->
          <div class="card">
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h3>📚 All Courses</h3>
            <input type="text" id="course-search" class="search-input" placeholder="🔍 Search courses..." style="width: 300px; margin-bottom: 0;">
          </div>
          
          <div class="table-responsive">
            <table class="data-table">
              <thead>
                <tr>
                  <th style="width: 30%;">Course Name</th>
                  <th style="width: 15%;">Status</th>
                  <th style="width: 15%;">Lessons</th>
                  <th style="width: 15%;">Enrolled</th>
                  <th style="width: 10%;">Completion</th>
                  <th style="width: 15%;">Actions</th>
                </tr>
              </thead>
              <tbody id="courses-table-body">
                <tr>
                  <td colspan="6" style="text-align: center; padding: 40px;">
                    <i class="fas fa-spinner fa-spin" style="font-size: 24px; color: #667eea;"></i>
                    <p style="margin-top: 10px; color: #999;">Loading courses...</p>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        </div>

        <!-- Tab Content: Lessons & Topics -->
        <div id="lessons-topics-tab" class="tab-content hidden">
          <!-- Header Section -->
          <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 25px; border-radius: 15px; margin-bottom: 25px; box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);">
            <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 15px;">
              <div>
                <h2 style="color: white; margin: 0 0 8px 0; font-size: 28px; display: flex; align-items: center; gap: 10px;">
                  <i class="fas fa-graduation-cap"></i> Course Management
                </h2>
                <p style="color: rgba(255,255,255,0.9); margin: 0; font-size: 15px;">
                  Create and organize courses, lessons, topics, and quiz questions
                </p>
              </div>
              <div style="display: flex; gap: 10px; align-items: center;">
                <select id="content-course-filter" style="padding: 10px 15px; border: 2px solid rgba(255,255,255,0.3); background: rgba(255,255,255,0.95); border-radius: 8px; font-size: 14px; min-width: 280px; cursor: pointer;">
                  <option value="">📚 Select Course to Manage</option>
                </select>
                <button id="add-lesson-btn" class="btn" disabled style="background: rgba(255,255,255,0.2); color: white; border: 2px solid rgba(255,255,255,0.3); padding: 10px 20px; border-radius: 8px; font-weight: 600; cursor: not-allowed; transition: all 0.3s;">
                  <i class="fas fa-plus-circle"></i> Add Lesson
                </button>
              </div>
            </div>
          </div>

          <!-- Main Content Area -->
          <div style="display: grid; grid-template-columns: 1fr; gap: 20px;">
            <!-- Course Tree View - Full Width -->
            <div class="card" style="background: white; border-radius: 15px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.08);">
              <div style="display: flex; justify-content: between; align-items: center; margin-bottom: 20px; border-bottom: 2px solid #f3f4f6; padding-bottom: 15px;">
                <h3 style="margin: 0; color: #1f2937; font-size: 20px; display: flex; align-items: center; gap: 10px;">
                  <i class="fas fa-sitemap" style="color: #667eea;"></i> 
                  Course Structure
                </h3>
                <div style="color: #6b7280; font-size: 14px;">
                  <i class="fas fa-info-circle"></i> Drag to reorder lessons and topics
                </div>
              </div>
              <div id="content-tree" class="content-tree" style="min-height: 400px;">
                <div style="text-align: center; padding: 60px 20px; color: #9ca3af;">
                  <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); width: 100px; height: 100px; border-radius: 50%; margin: 0 auto 20px; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);">
                    <i class="fas fa-book-open" style="font-size: 42px; color: white;"></i>
                  </div>
                  <h4 style="color: #4b5563; margin: 0 0 10px 0; font-size: 18px;">No Course Selected</h4>
                  <p style="margin: 0; font-size: 14px; color: #9ca3af;">Select a course from the dropdown above to view and manage its lessons and topics</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Course Modal -->
      <div id="course-modal" class="modal hidden">
        <div class="modal-content" style="max-width: 700px;">
          <div class="modal-header">
            <h2 id="course-modal-title">✨ Add New Course</h2>
            <button class="close-modal" onclick="closeCourseModal()">&times;</button>
          </div>
          <div class="modal-body">
            <form id="course-form">
              <input type="hidden" id="course-id">
              
              <div class="form-group">
                <label>Course Name <span style="color: #ef4444;">*</span></label>
                <input type="text" id="course-name" class="form-control" required placeholder="Enter course name">
              </div>

              <div class="grid grid-cols-2 gap-4">
                <div class="form-group">
                  <label>Slug</label>
                  <input type="text" id="course-slug" class="form-control" placeholder="auto-generated">
                  <small style="color: #6b7280;">URL-friendly identifier (leave empty for auto-generation)</small>
                </div>

                <div class="form-group">
                  <label>Chunk Words</label>
                  <input type="number" id="course-chunk-words" class="form-control" value="800" min="50" max="2000">
                  <small style="color: #6b7280;">Words per content chunk (default: 800)</small>
                </div>

                <!-- Study Time Limits -->
                <div class="form-group">
                  <label style="display: flex; align-items: center; cursor: pointer;">
                    <input type="checkbox" id="course-enable-study-time" style="margin-right: 10px;">
                    <span>⏱️ Enable Daily Study Time Limits</span>
                  </label>
                  <small style="color: #6b7280;">Set minimum and maximum study time per day</small>
                </div>

                <div id="study-time-fields" class="hidden" style="padding-left: 20px; margin-top: 10px;">
                  <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                    <div class="form-group">
                      <label>Min. Minutes Per Day</label>
                      <input type="number" id="course-min-study-minutes" class="form-control" value="15" min="0" max="1440">
                      <small style="color: #6b7280;">Minimum daily goal</small>
                    </div>
                    <div class="form-group">
                      <label>Max. Minutes Per Day</label>
                      <input type="number" id="course-max-study-minutes" class="form-control" value="60" min="0" max="1440">
                      <small style="color: #6b7280;">Maximum allowed per day</small>
                    </div>
                  </div>
                </div>

                <!-- Course Survey -->
                <div class="form-group">
                  <label style="display: flex; align-items: center; cursor: pointer;">
                    <input type="checkbox" id="course-enable-survey" style="margin-right: 10px;">
                    <span>📋 Enable Course Survey/Feedback</span>
                  </label>
                  <small style="color: #6b7280;">Collect feedback from students upon completion</small>
                </div>

                <div id="survey-fields" class="hidden" style="padding-left: 20px; margin-top: 10px;">
                  <div class="form-group">
                    <label>Survey Title</label>
                    <input type="text" id="course-survey-title" class="form-control" placeholder="e.g., Course Feedback">
                  </div>
                  <div class="form-group">
                    <label>Survey Description</label>
                    <textarea id="course-survey-description" class="form-control" rows="2" placeholder="Brief description shown to students"></textarea>
                  </div>
                  <small style="color: #6b7280;">You can add survey questions after creating the course</small>
                </div>
              </div>

              <div class="form-group">
                <label>Short Description</label>
                <textarea id="course-description" class="form-control" rows="3" placeholder="Brief description of the course"></textarea>
              </div>

              <div class="form-group">
                <label style="display: flex; align-items: center; cursor: pointer;">
                  <input type="checkbox" id="course-has-prerequisite" style="margin-right: 10px;">
                  <span>This course requires a prerequisite</span>
                </label>
              </div>

              <div id="prerequisite-select-container" class="form-group hidden">
                <label>Select Prerequisite Course <span style="color: #ef4444;">*</span></label>
                <select id="course-prerequisite" class="form-control">
                  <option value="">-- Select a prerequisite course --</option>
                </select>
                <small style="color: #6b7280;">Users must complete this course before accessing the current one</small>
              </div>

              <div class="form-group">
                <label style="font-weight: 600; margin-bottom: 10px;">Completion Behavior</label>
                <div style="display: flex; gap: 20px; margin-bottom: 15px;">
                  <label style="display: flex; align-items: center; cursor: pointer;">
                    <input type="radio" name="completion-type" value="certificate" id="completion-certificate" style="margin-right: 8px;">
                    <span>📜 Issue Certificate</span>
                  </label>
                  <label style="display: flex; align-items: center; cursor: pointer;">
                    <input type="radio" name="completion-type" value="instructions" id="completion-instructions-radio" style="margin-right: 8px;">
                    <span>📋 Show Instructions</span>
                  </label>
                  <label style="display: flex; align-items: center; cursor: pointer;">
                    <input type="radio" name="completion-type" value="none" id="completion-none" checked style="margin-right: 8px;">
                    <span>❌ None</span>
                  </label>
                </div>
              </div>

              <div id="certificate-template-group" class="form-group hidden">
                <label>Certificate Template (HTML)</label>
                <textarea id="course-certificate" class="form-control" rows="4" placeholder="HTML template for completion certificate. Use @{{user_name}}, @{{completion_date}}, @{{score}} as placeholders."></textarea>
                <small style="color: #6b7280;">Design a certificate that will be generated when users complete the course</small>
              </div>

              <div id="completion-instructions-group" class="form-group hidden">
                <label>Completion Instructions</label>
                <textarea id="course-instructions" class="form-control" rows="4" placeholder="Instructions or next steps shown to users upon course completion"></textarea>
                <small style="color: #6b7280;">Provide guidance on what students should do after completing this course</small>
              </div>

              <div class="form-group">
                <label style="display: flex; align-items: center; cursor: pointer;">
                  <input type="checkbox" id="course-active" style="margin-right: 10px;" checked>
                  <span>Active Course</span>
                </label>
                <small style="color: #6b7280;">Only active courses are visible to users</small>
              </div>

              <div style="display: flex; justify-content: flex-end; gap: 10px; margin-top: 20px;">
                <button type="button" class="btn btn-secondary" onclick="closeCourseModal()">Cancel</button>
                <button type="submit" class="btn btn-primary" id="save-course-btn">
                  <i class="fas fa-save"></i> <span id="save-course-text">Create Course</span>
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>

      <!-- Survey Management Modal -->
      <div id="survey-modal" class="modal hidden">
        <div class="modal-content" style="max-width: 800px; max-height: 90vh; overflow-y: auto;">
          <div class="modal-header">
            <h2 id="survey-modal-title">📋 Manage Course Survey</h2>
            <button class="close-modal" onclick="closeSurveyModal()">&times;</button>
          </div>
          <div class="modal-body">
            <div style="background: #f0f9ff; border-left: 4px solid #3b82f6; padding: 15px; margin-bottom: 20px; border-radius: 4px;">
              <p style="color: #1e40af; font-size: 14px; margin: 0;">
                <i class="fas fa-info-circle"></i> Create survey questions to collect feedback from students when they complete this course.
              </p>
            </div>

            <div id="survey-questions-list" style="margin-bottom: 20px;">
              <!-- Questions will be dynamically added here -->
            </div>

            <button type="button" class="btn btn-secondary" onclick="addSurveyQuestion()" style="width: 100%; margin-bottom: 20px;">
              <i class="fas fa-plus"></i> Add Question
            </button>

            <div style="display: flex; justify-content: flex-end; gap: 10px; padding-top: 20px; border-top: 1px solid #e5e7eb;">
              <button type="button" class="btn btn-secondary" onclick="closeSurveyModal()">Cancel</button>
              <button type="button" class="btn btn-primary" onclick="saveSurveyQuestions()">
                <i class="fas fa-save"></i> Save Survey
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- Delete Confirmation Modal -->
      <div id="delete-course-modal" class="modal hidden">
        <div class="modal-content" style="max-width: 500px;">
          <div class="modal-header" style="background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);">
            <h2>🗑️ Delete Course</h2>
            <button class="close-modal" onclick="closeDeleteCourseModal()">&times;</button>
          </div>
          <div class="modal-body">
            <p style="font-size: 16px; color: #374151; margin-bottom: 15px;">
              Are you sure you want to delete this course?
            </p>
            <div style="background: #fee2e2; border-left: 4px solid #ef4444; padding: 15px; margin-bottom: 20px; border-radius: 4px;">
              <p style="font-weight: 600; color: #991b1b; margin-bottom: 5px;">⚠️ This action cannot be undone!</p>
              <p style="color: #7f1d1d; font-size: 14px;">This will permanently delete:</p>
              <ul style="color: #7f1d1d; font-size: 14px; margin-left: 20px; margin-top: 5px;">
                <li>Course details and settings</li>
                <li>All lessons and topics</li>
                <li>All user progress data</li>
                <li>Quiz questions and results</li>
              </ul>
            </div>
            <div style="background: #f9fafb; padding: 15px; border-radius: 4px; margin-bottom: 20px;">
              <p style="font-weight: 600; color: #374151; margin-bottom: 5px;">Course: <span id="delete-course-name" style="color: #667eea;"></span></p>
              <p style="font-size: 14px; color: #6b7280;">ID: <span id="delete-course-id"></span></p>
            </div>
            <div style="display: flex; justify-content: flex-end; gap: 10px;">
              <button type="button" class="btn btn-secondary" onclick="closeDeleteCourseModal()">Cancel</button>
              <button type="button" class="btn btn-danger" onclick="confirmDeleteCourse()">
                <i class="fas fa-trash"></i> Delete Permanently
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- Lesson Modal -->
      <div id="lessonModal" class="modal hidden">
        <div class="modal-content" style="max-width: 800px; max-height: 90vh; overflow-y: auto;">
          <div class="modal-header">
            <h2 id="lesson-modal-title">Add New Lesson</h2>
            <button class="close-modal" onclick="closeModal('lessonModal')">&times;</button>
          </div>
          <div class="modal-body">
            <form id="lesson-form">
              <input type="hidden" id="lesson-id" name="id">
              <input type="hidden" id="lesson-course-id" name="course_id">
              
              <div class="form-group">
                <label>Lesson Name <span style="color: #ef4444;">*</span></label>
                <input type="text" id="lesson-name" name="name" class="form-control" required placeholder="Enter lesson name">
              </div>

              <div class="form-group">
                <label>Description</label>
                <textarea id="lesson-description" name="intro" class="form-control" rows="4" placeholder="Brief description of the lesson"></textarea>
              </div>

              <!-- Study Material Section -->
              <div class="form-group" style="border: 1px solid #e5e7eb; border-radius: 8px; padding: 15px; background: #f9fafb;">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                  <label style="margin: 0; font-weight: 600;">📎 Attach Study Material</label>
                  <label class="switch">
                    <input type="checkbox" id="lesson-share-enabled" name="share_enabled">
                    <span class="slider round"></span>
                  </label>
                </div>

                <div id="lesson-share-panel" class="hidden" style="margin-top: 15px;">
                  <div class="form-group">
                    <label>Attachment Type</label>
                    <select id="lesson-share-type" name="share_type" class="form-control">
                      <option value="upload">Upload File</option>
                      <option value="link">External Link</option>
                    </select>
                  </div>

                  <div id="lesson-upload-section" class="form-group">
                    <label>Upload File</label>
                    <input type="file" id="lesson-file-upload" class="form-control">
                    <button type="button" id="lesson-upload-btn" class="btn btn-secondary" style="margin-top: 10px;">
                      <i class="fas fa-upload"></i> Upload
                    </button>
                    <input type="hidden" id="lesson-share-url" name="share_url">
                    <input type="hidden" id="lesson-share-filename" name="share_filename">
                    <input type="hidden" id="lesson-share-size" name="share_size">
                    <p id="lesson-upload-status" class="text-sm" style="margin-top: 5px; color: #6b7280;"></p>
                  </div>

                  <div id="lesson-link-section" class="form-group hidden">
                    <label>External URL</label>
                    <input type="url" id="lesson-link-url" class="form-control" placeholder="https://...">
                  </div>
                </div>
              </div>

              <!-- Quiz Section -->
              <div class="form-group" style="border: 1px solid #e5e7eb; border-radius: 8px; padding: 15px; background: #f9fafb;">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                  <label style="margin: 0; font-weight: 600;">📝 Lesson Quiz</label>
                  <label class="switch">
                    <input type="checkbox" id="lesson-has-quiz" name="has_quiz">
                    <span class="slider round"></span>
                  </label>
                </div>
                <p class="text-sm" style="margin-top: 5px; color: #6b7280;">Enable quiz for this lesson (manage questions after saving)</p>
              </div>

              <!-- Certificate Section -->
              <div class="form-group" style="border: 1px solid #e5e7eb; border-radius: 8px; padding: 15px; background: #f9fafb;">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                  <label style="margin: 0; font-weight: 600;">🏆 Lesson Certificate</label>
                  <label class="switch">
                    <input type="checkbox" id="lesson-has-certificate" name="has_certificate">
                    <span class="slider round"></span>
                  </label>
                </div>
                <p class="text-sm" style="margin-top: 5px; color: #6b7280;">Award certificate upon lesson completion</p>
                <div id="lesson-certificate-panel" class="hidden" style="margin-top: 15px;">
                  <div class="form-group">
                    <label>Select Certificate Template</label>
                    <select id="lesson-certificate-id" name="certificate_id" class="form-control">
                      <option value="">No certificate selected</option>
                      <!-- Will be populated dynamically -->
                    </select>
                    <p class="text-sm" style="margin-top: 5px; color: #9ca3af;">Certificate templates will be created in the certificate builder</p>
                  </div>
                </div>
              </div>

              <div style="display: flex; justify-content: flex-end; gap: 10px; margin-top: 20px;">
                <button type="button" class="btn btn-secondary" onclick="closeModal('lessonModal')">Cancel</button>
                <button type="submit" class="btn btn-primary">
                  <i class="fas fa-save"></i> Save Lesson
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>

      <!-- Topic Modal -->
      <div id="topicModal" class="modal hidden">
        <div class="modal-content" style="max-width: 900px; max-height: 90vh; overflow-y: auto;">
          <div class="modal-header">
            <h2 id="topic-modal-title">Add New Topic</h2>
            <button class="close-modal" onclick="closeModal('topicModal')">&times;</button>
          </div>
          <div class="modal-body">
            <form id="topic-form">
              <input type="hidden" id="topic-id" name="topic_id">
              <input type="hidden" id="topic-lesson-id" name="lesson_id">
              
              <div class="form-group">
                <label>Topic Title <span style="color: #ef4444;">*</span></label>
                <input type="text" id="topic-title" name="title" class="form-control" required placeholder="Enter topic title">
              </div>

              <div class="form-group">
                <label>Content</label>
                <textarea id="topic-body" name="body" class="form-control" rows="8" placeholder="Enter topic content..."></textarea>
              </div>

              <!-- Media Section -->
              <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 20px;">
                <div class="form-group">
                  <label>📹 Video URL (optional)</label>
                  <input type="url" id="topic-video-url" name="video_url" class="form-control" placeholder="https://youtube.com/watch?v=...">
                  <p class="text-sm" style="margin-top: 5px; color: #6b7280;">YouTube, Vimeo, or direct video URL</p>
                </div>

                <div class="form-group">
                  <label>🖼️ Image URL (optional)</label>
                  <input type="url" id="topic-image-url" name="image_url" class="form-control" placeholder="https://...">
                  <button type="button" id="topic-image-upload-btn" class="btn btn-secondary" style="margin-top: 5px; width: 100%;">
                    <i class="fas fa-upload"></i> Or Upload Image
                  </button>
                  <input type="file" id="topic-image-file" accept="image/*" class="hidden">
                  <p id="topic-image-status" class="text-sm" style="margin-top: 5px; color: #6b7280;"></p>
                </div>
              </div>

              <!-- Publishing Status -->
              <div class="form-group" style="border: 1px solid #e5e7eb; border-radius: 8px; padding: 15px; background: #f9fafb;">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                  <div>
                    <label style="margin: 0; font-weight: 600;">👁️ Publish Topic</label>
                    <p class="text-sm" style="margin-top: 5px; color: #6b7280;">Make this topic visible to students</p>
                  </div>
                  <label class="switch">
                    <input type="checkbox" id="topic-is-published" name="is_published" checked>
                    <span class="slider round"></span>
                  </label>
                </div>
              </div>

              <div style="display: flex; justify-content: flex-end; gap: 10px; margin-top: 20px;">
                <button type="button" class="btn btn-secondary" onclick="closeModal('topicModal')">Cancel</button>
                <button type="submit" class="btn btn-primary">
                  <i class="fas fa-save"></i> Save Topic
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>

      <!-- Quiz Management Modal -->
      <div id="quizModal" class="modal hidden">
        <div class="modal-content" style="max-width: 1000px; max-height: 90vh; overflow-y: auto;">
          <div class="modal-header">
            <h2>📝 Manage Quiz Questions</h2>
            <button class="close-modal" onclick="closeModal('quizModal')">&times;</button>
          </div>
          <div class="modal-body">
            <input type="hidden" id="quiz-lesson-id">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
              <p class="text-sm" style="color: #6b7280;">Manage questions for: <strong id="quiz-lesson-name"></strong></p>
              <button type="button" class="btn btn-primary" onclick="addQuizQuestion()">
                <i class="fas fa-plus"></i> Add Question
              </button>
            </div>

            <div id="quiz-questions-list" class="space-y-4">
              <div style="text-align: center; padding: 40px; color: #999;">
                <i class="fas fa-spinner fa-spin" style="font-size: 24px;"></i>
                <p style="margin-top: 10px;">Loading quiz questions...</p>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Quiz Question Edit Modal -->
      <div id="quizQuestionModal" class="modal hidden">
        <div class="modal-content" style="max-width: 700px;">
          <div class="modal-header">
            <h2 id="quiz-question-modal-title">Add Quiz Question</h2>
            <button class="close-modal" onclick="closeModal('quizQuestionModal')">&times;</button>
          </div>
          <div class="modal-body">
            <form id="quiz-question-form">
              <input type="hidden" id="quiz-question-id">
              <input type="hidden" id="quiz-question-lesson-id">

              <div class="form-group">
                <label>Question <span style="color: #ef4444;">*</span></label>
                <textarea id="quiz-question-text" class="form-control" rows="3" required placeholder="Enter your question"></textarea>
              </div>

              <div class="form-group">
                <label>Answer Options <span style="color: #ef4444;">*</span></label>
                <div id="quiz-options-container" style="space-y-2;">
                  <!-- Options will be dynamically added here -->
                </div>
                <button type="button" class="btn btn-secondary btn-sm" onclick="addQuizOption()" style="margin-top: 10px;">
                  <i class="fas fa-plus"></i> Add Option
                </button>
              </div>

              <div class="form-group">
                <label>Explanation (optional)</label>
                <textarea id="quiz-question-explanation" class="form-control" rows="2" placeholder="Explain why this is the correct answer"></textarea>
              </div>

              <div style="display: flex; justify-content: flex-end; gap: 10px; margin-top: 20px;">
                <button type="button" class="btn btn-secondary" onclick="closeModal('quizQuestionModal')">Cancel</button>
                <button type="submit" class="btn btn-primary">
                  <i class="fas fa-save"></i> Save Question
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>

      <!-- Course Management Section (DEPRECATED - Duplicate Section) -->
      <div id="content-section-old" class="hidden">
        <div class="section-header" style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 15px;">
          <div>
            <h1>🗂️ Course Management (OLD)</h1>
            <p>This section is deprecated. Use the "Lessons & Topics" tab in the Courses section instead.</p>
          </div>
          <div style="display: flex; gap: 10px;">
            <select id="content-course-filter-old" style="margin-bottom: 0;">
              <option value="">Select Course</option>
            </select>
            <button id="add-lesson-btn-old" class="btn btn-primary" disabled style="opacity: 0.5;">
              <i class="fas fa-plus"></i> Add Lesson
            </button>
          </div>
        </div>

        <div class="grid grid-3" style="grid-template-columns: 1fr 2fr;">
          <!-- Course Tree View -->
          <div>
            <div class="card">
              <h3>📋 Content Tree</h3>
              <div id="content-tree-old" class="content-tree">
                <div style="text-center; padding: 40px 20px; color: #999;">
                  <i class="fas fa-exclamation-triangle" style="font-size: 48px; color: #f59e0b; opacity: 0.5;"></i>
                  <p style="margin-top: 10px;">This section is deprecated.<br>Use the "Lessons & Topics" tab in the Courses section.</p>
                </div>
              </div>
            </div>
          </div>

          <!-- Editor Panel (DEPRECATED - Renamed IDs to avoid conflicts) -->
          <div>
            <div id="lesson-editor-inline" class="card hidden">
              <h3>✏️ Lesson Editor</h3>

              <input type="hidden" id="edit-lesson-id-inline">
              <input type="hidden" id="edit-lesson-course-id-inline">

              <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                <div>
                  <label class="block text-gray-700 mb-2">Lesson Name *</label>
                  <input type="text" id="lesson-name-inline" class="w-full p-2 border rounded" required>
                </div>
                <div>
                  <label class="block text-gray-700 mb-2">Order Index</label>
                  <input type="number" id="lesson-order" class="w-full p-2 border rounded" value="0">
                </div>
              </div>

              <div class="mb-4">
                <label class="block text-gray-700 mb-2">Introduction</label>
                <textarea id="lesson-intro" class="w-full p-2 border rounded" rows="3"></textarea>
              </div>

              <!-- Study material toggle -->
              <div class="mb-4">
                <div class="flex items-center justify-between">
                  <label for="lesson-share-enabled" class="text-sm font-medium text-gray-700">Attach study material</label>
                  <label class="switch">
                    <input type="checkbox" id="lesson-share-enabled">
                    <span class="slider round"></span>
                  </label>
                </div>

                <div id="resource-panel" class="hidden mt-3">
                  <div class="mb-2">
                    <label class="block text-gray-700 mb-1">Attachment Type</label>
                    <select id="resource-type" class="w-full p-2 border rounded">
                      <option value="upload">Upload file</option>
                      <option value="link">Link URL</option>
                    </select>
                  </div>

                  <div id="resource-upload" class="mt-2">
                    <label class="block text-gray-700 mb-1">Upload (saved to /assets/uploads)</label>
                    <input type="file" id="resource-file" class="w-full p-2 border rounded">
                    <button id="resource-upload-btn" type="button" class="mt-2 bg-gray-200 text-gray-700 px-3 py-1 rounded text-sm">
                      <i class="fas fa-upload mr-1"></i> Upload
                    </button>
                    <p id="resource-upload-result" class="text-xs text-gray-500 mt-1"></p>
                  </div>

                  <div id="resource-link" class="mt-2 hidden">
                    <label class="block text-gray-700 mb-1">Resource URL</label>
                    <input type="text" id="resource-url" class="w-full p-2 border rounded" placeholder="https://...">
                  </div>
                </div>
              </div>

              <div class="flex justify-end space-x-4">
                <button id="cancel-lesson-edit" class="bg-gray-500 hover:bg-gray-600 text-white px-4 py-2 rounded">
                  Cancel
                </button>
                <button id="save-lesson" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded">
                  Save Lesson
                </button>
                <button id="delete-lesson" class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded">
                  Delete
                </button>
              </div>
            </div>

            <div id="topic-editor" class="bg-white p-6 rounded-lg shadow mb-6 hidden">
              <h3 class="text-xl font-semibold mb-4">Topic Editor</h3>

              <input type="hidden" id="edit-topic-id">
              <input type="hidden" id="edit-topic-lesson-id">

              <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                <div>
                  <label class="block text-gray-700 mb-2">Topic Title *</label>
                  <input type="text" id="topic-title" class="w-full p-2 border rounded" required>
                </div>
                <div>
                  <label class="block text-gray-700 mb-2">Order Index</label>
                  <input type="number" id="topic-order" class="w-full p-2 border rounded" value="0">
                </div>
              </div>

              <div class="mb-4">
                <label class="block text-gray-700 mb-2">Content</label>
                <textarea id="topic-content" class="w-full p-2 border rounded" rows="6"></textarea>
              </div>

              <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                <div>
                  <label class="block text-gray-700 mb-2">Video URL (optional)</label>
                  <input type="text" id="topic-video-url" class="w-full p-2 border rounded" placeholder="https://...">
                </div>
                <div>
                  <label class="block text-gray-700 mb-2">Image URL (optional)</label>
                  <input type="text" id="topic-image-url" class="w-full p-2 border rounded" placeholder="https://...">
                </div>
              </div>

              <div class="flex items-center mb-4">
                <input type="checkbox" id="topic-published" class="mr-2" checked>
                <label for="topic-published" class="text-sm font-medium text-gray-700">Published</label>
              </div>

              <div class="flex justify-end space-x-4">
                <button id="cancel-topic-edit" class="bg-gray-500 hover:bg-gray-600 text-white px-4 py-2 rounded">
                  Cancel
                </button>
                <button id="save-topic" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded">
                  Save Topic
                </button>
                <button id="delete-topic" class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded">
                  Delete
                </button>
              </div>
            </div>


            <div id="no-selection" class="bg-white p-12 rounded-lg shadow text-center">
              <i class="fas fa-sitemap text-4xl text-gray-400 mb-4"></i>
              <h3 class="text-xl font-semibold text-gray-700 mb-2">Select a Course</h3>
              <p class="text-gray-600">Choose a course from the dropdown to manage its lessons and topics.</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Toast Container -->
  <div id="toast-container"></div>

  <script>
    // CSRF Token Setup
    console.log('Admin Dashboard JavaScript starting...');
    window.csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

    // Escape HTML to prevent XSS
    function escapeHtml(text) {
      if (!text) return '';
      const div = document.createElement('div');
      div.textContent = text;
      return div.innerHTML;
    }

    // API Helper Function
    async function apiRequest(url, methodOrOptions = {}, data = null) {
      // Support both calling patterns:
      // 1. apiRequest(url, {method, body, headers}) - options object
      // 2. apiRequest(url, 'POST', data) - shorthand with method string
      let options = {};
      
      if (typeof methodOrOptions === 'string') {
        // Shorthand format: apiRequest(url, 'POST', data)
        options = {
          method: methodOrOptions,
          body: data ? JSON.stringify(data) : undefined
        };
      } else {
        // Full options format: apiRequest(url, {method, body, headers})
        options = methodOrOptions;
      }
      
      const headers = {
        'Content-Type': 'application/json',
        'X-CSRF-TOKEN': window.csrfToken,
        'Cache-Control': 'no-cache, no-store, must-revalidate',
        'Pragma': 'no-cache',
        'Expires': '0',
        ...options.headers
      };

      // Add timestamp to GET requests to prevent caching
      if (!options.method || options.method === 'GET') {
        const separator = url.includes('?') ? '&' : '?';
        url = `${url}${separator}_t=${Date.now()}`;
      }

      try {
        const response = await fetch(url, {
          ...options,
          headers
        });

        if (!response.ok) {
          throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }

        return await response.json();
      } catch (error) {
        console.error('API Request failed:', error);
        throw error;
      }
    }

    // Toast Notification System
    function showToast(message, type = 'info') {
      const container = document.getElementById('toast-container');
      const toast = document.createElement('div');
      toast.className = `toast ${type}`;
      toast.textContent = message;
      
      container.appendChild(toast);
      
      setTimeout(() => toast.classList.add('show'), 100);
      
      setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => container.removeChild(toast), 300);
      }, 3000);
    }

    // Navigation System
    function setupNavigation() {
      const navLinks = document.querySelectorAll('.admin-nav');
      const sections = document.querySelectorAll('[id$="-section"]');

      navLinks.forEach(link => {
        link.addEventListener('click', (e) => {
          e.preventDefault();
          const sectionId = link.getAttribute('data-section');

          if (sectionId) {
            // Hide all sections
            sections.forEach(section => section.classList.add('hidden'));

            // Remove active class from all nav links
            navLinks.forEach(nav => nav.classList.remove('active'));

            // Show selected section
            const targetSection = document.getElementById(sectionId + '-section');
            if (targetSection) {
              targetSection.classList.remove('hidden');
              link.classList.add('active');

              // Load section-specific content
              loadSectionContent(sectionId);
            }
          }
        });
      });
    }

    // Toggle submenu function
    function toggleSubmenu(event, element) {
      event.preventDefault();
      event.stopPropagation();
      
      const parentLi = element.closest('.nav-item-with-submenu');
      const isOpen = parentLi.classList.contains('open');
      
      // Close all other submenus
      document.querySelectorAll('.nav-item-with-submenu').forEach(item => {
        item.classList.remove('open');
      });
      
      // Toggle current submenu
      if (!isOpen) {
        parentLi.classList.add('open');
      }
    }

    // Navigate to section (used by quick action buttons)
    window.navigateToSection = function(sectionId) {
      const navLink = document.querySelector(`.admin-nav[data-section="${sectionId}"]`);
      if (navLink) {
        navLink.click();
      }
    }

    // Load content for specific sections
    async function loadSectionContent(sectionId) {
      switch (sectionId) {
        case 'dashboard':
          await loadDashboard();
          break;
        case 'users':
          await loadUsers();
          break;
        case 'roles':
          await loadRoles();
          break;
        case 'permissions':
          await loadPermissions();
          break;
        case 'manage-user-roles':
          await loadManageUserRoles();
          break;
        case 'access-code':
          await loadAccessCodes();
          break;
        case 'certificates':
          // Certificates are loaded via iframe, no additional loading needed
          break;
        case 'badges':
          await loadBadges();
          break;
        case 'penalties':
          await loadPenalties();
          break;
        case 'pages':
          await loadPages();
          break;
        case 'courses':
          await loadCourses();
          await loadContentStructure();
          break;
      }
    }

    // Dashboard Functions
    async function loadDashboard() {
      try {
        const data = await apiRequest('/admin/dashboard/data');

        // Update metrics
        document.getElementById('total-users').textContent = data.counts.users || 0;
        document.getElementById('active-courses').textContent = data.counts.courses || 0;
        document.getElementById('completed-users').textContent = data.counts.completed || 0;
        document.getElementById('avg-score').textContent = `${data.counts.avg_score || 0}%`;

        // User Growth Chart
        const userGrowthCtx = document.getElementById('user-growth-chart');
        if (userGrowthCtx) {
          new Chart(userGrowthCtx, {
            type: 'line',
            data: {
              labels: data.user_growth_labels || ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
              datasets: [{
                label: 'New Users',
                data: data.user_growth_data || [12, 19, 3, 5, 2, 3],
                borderColor: 'rgb(59, 130, 246)',
                backgroundColor: 'rgba(59, 130, 246, 0.1)',
                tension: 0.4,
                fill: true
              }]
            },
            options: {
              responsive: true,
              maintainAspectRatio: false,
              plugins: {
                legend: { display: false }
              },
              scales: {
                y: { beginAtZero: true }
              }
            }
          });
        }

        // Course Performance Chart
        const coursePerfCtx = document.getElementById('course-performance-chart');
        if (coursePerfCtx) {
          new Chart(coursePerfCtx, {
            type: 'doughnut',
            data: {
              labels: ['Completed', 'In Progress', 'Not Started'],
              datasets: [{
                data: [
                  data.counts.completed || 0,
                  data.counts.in_progress || 0,
                  (data.counts.users - data.counts.completed - data.counts.in_progress) || 0
                ],
                backgroundColor: [
                  'rgb(34, 197, 94)',
                  'rgb(251, 191, 36)',
                  'rgb(156, 163, 175)'
                ]
              }]
            },
            options: {
              responsive: true,
              maintainAspectRatio: false,
              plugins: {
                legend: {
                  position: 'bottom'
                }
              }
            }
          });
        }

      } catch (error) {
        showToast('Failed to load dashboard data', 'error');
        console.error('Dashboard load error:', error);
      }
    }

    // User Management Functions
    async function loadUsers() {
      const tableBody = document.getElementById('users-table-body');
      tableBody.innerHTML = '<tr><td colspan="6" style="text-align: center; padding: 20px;"><i class="fas fa-spinner fa-spin"></i> Loading users...</td></tr>';

      try {
        const data = await apiRequest('/admin/users');
        
        if (!data.users || data.users.length === 0) {
          tableBody.innerHTML = '<tr><td colspan="6" style="text-align: center; padding: 20px; color: #999;">No users found</td></tr>';
          return;
        }

        tableBody.innerHTML = data.users.map(user => {
          const progress = user.progress || {};
          const progressPercent = progress.progress_percentage || 0;
          const avgScore = progress.average_quiz_score || 0;
          
          // Progress bar color based on completion
          let progressColor = '#ef4444'; // red for low progress
          if (progressPercent >= 75) progressColor = '#10b981'; // green for high progress
          else if (progressPercent >= 40) progressColor = '#f59e0b'; // yellow for medium progress
          
          return `
            <tr style="border-bottom: 1px solid #eee;">
              <td style="padding: 12px;">
                <div style="font-weight: 600;">${user.name}</div>
                <div style="font-size: 12px; color: #666;">${user.email}</div>
              </td>
              <td style="padding: 12px;">
                ${user.roles.map(role => 
                  `<span class="status-badge ${role === 'admin' ? 'status-admin' : 'status-active'}">${role}</span>`
                ).join(' ')}
              </td>
              <td style="padding: 12px;">
                <div style="margin-bottom: 4px;">
                  <small style="color: #666;">${progress.completed_topics || 0} / ${progress.total_topics || 0} topics</small>
                </div>
                <div style="background: #f0f0f0; border-radius: 10px; height: 8px; overflow: hidden;">
                  <div style="background: ${progressColor}; height: 100%; width: ${progressPercent}%; transition: width 0.3s;"></div>
                </div>
                <small style="color: #666;">${progressPercent}%</small>
              </td>
              <td style="padding: 12px; text-align: center;">
                <div style="font-size: 18px; font-weight: 600; color: ${avgScore >= 80 ? '#10b981' : avgScore >= 60 ? '#f59e0b' : '#ef4444'};">
                  ${avgScore.toFixed(1)}%
                </div>
                <small style="color: #999;">Avg Score</small>
              </td>
              <td style="padding: 12px;">
                <small style="color: #666;">
                  ${progress.last_activity ? new Date(progress.last_activity).toLocaleDateString() : 'No activity'}
                </small>
              </td>
              <td style="padding: 12px; text-align: center;">
                <button onclick="viewUserDetails(${user.id})" style="background: #667eea; color: white; border: none; padding: 6px 12px; border-radius: 6px; cursor: pointer; font-size: 12px;">
                  <i class="fas fa-eye"></i> View
                </button>
              </td>
            </tr>
          `;
        }).join('');
      } catch (error) {
        console.error('Error loading users:', error);
        showToast('Failed to load users', 'error');
        tableBody.innerHTML = '<tr><td colspan="6" style="text-align: center; padding: 20px; color: #ef4444;">Error loading users</td></tr>';
      }
    }
    
    // View user details modal
    window.viewUserDetails = async function(userId) {
      try {
        const data = await apiRequest(`/admin/users/${userId}`);
        const user = data.user;
        const stats = data.statistics;
        
        // Create modal content
        const modalContent = `
          <div style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 1000;" onclick="this.remove()">
            <div style="background: white; padding: 30px; border-radius: 15px; max-width: 600px; width: 90%; max-height: 80vh; overflow-y: auto;" onclick="event.stopPropagation()">
              <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <h2 style="margin: 0; color: #333;">📊 User Details</h2>
                <button onclick="this.closest('div[style*=fixed]').remove()" style="background: none; border: none; font-size: 24px; cursor: pointer; color: #999;">&times;</button>
              </div>
              
              <div style="margin-bottom: 20px;">
                <h3 style="color: #667eea; margin-bottom: 10px;">${user.name}</h3>
                <p style="color: #666; margin: 5px 0;">${user.email}</p>
                <p style="color: #999; font-size: 14px;">Roles: ${user.roles.join(', ')}</p>
                <p style="color: #999; font-size: 14px;">Joined: ${new Date(user.created_at).toLocaleDateString()}</p>
              </div>
              
              <div style="background: #f8f9fa; padding: 20px; border-radius: 10px; margin-bottom: 15px;">
                <h4 style="margin-top: 0; color: #333;">Learning Progress</h4>
                <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px;">
                  <div>
                    <p style="color: #666; margin: 5px 0; font-size: 14px;">Topics Completed</p>
                    <p style="font-size: 24px; font-weight: bold; color: #667eea; margin: 5px 0;">${stats.completed_topics} / ${stats.total_topics}</p>
                  </div>
                  <div>
                    <p style="color: #666; margin: 5px 0; font-size: 14px;">Progress</p>
                    <p style="font-size: 24px; font-weight: bold; color: #10b981; margin: 5px 0;">${stats.progress_percentage}%</p>
                  </div>
                  <div>
                    <p style="color: #666; margin: 5px 0; font-size: 14px;">In Progress</p>
                    <p style="font-size: 24px; font-weight: bold; color: #f59e0b; margin: 5px 0;">${stats.in_progress_topics}</p>
                  </div>
                  <div>
                    <p style="color: #666; margin: 5px 0; font-size: 14px;">Avg Quiz Score</p>
                    <p style="font-size: 24px; font-weight: bold; color: ${stats.average_quiz_score >= 80 ? '#10b981' : '#ef4444'}; margin: 5px 0;">${stats.average_quiz_score}%</p>
                  </div>
                </div>
              </div>
              
              <div style="background: #f8f9fa; padding: 20px; border-radius: 10px;">
                <h4 style="margin-top: 0; color: #333;">Activity Summary</h4>
                <p style="margin: 10px 0; color: #666;"><strong>Total Attempts:</strong> ${stats.total_attempts}</p>
                <p style="margin: 10px 0; color: #666;"><strong>Video Watch Time:</strong> ${Math.floor(stats.total_video_watch_time / 60)} minutes</p>
                <p style="margin: 10px 0; color: #666;"><strong>Last Activity:</strong> ${stats.last_activity ? new Date(stats.last_activity).toLocaleString() : 'No activity yet'}</p>
              </div>
              
              <button onclick="this.closest('div[style*=fixed]').remove()" style="margin-top: 20px; width: 100%; padding: 12px; background: #667eea; color: white; border: none; border-radius: 8px; cursor: pointer; font-size: 16px;">Close</button>
            </div>
          </div>
        `;
        
        document.body.insertAdjacentHTML('beforeend', modalContent);
      } catch (error) {
        console.error('Error loading user details:', error);
        showToast('Failed to load user details', 'error');
      }
    }

    // Roles Functions
    async function loadRoles() {
      const tableBody = document.getElementById('roles-table-body');
      tableBody.innerHTML = '<tr><td colspan="6" style="text-align: center; padding: 20px;"><i class="fas fa-spinner fa-spin"></i> Loading roles...</td></tr>';

      try {
        const res = await fetch('/admin/roles');
        if (!res.ok) throw new Error('Failed to fetch roles');
        const json = await res.json();
        const roles = json.roles || [];

        if (roles.length === 0) {
          tableBody.innerHTML = '<tr><td colspan="6" style="text-align: center; padding: 20px; color: #999;">No roles found</td></tr>';
          return;
        }

        tableBody.innerHTML = roles.map(role => `
          <tr>
            <td>
              <span style="display: inline-flex; align-items: center; padding: 6px 12px; background: ${getRoleColor(role.name)}; color: white; border-radius: 6px; font-weight: 600;">
                <i class="fas fa-user-tag" style="margin-right: 8px;"></i>${role.name}
              </span>
            </td>
            <td>web</td>
            <td>
              <span style="display: inline-flex; align-items: center; padding: 4px 10px; background: #e0e7ff; color: #4338ca; border-radius: 6px; font-size: 0.9em;">
                <i class="fas fa-lock" style="margin-right: 6px; font-size: 0.8em;"></i>
                ${role.permissions ? role.permissions.length : 0} permissions
              </span>
            </td>
            <td>
              <span style="display: inline-flex; align-items: center; padding: 4px 10px; background: #dbeafe; color: #1e40af; border-radius: 6px; font-size: 0.9em;">
                <i class="fas fa-users" style="margin-right: 6px; font-size: 0.8em;"></i>
                ${role.users_count || 0} users
              </span>
            </td>
            <td style="font-size: 0.9em; color: #666;">
              ${new Date().toLocaleDateString()}
            </td>
            <td>
              ${role.name !== 'admin' && role.name !== 'user' && role.name !== 'tutor' ? `
                <button onclick="editRole(${role.id})" class="btn-sm" style="padding: 6px 12px; background: #3b82f6; color: white; border: none; border-radius: 6px; cursor: pointer; margin-right: 5px;">
                  <i class="fas fa-edit"></i> Edit
                </button>
                <button onclick="deleteRole(${role.id}, '${role.name.replace("'","\'")}')" class="btn-sm" style="padding: 6px 12px; background: #ef4444; color: white; border: none; border-radius: 6px; cursor: pointer;">
                  <i class="fas fa-trash"></i> Delete
                </button>
              ` : `
                <span style="color: #999; font-size: 0.9em;">System Role</span>
              `}
            </td>
          </tr>
        `).join('');
      } catch (error) {
        console.error('Error loading roles:', error);
        showToast('Failed to load roles', 'error');
        tableBody.innerHTML = '<tr><td colspan="6" style="text-align: center; padding: 20px; color: #ef4444;">Error loading roles</td></tr>';
      }
    }

    function getRoleColor(roleName) {
      const colors = {
        'admin': '#ef4444',
        'tutor': '#8b5cf6',
        'user': '#3b82f6',
        'teacher': '#10b981',
        'moderator': '#f59e0b'
      };
      return colors[roleName] || '#6b7280';
    }

    function getPermissionsForRole(roleName) {
      const permissions = {
        'admin': 'All',
        'tutor': '12',
        'user': '5'
      };
      return permissions[roleName] || '0';
    }

    // Permissions Functions
    async function loadPermissions() {
      const tableBody = document.getElementById('permissions-table-body');
      tableBody.innerHTML = '<tr><td colspan="5" style="text-align: center; padding: 20px;"><i class="fas fa-spinner fa-spin"></i> Loading permissions...</td></tr>';

      try {
        const res = await fetch('/admin/permissions');
        if (!res.ok) throw new Error('Failed to fetch permissions');
        const json = await res.json();
        const permissions = json.permissions || [];

        if (permissions.length === 0) {
          tableBody.innerHTML = '<tr><td colspan="5" style="text-align: center; padding: 20px; color: #999;">No permissions found</td></tr>';
          return;
        }

        tableBody.innerHTML = permissions.map(permission => `
          <tr>
            <td>
              <span style="display: inline-flex; align-items: center; padding: 6px 12px; background: #f3f4f6; color: #1f2937; border-radius: 6px; font-weight: 500; font-family: monospace;">
                <i class="fas fa-lock" style="margin-right: 8px; color: #6b7280;"></i>${permission.name}
              </span>
            </td>
            <td>${permission.guard_name || 'web'}</td>
            <td>
              <div style="display: flex; gap: 5px; flex-wrap: wrap;">
                ${(permission.roles || []).map(role => `
                  <span style="display: inline-block; padding: 4px 10px; background: ${getRoleColor(role.name)}; color: white; border-radius: 4px; font-size: 0.85em;">
                    ${role.name}
                  </span>
                `).join('')}
              </div>
            </td>
            <td style="font-size: 0.9em; color: #666;">${new Date(permission.created_at).toLocaleDateString()}</td>
            <td>
              <button onclick="editPermission(${permission.id})" class="btn-sm" style="padding: 6px 12px; background: #3b82f6; color: white; border: none; border-radius: 6px; cursor: pointer; margin-right: 5px;">
                <i class="fas fa-edit"></i> Edit
              </button>
              <button onclick="deletePermission(${permission.id}, '${permission.name.replace("'","\'")}')" class="btn-sm" style="padding: 6px 12px; background: #ef4444; color: white; border: none; border-radius: 6px; cursor: pointer;">
                <i class="fas fa-trash"></i> Delete
              </button>
            </td>
          </tr>
        `).join('');
      } catch (error) {
        console.error('Error loading permissions:', error);
        showToast('Failed to load permissions', 'error');
        tableBody.innerHTML = '<tr><td colspan="5" style="text-align: center; padding: 20px; color: #ef4444;">Error loading permissions</td></tr>';
      }
    }

    // Modal functions for creating roles and permissions
    async function showCreateRoleModal() {
      document.getElementById('roleModalTitle').textContent = 'Create New Role';
      document.getElementById('roleId').value = '';
      document.getElementById('roleName').value = '';
      
      // Load permissions for checkbox list
      await loadPermissionsForRoleModal();
      
      document.getElementById('roleModal').classList.add('active');
    }

    async function showCreatePermissionModal() {
      document.getElementById('permissionModalTitle').textContent = 'Create New Permission';
      document.getElementById('permissionId').value = '';
      document.getElementById('permissionName').value = '';
      
      // Load roles for checkbox list
      await loadRolesForPermissionModal();
      
      document.getElementById('permissionModal').classList.add('active');
    }

    function closeRoleModal() {
      document.getElementById('roleModal').classList.remove('active');
    }

    function closePermissionModal() {
      document.getElementById('permissionModal').classList.remove('active');
    }

    async function loadPermissionsForRoleModal(selectedPermissions = []) {
      const container = document.getElementById('permissionsCheckboxList');
      try {
        const res = await fetch('/admin/permissions');
        if (!res.ok) throw new Error('Failed to fetch');
        const json = await res.json();
        const permissions = json.permissions || [];
        
        if (permissions.length === 0) {
          container.innerHTML = '<div style="text-align: center; padding: 10px; color: #999;">No permissions available</div>';
          return;
        }
        
        container.innerHTML = permissions.map(perm => `
          <div class="checkbox-item">
            <input type="checkbox" id="perm_${perm.id}" name="permissions[]" value="${perm.id}" 
                   ${selectedPermissions.includes(perm.id) ? 'checked' : ''}>
            <label for="perm_${perm.id}">${perm.name}</label>
          </div>
        `).join('');
      } catch (error) {
        container.innerHTML = '<div style="text-align: center; padding: 10px; color: #ef4444;">Failed to load permissions</div>';
      }
    }

    async function loadRolesForPermissionModal(selectedRoles = []) {
      const container = document.getElementById('rolesCheckboxList');
      try {
        const res = await fetch('/admin/roles');
        if (!res.ok) throw new Error('Failed to fetch');
        const json = await res.json();
        const roles = json.roles || [];
        
        if (roles.length === 0) {
          container.innerHTML = '<div style="text-align: center; padding: 10px; color: #999;">No roles available</div>';
          return;
        }
        
        container.innerHTML = roles.map(role => `
          <div class="checkbox-item">
            <input type="checkbox" id="role_${role.id}" name="roles[]" value="${role.id}" 
                   ${selectedRoles.includes(role.id) ? 'checked' : ''}>
            <label for="role_${role.id}">${role.name}</label>
          </div>
        `).join('');
      } catch (error) {
        container.innerHTML = '<div style="text-align: center; padding: 10px; color: #ef4444;">Failed to load roles</div>';
      }
    }

    async function saveRole() {
      const roleId = document.getElementById('roleId').value;
      const name = document.getElementById('roleName').value.trim();
      
      if (!name) {
        showToast('Role name is required', 'error');
        return;
      }
      
      // Get selected permissions
      const selectedPerms = Array.from(document.querySelectorAll('#permissionsCheckboxList input:checked'))
        .map(cb => cb.value);
      
      const url = roleId ? `/admin/roles/${roleId}` : '/admin/roles';
      const method = roleId ? 'PUT' : 'POST';
      
      try {
        const res = await fetch(url, {
          method,
          headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
          },
          body: JSON.stringify({ name, permissions: selectedPerms })
        });
        
        const json = await res.json();
        
        if (json.success) {
          showToast(roleId ? 'Role updated successfully' : 'Role created successfully', 'success');
          closeRoleModal();
          await loadRoles();
        } else {
          showToast(json.message || 'Failed to save role', 'error');
        }
      } catch (error) {
        console.error('Save role error:', error);
        showToast('Failed to save role', 'error');
      }
    }

    async function savePermission() {
      const permissionId = document.getElementById('permissionId').value;
      const name = document.getElementById('permissionName').value.trim();
      
      if (!name) {
        showToast('Permission name is required', 'error');
        return;
      }
      
      // Get selected roles
      const selectedRoles = Array.from(document.querySelectorAll('#rolesCheckboxList input:checked'))
        .map(cb => cb.value);
      
      const url = permissionId ? `/admin/permissions/${permissionId}` : '/admin/permissions';
      const method = permissionId ? 'PUT' : 'POST';
      
      try {
        const res = await fetch(url, {
          method,
          headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
          },
          body: JSON.stringify({ name, roles: selectedRoles })
        });
        
        const json = await res.json();
        
        if (json.success) {
          showToast(permissionId ? 'Permission updated successfully' : 'Permission created successfully', 'success');
          closePermissionModal();
          await loadPermissions();
        } else {
          showToast(json.message || 'Failed to save permission', 'error');
        }
      } catch (error) {
        console.error('Save permission error:', error);
        showToast('Failed to save permission', 'error');
      }
    }

    async function editRole(roleId) {
      try {
        const res = await fetch(`/admin/roles/${roleId}`);
        if (!res.ok) { showToast('Failed to load role', 'error'); return; }
        const json = await res.json();
        const role = json.role;
        
        document.getElementById('roleModalTitle').textContent = 'Edit Role';
        document.getElementById('roleId').value = role.id;
        document.getElementById('roleName').value = role.name;
        
        // Load permissions and pre-select assigned ones
        const selectedPermissions = (role.permissions || []).map(p => p.id);
        await loadPermissionsForRoleModal(selectedPermissions);
        
        document.getElementById('roleModal').classList.add('active');
      } catch (e) { 
        showToast('Failed to load role', 'error'); 
      }
    }

    async function deleteRole(roleId, roleName) {
      if (!confirm(`Are you sure you want to delete the role "${roleName}"?\n\nThis action cannot be undone.`)) return;
      try {
        const res = await fetch(`/admin/roles/${roleId}`, { 
          method: 'DELETE', 
          headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content') } 
        });
        const json = await res.json();
        if (json.success) { 
          showToast('Role deleted successfully', 'success'); 
          loadRoles(); 
        } else { 
          showToast(json.message || 'Failed to delete role', 'error'); 
        }
      } catch (e) { 
        showToast('Failed to delete role', 'error'); 
      }
    }

    async function editPermission(permissionId) {
      try {
        const res = await fetch(`/admin/permissions/${permissionId}`);
        if (!res.ok) { showToast('Failed to load permission', 'error'); return; }
        const json = await res.json();
        const perm = json.permission;
        
        document.getElementById('permissionModalTitle').textContent = 'Edit Permission';
        document.getElementById('permissionId').value = perm.id;
        document.getElementById('permissionName').value = perm.name;
        
        // Load roles and pre-select assigned ones
        const selectedRoles = (perm.roles || []).map(r => r.id);
        await loadRolesForPermissionModal(selectedRoles);
        
        document.getElementById('permissionModal').classList.add('active');
      } catch (e) { 
        showToast('Failed to load permission', 'error'); 
      }
    }

    async function deletePermission(permissionId, permissionName) {
      if (!confirm(`Are you sure you want to delete the permission "${permissionName}"?\n\nThis action cannot be undone.`)) return;
      try {
        const res = await fetch(`/admin/permissions/${permissionId}`, { 
          method: 'DELETE', 
          headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content') } 
        });
        const json = await res.json();
        if (json.success) { 
          showToast('Permission deleted successfully', 'success'); 
          loadPermissions(); 
        } else { 
          showToast(json.message || 'Failed to delete permission', 'error'); 
        }
      } catch (e) { 
        showToast('Failed to delete permission', 'error'); 
      }
    }

    // Make Admin Functions
  async function loadManageUserRoles() {
  const tableBody = document.getElementById('manage-user-roles-table-body');
      tableBody.innerHTML = '<tr><td colspan="4" class="px-6 py-4 text-center"><i class="fas fa-spinner fa-spin"></i> Loading users...</td></tr>';

      try {
        const data = await apiRequest('/admin/users');
        
        if (data.users.length === 0) {
          tableBody.innerHTML = '<tr><td colspan="4" class="px-6 py-4 text-center text-gray-400">No users found</td></tr>';
          return;
        }

        tableBody.innerHTML = data.users.map(user => {
          // Determine current role (assume only one main role for simplicity)
          const currentRole = user.roles.includes('admin') ? 'admin' : (user.roles.includes('tutor') ? 'tutor' : 'user');
          return `
            <tr>
              <td class="px-6 py-4 whitespace-nowrap">${user.name}</td>
              <td class="px-6 py-4 whitespace-nowrap">${user.email}</td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${currentRole === 'admin' ? 'bg-red-100 text-red-800' : currentRole === 'tutor' ? 'bg-purple-100 text-purple-800' : 'bg-blue-100 text-blue-800'}">
                  ${user.roles.join(', ')}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <select onchange="changeUserRole(${user.id}, this.value)" class="px-2 py-1 rounded border focus:outline-none">
                  <option value="user" ${currentRole === 'user' ? 'selected' : ''}>User</option>
                  <option value="tutor" ${currentRole === 'tutor' ? 'selected' : ''}>Tutor</option>
                  <option value="admin" ${currentRole === 'admin' ? 'selected' : ''}>Admin</option>
                </select>
              </td>
            </tr>
          `;
        }).join('');
      } catch (error) {
        showToast('Failed to load users', 'error');
        tableBody.innerHTML = '<tr><td colspan="4" class="px-6 py-4 text-center text-red-600">Error loading users</td></tr>';
      }
    }

    // Admin Role Management
    async function changeUserRole(userId, newRole) {
      if (!['admin', 'tutor', 'user'].includes(newRole)) {
        showToast('Invalid role selected', 'error');
        return;
      }
      try {
        const data = await apiRequest('/admin/change-role', {
          method: 'POST',
          body: JSON.stringify({ user_id: userId, role: newRole })
        });
        showToast(data.message || 'Role updated', 'success');
  await loadManageUserRoles();
      } catch (error) {
        showToast('Failed to update user role', 'error');
      }
    }

    // Access Code Functions
    async function loadAccessCodes() {
      // Initialize access code toggle
      try {
        const response = await apiRequest('/admin/settings/access-code-status');
        const toggle = document.getElementById('access-code-toggle');
        if (toggle) {
          toggle.checked = response.required;
          // Remove any existing listener before adding new one
          const newToggle = toggle.cloneNode(true);
          toggle.parentNode.replaceChild(newToggle, toggle);
          newToggle.addEventListener('change', toggleAccessCode);
        }
      } catch (error) {
        console.error('Failed to load access code status:', error);
      }

      // Set up generate form
      const genForm = document.getElementById('generate-code-form');
      if (genForm) {
        // Remove any existing listener before adding new one
        const newForm = genForm.cloneNode(true);
        genForm.parentNode.replaceChild(newForm, genForm);
        newForm.addEventListener('submit', generateAccessCodes);
      }

      // Load the access codes table
      await loadAccessCodesTable();
    }

    async function toggleAccessCode() {
      const toggle = document.getElementById('access-code-toggle');
      try {
        await apiRequest('/admin/settings/access-code-toggle', {
          method: 'POST',
          body: JSON.stringify({ required: toggle.checked })
        });
        showToast(`Access code requirement ${toggle.checked ? 'enabled' : 'disabled'}`, 'success');
      } catch (error) {
        console.error('Toggle error:', error);
        showToast('Failed to update access code setting', 'error');
        toggle.checked = !toggle.checked; // Revert on error
      }
    }

    async function generateAccessCodes(e) {
      e.preventDefault();
      const count = document.getElementById('code-count').value;
      const type = document.getElementById('code-type').value;
      
      try {
        const data = await apiRequest('/admin/settings/generate-access-codes', {
          method: 'POST',
          body: JSON.stringify({ count: parseInt(count), type })
        });

        const resultDiv = document.getElementById('code-generation-result');
        resultDiv.textContent = `Generated ${data.codes.length} access codes successfully!`;
        showToast(`Generated ${data.codes.length} access codes`, 'success');
        
        // Reload access codes table
        await loadAccessCodesTable();
      } catch (error) {
        console.error('Generate error:', error);
        showToast('Failed to generate access codes', 'error');
      }
    }

    async function clearExpiredAccessCodes() {
      const btn = document.getElementById('clear-expired-btn');
      const resultDiv = document.getElementById('clear-result');
      
      // Confirm action
      if (!confirm('Are you sure you want to clear ALL expired access codes immediately?')) {
        return;
      }
      
      try {
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Clearing...';
        resultDiv.textContent = '';
        
        const data = await apiRequest('/admin/settings/clear-expired-codes', {
          method: 'POST'
        });

        resultDiv.style.color = '#10b981';
        resultDiv.textContent = data.message;
        showToast(data.message, 'success');
        
        // Reload access codes table
        await loadAccessCodesTable();
      } catch (error) {
        console.error('Clear error:', error);
        resultDiv.style.color = '#ef4444';
        resultDiv.textContent = 'Failed to clear expired codes';
        showToast('Failed to clear expired codes', 'error');
      } finally {
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-trash-alt"></i> Clear All Expired Codes Now';
      }
    }

    async function loadAccessCodesTable() {
      const tbody = document.getElementById('access-codes-table');
      
      try {
        tbody.innerHTML = '<tr><td colspan="4" style="text-align: center;"><i class="fas fa-spinner fa-spin"></i> Loading...</td></tr>';
        
        const response = await apiRequest('/admin/settings/access-codes');
        const codes = response.codes || [];
        
        if (codes.length === 0) {
          tbody.innerHTML = '<tr><td colspan="4" style="text-align: center; color: #999;">No access codes yet</td></tr>';
          return;
        }
        
        tbody.innerHTML = codes.map(code => {
          const isExpired = code.is_expired;
          const isUsed = code.is_used || code.used_by !== null;
          
          let statusBadge = '';
          if (isUsed) {
            statusBadge = '<span style="background: #10b981; color: white; padding: 2px 8px; border-radius: 4px; font-size: 11px;">Used</span>';
          } else if (isExpired) {
            statusBadge = '<span style="background: #ef4444; color: white; padding: 2px 8px; border-radius: 4px; font-size: 11px;">Expired</span>';
          } else {
            statusBadge = '<span style="background: #3b82f6; color: white; padding: 2px 8px; border-radius: 4px; font-size: 11px;">Active</span>';
          }
          
          const expiresAt = code.expires_at ? new Date(code.expires_at).toLocaleString() : 'Never';
          const usedBy = code.used_by ? `<br><small style="color: #666;">Used by: ${code.used_by}</small>` : '';
          
          // Show delete button only for expired codes
          const deleteBtn = isExpired ? `
            <button onclick="deleteAccessCode(${code.id}, '${code.code}')" class="btn-sm" style="background: #ef4444; color: white; padding: 4px 8px; border: none; border-radius: 4px; cursor: pointer; margin-left: 4px;" title="Delete expired code">
              <i class="fas fa-trash-alt"></i>
            </button>
          ` : '';
          
          return `
            <tr>
              <td><code style="background: #f3f4f6; padding: 4px 8px; border-radius: 4px; font-family: monospace;">${code.code}</code></td>
              <td>${statusBadge}${usedBy}</td>
              <td style="font-size: 13px;">${expiresAt}</td>
              <td>
                <button onclick="copyAccessCode('${code.code}')" class="btn-sm" style="background: #3b82f6; color: white; padding: 4px 8px; border: none; border-radius: 4px; cursor: pointer;">
                  <i class="fas fa-copy"></i>
                </button>
                ${deleteBtn}
              </td>
            </tr>
          `;
        }).join('');
      } catch (error) {
        console.error('Failed to load access codes:', error);
        tbody.innerHTML = '<tr><td colspan="4" style="text-align: center; color: #ef4444;">Error loading codes</td></tr>';
      }
    }

    function copyAccessCode(code) {
      navigator.clipboard.writeText(code).then(() => {
        showToast('Access code copied to clipboard!', 'success');
      }).catch(err => {
        showToast('Failed to copy code', 'error');
      });
    }

    async function deleteAccessCode(codeId, codeName) {
      if (!confirm(`Are you sure you want to delete the expired access code "${codeName}"?`)) {
        return;
      }

      try {
        const data = await apiRequest(`/admin/settings/access-codes/${codeId}`, {
          method: 'DELETE'
        });

        showToast(data.message, 'success');
        
        // Reload the table
        await loadAccessCodesTable();
      } catch (error) {
        console.error('Delete error:', error);
        showToast(error.message || 'Failed to delete access code', 'error');
      }
    }

    // Course Management Functions
    // ========================================
    // COURSE MANAGEMENT (Lessons & Topics)
    // ========================================
    async function loadContentStructure() {
      const filter = document.getElementById('content-course-filter');
      const tree = document.getElementById('content-tree');

      if (!filter || !tree) {
        console.warn('Content structure elements not found');
        return;
      }

      // Load courses for filter
      try {
        const data = await apiRequest('/admin/courses');
        filter.innerHTML = '<option value="">Select Course</option>';
        
        data.courses.forEach(course => {
          const option = document.createElement('option');
          option.value = course.id;
          option.textContent = course.name;
          filter.appendChild(option);
        });
      } catch (error) {
        console.error('Failed to load courses for filter:', error);
      }

      // Remove any existing event listeners by cloning the element
      const newFilter = filter.cloneNode(true);
      filter.parentNode.replaceChild(newFilter, filter);

      // Add fresh event listener
      newFilter.addEventListener('change', async (e) => {
        const courseId = e.target.value;
        const addLessonBtn = document.getElementById('add-lesson-btn');
        
        if (!courseId) {
          tree.innerHTML = `
            <div style="text-align: center; padding: 60px 20px; color: #9ca3af;">
              <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); width: 100px; height: 100px; border-radius: 50%; margin: 0 auto 20px; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);">
                <i class="fas fa-book-open" style="font-size: 42px; color: white;"></i>
              </div>
              <h4 style="color: #4b5563; margin: 0 0 10px 0; font-size: 18px;">No Course Selected</h4>
              <p style="margin: 0; font-size: 14px; color: #9ca3af;">Select a course from the dropdown above to view and manage its lessons and topics</p>
            </div>
          `;
          if (addLessonBtn) {
            addLessonBtn.disabled = true;
            addLessonBtn.style.background = 'rgba(255,255,255,0.2)';
            addLessonBtn.style.cursor = 'not-allowed';
            addLessonBtn.style.border = '2px solid rgba(255,255,255,0.3)';
          }
          return;
        }

        if (addLessonBtn) {
          addLessonBtn.disabled = false;
          addLessonBtn.style.background = 'white';
          addLessonBtn.style.color = '#667eea';
          addLessonBtn.style.cursor = 'pointer';
          addLessonBtn.style.border = '2px solid white';
        }
        await loadCourseLessons(courseId);
      });
    }

    async function loadCourseLessons(courseId) {
      const tree = document.getElementById('content-tree');
      tree.innerHTML = `
        <div style="text-align: center; padding: 40px 20px;">
          <i class="fas fa-spinner fa-spin" style="font-size: 36px; color: #667eea;"></i>
          <p style="margin-top: 15px; color: #6b7280; font-size: 14px;">Loading lessons and topics...</p>
        </div>
      `;

      try {
        const data = await apiRequest(`/admin/courses/${courseId}/lessons`);
        
        if (data.lessons.length === 0) {
          tree.innerHTML = `
            <div style="text-align: center; padding: 60px 20px;">
              <div style="background: #f3f4f6; width: 80px; height: 80px; border-radius: 50%; margin: 0 auto 20px; display: flex; align-items: center; justify-content: center;">
                <i class="fas fa-folder-plus" style="font-size: 32px; color: #9ca3af;"></i>
              </div>
              <h4 style="color: #4b5563; margin: 0 0 8px 0; font-size: 16px;">No Lessons Yet</h4>
              <p style="margin: 0 0 20px 0; font-size: 14px; color: #9ca3af;">Click "Add Lesson" to create your first lesson</p>
            </div>
          `;
          return;
        }

        tree.innerHTML = `<div id="lessons-sortable" style="display: flex; flex-direction: column; gap: 15px;">${data.lessons.map((lesson, index) => `
          <div class="course-node" data-lesson-id="${lesson.id}" style="background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%); border: 2px solid #e5e7eb; border-radius: 12px; padding: 20px; transition: all 0.3s; box-shadow: 0 1px 3px rgba(0,0,0,0.05);">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
              <div style="display: flex; align-items: center; flex: 1; gap: 12px;">
                <i class="fas fa-grip-vertical" style="color: #d1d5db; cursor: move; font-size: 18px;"></i>
                <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); width: 40px; height: 40px; border-radius: 10px; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold; font-size: 16px; box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);">
                  ${index + 1}
                </div>
                <div>
                  <h4 style="margin: 0; color: #1f2937; font-size: 16px; font-weight: 600;">${lesson.name}</h4>
                  <p style="margin: 5px 0 0 0; color: #6b7280; font-size: 13px;">
                    ${lesson.topics ? lesson.topics.length : 0} topic${lesson.topics && lesson.topics.length !== 1 ? 's' : ''}
                    ${lesson.has_quiz ? ' • <i class="fas fa-question-circle" style="color: #8b5cf6;"></i> Has Quiz' : ''}
                  </p>
                </div>
              </div>
              <div style="display: flex; gap: 6px;">
                <button style="background: #10b981; color: white; border: none; padding: 8px 14px; border-radius: 6px; cursor: pointer; font-size: 12px; font-weight: 600; transition: all 0.2s;" onclick="addTopic(${lesson.id})" title="Add topic">
                  <i class="fas fa-plus"></i> Topic
                </button>
                ${lesson.has_quiz ? `<button style="background: #8b5cf6; color: white; border: none; padding: 8px 14px; border-radius: 6px; cursor: pointer; font-size: 12px; font-weight: 600; transition: all 0.2s;" onclick="manageQuiz(${lesson.id})" title="Manage quiz">
                  <i class="fas fa-question-circle"></i> Quiz
                </button>` : ''}
                <button style="background: #3b82f6; color: white; border: none; padding: 8px 12px; border-radius: 6px; cursor: pointer; font-size: 12px; transition: all 0.2s;" onclick="editLesson(${lesson.id})" title="Edit lesson">
                  <i class="fas fa-edit"></i>
                </button>
                <button style="background: #ef4444; color: white; border: none; padding: 8px 12px; border-radius: 6px; cursor: pointer; font-size: 12px; transition: all 0.2s;" onclick="deleteLesson(${lesson.id})" title="Delete lesson">
                  <i class="fas fa-trash"></i>
                </button>
              </div>
            </div>
            <div class="topics-sortable topics-container" data-lesson-id="${lesson.id}" style="margin-left: 52px; display: flex; flex-direction: column; gap: 8px;">
              ${(lesson.topics && lesson.topics.length > 0) ? lesson.topics.map((topic, topicIndex) => `
                <div class="topic-node" data-topic-id="${topic.id}" style="background: white; border: 1px solid #e5e7eb; border-radius: 8px; padding: 12px 15px; transition: all 0.2s;">
                  <div style="display: flex; justify-content: space-between; align-items: center;">
                    <div style="display: flex; align-items: center; flex: 1; gap: 10px;">
                      <i class="fas fa-grip-vertical" style="color: #d1d5db; cursor: move; font-size: 14px;"></i>
                      <div style="background: #dbeafe; width: 28px; height: 28px; border-radius: 6px; display: flex; align-items: center; justify-content: center; color: #1e40af; font-weight: 600; font-size: 12px;">
                        ${topicIndex + 1}
                      </div>
                      <i class="fas fa-book-open" style="color: #3b82f6; font-size: 14px;"></i>
                      <span style="color: #374151; font-size: 14px; font-weight: 500;">${topic.title}</span>
                      ${topic.is_published === false ? '<span style="background: #fef3c7; color: #92400e; padding: 2px 8px; border-radius: 4px; font-size: 11px; font-weight: 600; margin-left: 8px;">DRAFT</span>' : ''}
                    </div>
                    <div style="display: flex; gap: 4px;">
                      <button style="background: #3b82f6; color: white; border: none; padding: 6px 10px; border-radius: 5px; cursor: pointer; font-size: 11px; transition: all 0.2s;" onclick="editTopic(${topic.id})" title="Edit">
                        <i class="fas fa-edit"></i>
                      </button>
                      <button style="background: #ef4444; color: white; border: none; padding: 6px 10px; border-radius: 5px; cursor: pointer; font-size: 11px; transition: all 0.2s;" onclick="deleteTopic(${topic.id})" title="Delete">
                        <i class="fas fa-trash"></i>
                      </button>
                    </div>
                  </div>
                </div>
              `).join('') : ''}
              ${(!lesson.topics || lesson.topics.length === 0) ? '<p style="color: #9ca3af; font-size: 13px; font-style: italic; margin: 10px 0;">No topics yet - click "Add Topic" to get started</p>' : ''}
            </div>
          </div>
        `).join('')}</div>`;
        
        // Initialize drag-and-drop for lessons
        initializeLessonsDragDrop(courseId);
        
        // Initialize drag-and-drop for topics in each lesson
        document.querySelectorAll('.topics-sortable').forEach(container => {
          const lessonId = container.getAttribute('data-lesson-id');
          initializeTopicsDragDrop(container, lessonId);
        });
      } catch (error) {
        showToast('Failed to load course lessons', 'error');
        tree.innerHTML = `
          <div style="text-align: center; padding: 40px 20px;">
            <i class="fas fa-exclamation-triangle" style="font-size: 36px; color: #ef4444;"></i>
            <p style="margin-top: 15px; color: #ef4444; font-size: 14px; font-weight: 600;">Error loading content</p>
            <p style="margin-top: 5px; color: #6b7280; font-size: 13px;">Please try refreshing the page</p>
          </div>
        `;
      }
    }

    // Initialize drag-and-drop for lessons
    function initializeLessonsDragDrop(courseId) {
      const container = document.getElementById('lessons-sortable');
      if (!container) return;

      new Sortable(container, {
        animation: 150,
        handle: '.fa-grip-vertical',
        ghostClass: 'sortable-ghost',
        dragClass: 'sortable-drag',
        onEnd: async function(evt) {
          const lessonIds = Array.from(container.children).map(el => el.getAttribute('data-lesson-id'));
          
          try {
            await apiRequest('/admin/lessons/reorder', {
              method: 'POST',
              body: JSON.stringify({ lesson_ids: lessonIds })
            });
            showToast('Lessons reordered successfully!', 'success');
          } catch (error) {
            showToast('Failed to reorder lessons', 'error');
            await loadCourseLessons(courseId); // Reload to restore order
          }
        }
      });
    }

    // Initialize drag-and-drop for topics within a lesson
    function initializeTopicsDragDrop(container, lessonId) {
      if (!container || container.children.length === 0) return;
      
      // Only initialize if there are actual topic nodes
      const hasTopics = Array.from(container.children).some(el => el.classList.contains('topic-node'));
      if (!hasTopics) return;

      new Sortable(container, {
        animation: 150,
        handle: '.fa-grip-vertical',
        ghostClass: 'sortable-ghost',
        dragClass: 'sortable-drag',
        onEnd: async function(evt) {
          const topicIds = Array.from(container.children)
            .filter(el => el.classList.contains('topic-node'))
            .map(el => el.getAttribute('data-topic-id'));
          
          try {
            await apiRequest('/admin/topics/reorder', {
              method: 'POST',
              body: JSON.stringify({ topic_ids: topicIds })
            });
            showToast('Topics reordered successfully!', 'success');
          } catch (error) {
            showToast('Failed to reorder topics', 'error');
            const courseId = document.getElementById('content-course-filter').value;
            await loadCourseLessons(courseId); // Reload to restore order
          }
        }
      });
    }

    // ========================================
    // LESSON CRUD OPERATIONS
    // ========================================
    let currentLessonId = null;
    let currentLessonCourseId = null;

    window.addLesson = function() {
      console.log('addLesson function called');
      const courseId = document.getElementById('content-course-filter').value;
      console.log('Selected course ID:', courseId);
      
      if (!courseId) {
        showToast('Please select a course first', 'error');
        return;
      }

      currentLessonId = null;
      currentLessonCourseId = courseId;
      
      document.getElementById('lesson-modal-title').textContent = 'Add New Lesson';
      document.getElementById('lesson-form').reset();
      document.getElementById('lesson-id').value = '';
      document.getElementById('lesson-course-id').value = courseId;
      
      // Reset all toggle panels
      document.getElementById('lesson-share-enabled').checked = false;
      document.getElementById('lesson-share-panel').classList.add('hidden');
      document.getElementById('lesson-has-quiz').checked = false;
      document.getElementById('lesson-has-certificate').checked = false;
      document.getElementById('lesson-certificate-panel').classList.add('hidden');
      document.getElementById('lesson-upload-status').textContent = '';
      
      console.log('Opening lesson modal');
      openModal('lessonModal');
    }

    window.editLesson = async function(lessonId) {
      currentLessonId = lessonId;
      
      try {
        const data = await apiRequest(`/admin/lessons/${lessonId}`);
        const lesson = data.lesson;
        
        document.getElementById('lesson-modal-title').textContent = 'Edit Lesson';
        document.getElementById('lesson-id').value = lesson.id;
        document.getElementById('lesson-name').value = lesson.name;
        document.getElementById('lesson-description').value = lesson.intro || '';
        document.getElementById('lesson-course-id').value = lesson.course_id;
        
        // Study material fields
        document.getElementById('lesson-share-enabled').checked = lesson.share_enabled || false;
        document.getElementById('lesson-share-panel').classList.toggle('hidden', !lesson.share_enabled);
        document.getElementById('lesson-share-type').value = lesson.share_type || 'upload';
        document.getElementById('lesson-share-url').value = lesson.share_url || '';
        document.getElementById('lesson-share-filename').value = lesson.share_filename || '';
        document.getElementById('lesson-share-size').value = lesson.share_size || '';
        document.getElementById('lesson-link-url').value = lesson.share_url || '';
        
        // Toggle upload/link sections
        if (lesson.share_type === 'link') {
          document.getElementById('lesson-upload-section').classList.add('hidden');
          document.getElementById('lesson-link-section').classList.remove('hidden');
        } else {
          document.getElementById('lesson-upload-section').classList.remove('hidden');
          document.getElementById('lesson-link-section').classList.add('hidden');
        }
        
        if (lesson.share_enabled && lesson.share_filename) {
          document.getElementById('lesson-upload-status').textContent = `✓ ${lesson.share_filename}`;
          document.getElementById('lesson-upload-status').style.color = '#10b981';
        }
        
        // Quiz and certificate
        document.getElementById('lesson-has-quiz').checked = lesson.has_quiz || false;
        document.getElementById('lesson-has-certificate').checked = lesson.has_certificate || false;
        document.getElementById('lesson-certificate-panel').classList.toggle('hidden', !lesson.has_certificate);
        document.getElementById('lesson-certificate-id').value = lesson.certificate_id || '';
        
        currentLessonCourseId = lesson.course_id;
        
        openModal('lessonModal');
      } catch (error) {
        showToast('Failed to load lesson details', 'error');
        console.error(error);
      }
    }

    window.saveLesson = async function(event) {
      event.preventDefault();
      
      const form = document.getElementById('lesson-form');
      const formData = new FormData(form);
      
      // Build data object with proper handling of checkboxes
      const data = {
        course_id: document.getElementById('lesson-course-id').value,
        name: document.getElementById('lesson-name').value,
        intro: document.getElementById('lesson-description').value,
        share_enabled: document.getElementById('lesson-share-enabled').checked,
        share_type: document.getElementById('lesson-share-type').value,
        share_url: document.getElementById('lesson-share-url').value,
        share_filename: document.getElementById('lesson-share-filename').value,
        share_size: document.getElementById('lesson-share-size').value,
        has_quiz: document.getElementById('lesson-has-quiz').checked,
        has_certificate: document.getElementById('lesson-has-certificate').checked,
        certificate_id: document.getElementById('lesson-certificate-id').value,
        order_index: 0
      };
      
      const lessonId = document.getElementById('lesson-id').value;
      const url = lessonId ? `/admin/lessons/${lessonId}` : '/admin/lessons';
      const method = lessonId ? 'PUT' : 'POST';
      
      try {
        const response = await apiRequest(url, {
          method,
          body: JSON.stringify(data)
        });
        
        showToast(`Lesson ${lessonId ? 'updated' : 'created'} successfully!`, 'success');
        closeModal('lessonModal');
        
        // Reload the course lessons
        if (currentLessonCourseId) {
          await loadCourseLessons(currentLessonCourseId);
        }
      } catch (error) {
        showToast(`Failed to ${lessonId ? 'update' : 'create'} lesson`, 'error');
        console.error('Save lesson error:', error);
      }
    }

    window.deleteLesson = async function(lessonId) {
      if (!confirm('Are you sure you want to delete this lesson? All topics within this lesson will also be deleted.')) {
        return;
      }
      
      try {
        await apiRequest(`/admin/lessons/${lessonId}`, {
          method: 'DELETE'
        });
        
        showToast('Lesson deleted successfully!', 'success');
        
        // Reload the course lessons
        const courseId = document.getElementById('content-course-filter').value;
        if (courseId) {
          await loadCourseLessons(courseId);
        }
      } catch (error) {
        showToast('Failed to delete lesson', 'error');
        console.error(error);
      }
    }

    // ========================================
    // TOPIC CRUD OPERATIONS
    // ========================================
    let currentTopicId = null;
    let currentTopicLessonId = null;

    window.addTopic = function(lessonId) {
      currentTopicId = null;
      currentTopicLessonId = lessonId;
      
      document.getElementById('topic-modal-title').textContent = 'Add New Topic';
      document.getElementById('topic-form').reset();
      document.getElementById('topic-id').value = '';
      document.getElementById('topic-lesson-id').value = lessonId;
      
      // Clear TinyMCE content and ensure it's editable
      const editor = tinymce.get('topic-body');
      if (editor) {
        editor.setContent('');
        editor.mode.set('design');
        setTimeout(() => {
          editor.selection.collapse(false);
          editor.focus();
        }, 100);
      }
      
      openModal('topicModal');
    }

    window.editTopic = async function(topicId) {
      currentTopicId = topicId;
      
      try {
        console.log('Fetching topic:', topicId);
        const data = await apiRequest(`/admin/topics/${topicId}`);
        console.log('Topic data received:', data);
        
        if (!data || !data.topic) {
          throw new Error('Invalid response format');
        }
        
        const topic = data.topic;
        
        document.getElementById('topic-modal-title').textContent = 'Edit Topic';
        document.getElementById('topic-id').value = topic.id;
        document.getElementById('topic-title').value = topic.title;
        document.getElementById('topic-lesson-id').value = topic.lesson_id;
        
        // Ensure TinyMCE is initialized and set content
        const editor = tinymce.get('topic-body');
        if (editor) {
          editor.setContent(topic.body || '');
          // Make sure it's editable
          editor.mode.set('design');
          // Clear any selection
          setTimeout(() => {
            editor.selection.collapse(false);
            editor.focus();
          }, 100);
        } else {
          console.warn('TinyMCE editor not found, using textarea');
          document.getElementById('topic-body').value = topic.body || '';
        }
        
        // Media fields
        document.getElementById('topic-video-url').value = topic.video_url || '';
        document.getElementById('topic-image-url').value = topic.image_url || '';
        
        // Published status
        document.getElementById('topic-is-published').checked = topic.is_published !== false;
        
        // Clear image upload status
        document.getElementById('topic-image-status').textContent = '';
        
        currentTopicLessonId = topic.lesson_id;
        
        openModal('topicModal');
      } catch (error) {
        console.error('Edit topic error:', error);
        showToast('Failed to load topic details: ' + (error.message || 'Unknown error'), 'error');
      }
    }

    window.saveTopic = async function(event) {
      event.preventDefault();
      
      const form = document.getElementById('topic-form');
      
      // Build data object manually to handle checkboxes properly
      const data = {
        lesson_id: document.getElementById('topic-lesson-id').value,
        title: document.getElementById('topic-title').value,
        video_url: document.getElementById('topic-video-url').value || '',
        image_url: document.getElementById('topic-image-url').value || '',
        is_published: document.getElementById('topic-is-published').checked,
        order_index: 0
      };
      
      // Get content from TinyMCE
      if (tinymce.get('topic-body')) {
        data.body = tinymce.get('topic-body').getContent();
      } else {
        data.body = document.getElementById('topic-body').value || '';
      }
      
      const topicId = document.getElementById('topic-id').value;
      const url = topicId ? `/admin/topics/${topicId}` : '/admin/topics';
      const method = topicId ? 'PUT' : 'POST';
      
      console.log('Saving topic with data:', data);
      
      try {
        const response = await apiRequest(url, {
          method,
          body: JSON.stringify(data)
        });
        
        console.log('Topic save response:', response);
        showToast(`Topic ${topicId ? 'updated' : 'created'} successfully!`, 'success');
        closeModal('topicModal');
        
        // Reload the content structure to show the new/updated topic
        await loadContentStructure();
      } catch (error) {
        console.error('Topic save error:', error);
        showToast(`Failed to ${topicId ? 'update' : 'create'} topic`, 'error');
      }
    }

    window.deleteTopic = async function(topicId) {
      if (!confirm('Are you sure you want to delete this topic?')) {
        return;
      }
      
      try {
        await apiRequest(`/admin/topics/${topicId}`, {
          method: 'DELETE'
        });
        
        showToast('Topic deleted successfully!', 'success');
        
        // Reload the course lessons
        const courseId = document.getElementById('content-course-filter').value;
        if (courseId) {
          await loadCourseLessons(courseId);
        }
      } catch (error) {
        showToast('Failed to delete topic', 'error');
        console.error(error);
      }
    }

    // ========================================
    // QUIZ QUESTION CRUD OPERATIONS
    // ========================================
    let currentQuizLessonId = null;
    let currentQuizQuestionId = null;

    window.manageQuiz = async function(lessonId) {
      currentQuizLessonId = lessonId;
      
      try {
        // Load lesson details
        const lessonData = await apiRequest(`/admin/lessons/${lessonId}`);
        document.getElementById('quiz-lesson-name').textContent = lessonData.lesson.name;
        document.getElementById('quiz-lesson-id').value = lessonId;
        
        // Load quiz questions
        await loadQuizQuestions(lessonId);
        
        openModal('quizModal');
      } catch (error) {
        showToast('Failed to load quiz', 'error');
        console.error(error);
      }
    }

    async function loadQuizQuestions(lessonId) {
      const container = document.getElementById('quiz-questions-list');
      container.innerHTML = '<div style="text-align: center; padding: 40px;"><i class="fas fa-spinner fa-spin"></i></div>';
      
      try {
        const response = await apiRequest(`/admin/lessons/${lessonId}/quiz-questions`);
        const questions = response.data || [];
        
        if (questions.length === 0) {
          container.innerHTML = `
            <div style="text-align: center; padding: 40px; color: #999;">
              <i class="fas fa-question-circle" style="font-size: 48px; margin-bottom: 15px;"></i>
              <p>No quiz questions yet. Click "Add Question" to get started.</p>
            </div>
          `;
          return;
        }
        
        container.innerHTML = questions.map((q, index) => `
          <div class="card" style="padding: 15px; margin-bottom: 10px;">
            <div style="display: flex; justify-content: space-between; align-items: start;">
              <div style="flex: 1;">
                <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 10px;">
                  <span style="background: #667eea; color: white; padding: 4px 12px; border-radius: 12px; font-size: 12px; font-weight: 600;">Q${index + 1}</span>
                  <h4 style="margin: 0;">${q.question}</h4>
                </div>
                <div style="margin-left: 15px;">
                  ${q.options.map((opt, i) => `
                    <div style="margin: 5px 0; display: flex; align-items: center;">
                      <i class="fas fa-${i === q.correct_answer ? 'check-circle' : 'circle'}" style="color: ${i === q.correct_answer ? '#10b981' : '#d1d5db'}; margin-right: 8px;"></i>
                      <span style="${i === q.correct_answer ? 'font-weight: 600; color: #10b981;' : ''}">${opt}</span>
                    </div>
                  `).join('')}
                </div>
                ${q.explanation ? `<p style="margin: 10px 0 0 15px; padding: 10px; background: #f3f4f6; border-radius: 4px; font-size: 14px; color: #6b7280;"><strong>Explanation:</strong> ${q.explanation}</p>` : ''}
              </div>
              <div style="display: flex; gap: 5px;">
                <button class="bg-blue-600 hover:bg-blue-700 text-white px-3 py-1 rounded text-xs" onclick="editQuizQuestion(${q.id})">
                  <i class="fas fa-edit"></i>
                </button>
                <button class="bg-red-600 hover:bg-red-700 text-white px-3 py-1 rounded text-xs" onclick="deleteQuizQuestion(${q.id})">
                  <i class="fas fa-trash"></i>
                </button>
              </div>
            </div>
          </div>
        `).join('');
      } catch (error) {
        container.innerHTML = '<div style="text-align: center; padding: 40px; color: #ef4444;">Error loading questions</div>';
        console.error(error);
      }
    }

    window.addQuizQuestion = function() {
      currentQuizQuestionId = null;
      document.getElementById('quiz-question-modal-title').textContent = 'Add Quiz Question';
      document.getElementById('quiz-question-form').reset();
      document.getElementById('quiz-question-id').value = '';
      document.getElementById('quiz-question-lesson-id').value = currentQuizLessonId;
      
      // Initialize with 4 empty options
      const container = document.getElementById('quiz-options-container');
      container.innerHTML = '';
      for (let i = 0; i < 4; i++) {
        addQuizOption(i === 0); // First option is correct by default
      }
      
      openModal('quizQuestionModal');
    }

    window.editQuizQuestion = async function(questionId) {
      currentQuizQuestionId = questionId;
      
      try {
        const response = await apiRequest(`/admin/quiz-questions/${questionId}`);
        const question = response.data;
        
        document.getElementById('quiz-question-modal-title').textContent = 'Edit Quiz Question';
        document.getElementById('quiz-question-id').value = question.id;
        document.getElementById('quiz-question-lesson-id').value = question.lesson_id;
        document.getElementById('quiz-question-text').value = question.question;
        document.getElementById('quiz-question-explanation').value = question.explanation || '';
        
        // Load options
        const container = document.getElementById('quiz-options-container');
        container.innerHTML = '';
        question.options.forEach((opt, index) => {
          addQuizOption(index === question.correct_answer, opt);
        });
        
        openModal('quizQuestionModal');
      } catch (error) {
        showToast('Failed to load question', 'error');
        console.error(error);
      }
    }

    window.addQuizOption = function(isCorrect = false, text = '') {
      const container = document.getElementById('quiz-options-container');
      const index = container.children.length;
      
      const optionDiv = document.createElement('div');
      optionDiv.className = 'quiz-option';
      optionDiv.style.cssText = 'display: flex; gap: 10px; margin-bottom: 10px; align-items: center;';
      optionDiv.innerHTML = `
        <input type="radio" name="quiz-correct" value="${index}" ${isCorrect ? 'checked' : ''} required style="margin: 0;">
        <input type="text" class="form-control quiz-option-text" placeholder="Option ${index + 1}" value="${text}" required style="flex: 1;">
        <button type="button" class="btn btn-danger btn-sm" onclick="this.parentElement.remove()">
          <i class="fas fa-times"></i>
        </button>
      `;
      container.appendChild(optionDiv);
    }

    window.saveQuizQuestion = async function(event) {
      event.preventDefault();
      
      const questionId = document.getElementById('quiz-question-id').value;
      const lessonId = document.getElementById('quiz-question-lesson-id').value;
      const questionText = document.getElementById('quiz-question-text').value;
      const explanation = document.getElementById('quiz-question-explanation').value;
      
      // Get options
      const optionTexts = Array.from(document.querySelectorAll('.quiz-option-text')).map(input => input.value);
      const correctAnswer = parseInt(document.querySelector('input[name="quiz-correct"]:checked').value);
      
      const data = {
        lesson_id: lessonId,
        question: questionText,
        options: optionTexts,
        correct_answer: correctAnswer,
        explanation: explanation,
        is_active: true
      };
      
      const url = questionId ? `/admin/quiz-questions/${questionId}` : '/admin/quiz-questions';
      const method = questionId ? 'PUT' : 'POST';
      
      try {
        await apiRequest(url, {
          method,
          body: JSON.stringify(data)
        });
        
        showToast(`Question ${questionId ? 'updated' : 'added'} successfully!`, 'success');
        closeModal('quizQuestionModal');
        await loadQuizQuestions(currentQuizLessonId);
      } catch (error) {
        showToast('Failed to save question', 'error');
        console.error(error);
      }
    }

    window.deleteQuizQuestion = async function(questionId) {
      if (!confirm('Are you sure you want to delete this question?')) {
        return;
      }
      
      try {
        await apiRequest(`/admin/quiz-questions/${questionId}`, {
          method: 'DELETE'
        });
        
        showToast('Question deleted successfully!', 'success');
        await loadQuizQuestions(currentQuizLessonId);
      } catch (error) {
        showToast('Failed to delete question', 'error');
        console.error(error);
      }
    }

    // ===========================
    // Settings System Functions
    // ===========================
    
    // Load settings from API and populate form fields
    async function loadSettings() {
      try {
        const response = await fetch('/admin/settings');
        if (!response.ok) throw new Error('Failed to load settings');
        
        const data = await response.json();
        
        // Populate all form fields
        Object.entries(data).forEach(([group, settings]) => {
          Object.entries(settings).forEach(([key, value]) => {
            const input = document.getElementById(key);
            if (input) {
              if (input.type === 'color') {
                input.value = value || '#667eea';
                // Sync with text input
                const textInput = document.querySelector(`input[type="text"][id="${key}"]`);
                if (textInput) textInput.value = value || '#667eea';
              } else if (input.type === 'file') {
                // Show preview if image exists
                if (value) {
                  const preview = document.getElementById(`${key}_preview`);
                  if (preview) {
                    preview.src = value;
                    preview.style.display = 'block';
                  }
                }
              } else {
                input.value = value || '';
              }
            }
          });
        });
        
      } catch (error) {
        console.error('Error loading settings:', error);
        showToast('Failed to load settings', 'error');
      }
    }
    
    // Save settings by group
    async function saveSettings(group) {
      const button = event.target;
      const originalText = button.textContent;
      button.disabled = true;
      button.textContent = 'Saving...';
      
      try {
        // Collect all settings for this group
        const groupMap = {
          'general': ['site_name', 'site_description', 'copyright_text', 'contact_email', 'contact_phone'],
          'branding': ['logo_path', 'favicon_path', 'logo_dark_path'],
          'theme': ['primary_color', 'secondary_color', 'success_color', 'danger_color', 'warning_color', 'info_color'],
          'seo': ['meta_title', 'meta_description', 'meta_keywords', 'og_image', 'google_analytics_id', 'google_site_verification'],
          'social': ['facebook_url', 'twitter_url', 'linkedin_url', 'instagram_url', 'youtube_url']
        };
        
        const keys = groupMap[group];
        if (!keys) {
          throw new Error('Invalid group');
        }
        
        const settings = [];
        keys.forEach(key => {
          const input = document.getElementById(key);
          if (input && input.type !== 'file') {
            settings.push({
              key: key,
              value: input.value || ''
            });
          }
        });
        
        const response = await fetch('/admin/settings/bulk', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
          },
          body: JSON.stringify({ settings })
        });
        
        if (!response.ok) throw new Error('Failed to save settings');
        
        const data = await response.json();
        showToast(data.message || 'Settings saved successfully', 'success');
        
        // If theme colors were updated, apply them
        if (group === 'theme') {
          applyThemeColors();
        }
        
      } catch (error) {
        console.error('Error saving settings:', error);
        showToast('Failed to save settings', 'error');
      } finally {
        button.disabled = false;
        button.textContent = originalText;
      }
    }
    
    // Handle image upload
    async function handleImageUpload(key, input) {
      if (!input.files || !input.files[0]) return;
      
      const file = input.files[0];
      const formData = new FormData();
      formData.append('key', key);
      formData.append('image', file);
      
      try {
        const response = await fetch('/admin/settings/upload-image', {
          method: 'POST',
          headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
          },
          body: formData
        });
        
        if (!response.ok) throw new Error('Failed to upload image');
        
        const data = await response.json();
        
        // Update preview
        const preview = document.getElementById(`${key}_preview`);
        if (preview) {
          preview.src = data.path;
          preview.style.display = 'block';
        }
        
        // Update hidden input if exists
        const hiddenInput = document.getElementById(key);
        if (hiddenInput && hiddenInput.type !== 'file') {
          hiddenInput.value = data.path;
        }
        
        showToast('Image uploaded successfully', 'success');
        
      } catch (error) {
        console.error('Error uploading image:', error);
        showToast('Failed to upload image', 'error');
      }
    }
    
    // Reset theme colors to defaults
    async function resetThemeColors() {
      if (!confirm('Are you sure you want to reset all theme colors to defaults? This will override your current color scheme.')) {
        return;
      }
      
      try {
        const response = await fetch('/admin/settings/reset', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
          },
          body: JSON.stringify({ group: 'theme' })
        });
        
        if (!response.ok) throw new Error('Failed to reset theme');
        
        const data = await response.json();
        
        // Reload settings to show defaults
        await loadSettings();
        applyThemeColors();
        
        showToast('Theme colors reset to defaults', 'success');
        
      } catch (error) {
        console.error('Error resetting theme:', error);
        showToast('Failed to reset theme', 'error');
      }
    }
    
    // Apply theme colors to document
    function applyThemeColors() {
      const colors = {
        primary: document.getElementById('primary_color')?.value || '#667eea',
        secondary: document.getElementById('secondary_color')?.value || '#764ba2',
        success: document.getElementById('success_color')?.value || '#10b981',
        danger: document.getElementById('danger_color')?.value || '#ef4444',
        warning: document.getElementById('warning_color')?.value || '#f59e0b',
        info: document.getElementById('info_color')?.value || '#3b82f6'
      };
      
      // Apply as CSS variables
      document.documentElement.style.setProperty('--color-primary', colors.primary);
      document.documentElement.style.setProperty('--color-secondary', colors.secondary);
      document.documentElement.style.setProperty('--color-success', colors.success);
      document.documentElement.style.setProperty('--color-danger', colors.danger);
      document.documentElement.style.setProperty('--color-warning', colors.warning);
      document.documentElement.style.setProperty('--color-info', colors.info);
    }
    
    // Settings tab switching
    function switchSettingsTab(tabId) {
      console.log('Switching to tab:', tabId);
      
      // Hide all tab content
      document.querySelectorAll('.settings-tab-content').forEach(content => {
        content.classList.add('hidden');
      });
      
      // Remove active state from all buttons
      document.querySelectorAll('.settings-tab-btn').forEach(btn => {
        btn.classList.remove('active');
        btn.style.background = 'transparent';
        btn.style.color = 'rgba(255,255,255,0.7)';
      });
      
      // Show selected tab content
      const tabContent = document.getElementById(tabId);
      if (tabContent) {
        console.log('Found tab content:', tabId);
        tabContent.classList.remove('hidden');
      } else {
        console.error('Tab content not found:', tabId);
      }
      
      // Add active state to clicked button
      const activeBtn = document.querySelector(`[data-tab="${tabId}"]`);
      if (activeBtn) {
        activeBtn.classList.add('active');
        activeBtn.style.background = 'rgba(255,255,255,0.2)';
        activeBtn.style.color = 'white';
      }
    }
    
    // Initialize settings tab listeners
    function initializeSettingsTabs() {
      document.querySelectorAll('.settings-tab-btn').forEach(btn => {
        btn.addEventListener('click', function(e) {
          e.preventDefault();
          const tabId = this.getAttribute('data-tab');
          if (tabId) {
            switchSettingsTab(tabId);
          }
        });
      });
    }
    
    // Sync color picker with hex input
    function syncColorPicker(colorKey) {
      const colorInput = document.getElementById(colorKey);
      const textInput = document.getElementById(colorKey + '_hex');
      
      if (colorInput && textInput) {
        console.log('Syncing color picker:', colorKey);
        
        // When color picker changes, update text input
        colorInput.addEventListener('input', function() {
          textInput.value = this.value;
        });
        
        // When text input changes, update color picker
        textInput.addEventListener('input', function() {
          if (/^#[0-9A-F]{6}$/i.test(this.value)) {
            colorInput.value = this.value;
          }
        });
      } else {
        console.warn('Color inputs not found for:', colorKey);
      }
    }

    // Initialize Everything
    document.addEventListener('DOMContentLoaded', function() {
      setupNavigation();
      loadDashboard(); // Load dashboard by default
      
      // Initialize TinyMCE for topic body editor
      tinymce.init({
        selector: '#topic-body',
        height: 400,
        menubar: true,
        plugins: [
          'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
          'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
          'insertdatetime', 'media', 'table', 'help', 'wordcount'
        ],
        toolbar: 'undo redo | blocks | bold italic forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat | help',
        content_style: `
          body { 
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; 
            font-size: 14px; 
            background-color: #ffffff !important; 
            color: #000000 !important;
            padding: 10px;
          }
          body.mce-content-body { 
            background-color: #ffffff !important; 
            color: #000000 !important;
          }
          * {
            background-color: transparent;
          }
          p, h1, h2, h3, h4, h5, h6, li, td, th, div, span {
            color: #000000 !important;
          }
        `,
        branding: false,
        promotion: false,
        readonly: false,
        setup: function(editor) {
          editor.on('init', function() {
            editor.mode.set('design'); // Ensure it's in design mode, not readonly
            // Force light background on editor body
            const body = editor.getBody();
            if (body) {
              body.style.backgroundColor = '#ffffff';
              body.style.color = '#000000';
            }
          });
        }
      });
      
      // Set up refresh button
      const refreshBtn = document.getElementById('refresh-users');
      if (refreshBtn) {
        refreshBtn.addEventListener('click', loadUsers);
      }

      // Set up course form
      const courseForm = document.getElementById('create-course-form');
      if (courseForm) {
        courseForm.addEventListener('submit', createCourse);
      }

      // Set up lesson form
      const lessonForm = document.getElementById('lesson-form');
      if (lessonForm) {
        lessonForm.addEventListener('submit', saveLesson);
      }

      // Set up topic form
      const topicForm = document.getElementById('topic-form');
      if (topicForm) {
        topicForm.addEventListener('submit', saveTopic);
      }

      // Set up quiz question form
      const quizQuestionForm = document.getElementById('quiz-question-form');
      if (quizQuestionForm) {
        quizQuestionForm.addEventListener('submit', saveQuizQuestion);
      }

      // Set up Add Lesson button
      const addLessonBtn = document.getElementById('add-lesson-btn');
      if (addLessonBtn) {
        console.log('Add Lesson button found, attaching click handler');
        addLessonBtn.addEventListener('click', function(e) {
          e.preventDefault();
          console.log('Add Lesson button clicked');
          addLesson();
        });
      } else {
        console.warn('Add Lesson button not found!');
      }

      // Set up lesson modal toggles
      setupLessonModalToggles();

      // Set up topic modal functions
      setupTopicModalFunctions();

      // Set up completion mode toggles
      setupCompletionModeToggles();

      // Initialize Settings System
      // Sync color pickers with hex inputs
      const colorKeys = ['primary_color', 'secondary_color', 'success_color', 'danger_color', 'warning_color', 'info_color'];
      colorKeys.forEach(key => syncColorPicker(key));
      
      // Initialize settings tab switching
      initializeSettingsTabs();
      
      // Load settings when viewing settings section
      const settingsLink = document.querySelector('[data-section="settings"]');
      if (settingsLink) {
        settingsLink.addEventListener('click', function() {
          setTimeout(() => {
            loadSettings();
            initializeSettingsTabs(); // Re-initialize in case tabs were just loaded
          }, 100);
        });
      }
      
      // Apply current theme colors on load
      applyThemeColors();

      console.log('Admin dashboard initialized successfully');
    });

    // Helper function for completion mode toggles
    function setupCompletionModeToggles() {
      const completionMode = document.getElementById('completion-mode');
      if (completionMode) {
        completionMode.addEventListener('change', function() {
          const certBlock = document.getElementById('cert-block');
          const instBlock = document.getElementById('inst-block');
          
          certBlock.classList.add('hidden');
          instBlock.classList.add('hidden');
          
          if (this.value === 'certificate') {
            certBlock.classList.remove('hidden');
          } else if (this.value === 'instructions') {
            instBlock.classList.remove('hidden');
          }
        });
      }
    }

    // Helper function for lesson modal toggles
    function setupLessonModalToggles() {
      // Study material toggle
      const shareToggle = document.getElementById('lesson-share-enabled');
      const sharePanel = document.getElementById('lesson-share-panel');
      const shareType = document.getElementById('lesson-share-type');
      const uploadSection = document.getElementById('lesson-upload-section');
      const linkSection = document.getElementById('lesson-link-section');

      if (shareToggle) {
        shareToggle.addEventListener('change', function() {
          if (this.checked) {
            sharePanel.classList.remove('hidden');
          } else {
            sharePanel.classList.add('hidden');
          }
        });
      }

      if (shareType) {
        shareType.addEventListener('change', function() {
          if (this.value === 'upload') {
            uploadSection.classList.remove('hidden');
            linkSection.classList.add('hidden');
          } else {
            uploadSection.classList.add('hidden');
            linkSection.classList.remove('hidden');
          }
        });
      }

      // File upload for lesson
      const uploadBtn = document.getElementById('lesson-upload-btn');
      const fileInput = document.getElementById('lesson-file-upload');
      if (uploadBtn && fileInput) {
        uploadBtn.addEventListener('click', async function() {
          const file = fileInput.files[0];
          if (!file) {
            showToast('Please select a file to upload', 'error');
            return;
          }

          const formData = new FormData();
          formData.append('file', file);

          try {
            uploadBtn.disabled = true;
            uploadBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Uploading...';
            
            const response = await fetch('/admin/upload-file', {
              method: 'POST',
              headers: {
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
              },
              body: formData
            });

            const data = await response.json();
            
            if (data.success) {
              document.getElementById('lesson-share-url').value = data.url;
              document.getElementById('lesson-share-filename').value = data.filename;
              document.getElementById('lesson-share-size').value = data.size;
              document.getElementById('lesson-upload-status').textContent = `✓ ${data.filename} uploaded successfully`;
              document.getElementById('lesson-upload-status').style.color = '#10b981';
              showToast('File uploaded successfully!', 'success');
            } else {
              throw new Error(data.message || 'Upload failed');
            }
          } catch (error) {
            showToast('Failed to upload file', 'error');
            console.error(error);
          } finally {
            uploadBtn.disabled = false;
            uploadBtn.innerHTML = '<i class="fas fa-upload"></i> Upload';
          }
        });
      }

      // Certificate toggle
      const certToggle = document.getElementById('lesson-has-certificate');
      const certPanel = document.getElementById('lesson-certificate-panel');
      if (certToggle && certPanel) {
        certToggle.addEventListener('change', function() {
          if (this.checked) {
            certPanel.classList.remove('hidden');
          } else {
            certPanel.classList.add('hidden');
          }
        });
      }

      // Link URL sync
      const linkUrlInput = document.getElementById('lesson-link-url');
      const shareUrlInput = document.getElementById('lesson-share-url');
      if (linkUrlInput && shareUrlInput) {
        linkUrlInput.addEventListener('input', function() {
          shareUrlInput.value = this.value;
        });
      }
    }

    // Helper function for topic modal functions
    function setupTopicModalFunctions() {
      // Image upload button
      const imageUploadBtn = document.getElementById('topic-image-upload-btn');
      const imageFileInput = document.getElementById('topic-image-file');
      const imageUrlInput = document.getElementById('topic-image-url');
      const imageStatus = document.getElementById('topic-image-status');

      if (imageUploadBtn && imageFileInput) {
        imageUploadBtn.addEventListener('click', function() {
          imageFileInput.click();
        });

        imageFileInput.addEventListener('change', async function() {
          const file = this.files[0];
          if (!file) return;

          if (!file.type.startsWith('image/')) {
            showToast('Please select an image file', 'error');
            return;
          }

          const formData = new FormData();
          formData.append('file', file);

          try {
            imageUploadBtn.disabled = true;
            imageUploadBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Uploading...';
            imageStatus.textContent = 'Uploading...';
            imageStatus.style.color = '#667eea';
            
            const response = await fetch('/admin/upload-image', {
              method: 'POST',
              headers: {
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
              },
              body: formData
            });

            const data = await response.json();
            
            if (data.success) {
              imageUrlInput.value = data.url;
              imageStatus.textContent = `✓ ${file.name} uploaded successfully`;
              imageStatus.style.color = '#10b981';
              showToast('Image uploaded successfully!', 'success');
            } else {
              throw new Error(data.message || 'Upload failed');
            }
          } catch (error) {
            imageStatus.textContent = '✗ Upload failed';
            imageStatus.style.color = '#ef4444';
            showToast('Failed to upload image', 'error');
            console.error(error);
          } finally {
            imageUploadBtn.disabled = false;
            imageUploadBtn.innerHTML = '<i class="fas fa-upload"></i> Or Upload Image';
          }
        });
      }
    }

    // ========================================
    // COURSES MANAGEMENT
    // ========================================
    let courses = [];
    let currentCourseId = null;
    let deleteCourseId = null;

    async function loadCourses() {
      const tableBody = document.getElementById('courses-table-body');
      tableBody.innerHTML = '<tr><td colspan="6" style="text-align: center; padding: 40px;"><i class="fas fa-spinner fa-spin" style="font-size: 24px; color: #667eea;"></i><p style="margin-top: 10px; color: #999;">Loading courses...</p></td></tr>';

      try {
        const data = await apiRequest('/admin/courses');
        courses = data.courses || [];
        displayCourses(courses);
      } catch (error) {
        tableBody.innerHTML = '<tr><td colspan="6" style="text-align: center; padding: 40px; color: #ef4444;">Error loading courses</td></tr>';
        console.error('Error loading courses:', error);
      }
    }

    function displayCourses(coursesToDisplay) {
      const tableBody = document.getElementById('courses-table-body');
      
      if (!coursesToDisplay || coursesToDisplay.length === 0) {
        tableBody.innerHTML = '<tr><td colspan="6" style="text-align: center; padding: 40px; color: #999;">No courses found. Click "Add New Course" to create one!</td></tr>';
        return;
      }

      tableBody.innerHTML = coursesToDisplay.map(course => {
        const stats = course.stats || {};
        const completionRate = stats.completion_rate || 0;
        const isActive = course.is_active;
        
        let completionColor = '#ef4444';
        if (completionRate >= 75) completionColor = '#10b981';
        else if (completionRate >= 50) completionColor = '#f59e0b';

        return `
          <tr style="border-bottom: 1px solid #eee;">
            <td style="padding: 12px;">
              <div style="font-weight: 600; margin-bottom: 4px;">${course.name}</div>
              <div style="font-size: 12px; color: #666;">${course.short_description || 'No description'}</div>
              ${course.has_prerequisite ? 
                `<div style="font-size: 11px; color: #667eea; margin-top: 4px;">
                  <i class="fas fa-lock"></i> Requires: ${course.prerequisite_course_name}
                </div>` : ''}
            </td>
            <td style="padding: 12px;">
              <span class="status-badge ${isActive ? 'status-active' : 'status-inactive'}">
                ${isActive ? '✓ Active' : '✕ Inactive'}
              </span>
            </td>
            <td style="padding: 12px; text-align: center;">
              <div style="font-size: 20px; font-weight: 600; color: #667eea;">${stats.lesson_count || 0}</div>
              <small style="color: #999;">${stats.topic_count || 0} topics</small>
            </td>
            <td style="padding: 12px; text-align: center;">
              <div style="font-size: 20px; font-weight: 600; color: #374151;">${stats.enrolled_users || 0}</div>
              <small style="color: #999;">students</small>
            </td>
            <td style="padding: 12px; text-align: center;">
              <div style="font-size: 18px; font-weight: 600; color: ${completionColor};">${completionRate}%</div>
              <small style="color: #999;">${stats.completed_users || 0} completed</small>
            </td>
            <td style="padding: 12px; text-align: center;">
              <div style="display: flex; gap: 5px; justify-content: center;">
                <button onclick="manageCourseContent(${course.id})" class="icon-btn icon-btn-primary" title="Manage Lessons & Topics" style="background: #667eea; color: white;">
                  <i class="fas fa-sitemap"></i>
                </button>
                ${course.enable_survey ? `
                  <button onclick="manageSurvey(${course.id}, '${course.name.replace(/'/g, "\\'")}' )" class="icon-btn" title="Manage Survey" style="background: #10b981; color: white;">
                    <i class="fas fa-poll"></i>
                  </button>
                ` : ''}
                <button onclick="editCourse(${course.id})" class="icon-btn" title="Edit Course">
                  <i class="fas fa-edit"></i>
                </button>
                <button onclick="showDeleteCourseModal(${course.id}, '${course.name.replace(/'/g, "\\'")}') "class="icon-btn icon-btn-danger" title="Delete Course">
                  <i class="fas fa-trash"></i>
                </button>
              </div>
            </td>
          </tr>
        `;
      }).join('');
    }

    // Course search
    document.getElementById('course-search')?.addEventListener('input', (e) => {
      const searchTerm = e.target.value.toLowerCase();
      const filtered = courses.filter(course => 
        course.name.toLowerCase().includes(searchTerm) ||
        (course.short_description && course.short_description.toLowerCase().includes(searchTerm)) ||
        (course.prerequisite_course_name && course.prerequisite_course_name.toLowerCase().includes(searchTerm))
      );
      displayCourses(filtered);
    });

    // Add course button
    document.getElementById('add-course-btn')?.addEventListener('click', () => {
      openCourseModal();
    });

    // Course modal management
    window.openCourseModal = async function(courseId = null) {
      currentCourseId = courseId;
      const modal = document.getElementById('course-modal');
      const title = document.getElementById('course-modal-title');
      const saveText = document.getElementById('save-course-text');
      
      // Reset form
      document.getElementById('course-form').reset();
      document.getElementById('course-id').value = '';
      document.getElementById('course-chunk-words').value = '800';
      document.getElementById('course-active').checked = true;
      document.getElementById('prerequisite-select-container').classList.add('hidden');
      document.getElementById('course-has-prerequisite').checked = false;
      
      // Reset study time fields
      document.getElementById('course-enable-study-time').checked = false;
      document.getElementById('study-time-fields').classList.add('hidden');
      document.getElementById('course-min-study-minutes').value = '15';
      document.getElementById('course-max-study-minutes').value = '60';
      
      // Reset survey fields
      document.getElementById('course-enable-survey').checked = false;
      document.getElementById('survey-fields').classList.add('hidden');
      document.getElementById('course-survey-title').value = '';
      document.getElementById('course-survey-description').value = '';

      // Load available prerequisites
      await loadAvailablePrerequisites(courseId);

      if (courseId) {
        // Edit mode
        title.textContent = '✏️ Edit Course';
        saveText.textContent = 'Update Course';
        
        try {
          const data = await apiRequest(`/admin/courses/${courseId}`);
          const course = data.course;
          
          document.getElementById('course-id').value = course.id;
          document.getElementById('course-name').value = course.name;
          document.getElementById('course-slug').value = course.slug;
          document.getElementById('course-description').value = course.short_description || '';
          document.getElementById('course-chunk-words').value = course.chunk_words || 800;
          
          // Study time limits
          document.getElementById('course-enable-study-time').checked = course.enable_study_time_limit || false;
          document.getElementById('course-min-study-minutes').value = course.min_study_minutes_per_day || 15;
          document.getElementById('course-max-study-minutes').value = course.max_study_minutes_per_day || 60;
          if (course.enable_study_time_limit) {
            document.getElementById('study-time-fields').classList.remove('hidden');
          }
          
          // Survey settings
          document.getElementById('course-enable-survey').checked = course.enable_survey || false;
          document.getElementById('course-survey-title').value = course.survey_title || '';
          document.getElementById('course-survey-description').value = course.survey_description || '';
          if (course.enable_survey) {
            document.getElementById('survey-fields').classList.remove('hidden');
          }
          
          document.getElementById('course-certificate').value = course.certificate_template || '';
          document.getElementById('course-instructions').value = course.completion_instructions || '';
          document.getElementById('course-active').checked = course.is_active;
          
          // Set completion type radio buttons
          if (course.certificate_template) {
            document.getElementById('completion-certificate').checked = true;
            document.getElementById('certificate-template-group').classList.remove('hidden');
          } else if (course.completion_instructions) {
            document.getElementById('completion-instructions-radio').checked = true;
            document.getElementById('completion-instructions-group').classList.remove('hidden');
          } else {
            document.getElementById('completion-none').checked = true;
          }
          
          if (course.has_prerequisite && course.prerequisite_course_id) {
            document.getElementById('course-has-prerequisite').checked = true;
            document.getElementById('prerequisite-select-container').classList.remove('hidden');
            document.getElementById('course-prerequisite').value = course.prerequisite_course_id;
          }
        } catch (error) {
          showToast('Error loading course details', 'error');
          return;
        }
      } else {
        // Create mode
        title.textContent = '✨ Add New Course';
        saveText.textContent = 'Create Course';
      }

      modal.classList.add('active');
      modal.classList.remove('hidden');
    }

    async function loadAvailablePrerequisites(excludeCourseId = null) {
      try {
        const url = excludeCourseId 
          ? `/admin/available-prerequisites/${excludeCourseId}`
          : '/admin/available-prerequisites';
        const data = await apiRequest(url);
        
        const select = document.getElementById('course-prerequisite');
        select.innerHTML = '<option value="">-- Select a prerequisite course --</option>';
        
        if (data.courses && data.courses.length > 0) {
          data.courses.forEach(course => {
            select.innerHTML += `<option value="${course.id}">${course.name}</option>`;
          });
        }
      } catch (error) {
        console.error('Error loading prerequisites:', error);
      }
    }

    window.closeCourseModal = function() {
      document.getElementById('course-modal').classList.add('hidden');
      currentCourseId = null;
    }

    // Prerequisite checkbox toggle
    document.getElementById('course-has-prerequisite')?.addEventListener('change', (e) => {
      const container = document.getElementById('prerequisite-select-container');
      if (e.target.checked) {
        container.classList.remove('hidden');
      } else {
        container.classList.add('hidden');
        document.getElementById('course-prerequisite').value = '';
      }
    });

    // Study time limits toggle
    document.getElementById('course-enable-study-time')?.addEventListener('change', (e) => {
      const container = document.getElementById('study-time-fields');
      if (e.target.checked) {
        container.classList.remove('hidden');
      } else {
        container.classList.add('hidden');
      }
    });

    // Survey toggle
    document.getElementById('course-enable-survey')?.addEventListener('change', (e) => {
      const container = document.getElementById('survey-fields');
      if (e.target.checked) {
        container.classList.remove('hidden');
      } else {
        container.classList.add('hidden');
      }
    });

    // Completion type radio buttons toggle
    document.querySelectorAll('input[name="completion-type"]').forEach(radio => {
      radio.addEventListener('change', (e) => {
        const certificateGroup = document.getElementById('certificate-template-group');
        const instructionsGroup = document.getElementById('completion-instructions-group');
        
        // Hide both
        certificateGroup.classList.add('hidden');
        instructionsGroup.classList.add('hidden');
        
        // Show selected
        if (e.target.value === 'certificate') {
          certificateGroup.classList.remove('hidden');
        } else if (e.target.value === 'instructions') {
          instructionsGroup.classList.remove('hidden');
        }
      });
    });

    // Course form submission
    document.getElementById('course-form')?.addEventListener('submit', async (e) => {
      e.preventDefault();
      
      const courseId = document.getElementById('course-id').value;
      const hasPrerequisite = document.getElementById('course-has-prerequisite').checked;
      const prerequisiteId = document.getElementById('course-prerequisite').value;

      // Validation
      if (hasPrerequisite && !prerequisiteId) {
        showToast('Please select a prerequisite course', 'error');
        return;
      }

      // Get completion type
      const completionType = document.querySelector('input[name="completion-type"]:checked').value;
      
      const courseData = {
        name: document.getElementById('course-name').value,
        slug: document.getElementById('course-slug').value || null,
        short_description: document.getElementById('course-description').value,
        chunk_words: parseInt(document.getElementById('course-chunk-words').value) || 800,
        enable_study_time_limit: document.getElementById('course-enable-study-time').checked,
        min_study_minutes_per_day: document.getElementById('course-enable-study-time').checked 
          ? parseInt(document.getElementById('course-min-study-minutes').value) || null 
          : null,
        max_study_minutes_per_day: document.getElementById('course-enable-study-time').checked 
          ? parseInt(document.getElementById('course-max-study-minutes').value) || null 
          : null,
        enable_survey: document.getElementById('course-enable-survey').checked,
        survey_title: document.getElementById('course-enable-survey').checked 
          ? document.getElementById('course-survey-title').value || null 
          : null,
        survey_description: document.getElementById('course-enable-survey').checked 
          ? document.getElementById('course-survey-description').value || null 
          : null,
        certificate_template: completionType === 'certificate' ? document.getElementById('course-certificate').value : null,
        completion_instructions: completionType === 'instructions' ? document.getElementById('course-instructions').value : null,
        has_prerequisite: hasPrerequisite,
        prerequisite_course_id: hasPrerequisite ? prerequisiteId : null,
        is_active: document.getElementById('course-active').checked
      };

      const saveBtn = document.getElementById('save-course-btn');
      saveBtn.disabled = true;
      saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Saving...';

      try {
        if (courseId) {
          // Update existing course
          await apiRequest(`/admin/courses/${courseId}`, 'PUT', courseData);
          showToast('Course updated successfully!', 'success');
        } else {
          // Create new course
          await apiRequest('/admin/courses', 'POST', courseData);
          showToast('Course created successfully!', 'success');
        }
        
        closeCourseModal();
        await loadCourses(); // Wait for courses to reload
        
        // Reload course lessons if currently viewing lessons tab
        const lessonsTab = document.getElementById('lessons-topics-tab');
        const courseFilter = document.getElementById('content-course-filter');
        if (lessonsTab && !lessonsTab.classList.contains('hidden') && courseFilter && courseFilter.value) {
          await loadCourseLessons(courseFilter.value);
        }
      } catch (error) {
        showToast(error.message || 'Error saving course', 'error');
      } finally {
        saveBtn.disabled = false;
        saveBtn.innerHTML = `<i class="fas fa-save"></i> <span id="save-course-text">${courseId ? 'Update' : 'Create'} Course</span>`;
      }
    });

    window.editCourse = function(courseId) {
      try {
        openCourseModal(courseId);
      } catch (error) {
        console.error('Error in editCourse:', error);
      }
    }

    window.showDeleteCourseModal = function(courseId, courseName) {
      deleteCourseId = courseId;
      document.getElementById('delete-course-name').textContent = courseName;
      document.getElementById('delete-course-id').textContent = courseId;
      document.getElementById('delete-course-modal').classList.remove('hidden');
    }

    window.closeDeleteCourseModal = function() {
      document.getElementById('delete-course-modal').classList.add('hidden');
      deleteCourseId = null;
    }

    window.confirmDeleteCourse = async function() {
      if (!deleteCourseId) return;

      try {
        await apiRequest(`/admin/courses/${deleteCourseId}`, 'DELETE');
        showToast('Course deleted successfully!', 'success');
        closeDeleteCourseModal();
        loadCourses();
      } catch (error) {
        showToast(error.message || 'Error deleting course', 'error');
      }
    }

    // Survey Management
    let currentSurveyCourseId = null;
    let surveyQuestions = [];
    let questionIdCounter = 0;

    window.manageSurvey = async function(courseId, courseName) {
      currentSurveyCourseId = courseId;
      document.getElementById('survey-modal-title').textContent = `📋 Manage Survey: ${courseName}`;
      document.getElementById('survey-modal').classList.remove('hidden');
      
      // Load existing questions
      try {
        const response = await apiRequest(`/courses/${courseId}/survey`);
        surveyQuestions = response.questions || [];
        renderSurveyQuestions();
      } catch (error) {
        surveyQuestions = [];
        renderSurveyQuestions();
      }
    }

    window.closeSurveyModal = function() {
      document.getElementById('survey-modal').classList.add('hidden');
      currentSurveyCourseId = null;
      surveyQuestions = [];
    }

    window.addSurveyQuestion = function() {
      const newQuestion = {
        id: `new_${questionIdCounter++}`,
        question: '',
        question_type: 'rating',
        is_required: false,
        options: [],
        order_index: surveyQuestions.length
      };
      surveyQuestions.push(newQuestion);
      renderSurveyQuestions();
    }

    window.removeSurveyQuestion = function(index) {
      if (confirm('Remove this question?')) {
        surveyQuestions.splice(index, 1);
        renderSurveyQuestions();
      }
    }

    window.moveQuestion = function(index, direction) {
      const newIndex = index + direction;
      if (newIndex < 0 || newIndex >= surveyQuestions.length) return;
      
      [surveyQuestions[index], surveyQuestions[newIndex]] = [surveyQuestions[newIndex], surveyQuestions[index]];
      renderSurveyQuestions();
    }

    window.renderSurveyQuestions = function() {
      const container = document.getElementById('survey-questions-list');
      
      if (surveyQuestions.length === 0) {
        container.innerHTML = `
          <div style="text-align: center; padding: 40px; color: #9ca3af;">
            <i class="fas fa-clipboard-question" style="font-size: 48px; margin-bottom: 15px; opacity: 0.5;"></i>
            <p>No questions yet. Click "Add Question" to get started.</p>
          </div>
        `;
        return;
      }

      container.innerHTML = surveyQuestions.map((q, index) => `
        <div class="survey-question-item" style="background: #f9fafb; border: 1px solid #e5e7eb; border-radius: 8px; padding: 20px; margin-bottom: 15px;">
          <div style="display: flex; justify-content: between; align-items: flex-start; margin-bottom: 15px;">
            <div style="flex: 1;">
              <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #374151;">
                Question ${index + 1}
              </label>
              <input type="text" 
                     value="${q.question}" 
                     onchange="surveyQuestions[${index}].question = this.value"
                     placeholder="Enter your question"
                     class="form-control" 
                     style="margin-bottom: 10px;">
            </div>
            <div style="display: flex; gap: 5px; margin-left: 10px;">
              <button type="button" onclick="moveQuestion(${index}, -1)" ${index === 0 ? 'disabled' : ''} class="icon-btn" title="Move Up">
                <i class="fas fa-arrow-up"></i>
              </button>
              <button type="button" onclick="moveQuestion(${index}, 1)" ${index === surveyQuestions.length - 1 ? 'disabled' : ''} class="icon-btn" title="Move Down">
                <i class="fas fa-arrow-down"></i>
              </button>
              <button type="button" onclick="removeSurveyQuestion(${index})" class="icon-btn icon-btn-danger" title="Remove">
                <i class="fas fa-trash"></i>
              </button>
            </div>
          </div>

          <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
            <div class="form-group">
              <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #374151;">Question Type</label>
              <select onchange="surveyQuestions[${index}].question_type = this.value; renderSurveyQuestions();" 
                      class="form-control">
                <option value="rating" ${q.question_type === 'rating' ? 'selected' : ''}>⭐ Rating (1-5)</option>
                <option value="text" ${q.question_type === 'text' ? 'selected' : ''}>📝 Text Response</option>
                <option value="multiple_choice" ${q.question_type === 'multiple_choice' ? 'selected' : ''}>☑️ Multiple Choice</option>
              </select>
            </div>

            <div class="form-group">
              <label style="display: flex; align-items: center; cursor: pointer; padding-top: 28px;">
                <input type="checkbox" 
                       ${q.is_required ? 'checked' : ''} 
                       onchange="surveyQuestions[${index}].is_required = this.checked"
                       style="margin-right: 8px;">
                <span style="font-weight: 600; color: #374151;">Required Question</span>
              </label>
            </div>
          </div>

          ${q.question_type === 'multiple_choice' ? `
            <div class="form-group" style="margin-top: 15px;">
              <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #374151;">Options (one per line)</label>
              <textarea 
                onchange="surveyQuestions[${index}].options = this.value.split('\\n').filter(o => o.trim())"
                rows="3" 
                class="form-control" 
                placeholder="Option 1&#10;Option 2&#10;Option 3">${Array.isArray(q.options) ? q.options.join('\\n') : ''}</textarea>
            </div>
          ` : ''}

          <div style="margin-top: 10px; padding: 10px; background: white; border-radius: 4px; border: 1px dashed #d1d5db;">
            <small style="color: #6b7280; font-weight: 600;">Preview:</small>
            <div style="margin-top: 8px; color: #374151;">
              ${q.question || '<em style="color: #9ca3af;">Question preview will appear here...</em>'}
              ${q.is_required ? '<span style="color: #ef4444;">*</span>' : ''}
            </div>
          </div>
        </div>
      `).join('');
    }

    window.saveSurveyQuestions = async function() {
      if (!currentSurveyCourseId) return;

      // Validate
      const invalidQuestions = surveyQuestions.filter(q => !q.question.trim());
      if (invalidQuestions.length > 0) {
        showToast('Please fill in all questions', 'error');
        return;
      }

      const multipleChoiceWithoutOptions = surveyQuestions.filter(q => 
        q.question_type === 'multiple_choice' && (!q.options || q.options.length === 0)
      );
      if (multipleChoiceWithoutOptions.length > 0) {
        showToast('Multiple choice questions must have at least one option', 'error');
        return;
      }

      try {
        await apiRequest(`/courses/${currentSurveyCourseId}/survey/questions`, 'POST', {
          questions: surveyQuestions.map((q, index) => ({
            question: q.question,
            question_type: q.question_type,
            is_required: q.is_required,
            options: q.question_type === 'multiple_choice' ? q.options : null,
            order_index: index
          }))
        });

        showToast('Survey questions saved successfully!', 'success');
        closeSurveyModal();
      } catch (error) {
        showToast(error.message || 'Error saving survey questions', 'error');
      }
    }

    // Tab Switching
    document.querySelectorAll('.tab-btn').forEach(btn => {
      btn.addEventListener('click', function() {
        const tabName = this.getAttribute('data-tab');
        
        // Update button styles
        document.querySelectorAll('.tab-btn').forEach(b => {
          b.style.background = 'transparent';
          b.style.color = 'rgba(255,255,255,0.7)';
          b.classList.remove('active');
        });
        this.style.background = 'rgba(255,255,255,0.2)';
        this.style.color = 'white';
        this.classList.add('active');
        
        // Show/hide tab content
        document.querySelectorAll('.tab-content').forEach(content => {
          content.classList.add('hidden');
        });
        document.getElementById(tabName + '-tab').classList.remove('hidden');
      });
    });

    // Manage Course Content - Switch to Lessons & Topics tab
    window.manageCourseContent = function(courseId) {
      // Navigate to courses section
      document.querySelector('.admin-nav[data-section="courses"]').click();
      
      // Wait a moment for section to load, then switch to Lessons & Topics tab
      setTimeout(() => {
        document.querySelector('.tab-btn[data-tab="lessons-topics"]').click();
        
        // Select the course in dropdown
        const dropdown = document.getElementById('content-course-filter');
        if (dropdown) {
          dropdown.value = courseId;
          dropdown.dispatchEvent(new Event('change'));
          loadCourseLessons(courseId);
        }
      }, 100);
    }

    // Generic modal functions
    window.openModal = function(modalId) {
      const modal = document.getElementById(modalId);
      if (modal) {
        modal.classList.add('active');
        modal.classList.remove('hidden');
      }
    }

    // =============================================
    // BADGE MANAGEMENT FUNCTIONS
    // =============================================

    let allBadges = [];
    let badgeStats = {};

    async function loadBadges() {
      try {
        // Load badge data
        const response = await fetch('/admin/badges/all', {
          headers: {
            'Accept': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
          }
        });

        if (!response.ok) throw new Error('Failed to load badges');

        const data = await response.json();
        allBadges = data.badges || [];
        badgeStats = data.stats || {};

        // Update statistics
        updateBadgeStats();

        // Display badges
        displayBadges(allBadges);

        // Setup badge tab switching
        setupBadgeTabs();

        // Setup badge filters
        setupBadgeFilters();

        // Setup create badge form
        setupCreateBadgeForm();

        // Load leaderboard
        loadLeaderboard();

      } catch (error) {
        console.error('Error loading badges:', error);
        showToast('Error loading badges', 'error');
      }
    }

    function updateBadgeStats() {
      document.getElementById('total-badges-count').textContent = badgeStats.total_badges || allBadges.length;
      document.getElementById('active-badges-count').textContent = allBadges.filter(b => b.is_active).length;
      document.getElementById('total-points-count').textContent = allBadges.reduce((sum, b) => sum + (b.points || 0), 0);
      document.getElementById('badges-earned-count').textContent = badgeStats.total_awarded || 0;
    }

    function displayBadges(badges) {
      const grid = document.getElementById('badges-grid');
      if (!grid) return;

      if (badges.length === 0) {
        grid.innerHTML = `
          <div style="grid-column: 1 / -1; text-align: center; padding: 40px; color: #666;">
            <i class="fas fa-trophy" style="font-size: 48px; margin-bottom: 16px; opacity: 0.3;"></i>
            <p style="font-size: 18px;">No badges found</p>
          </div>
        `;
        return;
      }

      grid.innerHTML = badges.map(badge => `
        <div class="badge-card" data-badge-id="${badge.id}" style="background: white; border-radius: 12px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); transition: transform 0.2s, box-shadow 0.2s; cursor: pointer; position: relative;">
          <div style="position: absolute; top: 12px; right: 12px; display: flex; gap: 8px;">
            ${badge.is_active 
              ? '<span style="background: #10b981; color: white; padding: 4px 8px; border-radius: 6px; font-size: 11px; font-weight: 600;">ACTIVE</span>'
              : '<span style="background: #6b7280; color: white; padding: 4px 8px; border-radius: 6px; font-size: 11px; font-weight: 600;">INACTIVE</span>'
            }
          </div>
          
          <div style="text-align: center; margin-bottom: 16px;">
            <div style="font-size: 48px; margin-bottom: 8px;">${badge.icon}</div>
            <h3 style="font-size: 18px; font-weight: 600; color: #333; margin-bottom: 4px;">${badge.name}</h3>
            <p style="color: #666; font-size: 13px; line-height: 1.4;">${badge.description}</p>
          </div>

          <div style="display: flex; justify-content: space-between; align-items: center; padding-top: 16px; border-top: 1px solid #e5e7eb;">
            <div>
              <span style="display: inline-block; padding: 4px 10px; background: ${badge.color}20; color: ${badge.color}; border-radius: 6px; font-size: 12px; font-weight: 600;">
                ${badge.points} pts
              </span>
              <span style="display: inline-block; padding: 4px 10px; background: #f3f4f6; color: #666; border-radius: 6px; font-size: 12px; margin-left: 6px;">
                ${badge.category}
              </span>
            </div>
            <div style="display: flex; gap: 8px;">
              <button onclick="editBadge(${badge.id})" class="icon-btn icon-btn-primary" title="Edit Badge" style="padding: 6px 10px; background: #667eea; color: white; border: none; border-radius: 6px; cursor: pointer; transition: background 0.2s;">
                <i class="fas fa-edit"></i>
              </button>
              <button onclick="toggleBadgeStatus(${badge.id}, ${badge.is_active ? 'false' : 'true'})" class="icon-btn ${badge.is_active ? 'icon-btn-warning' : 'icon-btn-success'}" title="${badge.is_active ? 'Deactivate' : 'Activate'}" style="padding: 6px 10px; background: ${badge.is_active ? '#f59e0b' : '#10b981'}; color: white; border: none; border-radius: 6px; cursor: pointer; transition: background 0.2s;">
                <i class="fas fa-${badge.is_active ? 'pause' : 'play'}"></i>
              </button>
              <button onclick="deleteBadge(${badge.id}, '${badge.name.replace(/'/g, "\\'")}') "class="icon-btn icon-btn-danger" title="Delete Badge" style="padding: 6px 10px; background: #ef4444; color: white; border: none; border-radius: 6px; cursor: pointer; transition: background 0.2s;">
                <i class="fas fa-trash"></i>
              </button>
            </div>
          </div>

          <div style="margin-top: 12px; padding-top: 12px; border-top: 1px solid #e5e7eb;">
            <div style="font-size: 12px; color: #666; margin-bottom: 4px;">Awarded to <strong>${badge.users_count || 0}</strong> students</div>
            ${badge.criteria ? `
              <div style="font-size: 11px; color: #999; background: #f9fafb; padding: 6px 10px; border-radius: 6px; margin-top: 6px;">
                <strong>Criteria:</strong> ${formatCriteria(badge.criteria)}
              </div>
            ` : ''}
          </div>
        </div>
      `).join('');

      // Add hover effects
      document.querySelectorAll('.badge-card').forEach(card => {
        card.addEventListener('mouseenter', function() {
          this.style.transform = 'translateY(-4px)';
          this.style.boxShadow = '0 8px 16px rgba(0,0,0,0.15)';
        });
        card.addEventListener('mouseleave', function() {
          this.style.transform = 'translateY(0)';
          this.style.boxShadow = '0 2px 8px rgba(0,0,0,0.1)';
        });
      });
    }

    function formatCriteria(criteriaObj) {
      if (!criteriaObj || typeof criteriaObj !== 'object') return 'N/A';
      
      const type = criteriaObj.type || 'unknown';
      const value = criteriaObj.value || criteriaObj.required_count || '';

      const labels = {
        'course_completion': 'Complete a course',
        'course_count': `Complete ${value} courses`,
        'quiz_score': `Score ${value}% or higher on quiz`,
        'perfect_score': 'Get 100% on a quiz',
        'speed_completion': `Complete within ${value} hours`,
        'streak': `Maintain ${value} day streak`,
        'lesson_count': `Complete ${value} lessons`
      };

      return labels[type] || type;
    }

    function setupBadgeTabs() {
      const tabs = document.querySelectorAll('.badge-tab');
      const contents = document.querySelectorAll('.badge-tab-content');

      tabs.forEach(tab => {
        tab.addEventListener('click', function() {
          const tabName = this.getAttribute('data-tab');

          // Update tab styles
          tabs.forEach(t => {
            t.style.borderBottomColor = 'transparent';
            t.style.color = '#666';
            t.classList.remove('active');
          });
          this.style.borderBottomColor = '#667eea';
          this.style.color = '#667eea';
          this.classList.add('active');

          // Show/hide content
          contents.forEach(content => {
            content.classList.add('hidden');
          });
          document.getElementById(tabName).classList.remove('hidden');
        });
      });
    }

    function setupBadgeFilters() {
      const categoryFilter = document.getElementById('badge-category-filter');
      const statusFilter = document.getElementById('badge-status-filter');

      if (categoryFilter) {
        categoryFilter.addEventListener('change', filterBadges);
      }
      if (statusFilter) {
        statusFilter.addEventListener('change', filterBadges);
      }
    }

    function filterBadges() {
      const category = document.getElementById('badge-category-filter')?.value || 'all';
      const status = document.getElementById('badge-status-filter')?.value || 'all';

      let filtered = allBadges;

      if (category !== 'all') {
        filtered = filtered.filter(b => b.category === category);
      }

      if (status === 'active') {
        filtered = filtered.filter(b => b.is_active === true || b.is_active === 1);
      } else if (status === 'inactive') {
        filtered = filtered.filter(b => b.is_active === false || b.is_active === 0);
      }

      displayBadges(filtered);
    }

    function setupCreateBadgeForm() {
      const form = document.getElementById('create-badge-form');
      const criteriaTypeSelect = document.getElementById('badge-criteria-type');
      const criteriaValueField = document.getElementById('criteria-value-field');

      if (criteriaTypeSelect) {
        criteriaTypeSelect.addEventListener('change', function() {
          const needsValue = ['course_count', 'quiz_score', 'speed_completion', 'streak', 'lesson_count'].includes(this.value);
          if (needsValue) {
            criteriaValueField.style.display = 'block';
          } else {
            criteriaValueField.style.display = 'none';
          }
        });
      }

      if (form) {
        form.addEventListener('submit', async function(e) {
          e.preventDefault();

          const formData = {
            name: document.getElementById('badge-name').value,
            description: document.getElementById('badge-description').value,
            icon: document.getElementById('badge-icon').value,
            color: document.getElementById('badge-color').value,
            category: document.getElementById('badge-category').value,
            points: parseInt(document.getElementById('badge-points').value),
            is_active: document.getElementById('badge-active').checked ? 1 : 0,
            criteria: {
              type: document.getElementById('badge-criteria-type').value
            }
          };

          const criteriaValue = document.getElementById('badge-criteria-value').value;
          if (criteriaValue) {
            formData.criteria.value = parseInt(criteriaValue);
          }

          try {
            const response = await fetch('/admin/badges', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
              },
              body: JSON.stringify(formData)
            });

            if (!response.ok) throw new Error('Failed to create badge');

            const data = await response.json();
            showToast(data.message || 'Badge created successfully!', 'success');

            // Reset form
            form.reset();
            document.getElementById('badge-active').checked = true;
            document.getElementById('badge-color').value = '#667eea';

            // Reload badges
            await loadBadges();

            // Switch to all badges tab
            document.querySelector('.badge-tab[data-tab="all-badges"]').click();

          } catch (error) {
            console.error('Error creating badge:', error);
            showToast('Failed to create badge', 'error');
          }
        });
      }
    }

    window.editBadge = async function(badgeId) {
      const badge = allBadges.find(b => b.id === badgeId);
      if (!badge) return;

      // Switch to create tab
      document.querySelector('.badge-tab[data-tab="create-badge"]').click();

      // Populate form
      setTimeout(() => {
        document.getElementById('badge-name').value = badge.name;
        document.getElementById('badge-description').value = badge.description;
        document.getElementById('badge-icon').value = badge.icon;
        document.getElementById('badge-color').value = badge.color;
        document.getElementById('badge-category').value = badge.category;
        document.getElementById('badge-points').value = badge.points;
        document.getElementById('badge-active').checked = badge.is_active;

        if (badge.criteria) {
          document.getElementById('badge-criteria-type').value = badge.criteria.type || '';
          if (badge.criteria.value) {
            document.getElementById('badge-criteria-value').value = badge.criteria.value;
            document.getElementById('criteria-value-field').style.display = 'block';
          }
        }
      }, 100);
    }

    window.toggleBadgeStatus = async function(badgeId, isActive) {
      try {
        const response = await fetch(`/admin/badges/${badgeId}/toggle`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
          },
          body: JSON.stringify({ is_active: isActive })
        });

        if (!response.ok) throw new Error('Failed to update badge status');

        const data = await response.json();
        showToast(data.message || 'Badge status updated!', 'success');

        // Reload badges
        await loadBadges();

      } catch (error) {
        console.error('Error toggling badge status:', error);
        showToast('Failed to update badge status', 'error');
      }
    }

    window.deleteBadge = async function(badgeId, badgeName) {
      if (!confirm(`Are you sure you want to delete the badge "${badgeName}"?\n\nThis will remove it from all users who have earned it.`)) {
        return;
      }

      try {
        const response = await fetch(`/admin/badges/${badgeId}`, {
          method: 'DELETE',
          headers: {
            'Accept': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
          }
        });

        if (!response.ok) throw new Error('Failed to delete badge');

        const data = await response.json();
        showToast(data.message || 'Badge deleted successfully!', 'success');

        // Reload badges
        await loadBadges();

      } catch (error) {
        console.error('Error deleting badge:', error);
        showToast('Failed to delete badge', 'error');
      }
    }

    async function loadLeaderboard() {
      try {
        const response = await fetch('/admin/badges/leaderboard', {
          headers: {
            'Accept': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
          }
        });

        if (!response.ok) throw new Error('Failed to load leaderboard');

        const data = await response.json();
        displayLeaderboard(data.leaderboard || []);

      } catch (error) {
        console.error('Error loading leaderboard:', error);
        document.getElementById('leaderboard-list').innerHTML = `
          <div style="text-align: center; padding: 40px; color: #666;">
            <i class="fas fa-exclamation-circle" style="font-size: 48px; margin-bottom: 16px; opacity: 0.3;"></i>
            <p>Failed to load leaderboard</p>
          </div>
        `;
      }
    }

    function displayLeaderboard(leaderboard) {
      const list = document.getElementById('leaderboard-list');
      if (!list) return;

      if (leaderboard.length === 0) {
        list.innerHTML = `
          <div style="text-align: center; padding: 40px; color: #666;">
            <i class="fas fa-trophy" style="font-size: 48px; margin-bottom: 16px; opacity: 0.3;"></i>
            <p>No students have earned badges yet</p>
          </div>
        `;
        return;
      }

      list.innerHTML = leaderboard.map((user, index) => {
        const medalColors = ['#FFD700', '#C0C0C0', '#CD7F32'];
        const medal = index < 3 ? medalColors[index] : 'transparent';
        
        return `
          <div style="background: white; border-radius: 10px; padding: 16px 20px; margin-bottom: 12px; display: flex; align-items: center; justify-content: space-between; box-shadow: 0 2px 4px rgba(0,0,0,0.05); ${index < 3 ? 'border-left: 4px solid ' + medal : ''}">
            <div style="display: flex; align-items: center; gap: 16px;">
              <div style="font-size: 24px; font-weight: 700; color: ${index < 3 ? medal : '#999'}; min-width: 40px; text-align: center;">
                ${index < 3 ? '🏆' : (index + 1)}
              </div>
              <div>
                <div style="font-size: 16px; font-weight: 600; color: #333; margin-bottom: 4px;">
                  ${user.name}
                </div>
                <div style="font-size: 13px; color: #666;">
                  ${user.email}
                </div>
              </div>
            </div>
            <div style="text-align: right;">
              <div style="font-size: 20px; font-weight: 700; color: #667eea; margin-bottom: 2px;">
                ${user.total_points || 0} pts
              </div>
              <div style="font-size: 13px; color: #666;">
                ${user.badge_count || 0} badges
              </div>
            </div>
          </div>
        `;
      }).join('');
    }

    window.closeModal = function(modalId) {
      const modal = document.getElementById(modalId);
      if (modal) {
        modal.classList.remove('active');
        modal.classList.add('hidden');
      }
    }

    // =============================================
    // PENALTY MANAGEMENT FUNCTIONS
    // =============================================

    let allPenalties = { rules: [], cards: [], stats: {} };

    async function loadPenalties() {
      try {
        console.log('Loading penalties...');
        
        // Load penalty data
        const [rulesRes, cardsRes, statsRes] = await Promise.all([
          fetch('/admin/penalties/rules', {
            headers: {
              'Accept': 'application/json',
              'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
            }
          }),
          fetch('/admin/penalties/cards', {
            headers: {
              'Accept': 'application/json',
              'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
            }
          }),
          fetch('/admin/penalties/stats', {
            headers: {
              'Accept': 'application/json',
              'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
            }
          })
        ]);

        console.log('Response statuses:', {
          rules: rulesRes.status,
          cards: cardsRes.status,
          stats: statsRes.status
        });

        if (!rulesRes.ok) {
          const errorText = await rulesRes.text();
          console.error('Rules error:', errorText);
          throw new Error(`Failed to load rules: ${rulesRes.status}`);
        }
        if (!cardsRes.ok) {
          const errorText = await cardsRes.text();
          console.error('Cards error:', errorText);
          throw new Error(`Failed to load cards: ${cardsRes.status}`);
        }
        if (!statsRes.ok) {
          const errorText = await statsRes.text();
          console.error('Stats error:', errorText);
          throw new Error(`Failed to load stats: ${statsRes.status}`);
        }

        const rulesData = await rulesRes.json();
        const cardsData = await cardsRes.json();
        const statsData = await statsRes.json();

        console.log('Loaded data:', { rulesData, cardsData, statsData });

        allPenalties.rules = rulesData.rules || [];
        allPenalties.cards = cardsData.cards || [];
        allPenalties.stats = statsData.stats || {};

        // Update statistics
        updatePenaltyStats();

        // Display data
        displayPenaltyRules(allPenalties.rules);
        displayIssuedCards(allPenalties.cards);
        displayPenaltyStatistics();

        // Setup tabs and forms
        setupPenaltyTabs();
        setupCreatePenaltyRuleForm();
        setupPenaltyFilters();

        console.log('Penalties loaded successfully');

      } catch (error) {
        console.error('Error loading penalties:', error);
        showToast('Error loading penalty data: ' + error.message, 'error');
      }
    }

    function updatePenaltyStats() {
      const stats = allPenalties.stats;
      document.getElementById('total-penalty-cards').textContent = stats.total_cards_issued || 0;
      document.getElementById('yellow-cards-count').textContent = stats.yellow_cards || 0;
      document.getElementById('red-cards-count').textContent = stats.red_cards || 0;
      document.getElementById('total-points-deducted').textContent = stats.total_points_deducted || 0;
    }

    function setupPenaltyTabs() {
      const tabs = document.querySelectorAll('[data-penalty-tab]');
      tabs.forEach(tab => {
        tab.addEventListener('click', () => {
          // Remove active class from all tabs
          tabs.forEach(t => t.classList.remove('active'));
          document.querySelectorAll('.penalty-tab-content').forEach(c => c.classList.add('hidden'));

          // Add active class to clicked tab
          tab.classList.add('active');
          const tabId = tab.dataset.penaltyTab;
          const content = document.getElementById(`${tabId}-tab`);
          if (content) content.classList.remove('hidden');
        });
      });
    }

    function displayPenaltyRules(rules) {
      const list = document.getElementById('penalty-rules-list');
      if (!list) return;

      if (rules.length === 0) {
        list.innerHTML = `
          <div style="text-align: center; padding: 40px; color: #666;">
            <i class="fas fa-exclamation-triangle" style="font-size: 48px; margin-bottom: 16px; opacity: 0.3;"></i>
            <p>No penalty rules configured</p>
          </div>
        `;
        return;
      }

      list.innerHTML = rules.map(rule => `
        <div class="rule-item" style="background: white; border-radius: 10px; padding: 20px; margin-bottom: 12px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); border-left: 4px solid ${rule.card_type === 'yellow' ? '#f59e0b' : '#ef4444'};">
          <div style="display: flex; justify-content: space-between; align-items: start;">
            <div style="flex: 1;">
              <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 8px;">
                <span style="font-size: 24px;">${rule.card_type === 'yellow' ? '⚠️' : '🚫'}</span>
                <h4 style="font-size: 18px; font-weight: 600; color: #333;">${rule.name}</h4>
                ${rule.is_active 
                  ? '<span style="background: #10b981; color: white; padding: 4px 8px; border-radius: 6px; font-size: 11px; font-weight: 600;">ACTIVE</span>'
                  : '<span style="background: #6b7280; color: white; padding: 4px 8px; border-radius: 6px; font-size: 11px; font-weight: 600;">INACTIVE</span>'
                }
              </div>
              <p style="color: #666; margin-bottom: 12px;">${rule.description}</p>
              <div style="display: flex; gap: 16px; flex-wrap: wrap;">
                <span style="font-size: 13px; color: #555;">
                  <strong>Trigger:</strong> ${rule.trigger_type.replace('_', ' ')}
                </span>
                <span style="font-size: 13px; color: #555;">
                  <strong>Threshold:</strong> ${rule.threshold_value} days
                </span>
                <span style="font-size: 13px; color: #555;">
                  <strong>Points:</strong> -${rule.points_deduction}
                </span>
                ${rule.escalation_days ? `
                  <span style="font-size: 13px; color: #e11d48;">
                    <strong>Escalates in:</strong> ${rule.escalation_days} days (-${rule.escalation_points} pts)
                  </span>
                ` : ''}
              </div>
            </div>
            <div style="display: flex; gap: 8px;">
              <button onclick="editPenaltyRule(${rule.id})" class="btn-icon" title="Edit Rule">
                <i class="fas fa-edit"></i>
              </button>
              <button onclick="togglePenaltyRule(${rule.id}, ${!rule.is_active})" 
                      class="btn-icon" 
                      title="${rule.is_active ? 'Deactivate' : 'Activate'} Rule">
                <i class="fas fa-${rule.is_active ? 'pause' : 'play'}"></i>
              </button>
              <button onclick="deletePenaltyRule(${rule.id})" class="btn-icon" title="Delete Rule">
                <i class="fas fa-trash"></i>
              </button>
            </div>
          </div>
        </div>
      `).join('');
    }

    function displayIssuedCards(cards) {
      const tbody = document.getElementById('issued-cards-tbody');
      if (!tbody) return;

      if (cards.length === 0) {
        tbody.innerHTML = `
          <tr>
            <td colspan="7" style="text-align: center; padding: 40px; color: #666;">
              <i class="fas fa-inbox" style="font-size: 48px; margin-bottom: 16px; opacity: 0.3; display: block;"></i>
              <p>No penalty cards issued yet</p>
            </td>
          </tr>
        `;
        return;
      }

      tbody.innerHTML = cards.map(card => {
        const cardColor = card.card_type === 'yellow' ? '#f59e0b' : '#ef4444';
        const statusColor = card.status === 'active' ? '#10b981' : '#6b7280';
        
        return `
          <tr>
            <td style="padding: 12px;">
              <span style="display: inline-block; padding: 6px 12px; background: ${cardColor}20; color: ${cardColor}; border-radius: 6px; font-weight: 600; font-size: 13px;">
                ${card.card_type === 'yellow' ? '⚠️ YELLOW' : '🚫 RED'}
              </span>
            </td>
            <td style="padding: 12px;">
              <div style="font-weight: 500; color: #333;">${card.user_name}</div>
              <div style="font-size: 12px; color: #666;">${card.user_email}</div>
            </td>
            <td style="padding: 12px; max-width: 200px;">
              <div style="font-size: 13px; color: #555;">${card.reason}</div>
            </td>
            <td style="padding: 12px;">
              <span style="color: #e11d48; font-weight: 600;">-${card.points_deducted} pts</span>
            </td>
            <td style="padding: 12px;">
              <div style="font-size: 13px; color: #555;">${new Date(card.issued_at).toLocaleDateString()}</div>
              <div style="font-size: 11px; color: #999;">${new Date(card.issued_at).toLocaleTimeString()}</div>
            </td>
            <td style="padding: 12px;">
              <span style="display: inline-block; padding: 4px 10px; background: ${statusColor}20; color: ${statusColor}; border-radius: 6px; font-size: 12px; font-weight: 600; text-transform: uppercase;">
                ${card.status}
              </span>
            </td>
            <td style="padding: 12px;">
              <div style="display: flex; gap: 8px;">
                <button onclick="viewCardDetails(${card.id})" class="btn-icon-sm" title="View Details">
                  <i class="fas fa-eye"></i>
                </button>
                ${card.status === 'active' ? `
                  <button onclick="revokePenaltyCard(${card.id})" class="btn-icon-sm" title="Revoke Card">
                    <i class="fas fa-times-circle"></i>
                  </button>
                ` : ''}
              </div>
            </td>
          </tr>
        `;
      }).join('');
    }

    function displayPenaltyStatistics() {
      const stats = allPenalties.stats;
      
      // Update detailed stats
      const detailedStats = document.getElementById('detailed-penalty-stats');
      if (detailedStats) {
        detailedStats.innerHTML = `
          <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 30px;">
            <div style="background: white; padding: 20px; border-radius: 10px; border-left: 4px solid #f59e0b;">
              <div style="font-size: 28px; font-weight: 700; color: #f59e0b; margin-bottom: 4px;">
                ${stats.yellow_cards || 0}
              </div>
              <div style="font-size: 13px; color: #666; text-transform: uppercase; letter-spacing: 0.5px;">
                Yellow Cards Issued
              </div>
            </div>
            <div style="background: white; padding: 20px; border-radius: 10px; border-left: 4px solid #ef4444;">
              <div style="font-size: 28px; font-weight: 700; color: #ef4444; margin-bottom: 4px;">
                ${stats.red_cards || 0}
              </div>
              <div style="font-size: 13px; color: #666; text-transform: uppercase; letter-spacing: 0.5px;">
                Red Cards Issued
              </div>
            </div>
            <div style="background: white; padding: 20px; border-radius: 10px; border-left: 4px solid #8b5cf6;">
              <div style="font-size: 28px; font-weight: 700; color: #8b5cf6; margin-bottom: 4px;">
                ${stats.users_with_cards || 0}
              </div>
              <div style="font-size: 13px; color: #666; text-transform: uppercase; letter-spacing: 0.5px;">
                Users Affected
              </div>
            </div>
            <div style="background: white; padding: 20px; border-radius: 10px; border-left: 4px solid #10b981;">
              <div style="font-size: 28px; font-weight: 700; color: #10b981; margin-bottom: 4px;">
                ${stats.escalations_count || 0}
              </div>
              <div style="font-size: 13px; color: #666; text-transform: uppercase; letter-spacing: 0.5px;">
                Cards Escalated
              </div>
            </div>
          </div>
        `;
      }

      // Recent activity
      const recentActivity = document.getElementById('recent-penalty-activity');
      if (recentActivity && stats.recent_cards) {
        if (stats.recent_cards.length === 0) {
          recentActivity.innerHTML = `
            <div style="text-align: center; padding: 40px; color: #666;">
              <p>No recent penalty activity</p>
            </div>
          `;
        } else {
          recentActivity.innerHTML = stats.recent_cards.map(card => `
            <div style="background: white; padding: 16px; border-radius: 8px; margin-bottom: 12px; border-left: 3px solid ${card.card_type === 'yellow' ? '#f59e0b' : '#ef4444'};">
              <div style="display: flex; justify-content: space-between; align-items: start;">
                <div>
                  <div style="font-weight: 600; color: #333; margin-bottom: 4px;">
                    ${card.card_type === 'yellow' ? '⚠️' : '🚫'} ${card.user_name} - ${card.card_type.toUpperCase()} CARD
                  </div>
                  <div style="font-size: 13px; color: #666; margin-bottom: 4px;">
                    ${card.reason}
                  </div>
                  <div style="font-size: 12px; color: #999;">
                    ${new Date(card.issued_at).toLocaleString()}
                  </div>
                </div>
                <div style="text-align: right;">
                  <div style="color: #e11d48; font-weight: 600;">-${card.points_deducted} pts</div>
                </div>
              </div>
            </div>
          `).join('');
        }
      }
    }

    function setupCreatePenaltyRuleForm() {
      const form = document.getElementById('create-penalty-rule-form');
      if (!form) return;

      form.addEventListener('submit', async (e) => {
        e.preventDefault();
        await createPenaltyRule(new FormData(form));
      });

      // Toggle escalation fields
      const cardTypeSelect = form.querySelector('[name="card_type"]');
      const escalationFields = document.getElementById('escalation-fields');
      
      if (cardTypeSelect && escalationFields) {
        cardTypeSelect.addEventListener('change', (e) => {
          if (e.target.value === 'yellow') {
            escalationFields.classList.remove('hidden');
          } else {
            escalationFields.classList.add('hidden');
          }
        });
      }
    }

    function setupPenaltyFilters() {
      const cardTypeFilter = document.getElementById('filter-card-type');
      const statusFilter = document.getElementById('filter-card-status');

      const applyFilters = () => {
        let filtered = [...allPenalties.cards];

        if (cardTypeFilter && cardTypeFilter.value !== 'all') {
          filtered = filtered.filter(c => c.card_type === cardTypeFilter.value);
        }

        if (statusFilter && statusFilter.value !== 'all') {
          filtered = filtered.filter(c => c.status === statusFilter.value);
        }

        displayIssuedCards(filtered);
      };

      if (cardTypeFilter) cardTypeFilter.addEventListener('change', applyFilters);
      if (statusFilter) statusFilter.addEventListener('change', applyFilters);
    }

    async function createPenaltyRule(formData) {
      try {
        const response = await fetch('/admin/penalties/rules', {
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
          },
          body: formData
        });

        if (!response.ok) throw new Error('Failed to create penalty rule');

        const data = await response.json();
        showToast('Penalty rule created successfully', 'success');
        
        // Reload penalties
        await loadPenalties();
        
        // Reset form and switch to rules tab
        document.getElementById('create-penalty-rule-form').reset();
        document.querySelector('[data-penalty-tab="penalty-rules"]').click();

      } catch (error) {
        console.error('Error creating penalty rule:', error);
        showToast('Error creating penalty rule', 'error');
      }
    }

    async function editPenaltyRule(ruleId) {
      const rule = allPenalties.rules.find(r => r.id === ruleId);
      if (!rule) return;

      // TODO: Implement edit modal or inline editing
      showToast('Edit functionality coming soon', 'info');
    }

    async function togglePenaltyRule(ruleId, activate) {
      try {
        const response = await fetch(`/admin/penalties/rules/${ruleId}/toggle`, {
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
          },
          body: JSON.stringify({ is_active: activate })
        });

        if (!response.ok) throw new Error('Failed to toggle penalty rule');

        showToast(`Rule ${activate ? 'activated' : 'deactivated'} successfully`, 'success');
        await loadPenalties();

      } catch (error) {
        console.error('Error toggling penalty rule:', error);
        showToast('Error updating penalty rule', 'error');
      }
    }

    async function deletePenaltyRule(ruleId) {
      if (!confirm('Are you sure you want to delete this penalty rule? This action cannot be undone.')) {
        return;
      }

      try {
        const response = await fetch(`/admin/penalties/rules/${ruleId}`, {
          method: 'DELETE',
          headers: {
            'Accept': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
          }
        });

        if (!response.ok) throw new Error('Failed to delete penalty rule');

        showToast('Penalty rule deleted successfully', 'success');
        await loadPenalties();

      } catch (error) {
        console.error('Error deleting penalty rule:', error);
        showToast('Error deleting penalty rule', 'error');
      }
    }

    async function revokePenaltyCard(cardId) {
      const reason = prompt('Enter reason for revoking this penalty card:');
      if (!reason) return;

      try {
        const response = await fetch(`/admin/penalties/cards/${cardId}/revoke`, {
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
          },
          body: JSON.stringify({ reason })
        });

        if (!response.ok) throw new Error('Failed to revoke penalty card');

        showToast('Penalty card revoked successfully', 'success');
        await loadPenalties();

      } catch (error) {
        console.error('Error revoking penalty card:', error);
        showToast('Error revoking penalty card', 'error');
      }
    }

    async function viewCardDetails(cardId) {
      const card = allPenalties.cards.find(c => c.id === cardId);
      if (!card) return;

      // TODO: Implement modal with full card details including history
      alert(`Card Details:\n\nType: ${card.card_type}\nUser: ${card.user_name}\nReason: ${card.reason}\nPoints: -${card.points_deducted}\nIssued: ${card.issued_at}\nStatus: ${card.status}`);
    }

    async function runPenaltyCheck() {
      const btn = document.getElementById('run-penalty-check-btn');
      if (!btn) return;

      const originalText = btn.innerHTML;
      btn.disabled = true;
      btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Running Check...';

      try {
        const response = await fetch('/admin/penalties/check', {
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
          }
        });

        if (!response.ok) throw new Error('Failed to run penalty check');

        const data = await response.json();
        showToast(data.message || 'Penalty check completed', 'success');
        
        // Reload penalties to show new cards
        await loadPenalties();

      } catch (error) {
        console.error('Error running penalty check:', error);
        showToast('Error running penalty check', 'error');
      } finally {
        btn.disabled = false;
        btn.innerHTML = originalText;
      }
    }

    // Expose penalty functions globally
    window.editPenaltyRule = editPenaltyRule;
    window.togglePenaltyRule = togglePenaltyRule;
    window.deletePenaltyRule = deletePenaltyRule;
    window.revokePenaltyCard = revokePenaltyCard;
    window.viewCardDetails = viewCardDetails;
    window.runPenaltyCheck = runPenaltyCheck;

    // PAGE MANAGEMENT FUNCTIONS
    async function loadPages() {
      try {
        console.log('Loading pages from /admin/pages...');
        const response = await apiRequest('/admin/pages');
        console.log('Pages response:', response);
        const pages = response.pages || [];
        console.log('Pages array:', pages);
        displayPagesTable(pages);
      } catch (error) {
        console.error('Failed to load pages:', error);
        showToast('Failed to load pages: ' + error.message, 'error');
        // Show error in table
        const tbody = document.getElementById('pages-table-body');
        if (tbody) {
          tbody.innerHTML = `
            <tr>
              <td colspan="6" style="padding: 20px; text-align: center; color: #dc3545;">
                ❌ Error loading pages: ${escapeHtml(error.message)}
              </td>
            </tr>`;
        }
      }
    }

    function displayPagesTable(pages) {
      const tbody = document.getElementById('pages-table-body');
      
      if (!pages || pages.length === 0) {
        tbody.innerHTML = `
          <tr>
            <td colspan="6" style="padding: 20px; text-align: center; color: #6c757d;">
              📄 No pages found. Create your first page!
            </td>
          </tr>`;
        return;
      }

      tbody.innerHTML = pages.map(page => {
        const isStatic = page.is_static === 1;
        const isPublished = page.is_published === 1;
        const statusBadge = isPublished 
          ? '<span style="background: #d4edda; color: #155724; padding: 4px 8px; border-radius: 4px; font-size: 12px;">✓ Published</span>'
          : '<span style="background: #f8d7da; color: #721c24; padding: 4px 8px; border-radius: 4px; font-size: 12px;">○ Draft</span>';
        const staticBadge = isStatic ? '<span style="background: #e2e3e5; color: #383d41; padding: 4px 8px; border-radius: 4px; font-size: 12px; margin-left: 5px;">🔒 System</span>' : '';
        
        const createdDate = new Date(page.created_at).toLocaleDateString();
        const author = page.created_by || 'System';
        
        return `
          <tr style="border-bottom: 1px solid #dee2e6;">
            <td style="padding: 12px;">
              <strong>${escapeHtml(page.title)}</strong>
              ${staticBadge}
            </td>
            <td style="padding: 12px;">
              <code style="background: #f8f9fa; padding: 2px 6px; border-radius: 3px; font-size: 12px;">${escapeHtml(page.slug)}</code>
            </td>
            <td style="padding: 12px; text-align: center;">
              ${statusBadge}
            </td>
            <td style="padding: 12px;">${createdDate}</td>
            <td style="padding: 12px;">${escapeHtml(author)}</td>
            <td style="padding: 12px; text-align: center;">
              <button onclick="openVisualBuilder(${page.id})" class="btn btn-sm" style="background: #17a2b8; color: white; padding: 6px 12px; margin: 2px;" title="Visual Builder">
                🎨
              </button>
              <button onclick="editPage(${page.id})" class="btn btn-sm" style="background: #ffc107; color: #000; padding: 6px 12px; margin: 2px;" title="Quick Edit">
                ✏️
              </button>
              ${!isStatic ? `
                <button onclick="togglePublishPage(${page.id}, ${isPublished ? 0 : 1})" class="btn btn-sm" style="background: ${isPublished ? '#6c757d' : '#28a745'}; color: white; padding: 6px 12px; margin: 2px;" title="${isPublished ? 'Unpublish' : 'Publish'}">
                  ${isPublished ? '👁️‍🗨️' : '✓'}
                </button>
                <button onclick="duplicatePage(${page.id})" class="btn btn-sm" style="background: #17a2b8; color: white; padding: 6px 12px; margin: 2px;" title="Duplicate">
                  📋
                </button>
                <button onclick="deletePage(${page.id}, '${escapeHtml(page.title)}')" class="btn btn-sm" style="background: #dc3545; color: white; padding: 6px 12px; margin: 2px;" title="Delete">
                  🗑️
                </button>
              ` : '<span style="color: #6c757d; font-size: 12px;">System Page</span>'}
            </td>
          </tr>`;
      }).join('');
    }

    function openPageModal(pageId = null) {
      const modal = document.getElementById('pageModal');
      const title = document.getElementById('pageModalTitle');
      const form = document.getElementById('pageForm');
      
      form.reset();
      document.getElementById('pageId').value = '';
      
      if (pageId) {
        title.textContent = 'Edit Page';
        loadPageData(pageId);
      } else {
        title.textContent = 'Create New Page';
      }
      
      modal.style.display = 'flex';
    }

    async function loadPageData(pageId) {
      try {
        const page = await apiRequest(`/admin/pages/${pageId}`);
        
        document.getElementById('pageId').value = page.id;
        document.getElementById('pageTitle').value = page.title;
        document.getElementById('pageSlug').value = page.slug;
        document.getElementById('pageMetaDescription').value = page.meta_description || '';
        document.getElementById('pageMetaKeywords').value = page.meta_keywords || '';
        document.getElementById('pageTemplate').value = page.template || 'default';
        document.getElementById('pageOrder').value = page.order || 0;
        document.getElementById('pagePublished').checked = page.is_published === 1;
        
        // Handle content (can be JSON array or string)
        let contentStr = '';
        if (Array.isArray(page.content)) {
          contentStr = page.content.map(block => {
            if (typeof block === 'object' && block.content) {
              return block.content;
            }
            return block;
          }).join('\n\n');
        } else if (typeof page.content === 'string') {
          contentStr = page.content;
        }
        document.getElementById('pageContent').value = contentStr;
        
      } catch (error) {
        console.error('Failed to load page:', error);
        showToast('Failed to load page data', 'error');
      }
    }

    function closePageModal() {
      document.getElementById('pageModal').style.display = 'none';
    }

    async function savePage() {
      const pageId = document.getElementById('pageId').value;
      const title = document.getElementById('pageTitle').value.trim();
      const content = document.getElementById('pageContent').value.trim();
      
      if (!title || !content) {
        showToast('Please fill in all required fields', 'error');
        return;
      }

      const pageData = {
        title: title,
        slug: document.getElementById('pageSlug').value.trim() || null,
        content: [{ type: 'html', content: content }], // Store as JSON array
        meta_description: document.getElementById('pageMetaDescription').value.trim() || null,
        meta_keywords: document.getElementById('pageMetaKeywords').value.trim() || null,
        template: document.getElementById('pageTemplate').value,
        order: parseInt(document.getElementById('pageOrder').value) || 0,
        is_published: document.getElementById('pagePublished').checked ? 1 : 0
      };

      try {
        if (pageId) {
          // Update existing page
          await apiRequest(`/admin/pages/${pageId}`, {
            method: 'PUT',
            body: JSON.stringify(pageData)
          });
          showToast('Page updated successfully!', 'success');
        } else {
          // Create new page
          await apiRequest('/admin/pages', {
            method: 'POST',
            body: JSON.stringify(pageData)
          });
          showToast('Page created successfully!', 'success');
        }
        
        closePageModal();
        await loadPages();
      } catch (error) {
        console.error('Failed to save page:', error);
        showToast(error.message || 'Failed to save page', 'error');
      }
    }

    async function editPage(pageId) {
      openPageModal(pageId);
    }

    async function togglePublishPage(pageId, publish) {
      try {
        await apiRequest(`/admin/pages/${pageId}/toggle-publish`, {
          method: 'POST'
        });
        showToast(publish ? 'Page published!' : 'Page unpublished!', 'success');
        await loadPages();
      } catch (error) {
        console.error('Failed to toggle publish:', error);
        showToast('Failed to update page status', 'error');
      }
    }

    async function duplicatePage(pageId) {
      if (!confirm('Create a copy of this page?')) return;
      
      try {
        await apiRequest(`/admin/pages/${pageId}/duplicate`, {
          method: 'POST'
        });
        showToast('Page duplicated successfully!', 'success');
        await loadPages();
      } catch (error) {
        console.error('Failed to duplicate page:', error);
        showToast('Failed to duplicate page', 'error');
      }
    }

    async function deletePage(pageId, pageTitle) {
      if (!confirm(`Delete page "${pageTitle}"?\n\nThis action cannot be undone.`)) return;
      
      try {
        await apiRequest(`/admin/pages/${pageId}`, {
          method: 'DELETE'
        });
        showToast('Page deleted successfully!', 'success');
        await loadPages();
      } catch (error) {
        console.error('Failed to delete page:', error);
        showToast(error.message || 'Failed to delete page', 'error');
      }
    }

    // VISUAL PAGE BUILDER FUNCTIONS
    let currentBuilderPageId = null;
    let currentBuilderBlocks = [];
    let selectedBlockIndex = null;

    async function openVisualBuilder(pageId) {
      currentBuilderPageId = pageId;
      const modal = document.getElementById('visualBuilderModal');
      const title = document.getElementById('visualBuilderTitle');
      
      try {
        console.log('🔄 Loading page for visual builder, ID:', pageId);
        const response = await apiRequest(`/admin/pages/${pageId}`);
        console.log('📡 Visual builder API response:', response);
        console.log('📡 Response type:', typeof response);
        console.log('📡 Response.page exists:', !!response.page);
        
        const page = response.page || response; // Handle both formats
        console.log('📄 Extracted page object:', page);
        console.log('📄 Page.content type:', typeof page.content);
        console.log('📄 Page.content is array:', Array.isArray(page.content));
        console.log('📄 Page.content length:', page.content?.length);
        
        title.textContent = `🎨 Visual Builder - ${page.title}`;
        
        // Load existing blocks
        currentBuilderBlocks = Array.isArray(page.content) ? page.content : [];
        console.log('✅ Loaded blocks into currentBuilderBlocks:', currentBuilderBlocks);
        console.log('✅ currentBuilderBlocks length:', currentBuilderBlocks.length);
        
        console.log('🎨 Calling renderCanvas()...');
        renderCanvas();
        
        modal.style.display = 'flex';
      } catch (error) {
        console.error('❌ Failed to load page for builder:', error);
        showToast('Failed to open visual builder: ' + error.message, 'error');
      }
    }

    function closeVisualBuilder() {
      document.getElementById('visualBuilderModal').style.display = 'none';
      currentBuilderPageId = null;
      currentBuilderBlocks = [];
      selectedBlockIndex = null;
    }

    function addBlock(type) {
      const newBlock = createBlockTemplate(type);
      currentBuilderBlocks.push(newBlock);
      renderCanvas();
      showToast(`${type} block added!`, 'success');
    }

    function createBlockTemplate(type) {
      const templates = {
        hero: {
          type: 'hero',
          content: {
            heading: 'Your Heading Here',
            subheading: 'Your subheading text',
            background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
            text_color: '#ffffff',
            button_text: 'Learn More',
            button_link: '#'
          }
        },
        text: {
          type: 'text',
          content: {
            html: '<p>Enter your text content here. You can use HTML for formatting.</p>'
          }
        },
        heading: {
          type: 'heading',
          content: {
            text: 'Section Heading',
            level: 'h2',
            align: 'left'
          }
        },
        image: {
          type: 'image',
          content: {
            url: 'https://via.placeholder.com/800x400',
            alt: 'Image description',
            caption: ''
          }
        },
        features: {
          type: 'features',
          content: {
            heading: 'Our Features',
            features: [
              { icon: '⭐', title: 'Feature 1', description: 'Description here' },
              { icon: '🚀', title: 'Feature 2', description: 'Description here' },
              { icon: '💎', title: 'Feature 3', description: 'Description here' }
            ]
          }
        },
        two_column: {
          type: 'two_column',
          content: {
            left: { type: 'text', html: '<p>Left column content</p>' },
            right: { type: 'text', html: '<p>Right column content</p>' }
          }
        },
        cta: {
          type: 'cta',
          content: {
            heading: 'Take Action Now',
            text: 'Description text here',
            button_text: 'Get Started',
            button_link: '#',
            background: '#667eea'
          }
        },
        stats: {
          type: 'stats',
          content: {
            stats: [
              { number: '100+', label: 'Stat 1' },
              { number: '50+', label: 'Stat 2' }
            ]
          }
        },
        testimonials: {
          type: 'testimonials',
          content: {
            heading: 'What Our Students Say',
            testimonials: [
              {
                text: 'This platform transformed my learning experience!',
                author: 'John Doe',
                role: 'Student',
                avatar: 'JD',
                rating: 5
              },
              {
                text: 'Highly recommended for anyone looking to upskill.',
                author: 'Jane Smith',
                role: 'Professional',
                avatar: 'JS',
                rating: 5
              }
            ]
          }
        },
        spacer: {
          type: 'spacer',
          content: {
            height: '50px'
          }
        }
      };
      
      return templates[type] || templates.text;
    }

    function renderCanvas() {
      const canvas = document.getElementById('pageCanvas');
      
      console.log('🎨 === RENDER CANVAS START ===');
      console.log('Total blocks to render:', currentBuilderBlocks?.length || 0);
      console.log('Blocks array:', currentBuilderBlocks);
      
      if (!currentBuilderBlocks || currentBuilderBlocks.length === 0) {
        console.log('⚠️ No blocks found, showing empty state');
        canvas.innerHTML = '<div class="canvas-empty" style="padding: 100px 20px; text-align: center; color: #6c757d;"><i class="fas fa-plus-circle" style="font-size: 48px; margin-bottom: 20px; opacity: 0.3;"></i><p>Click a block from the left to start building your page</p></div>';
        return;
      }
      
      const renderedBlocks = currentBuilderBlocks.map((block, index) => {
        console.log(`📦 Rendering block ${index}/${currentBuilderBlocks.length}:`, {
          type: block.type,
          hasContent: !!block.content,
          contentKeys: block.content ? Object.keys(block.content) : []
        });
        
        const preview = renderBlockPreview(block);
        console.log(`✅ Block ${index} preview generated, length: ${preview.length} chars`);
        
        return `
          <div class="content-block ${selectedBlockIndex === index ? 'selected' : ''}" data-index="${index}" onclick="selectBlock(${index})">
            <div class="block-controls">
              ${index > 0 ? `<button class="block-control-btn up" onclick="event.stopPropagation(); moveBlockUp(${index})">↑</button>` : ''}
              ${index < currentBuilderBlocks.length - 1 ? `<button class="block-control-btn down" onclick="event.stopPropagation(); moveBlockDown(${index})">↓</button>` : ''}
              <button class="block-control-btn edit" onclick="event.stopPropagation(); selectBlock(${index})">✏️</button>
              <button class="block-control-btn delete" onclick="event.stopPropagation(); deleteBlock(${index})">🗑️</button>
            </div>
            ${preview}
          </div>
        `;
      });
      
      const finalHTML = renderedBlocks.join('');
      console.log(`📝 Final HTML length: ${finalHTML.length} chars`);
      console.log('🎨 === RENDER CANVAS END ===');
      
      canvas.innerHTML = finalHTML;
    }

    function renderBlockPreview(block) {
      const { type, content } = block;
      
      switch(type) {
        case 'hero':
          return `<div style="background: ${content.background}; color: ${content.text_color}; padding: 60px 20px; text-align: center; border-radius: 8px;">
            <h1 style="margin-bottom: 15px;">${escapeHtml(content.heading)}</h1>
            <p style="font-size: 18px; margin-bottom: 20px;">${escapeHtml(content.subheading || '')}</p>
            ${content.button_text ? `<button style="padding: 12px 30px; background: rgba(255,255,255,0.2); border: 2px solid white; color: white; border-radius: 6px; cursor: pointer;">${escapeHtml(content.button_text)}</button>` : ''}
          </div>`;
        
        case 'text':
          return `<div style="padding: 20px;">${content.html || '<p>Text content</p>'}</div>`;
        
        case 'heading':
          const headingTag = content.level || 'h2';
          return `<${headingTag} style="text-align: ${content.align || 'left'}; padding: 10px 20px;">${escapeHtml(content.text || 'Heading')}</${headingTag}>`;
        
        case 'image':
          return `<div style="text-align: center; padding: 20px;">
            <img src="${content.url}" alt="${escapeHtml(content.alt || '')}" style="max-width: 100%; height: auto; border-radius: 8px;">
            ${content.caption ? `<p style="margin-top: 10px; color: #6c757d; font-size: 14px;">${escapeHtml(content.caption)}</p>` : ''}
          </div>`;
        
        case 'features':
          console.log('Rendering features block:', content);
          const features = Array.isArray(content.features) ? content.features : [];
          console.log('Features array:', features, 'Length:', features.length);
          return `<div style="padding: 40px 20px;">
            <h2 style="text-align: center; margin-bottom: 30px;">${escapeHtml(content.heading || 'Features')}</h2>
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px;">
              ${features.map(f => `
                <div style="text-align: center; padding: 20px; background: #f8f9fa; border-radius: 8px;">
                  <div style="font-size: 40px; margin-bottom: 10px;">${f.icon || '📦'}</div>
                  <h3 style="margin-bottom: 10px;">${escapeHtml(f.title || 'Feature')}</h3>
                  <p style="color: #6c757d;">${escapeHtml(f.description || '')}</p>
                </div>
              `).join('')}
            </div>
          </div>`;
        
        case 'two_column':
          // Handle nested structures with type or direct html
          const leftContent = content.left?.html || (content.left?.type ? `<p><em>${content.left.type} block</em></p>` : '<p>Left column</p>');
          const rightContent = content.right?.html || (content.right?.type ? `<p><em>${content.right.type} block</em></p>` : '<p>Right column</p>');
          return `<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 30px; padding: 20px;">
            <div style="padding: 20px; background: #f8f9fa; border-radius: 8px;">${leftContent}</div>
            <div style="padding: 20px; background: #f8f9fa; border-radius: 8px;">${rightContent}</div>
          </div>`;
        
        case 'cta':
          return `<div style="background: ${content.background || '#667eea'}; color: white; padding: 60px 20px; text-align: center; border-radius: 8px;">
            <h2 style="margin-bottom: 15px;">${escapeHtml(content.heading || 'Call to Action')}</h2>
            <p style="margin-bottom: 20px;">${escapeHtml(content.text || '')}</p>
            ${content.button_text ? `<button style="padding: 12px 30px; background: white; color: #667eea; border: none; border-radius: 6px; font-weight: bold; cursor: pointer;">${escapeHtml(content.button_text)}</button>` : ''}
          </div>`;
        
        case 'stats':
          console.log('Rendering stats block:', content);
          const stats = Array.isArray(content.stats) ? content.stats : [];
          console.log('Stats array:', stats, 'Length:', stats.length);
          return `<div style="padding: 40px 20px; background: #f8f9fa; border-radius: 8px;">
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 30px; text-align: center;">
              ${stats.map(s => `
                <div>
                  <div style="font-size: 36px; font-weight: bold; color: #667eea; margin-bottom: 5px;">${escapeHtml(s.number || '0')}</div>
                  <div style="color: #6c757d;">${escapeHtml(s.label || 'Stat')}</div>
                </div>
              `).join('')}
            </div>
          </div>`;
        
        case 'spacer':
          return `<div style="height: ${content.height || '50px'}; background: repeating-linear-gradient(45deg, #f8f9fa, #f8f9fa 10px, #e9ecef 10px, #e9ecef 20px);"></div>`;
        
        case 'testimonials':
          console.log('Rendering testimonials block:', content);
          const testimonials = Array.isArray(content.testimonials) ? content.testimonials : [];
          console.log('Testimonials array:', testimonials, 'Length:', testimonials.length);
          return `<div style="padding: 40px 20px; background: white;">
            <h2 style="text-align: center; margin-bottom: 30px;">${escapeHtml(content.heading || 'Testimonials')}</h2>
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 20px;">
              ${testimonials.map(t => `
                <div style="background: #f8f9fa; padding: 25px; border-radius: 12px; position: relative;">
                  <div style="margin-bottom: 15px;">
                    <span style="color: #fbbf24;">${'⭐'.repeat(t.rating || 5)}</span>
                  </div>
                  <p style="color: #4b5563; font-style: italic; margin-bottom: 15px; line-height: 1.6;">"${escapeHtml(t.text || '')}"</p>
                  <div style="display: flex; align-items: center; gap: 12px;">
                    <div style="width: 45px; height: 45px; border-radius: 50%; background: linear-gradient(135deg, #667eea, #764ba2); display: flex; align-items: center; justify-content: center; color: white; font-weight: bold; font-size: 14px;">
                      ${escapeHtml(t.avatar || 'A')}
                    </div>
                    <div>
                      <div style="font-weight: 700; color: #1f2937;">${escapeHtml(t.author || 'Author')}</div>
                      <div style="font-size: 13px; color: #6b7280;">${escapeHtml(t.role || 'Role')}</div>
                    </div>
                  </div>
                </div>
              `).join('')}
            </div>
          </div>`;
        
        case 'course_list':
          return `<div style="padding: 40px 20px; background: #f8f9fa; border-radius: 8px; text-align: center;">
            <h2 style="margin-bottom: 15px;">${escapeHtml(content.heading || 'Available Courses')}</h2>
            <p style="color: #6c757d; margin-bottom: 20px;">${escapeHtml(content.description || 'Browse all available courses')}</p>
            <div style="padding: 30px; background: white; border: 2px dashed #dee2e6; border-radius: 8px;">
              <i class="fas fa-graduation-cap" style="font-size: 48px; color: #667eea; margin-bottom: 10px;"></i>
              <p style="color: #6c757d;">Course list will be dynamically loaded from your courses database</p>
            </div>
          </div>`;
        
        case 'contact_info':
          return `<div style="padding: 20px;">${content.html || '<p>Contact information</p>'}</div>`;
        
        case 'contact_form':
          return `<div style="padding: 20px;">${content.html || '<p>Contact form</p>'}</div>`;
        
        default:
          console.warn('Unknown block type:', type, block);
          return `<div style="padding: 20px; background: #fff3cd; border: 2px dashed #ffc107; border-radius: 8px; text-align: center;">
            <strong>Unknown block type: ${type}</strong>
            <p style="font-size: 12px; margin-top: 10px; color: #6c757d;">This block will still be saved, but may not render correctly.</p>
          </div>`;
      }
    }

    function selectBlock(index) {
      selectedBlockIndex = index;
      renderCanvas();
      showBlockProperties(index);
    }

    function showBlockProperties(index) {
      const block = currentBuilderBlocks[index];
      const props = document.getElementById('blockProperties');
      
      let html = `<h3 style="margin-bottom: 15px; font-size: 16px;">⚙️ ${block.type.toUpperCase()} Settings</h3>`;
      
      // Generate property fields based on block type
      html += `<div class="property-group">`;
      html += generatePropertyFields(block, index);
      html += `</div>`;
      
      props.innerHTML = html;
    }

    function generatePropertyFields(block, index) {
      const { type, content } = block;
      let fields = '';
      
      switch(type) {
        case 'hero':
          fields = `
            <label class="property-label">Heading</label>
            <input type="text" class="property-input" value="${escapeHtml(content.heading || '')}" onchange="updateBlockProperty(${index}, 'heading', this.value)">
            
            <label class="property-label">Subheading</label>
            <input type="text" class="property-input" value="${escapeHtml(content.subheading || '')}" onchange="updateBlockProperty(${index}, 'subheading', this.value)">
            
            <label class="property-label">Background</label>
            <input type="text" class="property-input" value="${escapeHtml(content.background || '')}" onchange="updateBlockProperty(${index}, 'background', this.value)" placeholder="e.g., #667eea or gradient">
            
            <label class="property-label">Text Color</label>
            <div class="color-picker-wrapper">
              <input type="color" value="${content.text_color || '#ffffff'}" onchange="updateBlockProperty(${index}, 'text_color', this.value)">
              <input type="text" class="property-input" style="flex: 1; margin: 0;" value="${content.text_color || '#ffffff'}" onchange="updateBlockProperty(${index}, 'text_color', this.value)">
            </div>
            
            <label class="property-label">Button Text</label>
            <input type="text" class="property-input" value="${escapeHtml(content.button_text || '')}" onchange="updateBlockProperty(${index}, 'button_text', this.value)">
            
            <label class="property-label">Button Link</label>
            <input type="text" class="property-input" value="${escapeHtml(content.button_link || '')}" onchange="updateBlockProperty(${index}, 'button_link', this.value)">
          `;
          break;
        
        case 'text':
          fields = `
            <label class="property-label">HTML Content</label>
            <textarea class="property-input" rows="8" onchange="updateBlockProperty(${index}, 'html', this.value)">${escapeHtml(content.html || '')}</textarea>
          `;
          break;
        
        case 'heading':
          fields = `
            <label class="property-label">Text</label>
            <input type="text" class="property-input" value="${escapeHtml(content.text || '')}" onchange="updateBlockProperty(${index}, 'text', this.value)">
            
            <label class="property-label">Level</label>
            <select class="property-input" onchange="updateBlockProperty(${index}, 'level', this.value)">
              <option value="h1" ${content.level === 'h1' ? 'selected' : ''}>H1</option>
              <option value="h2" ${content.level === 'h2' ? 'selected' : ''}>H2</option>
              <option value="h3" ${content.level === 'h3' ? 'selected' : ''}>H3</option>
            </select>
            
            <label class="property-label">Align</label>
            <select class="property-input" onchange="updateBlockProperty(${index}, 'align', this.value)">
              <option value="left" ${content.align === 'left' ? 'selected' : ''}>Left</option>
              <option value="center" ${content.align === 'center' ? 'selected' : ''}>Center</option>
              <option value="right" ${content.align === 'right' ? 'selected' : ''}>Right</option>
            </select>
          `;
          break;
        
        case 'image':
          fields = `
            <label class="property-label">Image URL</label>
            <input type="text" class="property-input" value="${escapeHtml(content.url || '')}" onchange="updateBlockProperty(${index}, 'url', this.value)">
            
            <label class="property-label">Alt Text</label>
            <input type="text" class="property-input" value="${escapeHtml(content.alt || '')}" onchange="updateBlockProperty(${index}, 'alt', this.value)">
            
            <label class="property-label">Caption</label>
            <input type="text" class="property-input" value="${escapeHtml(content.caption || '')}" onchange="updateBlockProperty(${index}, 'caption', this.value)">
          `;
          break;
        
        case 'spacer':
          fields = `
            <label class="property-label">Height</label>
            <input type="text" class="property-input" value="${content.height || '50px'}" onchange="updateBlockProperty(${index}, 'height', this.value)" placeholder="e.g., 50px">
          `;
          break;
        
        case 'features':
          fields = `
            <label class="property-label">Heading</label>
            <input type="text" class="property-input" value="${escapeHtml(content.heading || '')}" onchange="updateBlockProperty(${index}, 'heading', this.value)">
            
            <label class="property-label">Features (JSON)</label>
            <textarea class="property-input" rows="12" onchange="updateBlockPropertyJSON(${index}, 'features', this.value)" placeholder='[{"icon":"📚","title":"Title","description":"Description"}]'>${escapeHtml(JSON.stringify(content.features || [], null, 2))}</textarea>
            <small style="color: #6c757d;">Format: Array of objects with icon, title, description</small>
          `;
          break;
        
        case 'stats':
          fields = `
            <label class="property-label">Stats (JSON)</label>
            <textarea class="property-input" rows="8" onchange="updateBlockPropertyJSON(${index}, 'stats', this.value)" placeholder='[{"number":"1000+","label":"Students"}]'>${escapeHtml(JSON.stringify(content.stats || [], null, 2))}</textarea>
            <small style="color: #6c757d;">Format: Array of objects with number, label</small>
          `;
          break;
        
        case 'testimonials':
          fields = `
            <label class="property-label">Heading</label>
            <input type="text" class="property-input" value="${escapeHtml(content.heading || '')}" onchange="updateBlockProperty(${index}, 'heading', this.value)">
            
            <label class="property-label">Testimonials (JSON)</label>
            <textarea class="property-input" rows="12" onchange="updateBlockPropertyJSON(${index}, 'testimonials', this.value)" placeholder='[{"text":"Great!","author":"Name","role":"Title","avatar":"AB","rating":5}]'>${escapeHtml(JSON.stringify(content.testimonials || [], null, 2))}</textarea>
            <small style="color: #6c757d;">Format: Array with text, author, role, avatar, rating (1-5)</small>
          `;
          break;
        
        case 'cta':
          fields = `
            <label class="property-label">Heading</label>
            <input type="text" class="property-input" value="${escapeHtml(content.heading || '')}" onchange="updateBlockProperty(${index}, 'heading', this.value)">
            
            <label class="property-label">Text</label>
            <textarea class="property-input" rows="3" onchange="updateBlockProperty(${index}, 'text', this.value)">${escapeHtml(content.text || '')}</textarea>
            
            <label class="property-label">Button Text</label>
            <input type="text" class="property-input" value="${escapeHtml(content.button_text || '')}" onchange="updateBlockProperty(${index}, 'button_text', this.value)">
            
            <label class="property-label">Button Link</label>
            <input type="text" class="property-input" value="${escapeHtml(content.button_link || '')}" onchange="updateBlockProperty(${index}, 'button_link', this.value)">
            
            <label class="property-label">Background Color</label>
            <div class="color-picker-wrapper">
              <input type="color" value="${content.background || '#667eea'}" onchange="updateBlockProperty(${index}, 'background', this.value)">
              <input type="text" class="property-input" style="flex: 1; margin: 0;" value="${content.background || '#667eea'}" onchange="updateBlockProperty(${index}, 'background', this.value)">
            </div>
          `;
          break;
        
        case 'two_column':
          fields = `
            <label class="property-label">Left Column HTML</label>
            <textarea class="property-input" rows="6" onchange="updateBlockPropertyNested(${index}, 'left', 'html', this.value)">${escapeHtml(content.left?.html || '')}</textarea>
            
            <label class="property-label">Right Column HTML</label>
            <textarea class="property-input" rows="6" onchange="updateBlockPropertyNested(${index}, 'right', 'html', this.value)">${escapeHtml(content.right?.html || '')}</textarea>
          `;
          break;
        
        case 'course_list':
          fields = `
            <label class="property-label">Heading</label>
            <input type="text" class="property-input" value="${escapeHtml(content.heading || '')}" onchange="updateBlockProperty(${index}, 'heading', this.value)">
            
            <label class="property-label">Description</label>
            <textarea class="property-input" rows="3" onchange="updateBlockProperty(${index}, 'description', this.value)">${escapeHtml(content.description || '')}</textarea>
            
            <small style="color: #6c757d;">Courses will be dynamically loaded from database</small>
          `;
          break;
        
        case 'contact_info':
        case 'contact_form':
          fields = `
            <label class="property-label">HTML Content</label>
            <textarea class="property-input" rows="8" onchange="updateBlockProperty(${index}, 'html', this.value)">${escapeHtml(content.html || '')}</textarea>
          `;
          break;
        
        default:
          fields = `<p style="color: #6c757d;">Select a block to edit its properties</p>`;
      }
      
      return fields;
    }

    function updateBlockPropertyJSON(index, property, value) {
      try {
        const parsed = JSON.parse(value);
        updateBlockProperty(index, property, parsed);
      } catch (e) {
        console.error('Invalid JSON:', e);
        showToast('Invalid JSON format', 'error');
      }
    }

    function updateBlockPropertyNested(index, parent, property, value) {
      if (!currentBuilderBlocks[index]) return;
      if (!currentBuilderBlocks[index].content[parent]) {
        currentBuilderBlocks[index].content[parent] = {};
      }
      currentBuilderBlocks[index].content[parent][property] = value;
      renderCanvas();
      if (selectedBlockIndex === index) {
        selectBlock(index);
      }
    }

    function updateBlockProperty(index, property, value) {
      if (!currentBuilderBlocks[index]) return;
      currentBuilderBlocks[index].content[property] = value;
      renderCanvas();
      if (selectedBlockIndex === index) {
        selectBlock(index); // Refresh properties panel
      }
    }

    function moveBlockUp(index) {
      if (index === 0) return;
      [currentBuilderBlocks[index - 1], currentBuilderBlocks[index]] = [currentBuilderBlocks[index], currentBuilderBlocks[index - 1]];
      if (selectedBlockIndex === index) selectedBlockIndex = index - 1;
      else if (selectedBlockIndex === index - 1) selectedBlockIndex = index;
      renderCanvas();
    }

    function moveBlockDown(index) {
      if (index === currentBuilderBlocks.length - 1) return;
      [currentBuilderBlocks[index], currentBuilderBlocks[index + 1]] = [currentBuilderBlocks[index + 1], currentBuilderBlocks[index]];
      if (selectedBlockIndex === index) selectedBlockIndex = index + 1;
      else if (selectedBlockIndex === index + 1) selectedBlockIndex = index;
      renderCanvas();
    }

    function deleteBlock(index) {
      if (!confirm('Delete this block?')) return;
      currentBuilderBlocks.splice(index, 1);
      if (selectedBlockIndex === index) selectedBlockIndex = null;
      else if (selectedBlockIndex && selectedBlockIndex > index) selectedBlockIndex--;
      renderCanvas();
      document.getElementById('blockProperties').innerHTML = '<h3 style="margin-bottom: 15px; font-size: 16px;">⚙️ Block Settings</h3><p style="color: #6c757d; font-size: 14px;">Select a block to edit its properties</p>';
    }

    window.saveVisualPage = async function() {
      if (!currentBuilderPageId) {
        showToast('No page selected', 'error');
        return;
      }
      
      try {
        await apiRequest(`/admin/pages/${currentBuilderPageId}`, {
          method: 'PUT',
          body: JSON.stringify({
            content: currentBuilderBlocks
          })
        });
        
        showToast('Page saved successfully!', 'success');
        closeVisualBuilder();
        await loadPages();
      } catch (error) {
        console.error('Failed to save visual page:', error);
        showToast('Failed to save page: ' + error.message, 'error');
      }
    }

    window.previewPage = function() {
      const previewWindow = window.open('', 'pagePreview', 'width=1200,height=800');
      const html = `
        <!DOCTYPE html>
        <html>
        <head>
          <title>Page Preview</title>
          <style>
            body { font-family: 'Segoe UI', sans-serif; margin: 0; padding: 0; }
            * { box-sizing: border-box; }
          </style>
        </head>
        <body>
          ${currentBuilderBlocks.map(block => renderBlockPreview(block)).join('')}
        </body>
        </html>
      `;
      previewWindow.document.write(html);
      previewWindow.document.close();
    }

    // All onclick handler functions are already defined as window.* throughout the script above
    
    // Diagnostic: Log which functions are available
    console.log('Admin Dashboard JavaScript loaded');
    console.log('editCourse available:', typeof window.editCourse);
    console.log('editLesson available:', typeof window.editLesson);
    console.log('addLesson available:', typeof window.addLesson);
  </script>

  <!-- Page Modal -->
  <div id="pageModal" class="modal">
    <div class="modal-content" style="max-width: 800px;">
      <div class="modal-header">
        <h2 id="pageModalTitle">Create New Page</h2>
        <button class="modal-close" onclick="closePageModal()">&times;</button>
      </div>
      <form id="pageForm" onsubmit="return false;">
        <div class="modal-body">
          <input type="hidden" id="pageId" name="page_id">
          
          <div class="form-group">
            <label for="pageTitle">Page Title *</label>
            <input type="text" id="pageTitle" name="title" required 
                   placeholder="Enter page title">
            <div class="help-text">This will be used as the page heading and to generate the URL slug.</div>
          </div>

          <div class="form-group">
            <label for="pageSlug">URL Slug</label>
            <input type="text" id="pageSlug" name="slug" 
                   placeholder="Auto-generated from title">
            <div class="help-text">Leave blank to auto-generate from title. Only lowercase letters, numbers, and hyphens.</div>
          </div>

          <div class="form-group">
            <label for="pageContent">Content *</label>
            <textarea id="pageContent" name="content" rows="10" required
                      placeholder="Enter page content (HTML supported)"></textarea>
            <div class="help-text">You can use HTML tags for formatting.</div>
          </div>

          <div class="form-group">
            <label for="pageMetaDescription">Meta Description</label>
            <input type="text" id="pageMetaDescription" name="meta_description" 
                   placeholder="Brief description for SEO">
            <div class="help-text">Used for search engine results (150-160 characters recommended).</div>
          </div>

          <div class="form-group">
            <label for="pageMetaKeywords">Meta Keywords</label>
            <input type="text" id="pageMetaKeywords" name="meta_keywords" 
                   placeholder="keyword1, keyword2, keyword3">
            <div class="help-text">Comma-separated keywords for SEO.</div>
          </div>

          <div class="form-group">
            <label for="pageTemplate">Template</label>
            <select id="pageTemplate" name="template">
              <option value="default">Default</option>
              <option value="full-width">Full Width</option>
              <option value="sidebar">With Sidebar</option>
            </select>
            <div class="help-text">Choose a layout template for this page.</div>
          </div>

          <div class="form-group">
            <label for="pageOrder">Display Order</label>
            <input type="number" id="pageOrder" name="order" value="0" min="0">
            <div class="help-text">Lower numbers appear first (0 = default).</div>
          </div>

          <div class="form-group">
            <label class="checkbox-label">
              <input type="checkbox" id="pagePublished" name="is_published" value="1">
              <span>Publish this page immediately</span>
            </label>
            <div class="help-text">Unpublished pages are only visible to administrators.</div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn-modal btn-modal-secondary" onclick="closePageModal()">Cancel</button>
          <button type="submit" class="btn-modal btn-modal-primary" onclick="savePage()">
            <i class="fas fa-save"></i> Save Page
          </button>
        </div>
      </form>
    </div>
  </div>

  <!-- Visual Page Builder Modal -->
  <div id="visualBuilderModal" class="modal">
    <div class="modal-content" style="max-width: 95%; max-height: 95%; width: 1400px;">
      <div class="modal-header" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
        <h2 id="visualBuilderTitle">🎨 Visual Page Builder</h2>
        <button class="modal-close" onclick="closeVisualBuilder()" style="color: white;">&times;</button>
      </div>
      <div class="modal-body" style="padding: 0; display: flex; height: calc(95vh - 120px);">
        <!-- Left Sidebar - Blocks -->
        <div style="width: 250px; background: #f8f9fa; border-right: 1px solid #dee2e6; overflow-y: auto; padding: 15px;">
          <h3 style="margin-bottom: 15px; font-size: 16px;">📦 Content Blocks</h3>
          <div class="block-palette">
            <button onclick="addBlock('hero')" class="block-btn">
              <span>🎯</span><br>Hero Section
            </button>
            <button onclick="addBlock('text')" class="block-btn">
              <span>📝</span><br>Text Block
            </button>
            <button onclick="addBlock('heading')" class="block-btn">
              <span>📰</span><br>Heading
            </button>
            <button onclick="addBlock('image')" class="block-btn">
              <span>🖼️</span><br>Image
            </button>
            <button onclick="addBlock('features')" class="block-btn">
              <span>⭐</span><br>Features Grid
            </button>
            <button onclick="addBlock('two_column')" class="block-btn">
              <span>📋</span><br>Two Columns
            </button>
            <button onclick="addBlock('cta')" class="block-btn">
              <span>📣</span><br>Call to Action
            </button>
            <button onclick="addBlock('stats')" class="block-btn">
              <span>📊</span><br>Statistics
            </button>
            <button onclick="addBlock('testimonials')" class="block-btn">
              <span>💬</span><br>Testimonials
            </button>
            <button onclick="addBlock('spacer')" class="block-btn">
              <span>⬜</span><br>Spacer
            </button>
          </div>
        </div>

        <!-- Center - Canvas -->
        <div style="flex: 1; background: #e9ecef; overflow-y: auto; padding: 30px;">
          <div id="pageCanvas" style="background: white; min-height: 600px; box-shadow: 0 0 20px rgba(0,0,0,0.1); max-width: 1000px; margin: 0 auto;">
            <div class="canvas-empty" style="padding: 100px 20px; text-align: center; color: #6c757d;">
              <i class="fas fa-plus-circle" style="font-size: 48px; margin-bottom: 20px; opacity: 0.3;"></i>
              <p>Click a block from the left to start building your page</p>
            </div>
          </div>
        </div>

        <!-- Right Sidebar - Properties -->
        <div style="width: 300px; background: #f8f9fa; border-left: 1px solid #dee2e6; overflow-y: auto; padding: 15px;">
          <div id="blockProperties">
            <h3 style="margin-bottom: 15px; font-size: 16px;">⚙️ Block Settings</h3>
            <p style="color: #6c757d; font-size: 14px;">Select a block to edit its properties</p>
          </div>
        </div>
      </div>
      <div class="modal-footer" style="padding: 15px; background: #f8f9fa; border-top: 2px solid #dee2e6;">
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <div>
            <button type="button" onclick="previewPage()" class="btn" style="background: #17a2b8; color: white; padding: 10px 20px; margin-right: 10px;">
              <i class="fas fa-eye"></i> Preview
            </button>
          </div>
          <div>
            <button type="button" class="btn" style="background: #6c757d; color: white; padding: 10px 20px; margin-right: 10px;" onclick="closeVisualBuilder()">Cancel</button>
            <button type="button" onclick="saveVisualPage()" class="btn" style="background: #28a745; color: white; padding: 10px 20px;">
              <i class="fas fa-save"></i> Save Page
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Role/Permission Modals -->
  <div id="roleModal" class="modal">
    <div class="modal-content">
      <div class="modal-header">
        <h2 id="roleModalTitle">Create Role</h2>
        <button class="modal-close" onclick="closeRoleModal()">&times;</button>
      </div>
      <form id="roleForm" onsubmit="return false;">
        <div class="modal-body">
          <input type="hidden" id="roleId" name="role_id">
          
          <div class="form-group">
            <label for="roleName">Role Name *</label>
            <input type="text" id="roleName" name="name" required maxlength="50" 
                   placeholder="e.g., moderator, instructor">
            <div class="help-text">Use lowercase, no spaces. Use hyphens for multi-word names.</div>
          </div>

          <div class="form-group">
            <label>Assign Permissions</label>
            <div id="permissionsCheckboxList" class="checkbox-group">
              <div style="text-align: center; padding: 20px; color: #999;">
                <i class="fas fa-spinner fa-spin"></i> Loading permissions...
              </div>
            </div>
            <div class="help-text">Select which permissions this role should have.</div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn-modal btn-modal-secondary" onclick="closeRoleModal()">Cancel</button>
          <button type="submit" class="btn-modal btn-modal-primary" onclick="saveRole()">
            <i class="fas fa-save"></i> Save Role
          </button>
        </div>
      </form>
    </div>
  </div>

  <div id="permissionModal" class="modal">
    <div class="modal-content">
      <div class="modal-header">
        <h2 id="permissionModalTitle">Create Permission</h2>
        <button class="modal-close" onclick="closePermissionModal()">&times;</button>
      </div>
      <form id="permissionForm" onsubmit="return false;">
        <div class="modal-body">
          <input type="hidden" id="permissionId" name="permission_id">
          
          <div class="form-group">
            <label for="permissionName">Permission Name *</label>
            <input type="text" id="permissionName" name="name" required maxlength="100" 
                   placeholder="e.g., manage-content, view-analytics">
            <div class="help-text">Use kebab-case (lowercase with hyphens). Be descriptive.</div>
          </div>

          <div class="form-group">
            <label>Assign to Roles</label>
            <div id="rolesCheckboxList" class="checkbox-group">
              <div style="text-align: center; padding: 20px; color: #999;">
                <i class="fas fa-spinner fa-spin"></i> Loading roles...
              </div>
            </div>
            <div class="help-text">Select which roles should have this permission.</div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn-modal btn-modal-secondary" onclick="closePermissionModal()">Cancel</button>
          <button type="submit" class="btn-modal btn-modal-primary" onclick="savePermission()">
            <i class="fas fa-save"></i> Save Permission
          </button>
        </div>
      </form>
    </div>
  </div>

</body>
</html>