<!-- StyleScore System Stylesheets -->


<?php if(!isset($hidenav) || !$hidenav): ?>



<!-- Session Info Modal -->
<div class="modal fade" id="sessionModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><i class="fas fa-info-circle me-2"></i>Session Information</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <div class="table-responsive">
          <table class="table table-striped table-hover">
            <thead class="table-dark">
              <tr>
                <th style="width: 30%;">Session Key</th>
                <th style="width: 70%;">Value</th>
              </tr>
            </thead>
            <tbody>
              <?php if(isset($_SESSION['user_logged_in'])): ?>
              <tr>
                <td><strong>Login Status</strong></td>
                <td>
                  <span class="badge bg-<?= $_SESSION['user_logged_in'] ? 'success' : 'danger' ?>">
                    <?= $_SESSION['user_logged_in'] ? 'Logged In' : 'Not Logged In' ?>
                  </span>
                </td>
              </tr>
              <?php endif; ?>
              
              <?php if(isset($_SESSION['user_type'])): ?>
              <tr>
                <td><strong>User Type</strong></td>
                <td>
                  <span class="badge bg-primary"><?= ucfirst(htmlspecialchars($_SESSION['user_type'])) ?></span>
                </td>
              </tr>
              <?php endif; ?>
              
              <?php if(isset($_SESSION['user_id'])): ?>
              <tr>
                <td><strong>User ID</strong></td>
                <td><code><?= htmlspecialchars($_SESSION['user_id']) ?></code></td>
              </tr>
              <?php endif; ?>
              
              <?php if(isset($_SESSION['username'])): ?>
              <tr>
                <td><strong>Username</strong></td>
                <td><?= htmlspecialchars($_SESSION['username']) ?></td>
              </tr>
              <?php endif; ?>
              
              <?php if(isset($_SESSION['user_name'])): ?>
              <tr>
                <td><strong>Display Name</strong></td>
                <td><?= htmlspecialchars($_SESSION['user_name']) ?></td>
              </tr>
              <?php endif; ?>
              
              <?php if(isset($_SESSION['judge_id'])): ?>
              <tr>
                <td><strong>Judge ID</strong></td>
                <td><code><?= htmlspecialchars($_SESSION['judge_id']) ?></code></td>
              </tr>
              <?php endif; ?>
              
              <?php if(isset($_SESSION['admin_logged_in'])): ?>
              <tr>
                <td><strong>Admin Access</strong></td>
                <td>
                  <span class="badge bg-<?= $_SESSION['admin_logged_in'] ? 'warning' : 'secondary' ?>">
                    <?= $_SESSION['admin_logged_in'] ? 'Yes' : 'No' ?>
                  </span>
                </td>
              </tr>
              <?php endif; ?>
              
              <?php if(isset($_SESSION['judge_logged_in'])): ?>
              <tr>
                <td><strong>Judge Access</strong></td>
                <td>
                  <span class="badge bg-<?= $_SESSION['judge_logged_in'] ? 'info' : 'secondary' ?>">
                    <?= $_SESSION['judge_logged_in'] ? 'Yes' : 'No' ?>
                  </span>
                </td>
              </tr>
              <?php endif; ?>
              
              <!-- Legacy session variables (if they exist) -->
              <?php if(isset($_SESSION['user'])): ?>
              <tr>
                <td><strong>Legacy User</strong></td>
                <td><?= htmlspecialchars($_SESSION['user']) ?></td>
              </tr>
              <?php endif; ?>
              
              <?php if(isset($_SESSION['role'])): ?>
              <tr>
                <td><strong>Legacy Role</strong></td>
                <td>
                  <span class="badge bg-secondary"><?= ucfirst(htmlspecialchars($_SESSION['role'])) ?></span>
                </td>
              </tr>
              <?php endif; ?>
              
              <!-- Session metadata -->
              <tr>
                <td><strong>Session ID</strong></td>
                <td><code class="text-muted"><?= session_id() ?></code></td>
              </tr>
              
              <tr>
                <td><strong>Session Started</strong></td>
                <td><?= date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']) ?></td>
              </tr>
              
              <?php if(empty($_SESSION)): ?>
              <tr>
                <td colspan="2" class="text-center text-muted">
                  <i class="fas fa-exclamation-triangle me-2"></i>
                  No session data available
                </td>
              </tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
        
        <!-- Debug: All session data -->
        <div class="mt-3">
          <button class="btn btn-outline-secondary btn-sm" type="button" data-bs-toggle="collapse" data-bs-target="#debugSession">
            <i class="fas fa-code me-1"></i>Show Raw Session Data
          </button>
          <div class="collapse mt-2" id="debugSession">
            <div class="border-0 shadow-none card bg-light">
              <div class="border-0 shadow-none card-body">
                <pre class="mb-0 small"><code><?= htmlspecialchars(print_r($_SESSION, true)) ?></code></pre>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
          <i class="fas fa-times me-1"></i>Close
        </button>
        <a href="http://<?php echo $_SERVER['SERVER_NAME'];?>/v2/admin/scoring_format_view.php" class="btn btn-primary" id="tiebreakHelpViewMore">
          <i class="fas fa-eye me-1"></i>View in Format Management
        </a>
      </div>
    </div>
  </div>
</div>


<style>
.btn-check:checked+.btn, .btn.active, .btn.show, .btn:first-child:active, :not(.btn-check)+.btn:active {
    color: #ffffff;
    background-color: #000cff;
    border-color: var(--bs-btn-active-border-color);
    box-shadow: var(--bs-btn-active-shadow);
}


 body.body-bg-aurora-bright {
    background: #EDEDED;
    background-size: cover;
    background-position: center center;
    background-repeat: no-repeat;
    background-attachment: fixed;
}
/* Sidebar Navigation Styles */
.sidebar-nav {
  position: fixed;
  top: 0;
  left: 0;
  height: 100vh;
  width: 280px;
  /*background: linear-gradient(180deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);*/
  background: #3C464F;
  color: white;
  z-index: 1030;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  transition: transform 0.3s ease;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
}
.sidebar-brand img {
    height: 50px;
    filter: brightness(1.5) contrast(1.6);
}
/* Mobile: Hide sidebar by default */
@media (max-width: 991.98px) {
  .sidebar-nav {
    transform: translateX(-100%);
  }
  
  .sidebar-nav.show {
    transform: translateX(0);
  }
  
  /* Push main content on larger screens */
  body {
    padding-left: 0;
  }
}

/* Desktop: Show sidebar and push content */
@media (min-width: 992px) {
  .sidebar-nav {
    transform: translateX(0);
  }
  

}

/* Sidebar Header */
.sidebar-header {
  padding: 1.5rem 1rem;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.sidebar-brand {
  color: white;
  text-decoration: none;
  font-size: 1.25rem;
  font-weight: bold;
  transition: all 0.3s ease;
      justify-content: center;
}

.sidebar-brand:hover {
  color: #e3f2fd;
  transform: scale(1.02);
}

.brand-icon {
  font-size: 1.5rem;
  animation: float 3s ease-in-out infinite;
}

.brand-text {
  background: linear-gradient(45deg, #fff, #e3f2fd);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

/* Sidebar Content */
.sidebar-content {
  flex: 1;
  padding: 1rem 0;
  overflow-y: auto;
}

.sidebar-nav-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.sidebar-nav-item {
  margin: 0.25rem 0;
}

.sidebar-nav-link {
  display: flex;
  align-items: center;
  padding: 0.75rem 1.5rem;
  color: rgba(255, 255, 255, 0.9);
  text-decoration: none;
  transition: all 0.3s ease;
  border-radius: 0 25px 25px 0;
  margin-right: 1rem;
  position: relative;
}

.sidebar-nav-link:hover {
  background: rgba(255, 255, 255, 0.1);
  color: white;
  transform: translateX(5px);
}

.sidebar-nav-link.active {
  background: rgba(255, 255, 255, 0.15);
  color: white;
  box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.2);
}

.sidebar-icon {
  font-size: 1.1rem;
  margin-right: 0.75rem;
  width: 1.5rem;
  text-align: center;
  font-style: normal;
}

.sidebar-text {
  font-weight: 500;
  flex: 1;
}

/* Submenu Styles */
.has-submenu > .sidebar-nav-link {
  position: relative;
}

.submenu-toggle {
  cursor: pointer;
}

.submenu-arrow {
  font-size: 0.8rem;
  transition: transform 0.3s ease;
  color: rgba(255, 255, 255, 0.6);
}

.submenu-toggle[aria-expanded="true"] .submenu-arrow {
  transform: rotate(90deg);
  color: rgba(255, 255, 255, 0.9);
}

.sidebar-submenu {
  list-style: none;
  padding: 0;
  margin: 0;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 0 0 15px 15px;
  margin-right: 1rem;
  overflow: hidden;
  transition: all 0.3s ease;
}

.sidebar-submenu.show {
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

/* Nested submenu styles for third-level items */
.sidebar-submenu .sidebar-submenu {
  background: rgba(0, 0, 0, 0.3);
  border-radius: 0 0 10px 10px;
  margin-right: 0;
  margin-top: 0;
  border-top: 1px solid rgba(255, 255, 255, 0.05);
}

.submenu-item {
  padding: 0.6rem 1.5rem 0.6rem 3rem;
  font-size: 0.9rem;
  border-radius: 0 20px 20px 0;
  margin-right: 0;
  position: relative;
}

/* Third-level submenu items (nested within submenu-item) */
.sidebar-submenu .sidebar-submenu .submenu-item {
  padding: 0.5rem 1.5rem 0.5rem 4rem;
  font-size: 0.85rem;
  border-radius: 0 15px 15px 0;
}

.submenu-item::before {
  content: '';
  position: absolute;
  left: 2.2rem;
  top: 50%;
  width: 6px;
  height: 6px;
  background: rgba(255, 255, 255, 0.4);
  border-radius: 50%;
  transform: translateY(-50%);
  transition: all 0.3s ease;
}

/* Third-level submenu item indicators */
.sidebar-submenu .sidebar-submenu .submenu-item::before {
  left: 3.2rem;
  width: 4px;
  height: 4px;
  background: rgba(255, 255, 255, 0.3);
}

.submenu-item:hover::before {
  background: rgba(255, 255, 255, 0.8);
  transform: translateY(-50%) scale(1.5);
}

.submenu-item.active::before {
  background: #28a745;
  transform: translateY(-50%) scale(1.5);
}

/* Third-level submenu hover effects */
.sidebar-submenu .sidebar-submenu .submenu-item:hover::before {
  background: rgba(255, 255, 255, 0.8);
  transform: translateY(-50%) scale(2);
}

.sidebar-submenu .sidebar-submenu .submenu-item.active::before {
  background: #28a745;
  transform: translateY(-50%) scale(2);
}

.submenu-icon {
  font-size: 0.9rem;
  opacity: 0.8;
}

/* Third-level submenu icons */
.sidebar-submenu .sidebar-submenu .submenu-icon {
  font-size: 0.8rem;
  opacity: 0.7;
}

/* Improved hover effects for submenus */
.submenu-item:hover {
  background: rgba(255, 255, 255, 0.15);
  transform: translateX(8px);
}

/* Third-level submenu hover effects */
.sidebar-submenu .sidebar-submenu .submenu-item:hover {
  background: rgba(255, 255, 255, 0.12);
  transform: translateX(6px);
}

.submenu-item.active {
  background: rgba(40, 167, 69, 0.3);
  border-left: 3px solid #28a745;
}

/* Animation for submenu expansion */
.sidebar-submenu.collapsing {
  transition: height 0.3s ease;
}

/* Adjust main nav link when it has submenu */
.has-submenu > .sidebar-nav-link:hover {
  background: rgba(255, 255, 255, 0.1);
}

.has-submenu > .sidebar-nav-link[aria-expanded="true"] {
  background: rgba(255, 255, 255, 0.15);
  border-bottom: none;
  border-radius: 0 25px 0 0;
}

/* Submenu item that also has submenu (tiebreak rules) */
.submenu-item.submenu-toggle {
  padding-right: 2rem; /* Make room for arrow */
}

.submenu-item.submenu-toggle .submenu-arrow {
  font-size: 0.7rem;
  position: absolute;
  right: 1rem;
  top: 50%;
  transform: translateY(-50%);
}

.submenu-item.submenu-toggle[aria-expanded="true"] .submenu-arrow {
  transform: translateY(-50%) rotate(90deg);
}

/* Remove old submenu header styles that are no longer needed */
.sidebar-nav-item.submenu-header,
.submenu-header-text {
  /* These classes are no longer used */
  display: none;
}

/* ...existing styles continue... */

/* Sidebar Footer */
.sidebar-footer {
  padding: 1rem;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  background: rgba(0, 0, 0, 0.1);
}

.sidebar-footer-item {
  margin-bottom: 0.75rem;
}

.sidebar-footer-item:last-child {
  margin-bottom: 0;
}

/* User Info in Footer */
.user-info {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 0.75rem;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  transition: all 0.3s ease;
}

.user-info:hover {
  background: rgba(255, 255, 255, 0.15);
}

.user-avatar {
  width: 40px;
  height: 40px;
  background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 1.2rem;
  flex-shrink: 0;
}

.user-details {
  flex: 1;
  min-width: 0;
}

.user-name {
  font-weight: 600;
  color: white;
  font-size: 0.9rem;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.user-role {
  margin-top: 0.25rem;
}

.user-actions {
  flex-shrink: 0;
}

/* Mobile Top Bar */
.navbar.d-lg-none {
  background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
}

/* Live badge animation */
.pulse {
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}

@keyframes float {
  0%, 100% { transform: translateY(0px); }
  50% { transform: translateY(-5px); }
}

/* Dropdown styling for sidebar footer */
.sidebar-footer .dropdown-menu {
  border: none;
  border-radius: 12px;
  padding: 0.5rem 0;
  background: rgba(255, 255, 255, 0.98);
  backdrop-filter: blur(10px);
  min-width: 200px;
  bottom: 100%;
  top: auto;
}

.sidebar-footer .dropdown-header {
  font-size: 0.75rem;
  font-weight: 600;
  color: #6c757d;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  padding: 0.5rem 1rem 0.25rem;
}

.sidebar-footer .dropdown-item {
  transition: all 0.2s ease;
}

.sidebar-footer .dropdown-item:hover {
  transform: translateX(4px);
}

.dropdown-icon {
  margin-right: 0.75rem;
  width: 1.2rem;
  text-align: center;
  font-style: normal;
}

/* Scrollbar styling for sidebar */
.sidebar-nav::-webkit-scrollbar {
  width: 6px;
}

.sidebar-nav::-webkit-scrollbar-track {
  background: transparent;
}

.sidebar-nav::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 3px;
}

.sidebar-nav::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.3);
}

/* Backdrop for mobile */
@media (max-width: 991.98px) {
  .sidebar-backdrop {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    z-index: 1025;
    opacity: 0;
    visibility: hidden;
    transition: all 0.3s ease;
  }
  
  .sidebar-backdrop.show {
    opacity: 1;
    visibility: visible;
  }
}

/* Navigation History Floating Element */
.navigation-history {
    position: fixed;
    top: 10%;
    right: 20px;
    transform: translateY(-50%);
    z-index: 1050;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}

.nav-history-toggle {
    width: 50px;
    height: 50px;
    background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    cursor: pointer;
    box-shadow: 0 4px 20px rgba(0, 123, 255, 0.3);
    transition: all 0.3s ease;
    position: relative;
    border: 3px solid rgba(255, 255, 255, 0.2);
}

.nav-history-toggle:hover {
    transform: scale(1.1);
    box-shadow: 0 6px 25px rgba(0, 123, 255, 0.4);
    background: linear-gradient(135deg, #0056b3 0%, #004085 100%);
}

.nav-history-toggle i {
    font-size: 1.2rem;
    transition: transform 0.3s ease;
}

.nav-history-toggle:hover i {
    transform: rotate(360deg);
}

.nav-history-badge {
    position: absolute;
    top: -5px;
    right: -5px;
    background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
    color: white;
    border-radius: 50%;
    width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 0.7rem;
    font-weight: bold;
    border: 2px solid white;
    box-shadow: 0 2px 8px rgba(220, 53, 69, 0.3);
    opacity: 0;
    transform: scale(0);
    transition: all 0.3s ease;
}

.nav-history-badge.visible {
    opacity: 1;
    transform: scale(1);
}

.nav-history-panel {
    position: absolute;
    top: 0;
    right: 70px;
    width: 350px;
    background: rgba(255, 255, 255, 0.98);
    backdrop-filter: blur(15px);
    border-radius: 15px;
    box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
    border: 1px solid rgba(255, 255, 255, 0.3);
    opacity: 0;
    visibility: hidden;
    transform: translateX(20px) scale(0.9);
    transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
    max-height: 80vh;
    display: flex;
    flex-direction: column;
}

.nav-history-panel.visible {
    opacity: 1;
    visibility: visible;
    transform: translateX(0) scale(1);
}

.nav-history-header {
    padding: 15px 20px;
    border-bottom: 1px solid #e9ecef;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-radius: 15px 15px 0 0;
}

.nav-history-header h6 {
    color: #495057;
    font-weight: 600;
}

.nav-history-controls .btn {
    padding: 0.25rem 0.5rem;
    margin-left: 0.25rem;
}

.nav-history-body {
    flex: 1;
    overflow-y: auto;
    max-height: 400px;
    padding: 10px 0;
}

.nav-history-empty {
    text-align: center;
    padding: 40px 20px;
}

.nav-history-item {
    display: flex;
    align-items: center;
    padding: 12px 20px;
    cursor: pointer;
    transition: all 0.2s ease;
    border-left: 3px solid transparent;
    position: relative;
}

.nav-history-item:hover {
    background: linear-gradient(90deg, rgba(0, 123, 255, 0.1) 0%, transparent 100%);
    border-left-color: #007bff;
    transform: translateX(3px);
}

.nav-history-item.current {
    background: linear-gradient(90deg, rgba(40, 167, 69, 0.1) 0%, transparent 100%);
    border-left-color: #28a745;
    font-weight: 600;
}

.nav-history-icon {
    width: 24px;
    height: 24px;
    background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
    border-radius: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 0.8rem;
    margin-right: 12px;
    flex-shrink: 0;
}

.nav-history-content {
    flex: 1;
    min-width: 0;
}

.nav-history-title {
    font-size: 0.9rem;
    font-weight: 500;
    color: #212529;
    margin: 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.nav-history-path {
    font-size: 0.75rem;
    color: #6c757d;
    margin: 2px 0 0 0;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.nav-history-time {
    font-size: 0.7rem;
    color: #adb5bd;
    margin-left: 8px;
    flex-shrink: 0;
}

.nav-history-footer {
    padding: 10px 20px;
    border-top: 1px solid #e9ecef;
    background: #f8f9fa;
    border-radius: 0 0 15px 15px;
}

.nav-history-shortcuts {
    display: flex;
    align-items: center;
    gap: 2px;
}

.nav-history-shortcuts kbd {
    background: #e9ecef;
    border: 1px solid #ced4da;
    border-radius: 3px;
    box-shadow: 0 1px 0 rgba(0, 0, 0, 0.2);
    color: #495057;
    display: inline-block;
    font-size: 0.7rem;
    font-weight: 700;
    line-height: 1;
    padding: 2px 4px;
    white-space: nowrap;
}

/* Quick Back Button */
.quick-back-button {
    position: fixed;
    top: 95%;
    left: 20px;
    transform: translateY(-50%);
    width: 45px;
    height: 45px;
    background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    cursor: pointer;
    box-shadow: 0 4px 20px rgba(40, 167, 69, 0.3);
    transition: all 0.3s ease;
    z-index: 1040;
    border: 3px solid rgba(255, 255, 255, 0.2);
    opacity: 0;
    transform: translateY(-50%) translateX(-100px);
}

.quick-back-button.visible {
    opacity: 1;
    transform: translateY(-50%) translateX(0);
}

.quick-back-button:hover {
    transform: translateY(-50%) scale(1.1);
    box-shadow: 0 6px 25px rgba(40, 167, 69, 0.4);
}

.quick-back-text {
    position: absolute;
    left: 60px;
    background: rgba(33, 37, 41, 0.9);
    color: white;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 0.8rem;
    font-weight: 500;
    white-space: nowrap;
    opacity: 0;
    transform: translateX(-10px);
    transition: all 0.2s ease;
    pointer-events: none;
}

.quick-back-button:hover .quick-back-text {
    opacity: 1;
    transform: translateX(0);
}

.quick-back-tooltip {
    position: absolute;
    bottom: 60px;
    left: 50%;
    transform: translateX(-50%);
    background: rgba(33, 37, 41, 0.9);
    color: white;
    padding: 6px 10px;
    border-radius: 6px;
    font-size: 0.75rem;
    white-space: nowrap;
    opacity: 0;
    transform: translateX(-50%) translateY(10px);
    transition: all 0.2s ease;
    pointer-events: none;
    max-width: 200px;
    text-align: center;
}

.quick-back-button:hover .quick-back-tooltip {
    opacity: 1;
    transform: translateX(-50%) translateY(0);
}
i.nav-icon {
    font-style: inherit;
}
.modal {
    backdrop-filter: blur(2px);
}
/* Responsive adjustments */
@media (max-width: 768px) {
    .navigation-history {
        right: 10px;
    }
    
    .nav-history-panel {
        width: 300px;
        right: 60px;
    }
    
    .quick-back-button {
        left: 10px;
        width: 40px;
        height: 40px;
    }
    
    .quick-back-text {
        left: 50px;
    }
}

@media (max-width: 480px) {
    .nav-history-panel {
        width: calc(100vw - 80px);
        right: 60px;
    }
}

/* Scrollbar styling for history panel */
.nav-history-body::-webkit-scrollbar {
    width: 6px;
}

.nav-history-body::-webkit-scrollbar-track {
    background: transparent;
}

.nav-history-body::-webkit-scrollbar-thumb {
    background: linear-gradient(180deg, #007bff 0%, #0056b3 100%);
    border-radius: 3px;
}

.nav-history-body::-webkit-scrollbar-thumb:hover {
    background: linear-gradient(180deg, #0056b3 0%, #004085 100%);
}

/* Animation for new history items */
@keyframes slideInHistory {
    from {
        opacity: 0;
        transform: translateX(-20px);
    }
    to {
        opacity: 1;
        transform: translateX(0);
    }
}

.nav-history-item.new {
    animation: slideInHistory 0.3s ease;
}

/* Pulse animation for toggle when new item is added */
@keyframes pulseHistory {
    0% { transform: scale(1); }
    50% { transform: scale(1.1); }
    100% { transform: scale(1); }
}

.nav-history-toggle.pulse {
    animation: pulseHistory 0.6s ease;
}
.form-check-input:checked[type=checkbox] {
    border: 1px solid #ffffff85;
   }

/* Auto-populate indicator styles */
.auto-populate-indicator {
    position: absolute;
    top: -8px;
    right: 5px;
    z-index: 10;
    animation: fadeInScale 0.3s ease-out;
    font-size: 0.7rem !important;
}

@keyframes fadeInScale {
    from {
        opacity: 0;
        transform: scale(0.8) translateY(5px);
    }
    to {
        opacity: 1;
        transform: scale(1) translateY(0);
    }
}

.auto-populate-indicator:hover {
    animation: pulse 1s infinite;
}

@keyframes pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.05); }
    100% { transform: scale(1); }
}

/* Ensure parent elements can contain absolutely positioned indicators */
.load-event-selection .form-floating,
.load-event-selection .input-group,
.load-event-selection .form-group,
.load-event-selection .mb-3,
.load-event-selection .col-md-3,
.load-event-selection .col-md-4,
.load-event-selection .col-md-6 {
    position: relative;
}

</style>


<style>
  :root{
    --sidebar-icon-color: #9FB0C9;     /* muted */
    --sidebar-icon-active: #39FF14;    /* StyleScore Neon Lime */
  }
  .sidebar-nav-link{
    color: #EAF2FF;
  }
  .sidebar-nav-link .sidebar-icon{
    display:inline-flex; align-items:center; justify-content:center;
    width:1.25rem; height:1.25rem; margin-right:.6rem; flex:0 0 auto;
    color: var(--sidebar-icon-color);
  }
  .sidebar-nav-link:hover .sidebar-icon,
  .sidebar-nav-link.active .sidebar-icon{
    color: var(--sidebar-icon-active); /* optional 2nd color on hover/active */
  }
  /* Make Lucide SVGs inherit sizing & color */
  .sidebar-icon svg{
    width:100%; height:100%;
    stroke: currentColor;
    stroke-width: 1.8;
  }
  /* Optional: slightly smaller submenu icons */
  .sidebar-icon.submenu-icon{ width:1.05rem; height:1.05rem; margin-right:.5rem; }
</style>

<script>
  class NavigationHistory {
    constructor() {
        this.history = JSON.parse(localStorage.getItem('navigationHistory') || '[]');
        this.maxHistoryItems = 20;
        this.isVisible = false;
        this.currentPage = this.getCurrentPageInfo();
        
        this.init();
    }
    
    init() {
        this.updateDisplay();
        this.addCurrentPage();
        this.setupEventListeners();
        this.updateQuickBackButton();
    }
    
    getCurrentPageInfo() {
        const path = window.location.pathname;
        const title = document.title || this.getTitleFromPath(path);
        const icon = this.getIconFromPath(path);
        
        return {
            path: path,
            title: title,
            icon: icon,
            timestamp: new Date().toISOString(),
            url: window.location.href
        };
    }
    
    getTitleFromPath(path) {
        const segments = path.split('/').filter(s => s);
        const page = segments[segments.length - 1] || 'Dashboard';
        return page.replace(/\.(php|html)$/, '').replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
    }
    
    getIconFromPath(path) {
        const iconMap = {
            'dashboard': '🏠',
            'events': '📅',
            'participants': '👤',
            'judges': '👨‍💼',
            'heats': '🔥',
            'score': '📝',
            'results': '🏆',
            'analytics': '📊',
            'admin': '🛠️',
            'live': '📺',
            'head_judge': '👑',
            'bib': '#️⃣',
            'categories': '📋'
        };
        
        for (const [key, icon] of Object.entries(iconMap)) {
            if (path.toLowerCase().includes(key)) {
                return icon;
            }
        }
        return '📄';
    }
    
    addCurrentPage() {
        const current = this.currentPage;
        
        // Don't add if it's the same as the last entry
        if (this.history.length > 0) {
            const lastEntry = this.history[this.history.length - 1];
            if (lastEntry.path === current.path && 
                new Date(current.timestamp) - new Date(lastEntry.timestamp) < 5000) {
                return;
            }
        }
        
        // Remove any existing entry for this path
        this.history = this.history.filter(item => item.path !== current.path);
        
        // Add to end of history
        this.history.push(current);
        
        // Limit history size
        if (this.history.length > this.maxHistoryItems) {
            this.history = this.history.slice(-this.maxHistoryItems);
        }
        
        this.saveHistory();
        this.updateDisplay();
        this.updateQuickBackButton();
        
        // Pulse animation for new item
        document.querySelector('.nav-history-toggle').classList.add('pulse');
        setTimeout(() => {
            document.querySelector('.nav-history-toggle').classList.remove('pulse');
        }, 600);
    }
    
    saveHistory() {
        localStorage.setItem('navigationHistory', JSON.stringify(this.history));
    }
    
    updateDisplay() {
        const countBadge = document.getElementById('historyCount');
        const historyBody = document.getElementById('historyBody');
        
        countBadge.textContent = this.history.length;
        countBadge.classList.toggle('visible', this.history.length > 0);
        
        if (this.history.length === 0) {
            historyBody.innerHTML = `
                <div class="nav-history-empty">
                    <i class="fas fa-map-signs fa-2x text-muted mb-2"></i>
                    <p class="text-muted mb-0">No navigation history yet</p>
                    <small class="text-muted">Start browsing to build your path</small>
                </div>
            `;
            return;
        }
        
        // Reverse history to show most recent first
        const reversedHistory = [...this.history].reverse();
        
        historyBody.innerHTML = reversedHistory.map((item, index) => {
            const isCurrentPage = item.path === this.currentPage.path;
            const timeAgo = this.getTimeAgo(item.timestamp);
            
            return `
                <div class="nav-history-item ${isCurrentPage ? 'current' : ''}" 
                     onclick="navigateToHistoryItem('${item.url}')"
                     title="${item.title} - ${item.path}">
                    <div class="nav-history-icon">
                        ${item.icon}
                    </div>
                    <div class="nav-history-content">
                        <p class="nav-history-title">${item.title}</p>
                        <p class="nav-history-path">${item.path}</p>
                    </div>
                    <div class="nav-history-time">${timeAgo}</div>
                </div>
            `;
        }).join('');
    }
    
    getTimeAgo(timestamp) {
        const now = new Date();
        const time = new Date(timestamp);
        const diffMs = now - time;
        const diffMins = Math.floor(diffMs / 60000);
        const diffHours = Math.floor(diffMins / 60);
        const diffDays = Math.floor(diffHours / 24);
        
        if (diffMins < 1) return 'now';
        if (diffMins < 60) return `${diffMins}m`;
        if (diffHours < 24) return `${diffHours}h`;
        if (diffDays < 7) return `${diffDays}d`;
        return time.toLocaleDateString();
    }
    
    clearHistory() {
        this.history = [];
        this.saveHistory();
        this.updateDisplay();
        this.updateQuickBackButton();
    }
    
    getPreviousPage() {
        const reversedHistory = [...this.history].reverse();
        const currentIndex = reversedHistory.findIndex(item => item.path === this.currentPage.path);
        
        if (currentIndex > 0) {
            return reversedHistory[currentIndex + 1];
        } else if (reversedHistory.length > 1) {
            return reversedHistory[1]; // Second most recent if current is most recent
        }
        
        return null;
    }
    
    updateQuickBackButton() {
        const quickBackButton = document.getElementById('quickBackButton');
        const backTooltip = document.getElementById('backTooltip');
        const previousPage = this.getPreviousPage();
        
        if (previousPage && this.history.length > 1) {
            quickBackButton.style.display = 'flex';
            backTooltip.textContent = `Back to ${previousPage.title}`;
            setTimeout(() => {
                quickBackButton.classList.add('visible');
            }, 100);
        } else {
            quickBackButton.classList.remove('visible');
            setTimeout(() => {
                quickBackButton.style.display = 'none';
            }, 300);
        }
    }
    
    setupEventListeners() {
        // Mobile toggle button
        const toggleBtn = document.querySelector('[data-bs-target="#sidebarMenu"]');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', (e) => {
                e.preventDefault();
                this.toggle();
            });
        }
        
        // Handle window resize
        window.addEventListener('resize', () => {
            this.handleResize();
        });
        
        // Handle submenu toggles (including nested submenus)
        const submenuToggles = document.querySelectorAll('.submenu-toggle');
        submenuToggles.forEach(toggle => {
            toggle.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation(); // Prevent event bubbling for nested submenus
                
                const target = toggle.getAttribute('data-bs-target');
                const submenu = document.querySelector(target);
                const isExpanded = toggle.getAttribute('aria-expanded') === 'true';
                
                // Toggle current submenu
                if (submenu) {
                    if (isExpanded) {
                        submenu.classList.remove('show');
                        toggle.setAttribute('aria-expanded', 'false');
                        
                        // Also close any nested submenus
                        const nestedSubmenus = submenu.querySelectorAll('.sidebar-submenu.show');
                        nestedSubmenus.forEach(nested => {
                            nested.classList.remove('show');
                            const nestedToggle = document.querySelector(`[data-bs-target="#${nested.id}"]`);
                            if (nestedToggle) {
                                nestedToggle.setAttribute('aria-expanded', 'false');
                            }
                        });
                    } else {
                        // Close other submenus at the same level
                        const parentSubmenu = toggle.closest('.sidebar-submenu');
                        if (parentSubmenu) {
                            // This is a nested submenu, only close siblings
                            const siblingSubmenus = parentSubmenu.querySelectorAll('.sidebar-submenu.show');
                            siblingSubmenus.forEach(sibling => {
                                if (sibling !== submenu) {
                                    sibling.classList.remove('show');
                                    const siblingToggle = document.querySelector(`[data-bs-target="#${sibling.id}"]`);
                                    if (siblingToggle) {
                                        siblingToggle.setAttribute('aria-expanded', 'false');
                                    }
                                }
                            });
                        } else {
                            // This is a top-level submenu, close other top-level submenus
                            const topLevelSubmenus = document.querySelectorAll('.sidebar-content > .sidebar-section > .sidebar-nav-list > .has-submenu .sidebar-submenu.show');
                            topLevelSubmenus.forEach(topLevel => {
                                if (topLevel !== submenu) {
                                    topLevel.classList.remove('show');
                                    const topToggle = document.querySelector(`[data-bs-target="#${topLevel.id}"]`);
                                    if (topToggle) {
                                        topToggle.setAttribute('aria-expanded', 'false');
                                    }
                                }
                            });
                        }
                        
                        // Open the clicked submenu
                        submenu.classList.add('show');
                        toggle.setAttribute('aria-expanded', 'true');
                    }
                }
            });
        });
        
        // Close sidebar when clicking on mobile menu items
        const sidebarLinks = document.querySelectorAll('.sidebar-nav-link:not(.submenu-toggle), .submenu-item');
        sidebarLinks.forEach(link => {
            link.addEventListener('click', () => {
                if (window.innerWidth < 992) {
                    this.hide();
                }
            });
        });
    }
}

// Global navigation history instance
let navHistory;

// Initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', function() {
    navHistory = new NavigationHistory();
});

// Global functions for UI interaction
function toggleNavigationHistory() {
    const panel = document.getElementById('historyPanel');
    navHistory.isVisible = !navHistory.isVisible;
    
    panel.classList.toggle('visible', navHistory.isVisible);
    
    if (navHistory.isVisible) {
        navHistory.updateDisplay();
    }
}

function navigateToHistoryItem(url) {
    window.location.href = url;
}

function navigateBack() {
    const previousPage = navHistory.getPreviousPage();
    if (previousPage) {
        window.location.href = previousPage.url;
    }
}

function clearNavigationHistory() {
    if (confirm('Are you sure you want to clear your navigation history?')) {
        navHistory.clearHistory();
        toggleNavigationHistory();
    }
}
// Add active class to current page
document.addEventListener('DOMContentLoaded', function() {
  const currentPath = window.location.pathname;
  const currentFullUrl = window.location.href;
  const sidebarLinks = document.querySelectorAll('.sidebar-nav-link, .submenu-item');
  
  let foundActiveLink = false;
  
  sidebarLinks.forEach(link => {
    const href = link.getAttribute('href');
    if (!href) return;
    
    let isActive = false;
    
    // Handle external links (like TV Overlay)
    if (href.startsWith('http://') || href.startsWith('https://')) {
      // For external links, only mark as active if we're actually on that domain/path
      try {
        const linkUrl = new URL(href);
        const currentUrl = new URL(currentFullUrl);
        isActive = linkUrl.pathname === currentUrl.pathname && linkUrl.hostname === currentUrl.hostname;
      } catch (e) {
        // Invalid URL, skip
        isActive = false;
      }
    } else {
      // Handle internal links
      const hrefPath = href.split('?')[0]; // Remove query parameters
      const filename = hrefPath.split('/').pop();
      const currentFilename = currentPath.split('/').pop();
      
      // Check for exact filename match first
      if (filename && currentFilename === filename) {
        isActive = true;
      } else if (filename && filename !== '' && currentPath.includes('/' + filename)) {
        // Check if the current path contains the filename as a path segment
        isActive = true;
      } else if (hrefPath !== '/' && currentPath.includes(hrefPath)) {
        // Check if current path contains the href path (but not root)
        isActive = true;
      }
    }
    
    if (isActive && !foundActiveLink) {
      link.classList.add('active');
      foundActiveLink = true;
      
      // If it's a submenu item, also expand the parent
      if (link.classList.contains('submenu-item')) {
        const submenu = link.closest('.sidebar-submenu');
        if (submenu) {
          submenu.classList.add('show');
          const toggle = document.querySelector(`[data-bs-target="#${submenu.id}"]`);
          if (toggle) {
            toggle.setAttribute('aria-expanded', 'true');
          }
          
          // Also expand any parent submenus (for nested menus)
          let parentSubmenu = submenu.closest('.sidebar-submenu');
          while (parentSubmenu) {
            parentSubmenu.classList.add('show');
            const parentToggle = document.querySelector(`[data-bs-target="#${parentSubmenu.id}"]`);
            if (parentToggle) {
              parentToggle.setAttribute('aria-expanded', 'true');
            }
            parentSubmenu = parentSubmenu.parentElement.closest('.sidebar-submenu');
          }
        }
      }
    }
  });
});

// Event Selection Storage and Restoration
window.EventSelectionManager = {
    // Keys for localStorage
    keys: {
        event: 'selectedEventId',
        heat: 'selectedHeatNumber', 
        run: 'selectedRunNumber'
    },
    
    // Track which fields have been triggered to prevent loops
    triggeredFields: new Set(),
    
    // Timer for debouncing input events
    inputDebounceTimer: null,
    
    // Save selection to localStorage
    saveSelection: function(type, value) {
        if (this.keys[type]) {
            localStorage.setItem(this.keys[type], value);
            console.log(`Saved ${type}:`, value);
            
            // Auto-populate forms after saving
            this.populateFormFields();
        }
    },
    
    // Get saved selection from localStorage
    getSavedSelection: function(type) {
        if (this.keys[type]) {
            const value = localStorage.getItem(this.keys[type]);
            console.log(`Retrieved ${type}:`, value);
            return value;
        }
        return null;
    },
    
    // Clear all saved selections
    clearAllSelections: function() {
        Object.values(this.keys).forEach(key => {
            localStorage.removeItem(key);
        });
        console.log('Cleared all event selections');
        
        // Clear form fields after clearing selections
        this.populateFormFields();
    },
    
    // Auto-populate form fields with saved selections
    populateFormFields: function() {
        // Find all forms with the load-event-selection class
        const forms = document.querySelectorAll('.load-event-selection');
        
        forms.forEach(form => {
            this.populateForm(form);
        });
        
        // Also check for individual elements with the class (not in forms)
        const elements = document.querySelectorAll('.load-event-selection:not(form) [name], .load-event-selection:not(form) [id]');
        elements.forEach(element => {
            this.populateElement(element);
        });
    },
    
    // Populate a specific form
    populateForm: function(form) {
        // Event ID fields
        const eventFields = form.querySelectorAll('[name="event_id"], [id="event_id"], [name="eventId"], [id="eventId"]');
        const savedEventId = this.getSavedSelection('event');
        
        eventFields.forEach(field => {
            if (savedEventId) {
                this.setFieldValue(field, savedEventId);
                this.triggerChangeEvent(field);
            } else {
                this.setFieldValue(field, '');
            }
        });
        
        // Heat fields
        const heatFields = form.querySelectorAll('[name="heat_number"], [id="heat_number"], [name="heatNumber"], [id="heatNumber"], [name="heat"], [id="heat"]');
        const savedHeatNumber = this.getSavedSelection('heat');
        
        heatFields.forEach(field => {
            if (savedHeatNumber) {
                this.setFieldValue(field, savedHeatNumber);
                this.triggerChangeEvent(field);
            } else {
                this.setFieldValue(field, '');
            }
        });
        
        // Run fields
        const runFields = form.querySelectorAll('[name="run_number"], [id="run_number"], [name="runNumber"], [id="runNumber"], [name="run"], [id="run"]');
        const savedRunNumber = this.getSavedSelection('run');
        
        runFields.forEach(field => {
            if (savedRunNumber) {
                this.setFieldValue(field, savedRunNumber);
                this.triggerChangeEvent(field);
            } else {
                this.setFieldValue(field, '');
            }
        });
    },
    
    // Populate a specific element
    populateElement: function(element) {
        const name = element.getAttribute('name') || element.getAttribute('id') || '';
        
        // Determine which type of field this is and populate accordingly
        if (name.includes('event')) {
            const savedValue = this.getSavedSelection('event');
            if (savedValue) {
                this.setFieldValue(element, savedValue);
                this.triggerChangeEvent(element);
            }
        } else if (name.includes('heat')) {
            const savedValue = this.getSavedSelection('heat');
            if (savedValue) {
                this.setFieldValue(element, savedValue);
                this.triggerChangeEvent(element);
            }
        } else if (name.includes('run')) {
            const savedValue = this.getSavedSelection('run');
            if (savedValue) {
                this.setFieldValue(element, savedValue);
                this.triggerChangeEvent(element);
            }
        }
    },
    
    // Set value for different field types
    setFieldValue: function(field, value) {
        if (!field) return;
        
        const tagName = field.tagName.toLowerCase();
        const type = field.type ? field.type.toLowerCase() : '';
        
        try {
            if (tagName === 'select') {
                // For select elements, check if option exists
                const option = field.querySelector(`option[value="${value}"]`);
                if (option) {
                    field.value = value;
                    this.showPopulatedIndicator(field, value);
                } else {
                    field.value = '';
                }
            } else if (tagName === 'input') {
                if (type === 'checkbox' || type === 'radio') {
                    field.checked = (field.value === value);
                    if (field.checked) {
                        this.showPopulatedIndicator(field, value);
                    }
                } else {
                    field.value = value;
                    if (value) {
                        this.showPopulatedIndicator(field, value);
                    }
                }
            } else if (tagName === 'textarea') {
                field.value = value;
                if (value) {
                    this.showPopulatedIndicator(field, value);
                }
            }
        } catch (error) {
            console.warn('Error setting field value:', error, field);
        }
    },
    
    // Check if URL already has the parameter
    hasUrlParameter: function(paramName) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.has(paramName);
    },
    
    // Get URL parameter value
    getUrlParameter: function(paramName) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(paramName);
    },
    
    // Check if we should trigger change event based on field type and URL params
    shouldTriggerChangeEvent: function(field) {
        const fieldName = field.name || field.id || '';
        
        // Check for event fields
        if (fieldName.includes('event')) {
            // Check if any event parameter exists in URL (even if empty)
            if (this.hasUrlParameter('event_id') || this.hasUrlParameter('eventId') || this.hasUrlParameter('event')) {
                const urlEventId = this.getUrlParameter('event_id') || this.getUrlParameter('eventId') || this.getUrlParameter('event');
                const savedEventId = this.getSavedSelection('event');
                console.log('Skipping event change trigger - URL has event parameter:', urlEventId || '(empty)', 'saved:', savedEventId);
                return false;
            }
        }
        
        // Check for heat fields
        if (fieldName.includes('heat')) {
            // Check if any heat parameter exists in URL (even if empty)
            if (this.hasUrlParameter('heat_id') || this.hasUrlParameter('heat_number') || this.hasUrlParameter('heatId') || this.hasUrlParameter('heat')) {
                const urlHeatId = this.getUrlParameter('heat_id') || this.getUrlParameter('heat_number') || this.getUrlParameter('heatId') || this.getUrlParameter('heat');
                const savedHeatId = this.getSavedSelection('heat');
                console.log('Skipping heat change trigger - URL has heat parameter:', urlHeatId || '(empty)', 'saved:', savedHeatId);
                return false;
            }
        }
        
        // Check for run fields
        if (fieldName.includes('run')) {
            // Check if any run parameter exists in URL (even if empty)
            if (this.hasUrlParameter('run_id') || this.hasUrlParameter('run_number') || this.hasUrlParameter('runId') || this.hasUrlParameter('run')) {
                const urlRunId = this.getUrlParameter('run_id') || this.getUrlParameter('run_number') || this.getUrlParameter('runId') || this.getUrlParameter('run');
                const savedRunId = this.getSavedSelection('run');
                console.log('Skipping run change trigger - URL has run parameter:', urlRunId || '(empty)', 'saved:', savedRunId);
                return false;
            }
        }
        
        return true;
    },
    
    // Trigger change event for field - only once per field per page visit and only if URL doesn't have params
    triggerChangeEvent: function(field) {
        if (!field) return;
        
        // Don't trigger if URL already has the relevant parameter
        if (!this.shouldTriggerChangeEvent(field)) {
            console.log('Skipping change event - URL already has parameter for:', field.name || field.id);
            return;
        }
        
        // Create unique field identifier
        const fieldId = field.name || field.id || field.tagName + '_' + Array.from(field.parentNode.children).indexOf(field);
        
        // Check if we've already triggered this field
        if (this.triggeredFields.has(fieldId)) {
            return;
        }
        
        // Mark field as triggered
        this.triggeredFields.add(fieldId);
        
        try {
            // Create and dispatch change event
            const changeEvent = new Event('change', { bubbles: true });
            field.dispatchEvent(changeEvent);
            
            // Also trigger input event for some frameworks
            const inputEvent = new Event('input', { bubbles: true });
            field.dispatchEvent(inputEvent);
        } catch (error) {
            console.warn('Error triggering change event:', error, field);
        }
    },
    
    // Show visual indicator that field was auto-populated
    showPopulatedIndicator: function(field, value) {
        // Don't show indicator for main navigation selects to avoid clutter
        if (field.id === 'eventSelect' || field.id === 'heatSelect' || field.id === 'runSelect') {
            return;
        }
        
        // Create indicator element
        const indicator = document.createElement('span');
        indicator.className = 'auto-populate-indicator badge bg-info ms-2';
        indicator.innerHTML = '<i class="fas fa-magic me-1"></i>Auto-filled';
        indicator.style.fontSize = '0.7rem';
        indicator.title = `Auto-populated with saved value: ${value}`;
        
        // Position indicator
        const parent = field.parentElement;
        if (parent && !parent.querySelector('.auto-populate-indicator')) {
            parent.style.position = 'relative';
            parent.appendChild(indicator);
            
            // Remove indicator after 3 seconds
            setTimeout(() => {
                if (indicator.parentElement) {
                    indicator.remove();
                }
            }, 3000);
        }
    },
    
    // Setup event listeners for manual changes in load-event-selection forms
    setupFormChangeListeners: function() {
        // Use event delegation to handle dynamically added forms
        document.addEventListener('change', (e) => {
            const field = e.target;
            const form = field.closest('.load-event-selection');
            
            // Only process fields within load-event-selection forms/containers
            if (!form) return;
            
            const fieldName = field.name || field.id || '';
            const fieldValue = field.type === 'checkbox' ? (field.checked ? field.value : '') : field.value;
            
            // Determine field type and save accordingly
            if (fieldName.includes('event')) {
                this.saveSelection('event', fieldValue);
                console.log('Manual event selection updated:', fieldValue);
                
                // Clear dependent selections when event changes
                if (!fieldValue) {
                    this.saveSelection('heat', '');
                    this.saveSelection('run', '');
                }
            } else if (fieldName.includes('heat')) {
                this.saveSelection('heat', fieldValue);
                console.log('Manual heat selection updated:', fieldValue);
                
                // Clear dependent run selection when heat changes
                if (!fieldValue) {
                    this.saveSelection('run', '');
                }
            } else if (fieldName.includes('run')) {
                this.saveSelection('run', fieldValue);
                console.log('Manual run selection updated:', fieldValue);
            }
        });
        
        // Also listen for input events for text fields
        document.addEventListener('input', (e) => {
            const field = e.target;
            const form = field.closest('.load-event-selection');
            
            // Only process text/number inputs within load-event-selection forms
            if (!form || !['text', 'number', 'search'].includes(field.type)) return;
            
            const fieldName = field.name || field.id || '';
            const fieldValue = field.value;
            
            // Debounce input events to avoid excessive saves
            clearTimeout(this.inputDebounceTimer);
            this.inputDebounceTimer = setTimeout(() => {
                if (fieldName.includes('event')) {
                    this.saveSelection('event', fieldValue);
                    console.log('Manual event input updated:', fieldValue);
                } else if (fieldName.includes('heat')) {
                    this.saveSelection('heat', fieldValue);
                    console.log('Manual heat input updated:', fieldValue);
                } else if (fieldName.includes('run')) {
                    this.saveSelection('run', fieldValue);
                    console.log('Manual run input updated:', fieldValue);
                }
            }, 300); // 300ms debounce
        });
    },
    
    // Setup event listeners for select elements
    setupEventListeners: function() {
        // Event select
        const eventSelect = document.getElementById('eventSelect');
        if (eventSelect) {
            eventSelect.addEventListener('change', (e) => {
                this.saveSelection('event', e.target.value);
                if (!e.target.value) {
                    // Clear heat and run when event is cleared
                    this.saveSelection('heat', '');
                    this.saveSelection('run', '');
                }
            });
        }
        
        // Heat select  
        const heatSelect = document.getElementById('heatSelect');
        if (heatSelect) {
            heatSelect.addEventListener('change', (e) => {
                this.saveSelection('heat', e.target.value);
                if (!e.target.value) {
                    // Clear run when heat is cleared
                    this.saveSelection('run', '');
                }
            });
        }
        
        // Run select
        const runSelect = document.getElementById('runSelect');
        if (runSelect) {
            runSelect.addEventListener('change', (e) => {
                this.saveSelection('run', e.target.value);
            });
        }
        
        // Watch for new forms being added to the page
        this.observeForNewForms();
    },
    
    // Observe for dynamically added forms
    observeForNewForms: function() {
        if (typeof MutationObserver !== 'undefined') {
            const observer = new MutationObserver((mutations) => {
                mutations.forEach((mutation) => {
                    mutation.addedNodes.forEach((node) => {
                        if (node.nodeType === Node.ELEMENT_NODE) {
                            // Check if the added node or its children have load-event-selection class
                            const forms = node.classList && node.classList.contains('load-event-selection') 
                                ? [node] 
                                : node.querySelectorAll ? node.querySelectorAll('.load-event-selection') : [];
                            
                            forms.forEach(form => {
                                setTimeout(() => this.populateForm(form), 100);
                            });
                        }
                    });
                });
            });
            
            observer.observe(document.body, {
                childList: true,
                subtree: true
            });
        }
    },
    
    // Restore saved selections to select elements
    restoreSelections: function() {
        const eventSelect = document.getElementById('eventSelect');
        const heatSelect = document.getElementById('heatSelect');
        const runSelect = document.getElementById('runSelect');
        
        // Restore event selection
        const savedEvent = this.getSavedSelection('event');
        if (savedEvent && eventSelect) {
            // Check if option exists in current select
            const eventOption = eventSelect.querySelector(`option[value="${savedEvent}"]`);
            if (eventOption) {
                eventSelect.value = savedEvent;
                eventSelect.dispatchEvent(new Event('change'));
                console.log('Restored event selection:', savedEvent);
                
                // Delay heat restoration to allow heat loading
                setTimeout(() => {
                    this.restoreHeatSelection();
                }, 500);
            } else {
                // Clear saved selection if option no longer exists
                this.saveSelection('event', '');
            }
        }
        
        // Populate all forms on page load
        setTimeout(() => {
            this.populateFormFields();
        }, 300);
    },
    
    // Restore heat selection (called after heats are loaded)
    restoreHeatSelection: function() {
        const heatSelect = document.getElementById('heatSelect');
        const savedHeat = this.getSavedSelection('heat');
        
        if (savedHeat && heatSelect) {
            const heatOption = heatSelect.querySelector(`option[value="${savedHeat}"]`);
            if (heatOption) {
                heatSelect.value = savedHeat;
                heatSelect.dispatchEvent(new Event('change'));
                console.log('Restored heat selection:', savedHeat);
                
                // Delay run restoration to allow run loading
                setTimeout(() => {
                    this.restoreRunSelection();
                }, 300);
            } else {
                // Clear saved selection if option no longer exists
                this.saveSelection('heat', '');
            }
        }
    },
    
    // Restore run selection (called after runs are loaded)
    restoreRunSelection: function() {
        const runSelect = document.getElementById('runSelect');
        const savedRun = this.getSavedSelection('run');
        
        if (savedRun && runSelect) {
            const runOption = runSelect.querySelector(`option[value="${savedRun}"]`);
            if (runOption) {
                runSelect.value = savedRun;
                runSelect.dispatchEvent(new Event('change'));
                console.log('Restored run selection:', savedRun);
            } else {
                // Clear saved selection if option no longer exists
                this.saveSelection('run', '');
            }
        }
    },
    
    // Initialize the manager
    init: function() {
        console.log('Initializing Event Selection Manager');
        this.setupEventListeners();
        this.setupFormChangeListeners();
        
        // Restore selections with a small delay to ensure elements are ready
        setTimeout(() => {
            this.restoreSelections();
        }, 200);
    },
    
    // Manual trigger for populating all forms (useful for testing or dynamic content)
    populateAllForms: function() {
        console.log('Manually populating all forms with load-event-selection class');
        this.populateFormFields();
        return {
            event: this.getSavedSelection('event'),
            heat: this.getSavedSelection('heat'),
            run: this.getSavedSelection('run')
        };
    },
    
    // Get current selections (useful for debugging)
    getCurrentSelections: function() {
        return {
            event: this.getSavedSelection('event'),
            heat: this.getSavedSelection('heat'),
            run: this.getSavedSelection('run')
        };
    }
};

// Initialize Event Selection Manager when DOM is loaded
document.addEventListener('DOMContentLoaded', function() {
    if (typeof window.EventSelectionManager !== 'undefined') {
        window.EventSelectionManager.init();
        
        // Add global helper functions for easy access
        window.populateEventForms = function() {
            return window.EventSelectionManager.populateAllForms();
        };
        
        window.getEventSelections = function() {
            return window.EventSelectionManager.getCurrentSelections();
        };
        
        window.clearEventSelections = function() {
            window.EventSelectionManager.clearAllSelections();
        };
        
        // Log that the system is ready
        console.log('Event Selection Manager ready. Use these console commands:');
        console.log('- populateEventForms(): Manually populate all forms');
        console.log('- getEventSelections(): Get current saved selections');
        console.log('- clearEventSelections(): Clear all saved selections');
    }
});
</script>
  <?php endif; ?>
<?php
// Render notification system UI components
if (function_exists('render_notification_system')) {
    render_notification_system();
}
?>
