.controls {
  position: sticky;
  top: var(--top-navbar-height);
  z-index: 999;
  background: rgba(0,0,0,0.5);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  border-style: solid;
  border-color: rgba(255,255,255,0.2);
  border-width: 1px 0;
  border-radius: 0;
  padding: 10px 20px;
  box-shadow: none;
  width: auto;
  margin: 0 -20px 15px -20px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  gap: 8px;
  opacity: 0;
  visibility: hidden;
}
.controls.loaded {
    visibility: visible;
    animation: navControlsContainer_FadeIn 0.2s ease-out forwards;
}

@media (max-width: 768px) {
  .controls {
    padding: 8px 15px;
  }
}

@media (max-width: 480px) {
  .controls {
    padding: 8px 10px;
  }
}

.controls-separator {
  width: 1px;
  height: 24px;
  background-color: rgba(255,255,255,0.3);
}

.controls.loaded .announcement-bar:not(.hidden) {
  animation: announcementBar_SlideDownAndFadeIn 0.4s cubic-bezier(0.215, 0.610, 0.355, 1.000) forwards;
  animation-delay: 0.05s;
  opacity: 0;
  width: 100%;
  justify-content: center;
}

/* Clean and consistent navigation controls */
.search-sort {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1 1 auto;
  opacity: 0;
  width: 100%;
  justify-content: flex-start;
  box-sizing: border-box;
  max-width: 1200px;
  margin: 0 auto;
  overflow: visible;
  min-width: 0; /* Allow flex children to shrink */
  flex-wrap: nowrap; /* Force single line */
}

/* Base nav item styling */
.search-sort .nav-item {
  flex-shrink: 0;
  box-sizing: border-box;
}

/* Search input - flexible sizing for large screens */
.search-sort .nav-item input[type="text"] {
  width: 100%;
  font-size: 0.9em;
  transition: width 0.3s ease, font-size 0.3s ease;
  box-sizing: border-box;
  flex: 1;
  background: transparent;
  border: none !important; /* ensure only wrapper shows the 1px border */
  height: 34px; /* 36px wrapper minus 2px border for perfect fit */
}

/* Select dropdowns - HIDDEN - replaced by button display text */
.search-sort .nav-item select {
  display: none !important;
  visibility: hidden !important;
  opacity: 0 !important;
  position: absolute !important;
  left: -9999px !important;
  width: 0 !important;
  height: 0 !important;
  z-index: -1 !important;
}

/* Keep input wrappers with balanced flexible sizing */
.search-sort .input-icon-wrapper {
  flex: 0 0 auto;
  min-width: 0;
  display: inline-flex;
  align-items: center;
  position: relative;
  width: fit-content;
  max-width: 100%;
  overflow: hidden;
  background: rgba(0,0,0,0.3);
  border: 1px solid rgba(255,255,255,0.2);
  border-radius: 4px;
  transition: opacity 0.2s ease, border-color 0.2s ease;
  box-sizing: border-box; /* match control buttons sizing */
  height: 36px; /* align height with Reset/Music/Settings */
}

/* Focus style mirrors Value Dynamics: white border on top + blue outline ring */
.search-sort .input-icon-wrapper:focus-within {
  border-color: rgba(255, 255, 255, 0.85) !important; /* keep white border visible */
  outline: 1px solid #1a73e8 !important;              /* blue ring outside */
  outline-offset: 0 !important;
  box-shadow: none !important;
}
/* On hover while focused, keep the white border (avoid flipping back) */
.search-sort .input-icon-wrapper:focus-within:hover {
  border-color: rgba(255, 255, 255, 0.85) !important;
}

/* Ensure outlines persist during click-and-hold (before focus commits on mouseup) */
.search-sort .input-icon-wrapper:active,
.search-sort .input-icon-wrapper:has(.nav-input-style:active),
.search-sort .input-icon-wrapper:has(input:active) {
  border-color: rgba(255, 255, 255, 0.85) !important;
  outline: 1px solid #1a73e8 !important;
  outline-offset: 0 !important;
  box-shadow: none !important;
}
.search-sort .input-icon-wrapper:active:hover {
  border-color: rgba(255, 255, 255, 0.85) !important;
}

/* Persist outlines while press-holding, even if cursor moves off */
.search-sort .input-icon-wrapper.pressing {
  border-color: rgba(255, 255, 255, 0.85) !important;
  outline: 1px solid #1a73e8 !important;
  outline-offset: 0 !important;
  box-shadow: none !important;
}
.search-sort .input-icon-wrapper.pressing:hover {
  border-color: rgba(255, 255, 255, 0.85) !important;
}

/* White hover outline for input wrappers */
.search-sort .input-icon-wrapper:hover {
  border-color: rgba(255, 255, 255, 0.8) !important;
}

/* Ensure search input itself has no browser outline */
.search-sort .nav-item input[type="text"]:focus {
  outline: none !important;
  border: none !important;
}

/* Ensure buttons have no browser outline */
.search-sort .nav-input-style:focus {
  outline: none !important;
}
/* Suppress any outline when disabled */
.search-sort .nav-input-style:disabled,
.search-sort .nav-input-style:disabled:focus,
.search-sort .nav-input-style.disabled,
.search-sort .nav-input-style.disabled:focus {
  outline: none !important;
}

/* Give search input flexible space but allow it to shrink */
.search-sort .input-icon-wrapper[data-nav-priority="1"] {
  flex: 0 1 auto;
  min-width: 120px;
  max-width: none;
}

/* Give sort and filter dynamic space - allow proper scaling */
.search-sort .input-icon-wrapper[data-nav-priority="2"],
.search-sort .input-icon-wrapper[data-nav-priority="3"] {
  flex: 0 0 auto;
  min-width: 120px;
  max-width: 300px;
}

/* Keep buttons as fixed flex items - match input/select styling */
.search-sort .nav-item.control-button {
  flex: 0 0 auto;
  min-width: 80px;
  max-width: 100px;
  padding: 8px 12px;
  background: rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 4px;
  color: #fff;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: border-color 0.2s ease, transform 0.2s ease, box-shadow 0.2s ease, width 0.3s ease;
  font-family: 'Montserrat', sans-serif;
  font-weight: bold;
  cursor: pointer;
}

.control-button:hover {
  background: rgba(0,0,0,0.5);
  border-color: rgba(255,255,255,0.4);
}

/* Immediate feedback on click */
.control-button:active {
  border-color: rgba(255, 255, 255, 0.85) !important; /* keep white border on top */
}

/* Blue focus outline like search/sort/filter */
.control-button:focus,
.control-button:focus-visible,
#LIResetButton:focus,
#LIResetButton:focus-visible,
#LISettingsButton:focus,
#LISettingsButton:focus-visible {
  border-color: rgba(255, 255, 255, 0.85) !important; /* white border */
  outline: 1px solid #1a73e8 !important;             /* blue outline */
  outline-offset: 0 !important;
}
/* Ensure disabled control buttons never show outlines */
.control-button:disabled,
.control-button.disabled {
  outline: none !important;
  border-color: rgba(255, 255, 255, 0.2) !important;
  pointer-events: none !important;
  box-shadow: none !important;
  transform: none !important;
  cursor: not-allowed !important;
}

/* Prevent text wrapping on the Reset Options button */
#LIResetButton {
  max-width: 160px; /* allow longer text without wrapping */
  white-space: nowrap;
}

/* Compact music player styling */
.search-sort .nav-audio-player {
    flex: 0 0 auto;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    min-width: 90px;
    max-width: 100%;
    height: 36px;
    box-sizing: border-box;
    padding: 0 8px;
    background: rgba(0, 0, 0, 0.3);
    border: 1px solid rgba(255, 255, 255, 0.2);
    border-radius: 4px;
    cursor: pointer;
    white-space: nowrap;
    flex-wrap: nowrap;
    transition: transform 0.3s ease, box-shadow 0.3s ease,
                border-color 0.2s ease;
}
/* Grey-out audio player container when its button is disabled */
.search-sort .nav-audio-player:has(button:disabled),
.search-sort .nav-audio-player.disabled {
    opacity: 0.5 !important;
    cursor: not-allowed !important;
    border-color: rgba(255, 255, 255, 0.2) !important;
    outline: none !important;
}
.search-sort .nav-audio-player:has(button:disabled):hover,
.search-sort .nav-audio-player.disabled:hover {
    transform: none !important;
    box-shadow: none !important;
    border-color: rgba(255, 255, 255, 0.2) !important;
}

.search-sort .nav-audio-player > * {
    flex-shrink: 0;
}

.search-sort .nav-audio-player:hover {
  transform: translateY(-2px);
  /* removed glow effect */
  border-color: rgba(255, 255, 255, 0.8);
}

.search-sort .nav-audio-player button {
    padding: 0;
    background: transparent;
    border: none;
    color: #fff;
    height: 36px;
    width: 36px;
    display: flex;
    flex: 0 0 auto;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    font-size: 1em;
}

.search-sort .nav-audio-player button i {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    line-height: 1;
}

.search-sort .nav-audio-player .audio-volume {
    -webkit-appearance: none;
    width: 120px;
    height: 4px;
    margin: 0 6px;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 2px;
    outline: none;
    position: relative;
    cursor: pointer;
    transition: all 0.2s ease;
}

.search-sort .nav-audio-player .audio-volume:hover {
    height: 6px;
    background: rgba(255, 255, 255, 0.3);
}

.search-sort .nav-audio-player .audio-volume::-webkit-slider-thumb {
    -webkit-appearance: none;
    width: 12px;
    height: 12px;
    background: #fff;
    border-radius: 50%;
    cursor: pointer;
    border: none;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
    transition: all 0.2s ease;
    transform: scale(1);
}

.search-sort .nav-audio-player .audio-volume:hover::-webkit-slider-thumb {
    transform: scale(1.1);
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.4);
}

.search-sort .nav-audio-player .audio-volume::-moz-range-thumb {
    width: 12px;
    height: 12px;
    background: #fff;
    border-radius: 50%;
    cursor: pointer;
    border: none;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
    transition: all 0.2s ease;
}

.search-sort .nav-audio-player .audio-volume:hover::-moz-range-thumb {
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.4);
}

.search-sort .nav-audio-player .audio-volume::-moz-range-track {
    background: rgba(255, 255, 255, 0.2);
    height: 4px;
    border-radius: 2px;
    border: none;
}

#audioInfoModal .audio-volume {
    -webkit-appearance: none;
    width: 100%;
    height: 6px;
    margin: 15px 0 25px;
    background: rgba(255, 255, 255, 0.15);
    border-radius: 3px;
    outline: none;
    cursor: pointer;
    position: relative;
    transition: all 0.2s ease;
}

#audioInfoModal .audio-volume:hover {
    height: 8px;
    background: rgba(255, 255, 255, 0.25);
}

#audioInfoModal .audio-progress {
    -webkit-appearance: none;
    width: 100%;
    height: 4px;
    margin: 15px 0;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 2px;
    outline: none;
    cursor: pointer;
    position: relative;
    transition: all 0.2s ease;
}

#audioInfoModal .audio-progress:hover {
    height: 6px;
    background: rgba(255, 255, 255, 0.2);
}

#audioInfoModal .audio-volume::-webkit-slider-thumb {
    -webkit-appearance: none;
    width: 16px;
    height: 16px;
    background: #fff;
    border-radius: 50%;
    cursor: pointer;
    border: none;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
    transition: all 0.2s ease;
    transform: scale(1);
}

#audioInfoModal .audio-volume:hover::-webkit-slider-thumb {
    transform: scale(1.1);
    box-shadow: 0 3px 12px rgba(0, 0, 0, 0.4);
}

#audioInfoModal .audio-progress::-webkit-slider-thumb {
    -webkit-appearance: none;
    width: 14px;
    height: 14px;
    background: #fff;
    border-radius: 50%;
    cursor: pointer;
    border: none;
    box-shadow: 0 1px 6px rgba(0, 0, 0, 0.3);
    transition: all 0.2s ease;
    transform: scale(1);
}

#audioInfoModal .audio-progress:hover::-webkit-slider-thumb {
    transform: scale(1.1);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.4);
}

#audioInfoModal .audio-volume::-moz-range-thumb {
    width: 16px;
    height: 16px;
    background: #fff;
    border-radius: 50%;
    cursor: pointer;
    border: none;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
    transition: all 0.2s ease;
}

#audioInfoModal .audio-volume:hover::-moz-range-thumb {
    box-shadow: 0 3px 12px rgba(0, 0, 0, 0.4);
}

#audioInfoModal .audio-progress::-moz-range-thumb {
    width: 14px;
    height: 14px;
    background: #fff;
    border-radius: 50%;
    cursor: pointer;
    border: none;
    box-shadow: 0 1px 6px rgba(0, 0, 0, 0.3);
    transition: all 0.2s ease;
}

#audioInfoModal .audio-progress:hover::-moz-range-thumb {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.4);
}

#audioInfoModal .audio-volume::-moz-range-track {
    background: rgba(255, 255, 255, 0.15);
    height: 6px;
    border-radius: 3px;
    border: none;
}

#audioInfoModal .audio-progress::-moz-range-track {
    background: rgba(255, 255, 255, 0.1);
    height: 4px;
    border-radius: 2px;
    border: none;
}

#audioInfoModal .audio-player-container {
    display: flex;
    flex-direction: column;
    gap: 12px;
    align-items: center;
    width: 100%;
}

#audioInfoModal .audio-player-row {
    display: flex;
    align-items: center;
    gap: 12px;
    width: 100%;
    max-width: 350px;
    background: #000;
    border: 1px solid rgba(255, 255, 255, 0.15);
    border-radius: 24px;
    padding: 8px 16px;
}

#audioInfoModal .volume-controls {
    display: flex;
    flex-direction: column;
    gap: 12px;
    align-items: center;
    width: 100%;
}

#audioInfoModal .volume-slider-row {
    display: flex;
    align-items: center;
    gap: 12px;
    width: 100%;
    max-width: 350px;
    background: #000;
    border: 1px solid rgba(255, 255, 255, 0.15);
    border-radius: 24px;
    padding: 8px 16px;
}

#audioInfoModal .volume-btn {
    background: #000;
    border: 1px solid rgba(255, 255, 255, 0.3);
    color: rgba(255, 255, 255, 0.7);
    width: 28px;
    height: 28px;
    border-radius: 50%;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;
    font-size: 0.8em;
    flex-shrink: 0;
    text-align: center;
}

#audioInfoModal .volume-btn:hover {
    border-color: rgba(255, 255, 255, 0.6);
    color: #fff;
    transform: scale(1.1);
}

#audioInfoModal .volume-btn:active {
    transform: scale(0.95);
    border-color: rgba(255, 255, 255, 0.8);
}

#audioInfoModal .volume-btn i {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    line-height: 1;
}


#audioInfoModal .volume-display {
    min-width: 35px;
    text-align: center;
    font-size: 0.75em;
    color: rgba(255, 255, 255, 0.7);
    font-weight: 500;
    flex-shrink: 0;
}

#audioInfoModal .volume-slider-row .audio-volume {
    flex: 1;
    margin: 0;
    height: 4px;
    background: rgba(255, 255, 255, 0.1);
}

#audioInfoModal .volume-slider-row .audio-volume:hover {
    height: 6px;
    background: rgba(255, 255, 255, 0.15);
}

#audioInfoModal .volume-presets {
    display: flex;
    gap: 6px;
    justify-content: center;
    flex-wrap: wrap;
    max-width: 350px;
}

#audioInfoModal .volume-preset {
    background: #000;
    border: 1px solid rgba(255, 255, 255, 0.2);
    color: rgba(255, 255, 255, 0.7);
    padding: 4px 8px;
    border-radius: 12px;
    cursor: pointer;
    transition: all 0.2s ease;
    font-size: 0.7em;
    font-weight: 500;
    min-width: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 4px;
}

#audioInfoModal .volume-preset i {
    font-size: 0.8em;
    line-height: 1;
    display: flex;
    align-items: center;
    justify-content: center;
}

#audioInfoModal .volume-preset.active {
    border-color: rgba(255, 255, 255, 0.8);
    color: #fff;
    box-shadow: 0 0 8px rgba(255, 255, 255, 0.3);
}

#audioInfoModal .volume-preset:hover {
    border-color: rgba(255, 255, 255, 0.5);
    color: rgba(255, 255, 255, 0.9);
}

#audioInfoModal .volume-preset:active {
    transform: scale(0.96);
    border-color: rgba(255, 255, 255, 0.7);
}

#audioInfoModal .audio-btn {
    background: #000;
    border: 1px solid rgba(255, 255, 255, 0.3);
    color: rgba(255, 255, 255, 0.7);
    width: 28px;
    height: 28px;
    border-radius: 50%;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;
    font-size: 0.8em;
    flex-shrink: 0;
    text-align: center;
}

#audioInfoModal .audio-btn:hover {
    border-color: rgba(255, 255, 255, 0.6);
    color: #fff;
    transform: scale(1.1);
}

#audioInfoModal .audio-btn:active {
    transform: scale(0.95);
    border-color: rgba(255, 255, 255, 0.8);
}

#audioInfoModal .play-btn {
    width: 32px;
    height: 32px;
    border-color: rgba(255, 255, 255, 0.4);
    font-size: 0.9em;
}

#audioInfoModal .play-btn:hover {
    border-color: rgba(255, 255, 255, 0.7);
}

#audioInfoModal .play-btn:active {
    border-color: rgba(255, 255, 255, 0.9);
}

#audioInfoModal .audio-btn i {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    line-height: 1;
}

#audioInfoModal .audio-player-row .audio-progress {
    flex: 1;
    margin: 0;
    height: 4px;
    background: rgba(255, 255, 255, 0.1);
}

#audioInfoModal .audio-player-row .audio-progress:hover {
    height: 6px;
    background: rgba(255, 255, 255, 0.15);
}

#audioInfoModal .audio-extra-controls {
    display: flex;
    gap: 6px;
    justify-content: center;
    flex-wrap: wrap;
    max-width: 350px;
}

#audioInfoModal .audio-control-preset {
    background: #000;
    border: 1px solid rgba(255, 255, 255, 0.2);
    color: rgba(255, 255, 255, 0.7);
    padding: 4px 8px;
    border-radius: 12px;
    cursor: pointer;
    transition: all 0.2s ease;
    font-size: 0.7em;
    font-weight: 500;
    min-width: 55px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 4px;
}

#audioInfoModal .audio-control-preset i {
    font-size: 0.8em;
    line-height: 1;
    display: flex;
    align-items: center;
    justify-content: center;
}

#audioInfoModal .audio-control-preset.active {
    border-color: rgba(255, 255, 255, 0.8);
    color: #fff;
    box-shadow: 0 0 8px rgba(255, 255, 255, 0.3);
}

#audioInfoModal .audio-control-preset:hover {
    border-color: rgba(255, 255, 255, 0.5);
    color: rgba(255, 255, 255, 0.9);
}

#audioInfoModal .audio-control-preset:active {
    transform: scale(0.96);
    border-color: rgba(255, 255, 255, 0.7);
}

#audioInfoModal .audio-time {
    min-width: 55px;
    text-align: center;
    font-size: 0.7em;
    color: rgba(255, 255, 255, 0.7);
    font-weight: 500;
    font-family: 'Courier New', monospace;
    flex-shrink: 0;
}

      /* Large screens (1400px+) - full size */
.search-sort .nav-audio-player .audio-time {
    font-size: 0.8em;
    color: #fff;
    margin: 0 6px;
    min-width: 48px;
    text-align: center;
    flex: 0 0 auto;
}
/* On narrow screens collapse time display */
@media (max-width: 600px) {
    .search-sort .nav-audio-player .audio-time {
        display: none;
    }
}
  /* Large desktop styles (1400px+) - covered by unified approach above */

/* All screens 1200px+ covered by unified large desktop styles above */

/* Compact mode for limited space (768px and below) - all elements become icon-only */
@media (max-width: 768px) {
  .search-sort {
    gap: 6px; /* Tighter spacing */
  }
  
  /* Search becomes compact */
  .search-sort .input-icon-wrapper[data-nav-priority="1"] {
    flex: 0 1 auto !important;
    min-width: 150px !important;
    max-width: none !important;
  }
  
  .search-sort .nav-item input[type="text"] {
    width: 100% !important;
    font-size: 0.85em !important;
    padding: 0 8px 0 2.5em !important;
  }
  
  /* Sort and filter become icon-only with proper button styling */
  .search-sort .input-icon-wrapper[data-nav-priority="2"],
  .search-sort .input-icon-wrapper[data-nav-priority="3"] {
    width: 36px !important;
    min-width: 36px !important;
    max-width: 36px !important;
    flex: 0 0 36px !important;
    height: 36px !important;
    background: rgba(0,0,0,0.3) !important;
    border: 1px solid rgba(255, 255, 255, 0.2) !important;
    border-radius: 4px !important;
    cursor: pointer !important;
    justify-content: center !important;
    align-items: center !important;
    display: flex !important;
    position: relative !important;
  }
  
  .search-sort .input-icon-wrapper[data-nav-priority="2"] .nav-input-style,
  .search-sort .input-icon-wrapper[data-nav-priority="3"] .nav-input-style {
    font-size: 0 !important; /* Hide text */
    padding: 0 !important;
    width: 36px !important;
    height: 36px !important;
    text-align: center !important;
    justify-content: center !important;
    display: flex !important;
    align-items: center !important;
    background: transparent !important;
    border: none !important;
  }
  
  /* Ensure icons are properly positioned */
  .search-sort .input-icon-wrapper[data-nav-priority="2"] .input-icon,
  .search-sort .input-icon-wrapper[data-nav-priority="3"] .input-icon {
    display: block !important;
    position: absolute !important;
    left: 50% !important;
    top: 50% !important;
    transform: translate(-50%, -50%) !important;
    color: #fff !important;
    font-size: 1em !important;
    pointer-events: none !important;
  }
  
  /* Add hover effects for icon buttons */
  .search-sort .input-icon-wrapper[data-nav-priority="2"]:hover,
  .search-sort .input-icon-wrapper[data-nav-priority="3"]:hover {
    border-color: rgba(255, 255, 255, 0.8) !important;
  }
  
  /* Control buttons become icon-only */
  .search-sort .nav-item.control-button:not(.nav-audio-player) {
    min-width: 36px !important;
    width: 36px !important;
    padding: 0 !important;
    box-sizing: border-box;
  }
  
  .search-sort .control-button span {
    display: none !important;
  }
  
  .search-sort .control-button i {
    margin: 0 !important;
    font-size: 1em !important;
  }
  
  /* Audio player becomes more compact */
  .search-sort .nav-audio-player {
    min-width: 85px !important;
    max-width: 85px !important;
  }
  
  .search-sort .nav-audio-player .audio-time {
    display: none !important;
  }
}

/* Medium screens (769px-1200px) - covered by new compact mode above */

/* Mobile select overlay for simplified text - starts at 600px */
@media (max-width: 600px) {
  /* Style mobile select elements to show simplified text */
  .search-sort .mobile-select::after {
    content: attr(data-mobile-text);
    position: absolute;
    top: 0;
    left: 0;
    right: 25px; /* Leave space for dropdown arrow */
    bottom: 0;
    background: inherit;
    border: inherit;
    border-radius: inherit;
    font-family: 'Montserrat', sans-serif;
    font-size: inherit;
    font-weight: bold;
    color: inherit;
    pointer-events: none;
    display: flex;
    align-items: center;
    padding-left: 8px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    transition: color 0.3s ease;
  }
  
  .search-sort .mobile-select {
    position: relative;
  }
  
  .search-sort .mobile-select select {
    color: transparent;
    font-family: 'Montserrat', sans-serif;
  }
  
  /* Ensure mobile overlay text follows navbar color transitions */
  .top-navbar.loaded .search-sort .mobile-select::after {
    color: var(--navbar-text-initial);
  }
  
  .top-navbar.scrolled .search-sort .mobile-select::after {
    color: var(--navbar-text-scrolled);
  }
}

/* Tablet styles (601px-800px) - covered by new compact mode above */

/* Mobile styles - simplified without text overlay */
@media (max-width: 600px) {
  /* Remove text overlay - just use native select with dropdown arrow */
  .search-sort .mobile-select::after {
    display: none;
  }
  
  .search-sort .mobile-select select {
    color: inherit;
    font-family: 'Montserrat', sans-serif;
    font-weight: bold;
  }

  /* Removed mobile button display text styles */
  .search-sort {
    gap: 4px;
    flex-wrap: nowrap;
  }
  
  .search-sort .input-icon-wrapper[data-nav-priority="1"] {
    flex: 0 1 auto;
    min-width: 160px;
    max-width: none;
  }
  
  .search-sort .nav-item input[type="text"] {
    width: 100% !important;
    font-size: 0.8em !important;
    padding: 0 8px 0 2.5em;
  }
  
  .search-sort .nav-item select {
    display: none !important;
    visibility: hidden !important;
  }
  
  
  /* Hide button text on mobile */
  .search-sort .control-button span {
    display: none;
  }
  
  .search-sort .nav-item.control-button:not(.nav-audio-player) {
    width: 36px !important;
    min-width: 36px !important;
    height: 36px !important;
    padding: 0 !important;
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
    background: rgba(0, 0, 0, 0.3) !important;
    border: 1px solid rgba(255, 255, 255, 0.2) !important;
    border-radius: 4px !important;
    color: #fff !important;
  }
  
  .search-sort .control-button i {
    margin: 0 !important;
    font-size: 1em !important;
  }
}

/* Removed button display text transitions - no longer needed */

.search-sort .mobile-select::after {
    transition: opacity 0.4s ease, 
               transform 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}

.search-sort .input-icon-wrapper {
    transition: width 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94), 
               min-width 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94), 
               opacity 0.2s ease,
               transform 0.3s ease,
               background-color 0.3s ease,
               border-color 0.2s ease;
}

.search-sort .input-icon-wrapper::before {
    transition: opacity 0.3s ease 0.1s, transform 0.3s ease;
    opacity: 0;
    transform: scale(0.8);
}

/* Mobile layout from 410px down to 311px */
@media (max-width: 410px) and (min-width: 311px) {
    .search-sort {
        gap: 3px;
        flex-wrap: nowrap;
        justify-content: flex-start;
        align-items: center;
    }
    
    /* Search input */
    .search-sort .input-icon-wrapper[data-nav-priority="1"] {
        flex: 1 1 auto;
        min-width: 100px;
    }
    .search-sort .nav-item input[type="text"] {
        width: 100% !important;
        min-width: 100px !important;
        padding: 0 8px 0 2.5em;
        font-size: 0.8em;
    }
    
    /* Sort and filter selects - HIDDEN */
    .search-sort .nav-item select {
        display: none !important;
        visibility: hidden !important;
    }
    
    .search-sort .input-icon-wrapper[data-nav-priority="2"],
    .search-sort .input-icon-wrapper[data-nav-priority="3"] {
        flex: 0 0 90px;
        width: 90px;
        min-width: 90px;
    }
    
    /* Control buttons - match sort/filter button size */
    .search-sort .nav-item.control-button:not(.nav-audio-player) {
        width: 36px !important;
        min-width: 36px !important;
        height: 36px !important;
        flex: 0 0 36px !important;
        padding: 0 !important;
        display: flex !important;
        align-items: center !important;
        justify-content: center !important;
    }
    
    .search-sort .control-button i {
        font-size: 1em !important;
        margin: 0 !important;
    }
    
    .search-sort .control-button span {
        display: none;
    }
}

/* Convert to icon buttons at 310px and below */
@media (max-width: 310px) {
    .search-sort {
        gap: 3px;
        flex-wrap: nowrap;
        justify-content: flex-start;
        align-items: center;
    }
    
    /* Search input expands but allows room for all buttons */
    .search-sort .input-icon-wrapper[data-nav-priority="1"] {
        flex: 1 1 auto;
        min-width: 100px;
    }
    .search-sort .nav-item input[type="text"] {
        width: 100% !important;
        min-width: 100px !important;
        padding: 0 8px 0 28px;
        font-size: 0.75em;
    }
    
    /* Hide the actual select elements completely */
    .search-sort .nav-item select {
        display: none !important;
    }
    
    /* Hide text on very small screens */
    .search-sort .input-icon-wrapper[data-nav-priority="2"] .nav-input-style,
    .search-sort .input-icon-wrapper[data-nav-priority="3"] .nav-input-style {
        font-size: 0;
        padding-left: 0;
        width: 36px;
        min-width: 36px;
        height: 36px;
    }
    
    /* Control buttons - same size as search box */
    .search-sort .nav-item.control-button:not(.nav-audio-player) {
        width: 36px !important;
        min-width: 36px !important;
        height: 36px !important;
        flex: 0 0 36px !important;
        padding: 0 !important;
    }
    
    .search-sort .control-button i {
        font-size: 1em !important;
        margin: 0 !important;
    }
    
    /* Removed old 380px icon styles - using real elements now */
}


.search-sort-left {
  display: contents;
}
/* Force reflow class */
.search-sort.force-reflow {
  transform: translateZ(0);
}

.search-sort > .input-icon-wrapper,
#LIResetButton,
#LISettingsButton,
#navAudioInfo {
  opacity: 0;
  transform: translateY(8px);
  transition: opacity 0.35s ease, transform 0.35s ease;
}
.controls.loaded .search-sort {
  animation: navSearchSort_SlideInFromLeft 0.45s cubic-bezier(0.215, 0.610, 0.355, 1.000) forwards;
  animation-delay: 0.1s;
}
.controls.loaded .search-sort > .input-icon-wrapper,
.controls.loaded #LIResetButton,
.controls.loaded #LISettingsButton,
.controls.loaded #navAudioInfo {
  opacity: 1;
  transform: translateY(0);
}

#LIResetButton,
#LISettingsButton,
#navAudioInfo {
  background: #000000;
}
#LIResetButton:not(:disabled):hover,
#LISettingsButton:not(:disabled):hover,
#navAudioInfo:not(:disabled):hover {
  background: rgba(0,0,0,0.5);
}
#LIResetButton:disabled,
#LIResetButton.disabled,
#LISettingsButton:disabled,
#LISettingsButton.disabled,
#navAudioInfo:disabled,
#navAudioInfo.disabled {
  background: #000000 !important;
}

.controls input[type="text"],
.controls .nav-input-style {
  font-family: 'Montserrat', sans-serif;
  background: rgba(0,0,0,0.3);
  border: 1px solid var(--navbar-border-scrolled);
  border-radius: 4px;
  color: var(--navbar-text-scrolled);
  font-weight: bold;
  box-sizing: border-box;
  padding: 0 8px;
  height: 36px;
  text-shadow: none;
  transition: border-color 0.2s ease, color 0.3s ease;
}

/* Style buttons to look exactly like inputs */
.controls .nav-input-style {
  width: 100%;
  text-align: left;
  padding-left: 2.5em;
  cursor: pointer;
  font-size: 0.9em;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  outline: none;
  white-space: nowrap;
  display: flex;
  align-items: center;
  position: relative;
  padding-right: 1.5em;
}

/* Make sort/filter buttons rely on wrapper border only (avoid double-thick look) */
.search-sort .nav-input-style {
  border: none !important;
  background: transparent;
}
/* Ensure button inside wrapper matches content height */
.search-sort .input-icon-wrapper .nav-input-style {
  height: 34px; /* 36px wrapper minus 2px border */
}

/* Ensure Sort and Filter buttons use the same border color as other
   navigation buttons */
#LISortButton.nav-input-style,
#LIFilterButton.nav-input-style {
  border-color: rgba(255, 255, 255, 0.2) !important;
}

/* Give Sort and Filter buttons a visible outline on hover */
#LISortButton.nav-input-style:hover,
#LIFilterButton.nav-input-style:hover,
.input-icon-wrapper:hover #LISortButton.nav-input-style,
.input-icon-wrapper:hover #LIFilterButton.nav-input-style {
  outline: none;
  border-color: rgba(255, 255, 255, 0.8) !important;
}

/* Search and select elements - yellow navbar state */
.top-navbar.loaded .search-sort input[type="text"],
.top-navbar.loaded .search-sort select,
.top-navbar.loaded .search-sort .nav-input-style {
  color: var(--navbar-text-initial);
  border-color: var(--navbar-border-initial);
}

/* Search and select elements - scrolled state */
.top-navbar.scrolled .search-sort input[type="text"],
.top-navbar.scrolled .search-sort select,
.top-navbar.scrolled .search-sort .nav-input-style {
  color: var(--navbar-text-scrolled);
  border-color: var(--navbar-border-scrolled);
}

.controls .nav-input-style .button-label {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1 1 auto;
}

.controls .nav-input-style i.fa-caret-down {
  position: absolute;
  right: 8px;
  flex-shrink: 0;
}

/* Search and select elements - yellow navbar state */
.top-navbar.loaded .controls input[type="text"],
.top-navbar.loaded .controls select,
.top-navbar.loaded .controls .nav-input-style {
  color: var(--navbar-text-initial);
  border-color: var(--navbar-border-initial);
}

/* Change dropdown arrow color for yellow navbar */
.top-navbar.loaded .controls select {
  background-image: url("data:image/svg+xml,%3Csvg width='12' height='12' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M6 9L2 3h8L6 9z' fill='%23000'/%3E%3C/svg%3E");
}

/* Search and select elements - scrolled state */
.top-navbar.scrolled .controls input[type="text"],
  .top-navbar.scrolled .controls select,
  .top-navbar.scrolled .controls .nav-input-style {
    color: var(--navbar-text-scrolled);
    border-color: var(--navbar-border-scrolled);
  }

  .top-navbar.loaded .controls .input-icon {
    color: var(--navbar-icon-initial);
  }

  .top-navbar.scrolled .controls .input-icon {
    color: var(--navbar-icon-scrolled);
  }

/* Keep dropdown arrow white for black navbar */
.top-navbar.scrolled .controls select {
  background-image: url("data:image/svg+xml,%3Csvg width='12' height='12' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M6 9L2 3h8L6 9z' fill='%23fff'/%3E%3C/svg%3E");
}
.controls select {
  font-family: 'Montserrat', sans-serif;
  background: rgba(0,0,0,0.3);
  border: 1px solid var(--navbar-border-scrolled);
  border-radius: 4px;
  color: var(--navbar-text-scrolled);
  font-weight: bold;
  box-sizing: border-box;
  padding: 0 25px 0 8px;
  height: 36px;
  text-shadow: none;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  background-position: right 6px center;
  background-repeat: no-repeat;
  background-image: url("data:image/svg+xml,%3Csvg width='12' height='12' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M6 9L2 3h8L6 9z' fill='%23fff'/%3E%3C/svg%3E");
  transition: border-color 0.2s ease, color 0.3s ease, background-image 0.3s ease;
  transition: border-color 0.2s ease;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
}
/* Unified glow hover animation for all navigation elements (matching value-bubble style) */
.search-sort .input-icon-wrapper:hover,
.search-sort .nav-item.control-button:hover {
  transform: translateY(-2px) !important;
  /* removed glow effect */
}

.search-sort .input-icon-wrapper:hover input[type="text"],
.search-sort .input-icon-wrapper:hover .nav-input-style,
.search-sort .nav-item.control-button:hover {
  border-color: rgba(255, 255, 255, 0.8) !important;
}



/* Ensure all elements have smooth transitions (matching value-bubble timing) */
.search-sort .input-icon-wrapper,
.search-sort .nav-item.control-button {
  transition: transform 0.3s ease, box-shadow 0.3s ease, border-color 0.2s ease !important;
}

/* Additional specific selectors to ensure hover works */
.search-sort span.input-icon-wrapper:hover,
.search-sort span.input-icon-wrapper.nav-item:hover {
  transform: translateY(-2px) !important;
  /* removed glow effect */
}

.controls input[type="text"],
.controls select {
  transition: border-color 0.2s ease;
}

/* Disabled state base, but allow visual hover feedback */
.search-sort .nav-item.control-button:disabled,
.search-sort .nav-item.control-button.disabled {
  opacity: 0.5;
  cursor: not-allowed;
  border-color: rgba(255, 255, 255, 0.2) !important;
  color: rgba(255, 255, 255, 0.7) !important;
  background: rgba(0, 0, 0, 0.3) !important;
  box-shadow: none !important;
  outline: none !important;
  transform: none !important;
  pointer-events: none !important;
}

.controls input[type="text"]:disabled,
.controls select:disabled,
.controls input[type="text"]:disabled:hover,
.controls select:disabled:hover {
  opacity: 0.5 !important;
  cursor: not-allowed !important;
  /* Disable most transitions but keep width for smooth resizing */
  transition: width 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94) !important;
}

/* Disabled wrappers: no hover lift or brighten, keep dimmed outline */
.search-sort .input-icon-wrapper:has(input:disabled):hover,
.search-sort .input-icon-wrapper:has(select:disabled):hover,
.search-sort .input-icon-wrapper:has(button:disabled):hover {
  transform: none !important;
  box-shadow: none !important;
  outline: none !important;
  border-color: rgba(255,255,255,0.2) !important;
  cursor: not-allowed !important;
}

/* Ensure transitions are restored when re-enabled */
.controls input[type="text"]:not(:disabled),
.controls select:not(:disabled) {
  transition: border-color 0.2s ease, transform 0.2s ease, box-shadow 0.2s ease;
}

/* Handled by unified approach - removed to prevent conflicts */

/* Bright white hover outline for dropdown options */
.controls select option:hover,
.controls select option:focus,
.search-sort select option:hover,
.search-sort select option:focus {
  /* Use an even inner stroke to avoid browser outline artifacts */
  outline: none !important;
  box-shadow: inset 0 0 0 2px #ffffff !important;
  background-color: rgba(255, 255, 255, 0.15) !important;
  color: #ffffff !important;
}

.controls select optgroup:hover,
.search-sort select optgroup:hover {
  outline: none !important;
  box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.6) !important;
  background-color: rgba(255, 255, 255, 0.05) !important;
}

/* Enhanced styling for better visibility */
.controls select option:checked,
.search-sort select option:checked {
  background-color: rgba(255, 255, 255, 0.2) !important;
  color: #ffffff !important;
  font-weight: bold !important;
}

/* Hide Filter by Category by default - only show on All Values page */
#LICategoryFilterGroup {
  display: none;
}

/* Show Filter by Category on All Values page */
.page-all-values #LICategoryFilterGroup {
  display: block;
}

.controls input[type="text"]::placeholder,
.controls select::placeholder {
  color: #fff;
  text-shadow: -1px -1px 2px #000, 1px -1px 2px #000, -1px 1px 2px #000, 1px 1px 2px #000;
}
/* Controls are already responsive in the main .controls styles above */

/* Hide category filters by default - shown only on All Values pages (handled by JS) */

/* Sort select is now always visible */

/* --- NEW NAVIGATION STYLING --- */

/* --- Animations --- */
@keyframes navControlsContainer_FadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

@keyframes navSearchSort_SlideInFromLeft {
    from { opacity: 0; transform: translateX(-30px); }
    to { opacity: 1; transform: translateX(0); }
}

.controls.loaded .search-sort {
    animation: navSearchSort_SlideInFromLeft 0.45s cubic-bezier(0.215, 0.610, 0.355, 1.000) forwards;
    animation-delay: 0.1s;
}

/* --- Flex Container for Inputs/Buttons --- */
.search-sort {
    display: flex;
    align-items: center;
    gap: 15px; /* Default gap for larger screens */
    opacity: 0;
    width: 100%;
    justify-content: center;
    box-sizing: border-box;
    max-width: 1400px;
    margin: 0 auto;
    flex-wrap: nowrap;
}

/* --- General Element Styling --- */
.controls input[type="text"], .controls select {
    font-family: 'Montserrat', sans-serif;
    background: rgba(0,0,0,0.3);
    border: 1px solid rgba(255,255,255,0.2);
    border-radius: 4px;
    color: #ffffff;
    font-weight: bold;
    box-sizing: border-box;
    padding: 0 8px;
    height: 36px;
    transition: border-color 0.2s ease, transform 0.2s ease, box-shadow 0.2s ease;
}

.controls select {
    padding: 0 25px 0 8px;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    background-position: right 8px center;
    background-repeat: no-repeat;
    background-image: url("data:image/svg+xml,%3Csvg width='12' height='12' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M6 9L2 3h8L6 9z' fill='%23fff'/%3E%3C/svg%3E");
    cursor: pointer;
    text-overflow: ellipsis;
}

.control-button {
    font-family: 'Montserrat', sans-serif;
    background: rgba(0,0,0,0.3);
    border: 1px solid rgba(255,255,255,0.2);
    border-radius: 4px;
    color: #fff;
    font-weight: bold;
    box-sizing: border-box;
    height: 36px;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    padding: 0 8px;
    transition: transform 0.2s ease, box-shadow 0.2s ease, border-color 0.2s ease;
}

/* --- Icon Styling --- */
.input-icon-wrapper {
    display: inline-flex;
    align-items: center;
    position: relative;
    transition: transform 0.2s ease, box-shadow 0.2s ease;
    width: fit-content;
    max-width: 100%;
    overflow: hidden;
}

.input-icon {
    position: absolute;
    left: 8px;
    top: 50%;
    transform: translateY(-50%);
    font-size: 1em;
    color: #fff !important;
    pointer-events: none;
    z-index: 2;
    transition: none !important; /* Remove default transition */
}

/* Force sort and filter icons to be bright white regardless of navbar state */
.top-navbar.loaded .search-sort .input-icon,
.top-navbar.scrolled .search-sort .input-icon,
.search-sort .input-icon-wrapper[data-nav-priority="2"] .input-icon,
.search-sort .input-icon-wrapper[data-nav-priority="3"] .input-icon {
    color: #ffffff !important;
}

/* Make enabled state instant too - no transition when re-enabling */
.input-icon-wrapper:not(.disabled):has(*:not(:disabled)) .input-icon,
.input-icon-wrapper:not(.disabled) .input-icon {
    transition: none !important; /* Instant color change when re-enabled */
}

.input-icon-wrapper input[type="text"],
.input-icon-wrapper select {
    padding-left: 2.5em;
    padding-right: 28px; /* room for clear (x) button */
    max-width: 100%;
    box-sizing: border-box;
    width: 100%;
}

/* Clear (x) button for search input (mirror og-item-finder) */
.search-clear {
  position: absolute;
  right: 6px;
  top: 50%;
  transform: translateY(-50%);
  width: 24px;
  height: 24px;
  border: none;
  background: #000000;
  border: 1px solid rgba(255,255,255,0.25);
  border-radius: 4px;
  color: rgba(255,255,255,0.85);
  display: none; /* shown when input has value */
  align-items: center;
  justify-content: center;
  cursor: pointer;
  padding: 0;
  z-index: 3;
  transition: none; /* mirror og-item-finder: crisp state change */
}
.search-clear i { font-size: 0.85em; line-height: 1; transition: none; }
.search-clear:hover { border-color: rgba(255,255,255,0.9); color: #ffffff; }
.search-clear:active { border-color: #ffffff; color: #ffffff; }
/* While hovering the (x), strengthen outline and keep wrapper from lifting */
.controls .input-icon-wrapper:has(.search-clear:hover) {
  transform: none !important; /* mirror og-item-finder: no lift while over the X */
  border-color: rgba(255, 255, 255, 0.95) !important;
  background: rgba(0,0,0,0.45);
}
.search-sort .input-icon-wrapper[data-nav-priority="1"]:has(.search-clear:hover) {
  border-color: rgba(255, 255, 255, 0.95) !important;
}
.search-sort .input-icon-wrapper:has(#LISearchInput:not(:placeholder-shown)) .search-clear { display: inline-flex; }
.search-clear.disabled {
  opacity: 0.4;
  cursor: not-allowed !important;
  pointer-events: none !important;
  color: rgba(255,255,255,0.4);
  border-color: rgba(255,255,255,0.15);
  background: #000000;
}

/* --- Simple Outline Hover Animation --- */
.search-sort .input-icon-wrapper:hover,
.search-sort .control-button:hover {
    border-color: rgba(255, 255, 255, 0.8);
}

.search-sort .input-icon-wrapper:hover input,
.search-sort .input-icon-wrapper:hover select {
     border-color: rgba(255, 255, 255, 0.8);
}



/* --- Disabled State --- */
.control-button:disabled,
.control-button.disabled,
.nav-input-style:disabled,
.nav-input-style:disabled:hover {
    opacity: 0.5;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
    border-color: rgba(255,255,255,0.2);
    pointer-events: none !important;
}

.controls input:disabled,
.controls select:disabled,
.controls .nav-input-style:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

.input-icon-wrapper:has(input:disabled):hover,
.input-icon-wrapper:has(select:disabled):hover,
.input-icon-wrapper:has(button:disabled):hover {
    transform: none !important;
    box-shadow: none !important;
    border-color: rgba(255,255,255,0.2) !important;
}

/* Ensure disabled wrappers have dimmed outlines */
.input-icon-wrapper:has(input:disabled),
.input-icon-wrapper:has(select:disabled),
.input-icon-wrapper:has(button:disabled) {
    border-color: rgba(255,255,255,0.2) !important;
    outline: none !important; /* suppress blue/white outlines while disabled */
}

/* Handled by the unified rule below - keeping this for text elements only */
.input-icon-wrapper:has(input:disabled) input,
.input-icon-wrapper:has(select:disabled) select,
.input-icon-wrapper:has(button:disabled) .nav-input-style,
.input-icon-wrapper:has(button:disabled) .button-label {
    color: rgba(255, 255, 255, 1) !important; /* Keep full white since opacity will dim it */
    transition: none !important; /* Instant color change to prevent double dimming */
}

/* Fallback for browsers without :has() support */
.input-icon-wrapper.disabled {
    opacity: 0.5;
    cursor: not-allowed;
    border-color: rgba(255,255,255,0.2) !important;
    outline: none !important;
}
.input-icon-wrapper.disabled:hover {
    transform: none !important;
    box-shadow: none !important;
    border-color: rgba(255,255,255,0.2) !important;
    outline: none !important;
}
/* Handled by the unified rule below - keeping this for text elements only */
.input-icon-wrapper.disabled input,
.input-icon-wrapper.disabled select,
.input-icon-wrapper.disabled .nav-input-style,
.input-icon-wrapper.disabled .button-label {
    color: rgba(255, 255, 255, 1) !important; /* Keep full white since opacity will dim it */
    transition: none !important; /* Instant color change to prevent double dimming */
}

/* --- Scaling & Responsiveness --- */

/* Default (Desktop) Sizing */
.search-sort .nav-item input[type="text"],
.search-sort .nav-item select {
    width: var(--nav-option-width);
}
.search-sort .input-icon-wrapper[data-nav-priority="2"],
.search-sort .input-icon-wrapper[data-nav-priority="3"] {
    width: var(--nav-option-width);
    min-width: var(--nav-option-width);
    flex: 0 0 var(--nav-option-width);
}
.search-sort .control-button { padding: 0 8px; }
.search-sort .control-button span { display: inline; }

/* Medium Desktop (1080px - 1299px) - Start shrinking things */
@media (max-width: 1299px) {
    /* Fluid sizing handled by CSS variable */
}

/* Large Tablet / Small Desktop (769px - 1079px) - Buttons become icon-only */
@media (max-width: 1079px) {
     /* Fluid sizing handled by CSS variable */
     .search-sort .nav-item.control-button:not(.nav-audio-player) {
        width: 36px;
        min-width: 36px;
        padding: 0;
    }
    .search-sort .nav-item.control-button span {
        display: none;
    }
     .search-sort .nav-item.control-button i {
        margin: 0;
        font-size: 1em;
    }
}

/* Tablet (601px - 768px) */
@media (max-width: 768px) {
    .controls { padding: 8px 15px; }
    .search-sort { gap: 8px; }
    .search-sort .nav-item input[type="text"] { font-size: 0.85em; }
    .search-sort .nav-item select { font-size: 0.85em; }
    .search-sort .control-button {
        width: 36px;
        min-width: 36px;
        height: 36px;
        padding: 0;
    }
    .search-sort .control-button i {
        font-size: 1em;
    }
}

/* Large Mobile (481px - 600px) */
@media (max-width: 600px) {
    .search-sort { gap: 6px; }
    .search-sort .nav-item input[type="text"] { font-size: 0.8em; }
    .search-sort .nav-item select { font-size: 0.8em; }
    .search-sort .control-button {
        width: 36px;
        min-width: 36px;
        height: 36px;
        padding: 0;
    }
    .search-sort .control-button i {
        font-size: 1em;
    }
}

/* Small Mobile (381px - 480px) */
@media (max-width: 480px) {
    .controls { padding: 8px 10px; }
    .search-sort { gap: 4px; flex-wrap: nowrap; }
    .search-sort .input-icon-wrapper[data-nav-priority="1"] { flex: 1 1 100px; min-width: 100px; }
    .search-sort .nav-item input[type="text"] { width: 100%; min-width: 0; }
    
    /* Make sort/filter buttons proper icon buttons */
    .search-sort .input-icon-wrapper[data-nav-priority="2"],
    .search-sort .input-icon-wrapper[data-nav-priority="3"] { 
        flex: 0 0 36px; 
        min-width: 36px; 
        width: 36px;
        height: 36px;
        background: rgba(0,0,0,0.3) !important;
        border: 1px solid rgba(255, 255, 255, 0.2) !important;
        border-radius: 4px !important;
        cursor: pointer !important;
        justify-content: center !important;
        align-items: center !important;
        display: flex !important;
        position: relative !important;
    }
    
    .search-sort .input-icon-wrapper[data-nav-priority="2"] .nav-input-style,
    .search-sort .input-icon-wrapper[data-nav-priority="3"] .nav-input-style {
        font-size: 0 !important;
        padding: 0 !important;
        width: 36px !important;
        height: 36px !important;
        background: transparent !important;
        border: none !important;
    }
    
    /* Ensure icons are properly positioned */
    .search-sort .input-icon-wrapper[data-nav-priority="2"] .input-icon,
    .search-sort .input-icon-wrapper[data-nav-priority="3"] .input-icon {
        display: block !important;
        position: absolute !important;
        left: 50% !important;
        top: 50% !important;
        transform: translate(-50%, -50%) !important;
        color: #fff !important;
        font-size: 1em !important;
        pointer-events: none !important;
    }
    
    /* Add hover effects */
    .search-sort .input-icon-wrapper[data-nav-priority="2"]:hover,
    .search-sort .input-icon-wrapper[data-nav-priority="3"]:hover {
        border-color: rgba(255, 255, 255, 0.8) !important;
    }
    
    .search-sort .nav-item select { width: 100%; min-width: 0; }
    .search-sort .control-button { width: 36px; min-width: 36px; height: 36px; padding: 0; }
    .search-sort .control-button i { font-size: 1em; margin: 0; }
    .search-sort .control-button span { display: none; }
}

/* Extra Small Mobile (321px - 380px) - Ensure icons remain visible */
@media (max-width: 380px) and (min-width: 321px) {
    .search-sort { gap: 3px; }
    .search-sort .input-icon-wrapper[data-nav-priority="1"] { flex: 1 1 auto; min-width: 100px; }
    .search-sort .nav-item input[type="text"] { width: 100%; font-size: 0.75em; }
    
    /* Make sort/filter buttons proper squares with button styling */
    .search-sort .input-icon-wrapper[data-nav-priority="2"],
    .search-sort .input-icon-wrapper[data-nav-priority="3"] {
        width: 36px;
        min-width: 36px;
        height: 36px;
        flex: 0 0 36px;
        background: rgba(0,0,0,0.3) !important;
        border: 1px solid rgba(255, 255, 255, 0.2) !important;
        border-radius: 4px !important;
        cursor: pointer !important;
        justify-content: center !important;
        align-items: center !important;
        display: flex !important;
        position: relative !important;
    }
    
    .search-sort .input-icon-wrapper[data-nav-priority="2"] .nav-input-style,
    .search-sort .input-icon-wrapper[data-nav-priority="3"] .nav-input-style {
        width: 36px;
        height: 36px;
        padding: 0;
        font-size: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        background: transparent !important;
        border: none !important;
    }
    
    /* Add hover effects for icon buttons */
    .search-sort .input-icon-wrapper[data-nav-priority="2"]:hover,
    .search-sort .input-icon-wrapper[data-nav-priority="3"]:hover {
        border-color: rgba(255, 255, 255, 0.8) !important;
    }
    
    /* Ensure sort/filter icons remain visible */
    .search-sort .input-icon-wrapper[data-nav-priority="2"] .input-icon,
    .search-sort .input-icon-wrapper[data-nav-priority="3"] .input-icon {
        display: block !important;
        position: absolute !important;
        left: 50% !important;
        top: 50% !important;
        transform: translate(-50%, -50%) !important;
        color: #fff !important;
        font-size: 1em !important;
        pointer-events: none !important;
    }
    
    .search-sort .control-button {
        width: 36px;
        min-width: 36px;
        height: 36px;
        padding: 0;
    }
    
    /* Audio player sizing to match other controls */
    .search-sort .nav-audio-player {
        height: 36px !important;
    }
    .search-sort .control-button i {
        font-size: 1em;
        margin: 0;
    }
    .search-sort .control-button span {
        display: none;
    }
}

/* Very Small Mobile (<= 320px) - Convert selects to icon buttons */
@media (max-width: 320px) {
    .search-sort { gap: 3px; }

    /* Search input takes remaining space */
    .search-sort .input-icon-wrapper[data-nav-priority="1"] { flex: 1 1 auto; min-width: 100px; }
    .search-sort .nav-item input[type="text"] { width: 100%; }

    /* Hide original select, but keep it functional */
    .search-sort .nav-item select {
        position: absolute;
        opacity: 0;
        width: 100%;
        height: 100%;
        cursor: pointer;
    }
    
    /* Style the wrapper to look like a button */
    .search-sort .input-icon-wrapper[data-nav-priority="2"],
    .search-sort .input-icon-wrapper[data-nav-priority="3"] {
        width: 36px;
        min-width: 36px;
        height: 36px;
        flex: 0 0 36px;
        background: rgba(0,0,0,0.3) !important;
        border: 1px solid rgba(255, 255, 255, 0.2) !important;
        border-radius: 4px !important;
        cursor: pointer !important;
        justify-content: center !important;
        align-items: center !important;
        display: flex !important;
        position: relative !important;
    }
    
    .search-sort .input-icon-wrapper[data-nav-priority="2"] .input-icon,
    .search-sort .input-icon-wrapper[data-nav-priority="3"] .input-icon {
         display: block !important;
         position: absolute !important;
         left: 50% !important;
         top: 50% !important;
         transform: translate(-50%, -50%) !important;
         color: #fff !important;
         font-size: 1em !important;
         pointer-events: none !important;
    }
    
    /* Ensure select elements are completely hidden */
    .search-sort .input-icon-wrapper[data-nav-priority="2"] select,
    .search-sort .input-icon-wrapper[data-nav-priority="3"] select {
        position: absolute !important;
        opacity: 0 !important;
        width: 100% !important;
        height: 100% !important;
        cursor: pointer !important;
        z-index: 2 !important;
    }
    
    /* Add hover effects for icon buttons */
    .search-sort .input-icon-wrapper[data-nav-priority="2"]:hover,
    .search-sort .input-icon-wrapper[data-nav-priority="3"]:hover {
        border-color: rgba(255, 255, 255, 0.8) !important;
    }

    /* Buttons also shrink */
    .search-sort .control-button {
        width: 36px;
        min-width: 36px;
        height: 36px;
        flex: 0 0 36px;
        padding: 0;
    }
    .search-sort .control-button i {
        font-size: 1em;
        margin: 0;
    }
    .search-sort .control-button span {
        display: none;
    }
}
/* --- END NEW NAVIGATION STYLING --- */

#custom-loading-overlay {
  position: fixed;
  top: var(--top-navbar-height);
  left: 0;
  width: 100vw;
  height: calc(100vh - var(--top-navbar-height));
  background-color: #000000;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  opacity: 1;
  padding: 20px;
  box-sizing: border-box;
  transition: opacity 0.5s ease-out;
  pointer-events: none; /* do not block header/dropdowns */
}

#loading-bubble-container {
  display: flex;
  flex-direction: row;
  background: #000000;
  border: 1px solid rgba(255, 255, 255, 0.15);
  border-radius: 16px;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.5);
  width: 100%;
  max-width: 1200px;
  height: auto;
  max-height: 92vh;
  overflow: hidden;
  pointer-events: auto; /* allow interaction with overlay content */
}
@supports (backdrop-filter: blur(10px)) or (-webkit-backdrop-filter: blur(10px)) {
    #loading-bubble-container {
        -webkit-backdrop-filter: blur(10px);
        backdrop-filter: blur(10px);
        background: #000000;
    }
}
.loading-bubble-logo-panel {
  flex: 0 0 40%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 25px;
  box-sizing: border-box;
  position: relative;
}

#loading-gif {
  max-width: 100%;
  max-height: 62vh;
  width: auto;
  height: auto;
  object-fit: contain;
  border-radius: 8px;
}

.loading-bubble-divider {
  width: 1px;
  background-color: rgba(255, 255, 255, 0.1);
  align-self: stretch;
  margin: 25px 0;
}

.loading-bubble-console-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 25px;
  box-sizing: border-box;
  overflow-y: auto;
  height: auto;
  min-height: 300px;
}

#custom-loading-overlay p#loading-message {
  color: #e0e0e0;
  font-family: 'Montserrat', sans-serif;
  font-size: clamp(1em, 2.5vw, 1.3em);
  font-weight: 600;
  text-shadow: 0 1px 2px rgba(0,0,0,0.5);
  margin-top: 0;
  margin-bottom: 15px;
  letter-spacing: 0.5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
  text-align: center;
  box-sizing: border-box;
}

#progress-bar-container {
  width: 90%;
  max-width: 400px;
  height: 10px;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 5px;
  overflow: hidden;
  margin-bottom: 15px;
  box-shadow: inset 0 1px 3px rgba(0,0,0,0.2);
}

#progress-bar {
  width: 0%;
  height: 100%;
  background: #ff0000;
  border-radius: 5px;
  transition: width 0.4s ease-in-out, background 0.4s ease-in-out;
  position: relative;
  overflow: hidden;
}
 #progress-bar.error-state {
    background: #d32f2f !important;
}
#progress-bar.error-state::after {
    display: none;
}

#loading-log-box {
    width: 100%;
    height: 150px;
    background-color: rgba(0,0,0,0.6);
    border: 1px solid rgba(255, 255, 255, 0.15);
    border-radius: 4px;
    padding: 8px;
    font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
    font-size: clamp(0.65em, 1.8vw, 0.8em);
    color: #b0b0b0;
    overflow-y: auto;
    margin-top: 10px;
    margin-bottom: 15px;
    text-align: left;
    line-height: 1.4;
    box-sizing: border-box;
    box-shadow: inset 0 0 5px rgba(0,0,0,0.3);
}
#loading-log-box p {
    margin: 0 0 4px 0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
#loading-log-box p:last-child { margin-bottom: 0; }
#loading-log-box p.log-error { color: #ff0000; font-weight: bold; }
#loading-log-box::-webkit-scrollbar { width: 6px; }
#loading-log-box::-webkit-scrollbar-track { background: rgba(255,255,255,0.05); border-radius: 3px; }
#loading-log-box::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.2); border-radius: 3px; }
#loading-log-box::-webkit-scrollbar-thumb:hover { background: rgba(255,255,255,0.3); }

.loading-refresh-prompt {
    text-align: center;
    font-family: 'Montserrat', sans-serif;
    font-size: 0.85em;
    color: #a0a0a0;
    font-weight: 500;
    margin-top: 0;
    margin-bottom: 10px;
}

.loading-social-icons {
  display: flex;
  gap: 10px;
  justify-content: center;
  align-items: center;
  margin-top: 15px;
  margin-bottom: 10px;
  flex-wrap: wrap;
}
.loading-social-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  text-decoration: none;
  color: #c0c0c0;
  opacity: 0.7;
  transition: opacity 0.2s ease, transform 0.2s ease, color 0.2s ease;
  gap: 5px;
  padding: 5px;
}
.loading-social-item:hover {
  opacity: 1;
  transform: scale(1.05);
  color: #fff;
}
.loading-social-item img {
  width: 28px;
  height: 28px;
  object-fit: contain;
  border-radius: 4px;
  flex-shrink: 0;
}
.loading-social-name {
  font-size: 0.7em;
  font-weight: 500;
  font-family: 'Montserrat', sans-serif;
  white-space: nowrap;
  line-height: 1.2;
}

#custom-loading-overlay p#error-message {
    color: #ff0000;
    font-family: 'Montserrat', sans-serif;
    font-size: clamp(0.8em, 2.3vw, 1.1em);
    font-weight: 500;
    margin-top: 0;
    display: none;
    max-width: 95%;
    line-height: 1.5;
    text-shadow: 0 1px 2px rgba(0,0,0,0.5);
}

@media (max-width: 800px) {
    #custom-loading-overlay {
        padding: 10px;
    }
    #loading-bubble-container {
        flex-direction: column;
        max-height: 100%;
        max-width: 95vw;
        height: auto;
        width: 100%;
    }
    .loading-bubble-logo-panel {
        flex: 0 0 auto;
        width: 100%;
        padding: 15px;
    }
    #loading-gif {
        max-width: clamp(180px, 45vw, 280px);
        max-height: 27vh;
    }
    .loading-bubble-divider {
        width: 80%;
        height: 1px;
        margin: 15px auto;
        align-self: center;
    }
    .loading-bubble-console-panel {
        flex: 1;
        width: 100%;
        padding: 15px;
        min-height: 250px;
    }
     #loading-log-box {
        height: 120px;
    }
    .loading-social-icons {
        gap: 8px;
        margin-top: 10px;
    }
    .loading-social-item {
        gap: 4px;
    }
    .loading-social-item img {
        width: 24px;
        height: 24px;
    }
    .loading-social-name {
        font-size: 0.65em;
    }
}
.value-bubbles-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, 280px);
  justify-content: center;
  margin: 20px auto 25px auto;
  gap: 20px;
  padding: 0;
  transform: translateZ(0);
}
.value-bubble {
  position: relative;
  overflow: hidden;
  width: 280px;
  min-height: 400px;
  border: 1px solid rgba(255,255,255,0.2);
  border-radius: 12px;
  padding: 12px;
  text-align: center;
  color: #fff;
  display: flex;
  flex-direction: column;
  background: #000000;
  box-sizing: border-box;
  opacity: 0;
  transform: scale(0.98);
  /* Match OG item finder: smoother/longer opacity+transform */
  transition: opacity 0.35s ease, transform 0.35s ease, box-shadow 0.3s ease, border-color 0.3s ease;
  will-change: opacity, transform;
  content-visibility: auto;
  contain-intrinsic-size: 280px 420px;
  pointer-events: auto;
}
@media (max-width: 600px) {
  .value-bubble {
    padding: 12px;
  }
}
.value-bubble.visible {
  box-shadow: 0 0 8px rgba(0,0,0,0.4);
  opacity: 1;
  transform: scale(1);
}
/* Subtle directional fade when card leaves viewport before unload */
.value-bubble.leaving {
  opacity: 0;
  transform: translateY(8px) scale(0.98);
  transition: opacity 0.18s ease-out, transform 0.18s ease-out;
}
body.scrolling-up .value-bubble.leaving {
  transform: translateY(-8px) scale(0.98);
}
.value-bubble:hover {
  transform: translateY(-2px);
  opacity: 1;
  box-shadow: 0 0 16px -4px var(--glow-color);
  border-color: var(--glow-color);
  transition: transform 0.3s ease, opacity 0.2s ease, box-shadow 0.3s ease, border-color 0.3s ease;
}
.value-bubbles-container.sorting .value-bubble {
  /* Disable interactions while sorting */
  pointer-events: none;
  /* Suppress hover/glow during animation to avoid flicker; align with OG cards */
  box-shadow: none !important;
  border-color: rgba(255,255,255,0.2) !important;
  /* Limit transitions to only opacity/transform so borders don't animate */
  transition: opacity 0.35s ease, transform 0.35s ease !important;
}
/* Only non-visible bubbles should be hidden immediately;
   visible ones will fade out individually when their class is removed */
.value-bubbles-container.sorting .value-bubble:not(.visible) {
  opacity: 0;
  transform: scale(0.98);
  /* Slow down fade-out during sort/filter to match fade-in pace */
  transition: opacity 0.35s ease, transform 0.35s ease;
}
/* Keep inner content always opaque; the card itself handles fade/scale.
   This prevents the description block from doing an extra fade-in. */
.value-bubble-content {
  position: relative;
  z-index: 2;
  opacity: 1;
  transition: none;
}
/* Placeholder used when unloading offscreen bubbles to preserve layout */
.value-bubble-placeholder {
  border: 1px solid rgba(255,255,255,0.12);
  border-radius: 12px;
  background: linear-gradient(90deg, rgba(255,255,255,0.05) 25%, rgba(255,255,255,0.10) 37%, rgba(255,255,255,0.05) 63%);
  background-size: 400% 100%;
  animation: skeleton-shimmer 1.2s ease-in-out infinite;
  width: 100%;
}
.image-container {
  position: relative;
  display: inline-block;
  width: 100%;
  margin-bottom: 0px; /* no gap for content below image */
  transition: transform 0.3s ease;
  border-radius: 8px;
  /* Reserve space to prevent layout shift while image loads */
  aspect-ratio: 16 / 9;
  overflow: hidden;
  background: linear-gradient(90deg, rgba(255,255,255,0.06) 25%, rgba(255,255,255,0.12) 37%, rgba(255,255,255,0.06) 63%);
  background-size: 400% 100%;
  animation: skeleton-shimmer 1.2s ease-in-out infinite;
}
@keyframes skeleton-shimmer {
  0% { background-position: 100% 0; }
  100% { background-position: -100% 0; }
}
/* Fade-in image and remove skeleton when loaded */
.image-container img {
  width: 100%;
  /* Reserve stable height to prevent layout shift when image loads */
  height: 100% !important;
  object-fit: contain !important;
  display: block;
  opacity: 0;
  transition: opacity 0.25s ease;
}
.image-container.img-loaded { animation: none; background: transparent; }
.image-container.img-loaded img { opacity: 1; }
        .value-bubble img {
  max-width: 1280px;
  max-height: 720px;
  width: 100%;
  height: auto;
  border-radius: 8px;
  display: block;
  cursor: pointer;
  object-fit: contain;
}
@media (max-width: 600px) {
  .value-bubble img {
    max-height: 720px;
  }
}
.image-border-overlay {
  position: absolute;
  top: 0; left: 0; right: 0; bottom: 0;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  z-index: 3;
  pointer-events: none;
  transition: border-color 0.3s ease;
}

.image-container:hover {
  transform: scale(1.02);
}

.image-container:hover .image-border-overlay {
  border-color: rgba(255, 255, 255, 0.8);
}

.value-bubbles-container.sorting .image-container:hover {
  transform: scale(1);
}



    .value-bubble h3 {
  margin: 0;
  padding: 2px 0;
  font-weight: bold;
  font-size: 1.1em;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 0;
  flex-wrap: wrap;
  text-shadow:
    -1.5px -1.5px 2px #000, 1.5px -1.5px 2px #000,
    -1.5px 1.5px 2px #000, 1.5px 1.5px 2px #000,
    0px 1px 3px rgba(0,0,0,0.5),
    0 0 5px rgba(255,0,0,0.3);
  pointer-events: none;
}

/* This rule positions the name over the image and sets its text style. */
.image-container h3 {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    margin: 0;
    padding: 20px 10px 2px;
    color: white;
    font-size: 1.2em; 
    text-align: left;
    z-index: 2;
    text-shadow:
        -1.5px -1.5px 2px #000, 1.5px -1.5px 2px #000,
        -1.5px 1.5px 2px #000, 1.5px 1.5px 2px #000,
        0px 1px 3px rgba(0,0,0,0.5),
        0 0 5px rgba(255,0,0,0.3);
}

.value-bubble h3 i {
  margin-right: 6px;
  opacity: 0.95;
  font-size: 0.9em;
  color: #ffffff;
  text-shadow:
    -1.5px -1.5px 2px #000, 1.5px -1.5px 2px #000,
    -1.5px 1.5px 2px #000, 1.5px 1.5px 2px #000,
    0px 1px 3px rgba(0,0,0,0.5),
    0 0 5px rgba(255,0,0,0.3);
}
@media (max-width: 600px) {
  .value-bubble h3 {
    font-size: 1.1em;
    padding: 2px 0; /* 2px gap around title */
  }
}
.blog-post-button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  padding: 4px 10px;
  background: #000000;
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: #fff;
  border-radius: 6px;
  text-decoration: none;
  font-size: 14px;
  line-height: 1.2;
  transition: all 0.2s ease;
  text-shadow: none;
}
.blog-post-button.active {
  border-color: rgba(255, 255, 255, 0.9);
  color: #fff;
}
.blog-post-button:hover:not(.inactive) {
  transform: scale(1.05);
  border-color: #fff;
}
.blog-post-button.active:hover:not(.inactive) {
  box-shadow: 0 0 8px rgba(255, 255, 255, 0.2);
}
.blog-post-button.inactive {
  pointer-events: auto;
  opacity: 0.5;
  cursor: not-allowed;
}
.blog-post-button.inactive:hover::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.8);
  color: #fff;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 0.75em;
  white-space: nowrap;
  z-index: 10;
}
.value-category {
  margin-top: 4px; /* increase gap above category grid */
  font-size: 0.85em;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 6px;
  justify-content: center;
  opacity: 1;
}
@media (max-width: 600px) {
  .value-category {
    font-size: 0.85em;
    margin-top: 4px; /* increase gap above category grid */
  }
}
.value-category span {
  display: block;
  padding: 5px 5px;
  border-radius: 8px;
  text-shadow: 0 1px 1px rgba(0,0,0,0.4);
  text-align: center;
  box-sizing: border-box;
  transition: background-color 0.3s ease, box-shadow 0.3s ease, border-color 0.2s ease;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 0.9em;
  background-color: #000000;
  border: 1px solid rgba(255, 255, 255, 0.2);
}
.value-bubble.visible .value-category span {
  box-shadow: 0 1px 3px rgba(0,0,0,0.4);
}
.value-category span > span {
  display: block;
  margin-top: 4px;
  background-color: transparent;
  padding: 2px 4px;
  border-radius: 6px;
  font-size: 0.85em;
}
.value-bubble:hover .value-category span {
  border-color: rgba(255, 255, 255, 0.4);
}
.value-category .jbt { font-weight: bold; color: #00ff00; }
.value-category .duped { font-weight: bold; color: red; }
.value-bubble:hover .value-category .jbt { color: #00ff00 !important; }
.value-category i {
  color: inherit;
}
.value-bubble:hover .value-category .duped { color: red !important; }
.value-bubble.limited-item { --glow-color: #FFD700; }
.value-bubble.obtainable-item { --glow-color: #00ADFF; }
.value-bubble.safe-item    { --glow-color: #76FF03; }
.value-bubble.retired-item { --glow-color: #FFA500; }
.value-bubble.event-exclusive-item { --glow-color: #FF1493; }
.value-bubble.reference-item { --glow-color: #800080; }
.status-label {
  position: absolute;
  top: 3.5%;
  left: 2.2%;
  z-index: 100;
  color: #fff;
  font-size: 12.7px;
  padding: 2.86px 5.08px;
  font-weight: bold;
  border-radius: 3px;
  display: flex;
  align-items: center;
  text-shadow: -1px -1px 2px #000, 1px -1px 2px #000, -1px 1px 2px #000, 1px 1px 2px #000;
  opacity: 1;
  transition: transform 0.3s ease, background-color 0.3s ease;
  box-sizing: border-box;
  line-height: 1;
  gap: 3px;
  pointer-events: none;
  background-position: 0% 50%;
}



/* Fix emoji alignment across different display densities */
@media (-webkit-min-device-pixel-ratio: 1), (min-resolution: 96dpi) {
  .status-label {
    align-items: baseline;
    line-height: 1.1;
  }
}

@media (-webkit-min-device-pixel-ratio: 1.5), (min-resolution: 144dpi) {
  .status-label {
    align-items: center;
    line-height: 1;
  }
}

@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
  .status-label {
    align-items: center;
    line-height: 0.95;
  }
}

.status-label i {
  margin-right: 5px;
  vertical-align: middle;
}
.value-bubble:hover .status-label {
  animation: var(--gradient-animation);
}
.image-container:hover .status-label {
  transform: none;
  animation: var(--gradient-animation);
}
.value-bubble.limited-item .status-label {
  background: linear-gradient(45deg, #FFD700, #FFECB3, #FFD700, #FFA500, #FFD700, #FFECB3, #FFD700);
  background-size: 200%;
}
.value-bubble.obtainable-item .status-label {
  background: linear-gradient(45deg, #00ADFF, #B3E5FC, #00ADFF, #0077CC, #00ADFF, #B3E5FC, #00ADFF);
  background-size: 200%;
}
.value-bubble.safe-item .status-label {
  background: linear-gradient(45deg, #76FF03, #ADFF2F, #76FF03, #32CD32, #76FF03, #ADFF2F, #76FF03);
  background-size: 200%;
}
.value-bubble.retired-item .status-label {
  background: linear-gradient(45deg, #FFA500, #FF8C00, #FFA500, #FF4500, #FFA500, #FF8C00, #FFA500);
  background-size: 200%;
}
.value-bubble.event-exclusive-item .status-label {
  background: linear-gradient(45deg, #FF1493, #FF69B4, #FF1493, #FF34B3, #FF1493, #FF69B4, #FF1493);
  background-size: 200%;
}
.value-bubble.reference-item .status-label {
  background: linear-gradient(45deg, #800080, #BA55D3, #800080, #4B0082, #800080, #BA55D3, #800080);
  background-size: 200%;
}
.value-explanation-container {
  margin-top: 5px;
  font-size: 0.7em;
  color: #fff;
  font-weight: bold;
  line-height: 1.2;
  height: calc(4 * 1.3em + 2px);
  overflow: hidden;
  text-align: justify;
  letter-spacing: 0em;
  word-spacing: 0em;
  hyphens: auto;
  opacity: 1; /* Keep description always visible; no fade */
  width: 100%;
  box-sizing: border-box;
  display: block;
  position: relative;
  animation: none; /* Disable fade-in animation for description */
}
.value-explanation {
  display: -webkit-box;
  -webkit-line-clamp: 4;
  -webkit-box-orient: vertical;
  overflow: hidden;
  margin: 0;
  line-height: 1.3;
  padding-bottom: 2px;
}
.clickable-description {
  cursor: pointer;
  transition: color 0.2s ease, text-shadow 0.2s ease;
  border-radius: 4px;
  padding: 2px 4px;
}
.clickable-description:hover {
  color: #ffffff;
  text-shadow: 0 0 4px rgba(255, 255, 255, 0.3);
  background-color: rgba(255, 255, 255, 0.05);
}
.blog-post-link {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  padding: 4px 8px;
  background: #000000;
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: #ccc;
  border-radius: 6px;
  text-decoration: none;
  font-size: 10px;
  line-height: 1.2;
  font-weight: bold;
  transition: all 0.2s ease;
  text-shadow: none;
}
.blog-post-link.active {
  border-color: rgba(255, 255, 255, 0.9);
  color: #fff;
}
.blog-post-link:hover:not(.inactive) {
  transform: scale(1.05);
  border-color: #fff;
}
.blog-post-link.active:hover:not(.inactive) {
  box-shadow: 0 0 8px rgba(255, 255, 255, 0.2);
}
.blog-post-link.inactive {
  pointer-events: auto;
  opacity: 0.5;
  cursor: not-allowed;
}
.blog-post-link.inactive:hover::after {
  content: "";
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.8);
  color: #fff;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 0.75em;
  white-space: nowrap;
  z-index: 10;
}
.explanation-button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  padding: 4px 8px;
  background: #000000;
  border: 1px solid rgba(255, 255, 255, 0.9);
  color: #fff;
  border-radius: 6px;
  text-decoration: none;
  font-size: 10px;
  line-height: 1.2;
  font-weight: bold;
  transition: all 0.2s ease;
  text-shadow: none;
  cursor: pointer;
}
.explanation-button:hover {
  transform: scale(1.02);
  border-color: #fff;
  box-shadow: 0 0 4px rgba(255, 255, 255, 0.2);
  background-color: #000;
}
.update-timestamp {
  font-size: 0.6em;
  color: #FFFFFF;
  margin-top: 8px;
  margin-bottom: 0px;
  opacity: 1;
  display: flex;
  align-items: baseline; /* Align by text baseline */
  justify-content: center;
  width: 100%;
  gap: 6px;
  white-space: nowrap;
  padding: 0;
  text-align: center;
  min-height: unset; /* Remove fixed height */
  box-sizing: border-box;
}
.update-timestamp i {
  margin-right: 4px; /* Space for new icon */
}
.timestamp-text {
  font-size: 9.6px;
  line-height: 1;
}
/* DISCORD SUBMISSION INFO STYLES START (mirrors OG Item Finder) */
.discord-submission-info {
  background: rgba(88, 101, 242, 0.1);
  border: 1px solid rgba(88, 101, 242, 0.3);
  border-radius: 12px;
  padding: 25px;
  margin: 20px auto 20px auto;
  max-width: 900px;
  text-align: center;
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  box-shadow: 0 4px 12px rgba(88, 101, 242, 0.1);
  transition: transform 0.2s ease, box-shadow 0.2s ease, border-color 0.2s ease;
  cursor: default;
  opacity: 0;
  transform: translateY(20px);
  transition: opacity 0.45s ease, transform 0.2s ease, box-shadow 0.2s ease, border-color 0.2s ease;
  -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none;
}
.discord-submission-info:hover {
  transform: translateY(-2px) !important;
  box-shadow: 0 6px 16px rgba(88, 101, 242, 0.25);
  border-color: rgba(88, 101, 242, 0.6);
}
.discord-submission-info:active { transform: translateY(-2px) !important; box-shadow: 0 5px 14px rgba(88, 101, 242, 0.22); }
.submission-info-content { text-align: center; }
.submission-text { display: inline-block; max-width: 100%; -webkit-user-select: text; -moz-user-select: text; -ms-user-select: text; user-select: text; }
.submission-text h3 { margin: 0 0 8px 0; color: #fff; font-size: 1.3em; font-weight: 600; display: inline-flex; align-items: center; justify-content: center; gap: 10px; cursor: text; }
.submission-icon { font-size: 1.2em; color: #5865F2; }
.submission-text p { margin: 0; color: #b0b0b0; font-size: 1em; line-height: 1.7; word-wrap: break-word; hyphens: auto; cursor: text; }
.submission-text a { color: #5865F2; text-decoration: none; font-weight: 600; transition: color 0.2s ease; cursor: pointer; }
.submission-text a:hover { color: #7289DA; text-decoration: underline; }
@media (max-width: 600px) { .submission-text p { font-size: 0.9em; } }
/* DISCORD SUBMISSION INFO STYLES END */
/* Item count indicator (mirrors OG Item Finder) */
.items-count {
  text-align: center;
  margin: 15px auto 5px auto;
  color: #b0b0b0 !important;
  font-size: 0.9em;
  padding: 0.25em 0.5em;
  opacity: 0;
  transform: translateY(30px) translateZ(0);
  position: relative;
  z-index: 0;
  visibility: hidden;
}
.items-count strong { padding: 0 0.1em; color: #b0b0b0 !important; }
/* Prevent early flash: hide until page reveal explicitly allows */
body:not(.count-reveal-allowed) #ItemsCount { display: none !important; }
/* Also keep hidden while the custom loading overlay is active */
body.loading-active #ItemsCount { visibility: hidden !important; }
@keyframes itemsCountIn {
  0% { opacity: 0; transform: translateY(30px) translateZ(0); }
  100% { opacity: 1; transform: translateY(0) translateZ(0); }
}
.items-count.anim-fade-in {
  animation: itemsCountIn 0.45s ease;
  animation-fill-mode: both;
  will-change: opacity, transform;
  visibility: visible;
}
.items-count.hidden { opacity: 0 !important; transform: translateY(-4px) !important; visibility: hidden !important; }
@keyframes itemsCountOut { 0% { opacity: 1; transform: translateY(0); } 100% { opacity: 0; transform: translateY(-4px); } }
.items-count.anim-fade-out { animation: itemsCountOut 0.15s ease forwards; will-change: opacity, transform; visibility: visible; }
/* When the community box is hidden, balance spacing so the count sits centered */
body.submission-hidden #ItemsCount { margin: 20px auto 15px auto; }
@keyframes fadeInContent {
  to { opacity: 1; }
}
.fullscreen-overlay {
  position: fixed;
  top: var(--top-navbar-height);
  left: 0;
  width: 100%;
  height: calc(100% - var(--top-navbar-height));
  background: rgba(0, 0, 0, 0.9);
  z-index: 1000; /* Behind navbar dropdowns */
  display: grid;
  place-items: center;
  opacity: 0;
  visibility: hidden;
  transition: opacity 0.3s ease, visibility 0s linear 0.3s;
}
.fullscreen-overlay.active {
  opacity: 1;
  visibility: visible;
  transition: opacity 0.3s ease, visibility 0s linear 0s;
}
.fullscreen-image {
  width: 800px;
  height: 450px;
  object-fit: contain;
  border-radius: 8px;
  transform: scale(0.8);
  transition: transform 0.3s ease;
}
.fullscreen-overlay.active .fullscreen-image {
  transform: scale(1);
}
@media (max-width: 960px) {
  .fullscreen-image {
    width: 600px;
    height: 337.5px;
  }
}
@media (max-width: 600px) {
  .fullscreen-image {
    width: 90vw;
    height: 50.625vw;
    max-width: 400px;
    max-height: 225px;
  }
}

/* Fullscreen image caption */
.fullscreen-caption {
    position: absolute;
    bottom: 32px;
    left: 50%;
    transform: translateX(-50%);
    background: rgba(0, 0, 0, 0.8);
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    color: #A9A9A9;
    padding: 8px 16px;
    border-radius: 8px;
    font-size: 0.85rem;
    text-align: center;
    border: 1px solid #2F3336;
    max-width: 90vw;
    line-height: 1.4;
}
.fullscreen-caption a {
    color: #FFFFFF;
    text-decoration: underline;
    font-weight: 600;
}
.fullscreen-caption a:hover {
    text-decoration: underline;
}
/* Use the same close button styles as menus for fullscreen close */

/* Fullscreen close button responsive positioning to match modal close buttons */
@media (max-width: 768px) {
  /* inherits responsive sizing from .jbtn-modal-close */
}

@media (max-width: 480px) {
  /* inherits responsive sizing from .jbtn-modal-close */
}

@media (max-width: 360px) {
  /* inherits responsive sizing from .jbtn-modal-close */
}
.no-items-found-message {
  background: #000000;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  padding: 25px 30px;
  width: auto;
  max-width: 450px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  color: #fff;
  content-visibility: auto;
  contain-intrinsic-size: 280px 220px;
  opacity: 0;
  transform: scale(0.95);
  transition: opacity 0.3s ease, transform 0.3s ease, border-color 0.2s ease, box-shadow 0.3s ease;
}
.no-items-found-message.visible {
  opacity: 1;
  transform: scale(1);
}
.no-items-found-message.visible:hover {
    transform: scale(1.02);
    border-color: rgba(255, 255, 255, 0.4);
    box-shadow: 0 0 15px rgba(255, 255, 255, 0.2);
}
.no-items-icon {
    font-size: 2.5em;
    color: #ffffff;
    margin-bottom: 15px;
}
.no-items-found-message h4 {
    margin: 0 0 10px 0;
    font-size: 1.2em;
    font-weight: 600;
    color: #fff;
}
.no-items-found-message p {
    margin: 0 0 20px 0;
    font-size: 0.9em;
    color: #a0a0a0;
    line-height: 1.6;
}
#noItemsResetButton {
    padding: 8px 16px;
}

@supports not (backdrop-filter: blur(10px)) {
  .no-items-found-message {
    background: #111;
    border: 1px solid rgba(255, 255, 255, 0.15);
    border-radius: 12px;
    padding: 25px 30px;
    width: auto;
    max-width: 450px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  color: #fff;
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  content-visibility: auto;
  contain-intrinsic-size: 280px 220px;
  opacity: 0;
  transform: scale(0.95);
  transition: opacity 0.3s ease, transform 0.3s ease, border-color 0.2s ease, box-shadow 0.3s ease;
  }
  .no-items-found-message.visible {
    opacity: 1;
    transform: scale(1);
  }
  .no-items-found-message.visible:hover {
      transform: scale(1.02);
      border-color: rgba(255, 255, 255, 0.4);
      box-shadow: 0 0 15px rgba(255, 255, 255, 0.2);
  }
  .no-items-icon {
      font-size: 2.5em;
      color: #ffffff;
      margin-bottom: 15px;
  }
  .no-items-found-message h4 {
      margin: 0 0 10px 0;
      font-size: 1.2em;
      font-weight: 600;
      color: #fff;
  }
  .no-items-found-message p {
      margin: 0 0 20px 0;
      font-size: 0.9em;
      color: #a0a0a0;
      line-height: 1.6;
  }
  #noItemsResetButton {
      padding: 8px 16px;
  }
}

.main-app-footer {
    text-align: center;
    padding: 30px 20px;
    margin: 40px -20px -20px -20px;
    font-size: 0.9em;
    color: #b0b0b0;
    border-top: 1px solid rgba(255, 255, 255, 0.2);
    background: #000000;
    backdrop-filter: blur(5px);
    -webkit-backdrop-filter: blur(5px);
}
@supports not (backdrop-filter: blur(5px)) {
    .main-app-footer { background: #000000; }
}

.footer-content-wrapper {
    max-width: 900px;
    margin: 0 auto;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
}

.footer-row {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
}

.footer-summary-text {
    font-size: 0.85em;
    color: #aaa;
    line-height: 1.6;
    margin: 0;
    max-width: 100%;
    text-align: center;
}

#footer-copyright-info-row {
    flex-direction: row;
    justify-content: center;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
    margin-top: 0;
    border-top: none;
    padding-top: 0;
}

.footer-copyright-image {
    width: 24px;
    height: 24px;
    object-fit: contain;
    flex-shrink: 0;
}

.footer-copyright-text {
    font-size: 0.8em;
    color: #888;
    margin: 0;
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
    line-height: 1.6;
}
.footer-copyright-text > span:not(.footer-link-separator),
.footer-copyright-text > a {
    margin: 0;
}
.footer-copyright-text > span:first-child { margin-left: 0; }
.footer-copyright-text > a:last-of-type { margin-right: 0;}


.footer-modal-overlay {
    position: fixed;
    top: var(--top-navbar-height);
    left: 0;
    width: 100%;
    height: calc(100% - var(--top-navbar-height));
    background: rgba(0, 0, 0, 0.9);
    display: grid;
    place-items: center;
    z-index: 1001;
    opacity: 0;
    visibility: hidden;
    transition: opacity 0.3s ease, visibility 0s linear 0.3s;
    padding: 15px;
    box-sizing: border-box;
}
.footer-modal-overlay.active {
    opacity: 1;
    visibility: visible;
    transition-delay: 0s;
}
.footer-modal-content {
    background: #000000;
    border: 1px solid rgba(255, 255, 255, 0.3);
    border-radius: 10px;
    padding: 25px 30px 25px;
    width: 100%;
    max-width: 550px;
    max-height: 80vh;
    overflow-y: auto;
    position: relative;
    color: #e0e0e0;
    box-shadow: 0 8px 30px rgba(0,0,0,0.6);
    transform: scale(0.9);
    transition: transform 0.3s ease;
    box-sizing: border-box;
    text-align: left;
}
.footer-modal-overlay.active .footer-modal-content {
    transform: scale(1);
}
@media (max-width: 600px) {
    .footer-modal-content {
        padding: 20px 15px 5px;
        width: 100%;
    }
}
.footer-modal-content h2,
.footer-modal-content h3 {
    color: #fff;
    margin-top: 0;
    border-bottom: 1px solid #ffffff;
    padding-bottom: 10px;
    margin-bottom: 15px;
}
.footer-modal-content p {
    font-size: 0.9em;
    line-height: 1.7;
    color: #ccc;
}
.footer-modal-content p:not(:last-child) {
    margin-bottom: 1em;
}
.footer-modal-close {
    position: fixed;
    top: calc(var(--top-navbar-height) + 10px);
    right: 20px;
    background: #000;
    border: 1px solid rgba(255, 255, 255, 0.3);
    color: #ccc;
    font-size: 1.6em;
    font-weight: bold;
    cursor: pointer;
    width: 32px;
    height: 32px;
    padding: 0;
    border-radius: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: border-color 0.2s ease, transform 0.2s ease;
    z-index: 1002;
    text-align: center;
    vertical-align: middle;
    font-family: inherit;
}
.footer-modal-close:hover {
    background: #000;
    color: #fff;
    border-color: rgba(255, 255, 255, 0.9);
    transform: scale(1.05);
}
.modal-text-content {
    display: none;
}
.modal-text-content.active {
    display: block;
}


.footer-legal-links-group {
}

.footer-link {
    color: #ccc;
    text-decoration: none;
    font-weight: 500;
    font-size: 0.9em;
    transition: color 0.2s ease;
    display: inline-flex;
    align-items: center;
}
.footer-link:hover {
    color: #fff;
}
.footer-link-text {
}
.footer-link[data-modal="about"] .footer-link-text,
.footer-link[data-modal="about"]:hover .footer-link-text {
    text-decoration: none;
}
.footer-link:hover .footer-link-text {
    text-decoration: none;
}

.footer-link-icon {
    margin-right: 5px;
}

.footer-link-separator {
    color: rgba(255, 255, 255, 0.3);
    user-select: none;
    margin: 0 0.25em;
}

@media (max-width: 767px) {
}

@media (max-width: 480px) {
    .main-app-footer {
        padding: 20px 15px;
        margin-left: 0;
        margin-right: 0;
        margin-bottom: 0;
    }
    .footer-content-wrapper {
        gap: 15px;
    }
    .footer-copyright-image {
        width: 20px;
        height: 20px;
    }
    .footer-summary-text {
        font-size: 0.8em;
    }
    .footer-copyright-text {
        font-size: 0.75em;
    }
}
.navbar-link-text {
  display: inline;
  white-space: nowrap;
  overflow: visible;
  max-width: none;
}
.navbar-more-dropdown .navbar-dropdown > .navbar-dropdown-toggle {
  min-width: 0;
  flex: 1 1 auto;
}
.navbar-container { min-width: 0 !important; }
.navbar-links-desktop { flex-shrink: 1 !important; min-width: 0 !important; }
.navbar-more-dropdown { flex-shrink: 0 !important; }

.input-icon-wrapper {
  display: inline-flex;
  align-items: center;
  position: relative;
  width: fit-content;
  max-width: 100%;
  overflow: hidden;
}
/* Explicit enabled-state outline behavior for search/sort/filter wrappers (no :has dependency) */
.search-sort .input-icon-wrapper:not(.disabled):hover {
  border-color: rgba(255,255,255,0.8) !important;
}
.search-sort .input-icon-wrapper:not(.disabled):focus-within {
  border-color: rgba(255,255,255,0.85) !important;
  outline: 1px solid #1a73e8 !important;
  outline-offset: 0 !important;
}
.input-icon {
  position: absolute;
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 1em;
  color: #fff;
  pointer-events: none;
  z-index: 2;
  transition: none !important; /* Remove default transition - controlled by specific rules */
}
/* Handled by the unified rule below - keeping this for text elements only */
.input-icon-wrapper:has(input:disabled) input,
.input-icon-wrapper:has(select:disabled) select,
.input-icon-wrapper:has(input:disabled) .nav-input-style,
.input-icon-wrapper:has(select:disabled) .button-label {
    color: rgba(255, 255, 255, 1) !important; /* Keep full white since opacity will dim it */
    transition: none !important; /* Instant color change to prevent double dimming */
}
.input-icon-wrapper input[type="text"] {
  padding-left: 2.8em;
  max-width: 100%;
  box-sizing: border-box;
}
.input-icon-wrapper select {
  padding-left: 2.8em;
  max-width: 100%;
  box-sizing: border-box;
}
.navbar-separator {
  color: var(--navbar-text-scrolled);
  margin: 0 6px; /* tighter gap */
  font-weight: 600;
  user-select: none;
  pointer-events: none;
  transition: color 0.3s ease;
}
.top-navbar.loaded .navbar-separator {
  color: var(--navbar-text-initial);
}
.top-navbar.scrolled .navbar-separator {
  color: var(--navbar-text-scrolled);
}
.navbar-more-dropdown .navbar-dropdown.open > .navbar-dropdown-toggle i.fa-caret-down {
    transform: rotate(180deg);
    color: var(--navbar-icon-scrolled);
}

.top-navbar.loaded .navbar-more-dropdown .navbar-dropdown.open > .navbar-dropdown-toggle i.fa-caret-down {
    color: var(--navbar-icon-initial);
}

.navbar-more-dropdown #legacy-features-dropdown > .navbar-dropdown-toggle {
    pointer-events: none;
    font-weight: 600;
    color: #888;
    text-transform: uppercase;
    font-size: 0.8em;
    padding: 15px 15px 5px 15px;
    cursor: default;
}
.navbar-more-dropdown #legacy-features-dropdown > .navbar-dropdown-toggle:hover {
    background-color: transparent;
}
.navbar-more-dropdown #legacy-features-dropdown > .navbar-dropdown-toggle .fa-caret-down {
    display: none;
}
.navbar-more-dropdown #legacy-features-dropdown > .navbar-dropdown-menu {
    display: block !important; /* Keep it open */
    padding-left: 15px; /* Indent items */
}

.navbar-more-dropdown .navbar-dropdown-menu .navbar-dropdown > .navbar-dropdown-toggle {
    justify-content: flex-start;
}

.navbar-more-dropdown .navbar-dropdown-menu .navbar-dropdown > .navbar-dropdown-toggle i.fa-caret-down {
    transform: rotate(-90deg); /* Point right */
    margin-left: auto; /* Push arrow to the far right */
    transition: color 0.3s ease, transform 0.3s ease;
    color: var(--navbar-icon-scrolled);
}

.top-navbar.loaded .navbar-more-dropdown .navbar-dropdown-menu .navbar-dropdown > .navbar-dropdown-toggle i.fa-caret-down {
    color: var(--navbar-icon-initial);
}

.navbar-more-dropdown .navbar-dropdown-menu .navbar-dropdown.open > .navbar-dropdown-toggle i.fa-caret-down {
    transform: rotate(0deg); /* Point down when open */
    color: var(--navbar-icon-scrolled);
}

.top-navbar.loaded .navbar-more-dropdown .navbar-dropdown-menu .navbar-dropdown.open > .navbar-dropdown-toggle i.fa-caret-down {
    color: var(--navbar-icon-initial);
}

/* Ensure all More dropdown arrows transition properly - comprehensive fix */
.navbar-more-dropdown i.fa-caret-down {
    transition: color 0.3s ease, transform 0.2s ease !important;
    color: var(--navbar-icon-scrolled) !important;
}

.top-navbar.loaded .navbar-more-dropdown i.fa-caret-down {
    color: var(--navbar-icon-initial) !important;
}

/* Fix for scroll state - when navbar changes color during scroll */
.top-navbar.scrolled .navbar-more-dropdown i.fa-caret-down {
    color: var(--navbar-icon-scrolled) !important;
}

/* Ultra-specific fix for Other Values and all dropdown arrows in More menu */
.navbar-more-dropdown .navbar-dropdown-menu .navbar-dropdown .navbar-dropdown-toggle i.fa-caret-down,
.navbar-more-dropdown .navbar-dropdown .navbar-dropdown-toggle i.fa-caret-down {
    transition: color 0.3s ease, transform 0.2s ease !important;
    color: var(--navbar-icon-scrolled) !important;
}

.top-navbar.loaded .navbar-more-dropdown .navbar-dropdown-menu .navbar-dropdown .navbar-dropdown-toggle i.fa-caret-down,
.top-navbar.loaded .navbar-more-dropdown .navbar-dropdown .navbar-dropdown-toggle i.fa-caret-down {
    color: var(--navbar-icon-initial) !important;
}

.top-navbar.scrolled .navbar-more-dropdown .navbar-dropdown-menu .navbar-dropdown .navbar-dropdown-toggle i.fa-caret-down,
.top-navbar.scrolled .navbar-more-dropdown .navbar-dropdown .navbar-dropdown-toggle i.fa-caret-down {
    color: var(--navbar-icon-scrolled) !important;
}

/* Nuclear option - target all arrows by their position and force color */
.navbar-more-dropdown .navbar-dropdown-toggle .fa-caret-down,
.navbar-more-dropdown .navbar-dropdown .navbar-dropdown-toggle .fa-caret-down {
    color: #ffffff !important;
    transition: color 0.3s ease !important;
}

.top-navbar.loaded .navbar-more-dropdown .navbar-dropdown-toggle .fa-caret-down,
.top-navbar.loaded .navbar-more-dropdown .navbar-dropdown .navbar-dropdown-toggle .fa-caret-down {
    color: #000000 !important;
}

.top-navbar.scrolled .navbar-more-dropdown .navbar-dropdown-toggle .fa-caret-down,
.top-navbar.scrolled .navbar-more-dropdown .navbar-dropdown .navbar-dropdown-toggle .fa-caret-down {
    color: #ffffff !important;
}

/* Fix mobile menu arrows to ensure they are ALWAYS white - highest specificity */
.navbar-links-mobile .fa-caret-down,
.navbar-mobile-menu .fa-caret-down,
.navbar-links-mobile .navbar-dropdown > .navbar-dropdown-toggle .fa-caret-down,
.navbar-mobile-menu .navbar-dropdown > .navbar-dropdown-toggle .fa-caret-down,
.navbar-links-mobile .navbar-dropdown-menu .navbar-dropdown > .navbar-dropdown-toggle .fa-caret-down,
.navbar-mobile-menu .navbar-dropdown-menu .navbar-dropdown > .navbar-dropdown-toggle .fa-caret-down {
    color: #ffffff !important;
    transition: color 0.3s ease, transform 0.2s ease !important;
}

/* Override any state-specific rules for mobile menu arrows */
.top-navbar.loaded .navbar-links-mobile .fa-caret-down,
.top-navbar.loaded .navbar-mobile-menu .fa-caret-down,
.top-navbar.loaded .navbar-links-mobile .navbar-dropdown > .navbar-dropdown-toggle .fa-caret-down,
.top-navbar.loaded .navbar-mobile-menu .navbar-dropdown > .navbar-dropdown-toggle .fa-caret-down,
.top-navbar.loaded .navbar-links-mobile .navbar-dropdown-menu .navbar-dropdown > .navbar-dropdown-toggle .fa-caret-down,
.top-navbar.loaded .navbar-mobile-menu .navbar-dropdown-menu .navbar-dropdown > .navbar-dropdown-toggle .fa-caret-down,
.top-navbar.scrolled .navbar-links-mobile .fa-caret-down,
.top-navbar.scrolled .navbar-mobile-menu .fa-caret-down,
.top-navbar.scrolled .navbar-links-mobile .navbar-dropdown > .navbar-dropdown-toggle .fa-caret-down,
.top-navbar.scrolled .navbar-mobile-menu .navbar-dropdown > .navbar-dropdown-toggle .fa-caret-down,
.top-navbar.scrolled .navbar-links-mobile .navbar-dropdown-menu .navbar-dropdown > .navbar-dropdown-toggle .fa-caret-down,
.top-navbar.scrolled .navbar-mobile-menu .navbar-dropdown-menu .navbar-dropdown > .navbar-dropdown-toggle .fa-caret-down {
    color: #ffffff !important;
}

/* Ultimate override - target ALL arrows in More dropdown regardless of nesting */
.navbar-more-dropdown .fa-caret-down {
    color: #ffffff !important;
    transition: color 0.3s ease !important;
}

.top-navbar.loaded .navbar-more-dropdown .fa-caret-down {
    color: #000000 !important;
}

.top-navbar.scrolled .navbar-more-dropdown .fa-caret-down {
    color: #ffffff !important;
}

/* Also override any Font Awesome base styles */
.navbar-more-dropdown [class*="fa-caret-down"] {
    color: inherit !important;
}

/* Specific fix for Other Values dropdown arrow */
.navbar-dropdown .navbar-dropdown-toggle i.fa-caret-down {
    transition: color 0.3s ease, transform 0.2s ease !important;
    color: var(--navbar-icon-scrolled) !important;
}

.top-navbar.loaded .navbar-dropdown .navbar-dropdown-toggle i.fa-caret-down {
    color: var(--navbar-icon-initial) !important;
}

.top-navbar.scrolled .navbar-dropdown .navbar-dropdown-toggle i.fa-caret-down {
    color: var(--navbar-icon-scrolled) !important;
}

.navbar-more-dropdown .navbar-dropdown-menu .navbar-dropdown.open > .navbar-dropdown-toggle {
    background-color: transparent;
}
.top-navbar.scrolled .navbar-more-dropdown .navbar-dropdown-menu .navbar-dropdown.open > .navbar-dropdown-toggle {
    background-color: transparent;
}

.top-navbar.scrolled .hamburger-inner,
.top-navbar.scrolled .hamburger-inner::before,
.top-navbar.scrolled .hamburger-inner::after {
    background-color: var(--navbar-icon-scrolled);
}

.top-navbar.scrolled .navbar-dropdown-menu {
    background-color: var(--navbar-bg-scrolled);
    border-color: var(--navbar-border-scrolled);
}
.top-navbar:not(.loaded) .navbar-dropdown-menu {
    background-color: var(--navbar-bg-scrolled);
    border-color: var(--navbar-border-scrolled);
}
.top-navbar:not(.loaded) .navbar-dropdown-menu a {
    color: var(--navbar-text-scrolled);
}
.top-navbar:not(.loaded) .navbar-dropdown-menu .navbar-dropdown > .navbar-dropdown-toggle {
    color: var(--navbar-text-scrolled);
}
/* Not loaded state inherits from base rule */
.top-navbar.scrolled .navbar-dropdown-menu a {
    color: var(--navbar-text-scrolled);
}

.top-navbar.scrolled .navbar-dropdown-menu .navbar-dropdown > .navbar-dropdown-toggle {
    color: var(--navbar-text-scrolled);
}

/* Nested dropdown icons inherit color from base rule */

.navbar-mobile-menu-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.9);
    z-index: -1;
}

.navbar-mobile-menu {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    max-width: none;
    background-color: #000000;
    z-index: 1200;
    opacity: 0;
    pointer-events: none;
    transition: opacity 0.3s ease;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: var(--top-navbar-height) 20px 20px;
    box-sizing: border-box;
    overflow-y: auto;
}

@supports (backdrop-filter: blur(10px)) or (-webkit-backdrop-filter: blur(10px)) {
    .navbar-mobile-menu {
        /* Removed backdrop filter - using solid black background */
    }
}

.navbar-mobile-menu.open {
    opacity: 1;
    pointer-events: auto;
}

.navbar-links-mobile {
    flex-grow: 0;
    overflow-y: scroll;
    width: 100%;
    max-width: 400px;
    padding: 20px 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    gap: 8px;
    min-height: 200px; /* Ensure minimum height for tablet visibility */
}

/* Tablet-specific mobile menu fixes */
@media (min-width: 768px) and (max-width: 991px) {
    .navbar-links-mobile {
        max-width: 500px; /* Wider on tablets */
        padding: 30px 0; /* More padding on tablets */
        gap: 12px; /* Larger gaps on tablets */
    }
    
    /* Ensure mobile toggle is visible on tablets including 973px width */
    .navbar-right-side {
        display: flex !important;
    }
    .navbar-links-desktop {
        display: none !important;
    }
}

.navbar-links-mobile::-webkit-scrollbar {
    width: 8px;
}
.navbar-links-mobile::-webkit-scrollbar-track {
    background: rgba(255, 255, 255, 0.1);
    border-radius: 4px;
}
.navbar-links-mobile::-webkit-scrollbar-thumb {
    background: rgba(255, 255, 255, 0.3);
    border-radius: 4px;
}
.navbar-links-mobile::-webkit-scrollbar-thumb:hover {
    background: rgba(255, 255, 255, 0.5);
}

.navbar-links-mobile a,
.navbar-links-mobile .navbar-dropdown > .navbar-dropdown-toggle {
    font-size: clamp(1.1rem, 4.5vw, 1.4rem);
    font-weight: 600;
    color: #ffffff;
    text-decoration: none;
    border: 1px solid transparent;
    padding: 10px 15px;
    width: auto;
    box-sizing: border-box;
    border-radius: 8px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    align-self: center;
    background-color: transparent;
    text-shadow: none;
    transition: transform 0.3s ease, background-color 0.25s ease, border-color 0.25s ease, color 0.3s ease;
    will-change: transform;
    transform: translateY(0);
}

.navbar-links-mobile a:hover,
.navbar-links-mobile a:focus,
.navbar-links-mobile a:active,
.navbar-links-mobile .navbar-dropdown > .navbar-dropdown-toggle:hover,
.navbar-links-mobile .navbar-dropdown > .navbar-dropdown-toggle:focus,
.navbar-links-mobile .navbar-dropdown > .navbar-dropdown-toggle:active {
    background-color: rgba(255, 255, 255, 0.12) !important;
    border-color: rgba(255, 255, 255, 0.28) !important;
    color: #ffffff;
    transform: translateY(-2px) !important;
    outline: none;
}
.navbar-links-mobile a.active,
.navbar-links-mobile .navbar-dropdown-toggle.active,
.navbar-links-mobile .navbar-dropdown-menu a.active {
    background-color: rgba(255, 255, 255, 0.1) !important;
    color: #ffffff !important;
    text-decoration: none;
    font-weight: 600;
    border-bottom: 3px solid currentColor;
    box-shadow: none;
    border-radius: 8px;
}

.navbar-links-mobile .navbar-separator {
    width: 80%;
    max-width: 250px;
    height: 0;
    border-top: 1px solid rgba(255, 255, 255, 0.25);
    margin: 10px 0;
    padding: 0;
}

.navbar-links-mobile .navbar-dropdown-menu {
    position: static;
    width: 100%;
    background: transparent;
    border: none;
    box-shadow: none;
    max-height: 0;
    overflow: hidden;
    padding: 0;
    margin: 5px 0 0 0;
    border-radius: 8px;
    opacity: 0;
    transition: max-height 0.3s ease-in-out, padding 0.3s ease-in-out, opacity 0.2s ease-in-out;
    pointer-events: none;
    /* Stack children vertically and center them */
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;
}
.navbar-links-mobile .navbar-dropdown.open .navbar-dropdown-menu {
    max-height: 1000px;
    padding: 8px;
    opacity: 1;
    pointer-events: auto;
}
.navbar-links-mobile .navbar-dropdown-menu a,
.navbar-links-mobile .navbar-dropdown-menu .navbar-dropdown > .navbar-dropdown-toggle {
    font-size: clamp(0.9rem, 4vw, 1.1rem);
    padding: 8px 10px;
    justify-content: center;
    border: 1px solid transparent;
    margin: 2px 0;
    background-color: transparent;
    position: relative;
    overflow: hidden;
    transition: transform 0.3s ease, background-color 0.2s ease, border-color 0.2s ease, color 0.3s ease, box-shadow 0.3s ease;
    will-change: transform;
}

.navbar-links-mobile .navbar-dropdown-menu a:hover,
.navbar-links-mobile .navbar-dropdown-menu a:focus,
.navbar-links-mobile .navbar-dropdown-menu a:active,
.navbar-links-mobile .navbar-dropdown-menu .navbar-dropdown > .navbar-dropdown-toggle:hover,
.navbar-links-mobile .navbar-dropdown-menu .navbar-dropdown > .navbar-dropdown-toggle:focus,
.navbar-links-mobile .navbar-dropdown-menu .navbar-dropdown > .navbar-dropdown-toggle:active {
    background-color: rgba(255, 255, 255, 0.12) !important;
    border-color: rgba(255, 255, 255, 0.28);
    transform: translateY(-2px);
    outline: none;
}
/* Ensure active items also animate on hover */
.navbar-links-mobile a.active:hover,
.navbar-links-mobile .navbar-dropdown-toggle.active:hover,
.navbar-links-mobile .navbar-dropdown-menu a.active:hover {
    background-color: rgba(255, 255, 255, 0.12) !important;
    border-color: rgba(255, 255, 255, 0.28);
    transform: translateY(-2px) !important;
}
.navbar-links-mobile .navbar-dropdown-menu .navbar-dropdown > .navbar-dropdown-toggle.active,
.navbar-links-mobile .navbar-dropdown-menu .navbar-dropdown > .navbar-dropdown-toggle.active:focus {
    color: #ffffff !important;
    font-weight: 600;
    text-decoration: none;
    border-bottom: 3px solid currentColor;
    box-shadow: none;
    border-radius: 8px;
    transition: background-color 0.2s ease, color 0.2s ease, border 0.2s ease, transform 0.3s ease;
}

/* Regular highlight effects - no shimmer needed */

/* Regular highlight effect for desktop menu hover */
.navbar-links-desktop a:hover,
.navbar-links-desktop .navbar-dropdown > .navbar-dropdown-toggle:hover {
    background-color: rgba(255, 255, 255, 0.1);
}

.navbar-links-mobile .navbar-dropdown > .navbar-dropdown-toggle {
    justify-content: center;
}
 .navbar-links-mobile .navbar-dropdown > .navbar-dropdown-toggle i.fa-caret-down {
    margin-left: 8px;
    color: var(--navbar-icon-scrolled);
    transition: color 0.3s ease, transform 0.2s ease;
}

/* Mobile nested dropdown arrows */
.navbar-links-mobile .navbar-dropdown-menu .navbar-dropdown > .navbar-dropdown-toggle i.fa-caret-down {
    color: var(--navbar-icon-scrolled);
    margin-left: auto;
    transform: rotate(-90deg);
    transition: color 0.3s ease, transform 0.3s ease;
}

.navbar-links-mobile .navbar-dropdown-menu .navbar-dropdown.open > .navbar-dropdown-toggle i.fa-caret-down {
    transform: rotate(0deg);
    color: var(--navbar-icon-scrolled);
}

/* Strong override for all mobile dropdown arrows */
.navbar-mobile-menu .fa-caret-down {
    color: var(--navbar-icon-scrolled);
}

.navbar-mobile-menu .navbar-dropdown > .navbar-dropdown-toggle i {
    color: var(--navbar-icon-scrolled);
}

.navbar-mobile-menu .navbar-links-mobile > * {
  opacity: 0;
  transform: translateY(12px);
  transition: transform 0.35s cubic-bezier(0.215, 0.61, 0.355, 1), opacity 0.25s ease, background-color 0.25s ease, border-color 0.25s ease, color 0.3s ease;
  transition-delay: 0s;
  pointer-events: none;
}
.navbar-mobile-menu.open .navbar-links-mobile > * {
  opacity: 1;
  transform: translateY(0);
  pointer-events: auto;
}
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(1) { transition-delay: 0.1s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(2) { transition-delay: 0.15s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(3) { transition-delay: 0.2s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(4) { transition-delay: 0.25s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(5) { transition-delay: 0.3s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(6) { transition-delay: 0.35s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(7) { transition-delay: 0.4s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(8) { transition-delay: 0.45s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(9) { transition-delay: 0.5s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(10) { transition-delay: 0.55s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(11) { transition-delay: 0.6s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(12) { transition-delay: 0.65s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(13) { transition-delay: 0.7s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(14) { transition-delay: 0.75s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(15) { transition-delay: 0.8s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(16) { transition-delay: 0.85s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(17) { transition-delay: 0.9s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(18) { transition-delay: 0.95s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(19) { transition-delay: 1.0s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(20) { transition-delay: 1.05s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(21) { transition-delay: 1.1s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(22) { transition-delay: 1.15s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(23) { transition-delay: 1.2s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(24) { transition-delay: 1.25s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(25) { transition-delay: 1.3s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(26) { transition-delay: 1.35s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(27) { transition-delay: 1.4s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(28) { transition-delay: 1.45s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(29) { transition-delay: 1.5s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(30) { transition-delay: 1.55s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(31) { transition-delay: 1.6s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(32) { transition-delay: 1.65s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(33) { transition-delay: 1.7s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(34) { transition-delay: 1.75s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(35) { transition-delay: 1.8s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(36) { transition-delay: 1.85s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(37) { transition-delay: 1.9s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(38) { transition-delay: 1.95s; }
.navbar-mobile-menu.open .navbar-links-mobile > *:nth-child(39) { transition-delay: 2.0s; }

.mobile-menu-subheading {
    padding: 10px 20px 5px;
    font-size: 0.8em;
    font-weight: 600;
    color: #888;
    text-transform: uppercase;
    margin-top: 10px;
    border-top: 1px solid #2a2a2a;
}
.mobile-other-value-link {
    padding-left: 30px !important;
}

.navbar-mobile-menu.closing {
    opacity: 0;
    visibility: hidden;
    transition: opacity 0.4s ease, visibility 0s linear 0.4s;
}

.navbar-dropdown-menu .navbar-separator {
    display: block;
    width: 100%;
    height: 1px;
    background-color: rgba(0, 0, 0, 0.15); /* default matches dark text */
    margin: 6px 0;
    font-size: 0; /* hide the '|' character */
    line-height: 0;
    transition: color 0.3s ease;
}
.top-navbar.scrolled .navbar-dropdown-menu .navbar-separator {
    background-color: rgba(255, 255, 255, 0.15); /* switch to light when navbar is dark */
}

.control-button {
  font-family: 'Montserrat', sans-serif;
  background: rgba(0,0,0,0.3);
  border: 1px solid rgba(255,255,255,0.2);
  border-radius: 4px;
  color: #fff;
  font-weight: bold;
  box-sizing: border-box;
  height: 36px;
  text-shadow: none;
  transition: border-color 0.2s ease, background-color 0.2s ease;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}
.control-button:hover {
  background: rgba(255,255,255,0.12);
  transform: translateY(-2px) scale(1.05);
}
/* Explicit enabled-state outline behavior for nav buttons */
.control-button:not(:disabled):hover {
  border-color: rgba(255,255,255,0.8) !important;
}
.control-button:not(:disabled):focus,
.control-button:not(:disabled):focus-visible {
  border-color: rgba(255,255,255,0.85) !important;
  outline: 1px solid #1a73e8 !important;
  outline-offset: 0 !important;
}
.control-button:disabled,
.control-button.disabled {
    opacity: 0.5;
    cursor: not-allowed !important;
    background: rgba(0,0,0,0.3) !important;
    border-color: rgba(255,255,255,0.2) !important;
    transform: none !important;
    pointer-events: none !important;
    box-shadow: none !important;
    outline: none !important;
}

/* Control button disabled icon and text transitions */
.control-button.disabled i,
.control-button:disabled i,
.control-button.disabled span,
.control-button:disabled span,
#LIResetButton.disabled i,
#LIResetButton:disabled i,
#LIResetButton.disabled span,
#LIResetButton:disabled span,
#LISettingsButton.disabled i,
#LISettingsButton:disabled i,
#LISettingsButton.disabled span,
#LISettingsButton:disabled span,
#navAudioInfo.disabled i,
#navAudioInfo:disabled i,
#navAudioInfo.disabled span,
#navAudioInfo:disabled span {
    color: rgba(255, 255, 255, 1) !important; /* Keep full white since opacity will dim it */
    transition: none !important; /* Disable transition to prevent staggered effects */
}

/* Make search/sort/filter icons change instantly - no transition delay */
.input-icon-wrapper.disabled .input-icon,
.input-icon-wrapper:has(input:disabled) .input-icon,
.input-icon-wrapper:has(select:disabled) .input-icon,
.input-icon-wrapper:has(button:disabled) .input-icon,
#LIResetButton.disabled,
#LIResetButton:disabled,
#LISettingsButton.disabled,
#LISettingsButton:disabled,
#navAudioInfo.disabled,
#navAudioInfo:disabled {
    opacity: 0.5 !important; /* Ensure visible dimming */
    color: rgba(255, 255, 255, 0.7) !important; /* Additional text dimming */
    transition: none !important; /* Instant color change */
}

/* Fixed lock mode to keep nav bar pinned at viewport top below menu bar (mirror og-item-finder) */
@media (min-width: 768px) {
  #LIMenuContainer.controls.fixed {
    position: fixed !important;
    top: var(--top-navbar-height) !important;
    left: 0 !important;
    right: 0 !important;
    width: 100% !important;
    z-index: 998 !important; /* under header, above content */
    padding-left: 0 !important;  /* full-bleed stretch */
    padding-right: 0 !important;
    margin: 0 !important;
    box-sizing: border-box !important;
    background: rgba(0,0,0,0.8) !important;
    backdrop-filter: blur(10px) !important;
    -webkit-backdrop-filter: blur(10px) !important;
  }
  #LIMenuContainer.controls.fixed .search-sort {
    max-width: none;
    margin: 0;
    justify-content: center;
  }
}

/* --- Settings Modal Styles --- */
.jbtn-modal-overlay {
    position: fixed;
    top: var(--top-navbar-height);
    left: 0;
    width: 100%;
    height: calc(100% - var(--top-navbar-height));
    background: rgba(0, 0, 0, 0.9);
    display: grid;
    place-items: center;
    z-index: 1400; /* ensure above header/footer */
    opacity: 0;
    visibility: hidden;
    transition: opacity 0.3s ease, visibility 0s linear 0.3s;
    padding: 15px;
    box-sizing: border-box;
}

/* Keep navbar underline visible while any modal overlay is active */
.jbtn-modal-overlay.active::before {
    content: '';
    position: fixed;
    top: var(--top-navbar-height);
    left: 0;
    right: 0;
    height: 1px;
    background: var(--navbar-border-scrolled, rgba(255,255,255,0.3));
    pointer-events: none;
    z-index: 1;
}

.jbtn-modal-overlay.active {
    opacity: 1;
    visibility: visible;
    transition-delay: 0s;
}

body.jbtn-modal-open {
    overflow: hidden;
}

.jbtn-modal-content {
    background: #000000;
    padding: 25px 30px 5px;
    border-radius: 10px;
    border: 1px solid rgba(255, 255, 255, 0.3);
    max-width: 500px;
    width: 100%;
    max-height: 90vh;
    overflow-y: auto;
    position: relative;
    color: #E0E0E0;
    box-shadow: 0 8px 30px rgba(0,0,0,0.6);
    transform: scale(0.9);
    transition: transform 0.3s ease;
    box-sizing: border-box;
    text-align: center;
}

.jbtn-modal-overlay.active .jbtn-modal-content {
    transform: scale(1);
}

@media (max-width: 600px) {
    .jbtn-modal-content {
        padding: 20px 15px 5px;
    }
    /* Maintain small bottom cushion on mobile as well */
    #settingsModal .jbtn-modal-content,
    #audioInfoModal .jbtn-modal-content {
        padding: 20px 15px 12px;
    }
}

#settingsModal .jbtn-modal-content {
    max-width: 550px;
    width: 100%;
    padding: 20px 30px 12px; /* add bottom cushion so actions aren't flush */
    max-height: 80vh;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    margin: auto;
}

  #audioInfoModal .jbtn-modal-content {
      max-width: 550px;
      width: 100%;
      padding: 20px 30px 12px; /* add bottom cushion */
      max-height: 80vh;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      margin: auto;
  }

  #footer-modal-overlay .jbtn-modal-content {
      max-width: 550px;
      width: 100%;
      padding: 25px 30px 25px;
      max-height: 80vh;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      margin: auto;
      text-align: left;
  }

  #footer-modal-overlay .settings-header {
      justify-content: flex-start;
      text-align: left;
  }

  #about-modal-content .settings-header h2,
  #about-modal-content .settings-header h2 *,
  #about-modal-content h2 {
      text-decoration: none !important;
      border-bottom: none !important;
      padding-bottom: 0 !important;
  }


#settingsModal .modal-scrollable-content {
    overflow-y: auto;
    flex-grow: 1;
    padding: 10px 10px 0 0; /* remove bottom padding to snug divider */
    margin-right: -10px;
    scrollbar-width: thin;
    scrollbar-color: #555 #111;
}

#audioInfoModal .modal-scrollable-content {
    overflow-y: auto;
    flex-grow: 1;
    padding: 10px 10px 0 0; /* remove bottom padding to snug divider */
    margin-right: -10px;
    scrollbar-width: thin;
    scrollbar-color: #555 #111;
}

#explanationModal .modal-scrollable-content {
    overflow-y: auto;
    flex-grow: 1;
    padding: 10px 10px 6px 0; /* reduce bottom padding to tighten bottom spacing */
    margin-right: -10px;
    scrollbar-width: thin;
    scrollbar-color: #555 #111;
}

#settingsModal .modal-scrollable-content::-webkit-scrollbar {
    width: 8px;
}
#settingsModal .modal-scrollable-content::-webkit-scrollbar-track {
    background: #111;
    border-radius: 10px;
}
#settingsModal .modal-scrollable-content::-webkit-scrollbar-thumb {
    background: #444;
    border-radius: 10px;
}
#settingsModal .modal-scrollable-content::-webkit-scrollbar-thumb:hover {
    background: #666;
}

#audioInfoModal .modal-scrollable-content::-webkit-scrollbar {
    width: 8px;
}
#audioInfoModal .modal-scrollable-content::-webkit-scrollbar-track {
    background: #111;
    border-radius: 10px;
}
#audioInfoModal .modal-scrollable-content::-webkit-scrollbar-thumb {
    background: #444;
    border-radius: 10px;
}
#audioInfoModal .modal-scrollable-content::-webkit-scrollbar-thumb:hover {
    background: #666;
}

#explanationModal .modal-scrollable-content::-webkit-scrollbar {
    width: 8px;
}
#explanationModal .modal-scrollable-content::-webkit-scrollbar-track {
    background: #111;
    border-radius: 10px;
}
#explanationModal .modal-scrollable-content::-webkit-scrollbar-thumb {
    background: #444;
    border-radius: 10px;
}
#explanationModal .modal-scrollable-content::-webkit-scrollbar-thumb:hover {
    background: #666;
}

/* Description Modal Styles */
#descriptionModal .modal-scrollable-content {
    overflow-y: auto;
    flex-grow: 1;
    padding: 10px 10px 12px 0;
    margin-right: -10px;
    scrollbar-width: thin;
    scrollbar-color: #555 #111;
}
#descriptionModal .modal-scrollable-content::-webkit-scrollbar {
    width: 8px;
}
#descriptionModal .modal-scrollable-content::-webkit-scrollbar-track {
    background: #111;
    border-radius: 10px;
}
#descriptionModal .modal-scrollable-content::-webkit-scrollbar-thumb {
    background: #444;
    border-radius: 10px;
}
#descriptionModal .modal-scrollable-content::-webkit-scrollbar-thumb:hover {
    background: #666;
}

.description-modal-text {
    font-size: 0.95rem;
    line-height: 1.6;
    color: #e8e8e8;
    text-align: justify;
    text-justify: inter-word;
    word-wrap: break-word;
    word-spacing: 0.03em;
    letter-spacing: 0.008em;
    white-space: pre-wrap;
    background: #000;
    margin-bottom: 5px;
    border: 1px solid #333;
    border-radius: 8px;
    padding: 25px;
    margin-top: 15px;
    hyphens: auto;
    -webkit-hyphens: auto;
    -moz-hyphens: auto;
    font-weight: 400;
    font-family: 'Montserrat', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
    text-rendering: optimizeLegibility;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-size-adjust: 100%;
    -webkit-text-size-adjust: 100%;
    /* Advanced text spacing controls for perfect justification */
    word-break: normal;
    overflow-wrap: break-word;
    hanging-punctuation: first last;
    text-wrap: pretty;
    text-balance: stable;
    /* Smart justification with minimal gaps */
    text-justify-trim: punctuation;
    text-spacing-trim: space-first;
    /* Prevent orphaned words and improve flow */
    orphans: 2;
    widows: 2;
    /* Enhanced readability */
    font-variant-ligatures: common-ligatures discretionary-ligatures;
    font-feature-settings: "kern" 1, "liga" 1, "clig" 1;
}

/* Improve paragraph spacing within description */
.description-modal-text p {
    margin: 0 0 1.2em 0;
    text-indent: 0;
}

.description-modal-text p:last-child {
    margin-bottom: 0;
}


/* Better handling for long words and URLs */
.description-modal-text a,
.description-modal-text code {
    word-break: break-all;
    hyphens: none;
}

#descriptionModal h3 {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 15px;
    color: #ffffff;
}

#descriptionModal h3 i {
    font-size: 1.2em;
    color: #ccc;
}

#explanationModal .jbtn-modal-content {
    max-width: 550px;
    width: 100%;
    padding: 20px 24px 12px; /* reduce overall and bottom padding */
    max-height: 80vh;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    margin: auto;
    text-align: center;
}

.jbtn-modal-close {
    position: fixed;
    top: calc(var(--top-navbar-height) + 10px);
    right: 10px;
    font-size: 1.6em;
    line-height: 1;
    background: #000;
    border: 1px solid rgba(255, 255, 255, 0.3);
    color: #ccc;
    border-radius: 6px;
    width: 36px;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    padding: 0;
    margin: 0;
    transition: border-color 0.2s ease, transform 0.2s ease;
    z-index: 1002;
    text-align: center;
    vertical-align: middle;
    box-sizing: border-box;
    font-family: inherit;
    font-weight: normal;
}

.jbtn-modal-close:hover {
    background: #000;
    color: #fff;
    border-color: rgba(255, 255, 255, 0.9);
    transform: scale(1.05);
}

.jbtn-modal-content h3 {
    margin-top: 0;
    margin-bottom: 20px;
    font-size: 1.4em;
    color: #FFFFFF;
    border-bottom: 1px solid rgba(255, 255, 255, 0.3);
    padding-bottom: 10px;
    text-transform: uppercase;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.5em;
}

#explanationModal h3 {
  margin-bottom: 10px;
}

.explanation-modal-description {
    font-size: 0.9em;
    color: #b0b0b0;
    margin: 0 auto 25px;
    line-height: 1.4;
    max-width: 90%;
}

.explanation-options-container {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 15px;
    margin-bottom: 0;
}

.explanation-option-button {
    background: #000000;
    border: 1px solid rgba(255, 255, 255, 0.3);
    color: #ccc;
    padding: 12px;
    border-radius: 8px;
    text-decoration: none;
    font-size: 0.9em;
    font-weight: 600;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 8px;
    transition: all 0.2s ease;
    text-align: center;
    cursor: pointer;
    font-family: 'Montserrat', sans-serif;
    width: 100%;
    height: 100%;
    min-height: 80px;
    box-sizing: border-box;
}

.explanation-option-button i {
    font-size: 1.8em;
    margin-bottom: 5px;
}

.explanation-option-button.active {
   border-color: rgba(255, 255, 255, 0.9);
   color: #fff;
}

.explanation-option-button.active:hover {
    transform: scale(1.03);
    border-color: #fff;
    background-color: #000;
}

.explanation-option-button.inactive {
    opacity: 0.5;
    cursor: not-allowed;
    pointer-events: auto;
}

.explanation-option-button.inactive:hover {
    transform: none;
    background-color: #000000;
    border-color: rgba(255, 255, 255, 0.3);
}

.explanation-section {
    background-color: #000;
    border: 1px solid #333;
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 15px;
}
/* Tighten the bottom of the modal by removing the last section's margin */
#explanationModal .explanation-section:last-of-type {
    margin-bottom: 0;
}

.explanation-section-header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 10px;
}

.explanation-section-header i { font-size: 1.2em; }

.explanation-section-header h4 {
    margin: 0;
    font-size: 1.1rem;
    font-weight: 600;
}

.explanation-section-description {
    font-size: 0.85em;
    color: #999;
    margin: 8px 0 15px 0;
    line-height: 1.4;
    text-align: left;
}

@media (max-width: 768px) {
    #explanationModal .jbtn-modal-content {
        max-width: 550px;
        width: 100%;
        margin: 5vh auto;
        max-height: 80vh;
        overflow: hidden;
    }

    .jbtn-modal-content h3 {
        font-size: 1.2em;
        margin-bottom: 15px;
    }

    .explanation-modal-description {
        font-size: 0.85em;
        margin-bottom: 20px;
        max-width: 95%;
    }

    .explanation-options-container {
        gap: 12px;
    }

    .explanation-option-button {
        padding: 14px 12px;
        font-size: 0.85em;
    }

    .explanation-option-button i {
        font-size: 1.6em;
    }
}

@media (max-width: 600px) {
    #explanationModal .jbtn-modal-content {
        width: 100%;
        height: auto;
        max-height: 85vh;
        margin: 7.5vh auto;
        border-radius: 12px;
    }

    .jbtn-modal-close {
        top: calc(var(--top-navbar-height) + 8px);
        right: 8px;
        width: 32px;
        height: 32px;
        font-size: 1.4em;
        border-radius: 6px;
        display: flex;
        align-items: center;
        justify-content: center;
        line-height: 1;
    }
}

@media (max-width: 480px) {
    .jbtn-modal-close {
        top: calc(var(--top-navbar-height) + 6px);
        right: 6px;
        width: 30px;
        height: 30px;
        font-size: 1.3em;
    }

    .footer-modal-close {
        top: calc(var(--top-navbar-height) + 6px);
        right: 10px;
        width: 30px;
        height: 30px;
        font-size: 1.3em;
    }

    .custom-dropdown-close {
        top: calc(var(--top-navbar-height) + 6px);
        right: 6px;
        width: 30px;
        height: 30px;
        font-size: 1.3em;
    }
}

@media (max-width: 360px) {
    .jbtn-modal-close {
        top: calc(var(--top-navbar-height) + 5px);
        right: 5px;
        width: 28px;
        height: 28px;
        font-size: 1.2em;
    }

    .footer-modal-close {
        top: calc(var(--top-navbar-height) + 5px);
        right: 8px;
        width: 28px;
        height: 28px;
        font-size: 1.2em;
    }

    .custom-dropdown-close {
        top: calc(var(--top-navbar-height) + 5px);
        right: 5px;
        width: 28px;
        height: 28px;
        font-size: 1.2em;
    }

    .jbtn-modal-content h3 {
        font-size: 1.1em;
        margin-bottom: 12px;
        padding-bottom: 8px;
        gap: 0.4em;
    }

    .explanation-modal-description {
        font-size: 0.8em;
        margin-bottom: 18px;
        line-height: 1.5;
        max-width: 100%;
    }

    .explanation-options-container {
        grid-template-columns: 1fr;
        gap: 8px;
        margin-bottom: 0;
    }

    .explanation-option-button {
        padding: 12px 15px;
        flex-direction: row;
        justify-content: flex-start;
        text-align: left;
        font-size: 0.8em;
        min-height: 48px;
        border-radius: 6px;
    }

.explanation-option-button i {
    margin-bottom: 0;
    margin-right: 12px;
    font-size: 1.4em;
    flex-shrink: 0;
}
}

.settings-header {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 20px;
    color: #FFFFFF;
    border-bottom: 1px solid rgba(255, 255, 255, 0.3);
    padding-bottom: 15px;
    text-align: center;
}

.settings-header-icon {
    font-size: 1.6em;
    margin-right: 12px;
    vertical-align: middle; /* keep icon level with heading */
}

.settings-header h2 {
    margin: 0;
    font-size: 1.6rem;
    font-weight: 600;
}

.settings-subtitle {
    text-align: center;
    margin-top: -10px;
    margin-bottom: 25px;
    font-size: 0.9em;
    color: #B0B0B0;
}

.settings-section-new {
    background-color: #000;
    border: 1px solid #333;
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 15px;
}

.settings-divider-new {
    border-top: 1px solid #2c2c2c;
    margin: 15px 0;
}

.settings-section-header {
    display: flex;
    /* Baseline alignment keeps icon/text aligned even with different font metrics */
    align-items: baseline;
    gap: 6px; /* place icon closer to title */
    margin-bottom: 2px; /* tighter spacing between title and description */
    padding-bottom: 0;
    border-bottom: none;
}

.settings-section-header i {
    /* Match icon size to heading for consistent vertical centering */
    font-size: 1.25rem;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    /* Ensure the icon box matches the text line box */
    height: 1em;
    width: 1em;
    line-height: 1em;
    vertical-align: middle;
}

.settings-section-header h3 {
    margin: 0;
    font-size: 1.25rem;
    font-weight: 600;
    border-bottom: none;
    text-transform: none;
    /* Align text to the icon's center */
    line-height: 1.25rem;
    display: flex;
    align-items: center;
}

.setting-section-description {
    font-size: 0.9rem;
    color: #B0B0B0;
    margin-top: 0; /* remove default paragraph spacing */
    margin-bottom: 15px;
    line-height: 1.6;
    text-align: left;
}

.setting-option-new {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 5px;
    border-top: 1px solid #2c2c2c;
}

.settings-section-new .setting-option-new:first-of-type {
    border-top: none;
    padding-top: 5px;
}

.setting-option-new span {
    color: var(--text-primary);
    font-size: 0.95rem;
}

.switch {
  position: relative;
  display: inline-block;
  width: 50px;
  height: 28px;
  flex-shrink: 0;
}

.switch input { opacity: 0; width: 0; height: 0; }

/* Add hover effect to highlight toggle outline */
.switch:hover .slider {
    border-color: #fff;
    box-shadow: none;
}
.switch:hover input:not(:checked) + .slider:before {
    background-color: #fff;
}
.switch:hover input:checked + .slider:before {
    background-color: #000;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: transparent;
  border: 1px solid #888;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 20px;
  width: 20px;
  left: 3px;
  bottom: 3px;
  background-color: #888;
  transition: .4s;
}

input:checked + .slider {
  background-color: #fff;
  border-color: #fff;
}

input:checked + .slider:before {
  background-color: #000;
  transform: translateX(22px);
}

.slider.round { border-radius: 34px; }
.slider.round:before { border-radius: 50%; }

.modal-actions-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
    gap: 15px;
    margin-top: 0;
    padding: 12px 0 5px 0; /* default; overridden per modal for full-bleed */
    border-top: 1px solid rgba(255, 255, 255, 0.2);
    flex-shrink: 0;
}

/* Reuse modal action styles for dropdowns */
.custom-dropdown-actions {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
    gap: 15px;
    margin-top: 0;
    padding: 20px 30px 5px 30px; /* full-bleed divider spacing */
    margin-left: -30px;          /* extend divider to container edges */
    margin-right: -30px;
    border-top: 1px solid rgba(255, 255, 255, 0.2);
    background: #000000;
    flex-shrink: 0;
}

/* Sort dropdown specific spacing adjustments */
.custom-dropdown-container.sort-dropdown .custom-dropdown-content {
    padding: 0 10px 0 0; /* mirror og-item-finder compact content */
    position: relative;
    z-index: 0;
}
/* Remove container bottom padding so action bar doesn't float with extra gap */
.custom-dropdown-container.sort-dropdown { padding-bottom: 12px; }

.custom-dropdown-container.sort-dropdown .custom-dropdown-actions {
    padding: 20px 30px 12px 30px; /* add cushion to match Settings/Music */
    margin: 0 -30px;              /* full-bleed divider */
    background: #000000;
    border-top: 1px solid rgba(255,255,255,0.2);
}

/* Header spacing inside scrollable content for sort dropdown - match settings menu exactly */
.custom-dropdown-container.sort-dropdown .settings-header {
    margin: 0 0 12px 0; /* tighter spacing */
    padding: 0 0 12px 0; /* room for pseudo divider */
    text-align: center;
    border-bottom: none; /* use centered divider */
    position: relative;
}
.custom-dropdown-container.sort-dropdown .settings-header::after {
    content: '';
    position: absolute;
    left: 0; right: 0; bottom: 0;
    width: auto;
    height: 1px;
    background: rgba(255,255,255,0.3);
    border-radius: 1px;
}
/* Proper subtitle spacing under header divider (mirrors og-item-finder) */
.custom-dropdown-container.sort-dropdown .settings-subtitle,
.custom-dropdown-container.filter-dropdown .settings-subtitle {
    margin-top: 6px;
    margin-bottom: 14px;
    padding: 0 12px;
}

/* Filter dropdown specific spacing adjustments - same as sort */
.custom-dropdown-container.filter-dropdown .custom-dropdown-content {
    padding: 0 10px 0 0; /* mirror og-item-finder */
    position: relative;
    z-index: 0;
}
.custom-dropdown-container.filter-dropdown { padding-bottom: 12px; }
/* Spacing above action divider (mirror og-item-finder)
   - Sort: a bit more space above the divider
   - Filter: slightly tighter */
.custom-dropdown-container.sort-dropdown .custom-dropdown-content > .custom-dropdown-group:last-of-type {
    margin-bottom: 15px;
}
.custom-dropdown-container.filter-dropdown .custom-dropdown-content > .custom-dropdown-group:last-of-type {
    margin-bottom: 15px; /* match Sort Options spacing above divider */
}

.custom-dropdown-container.filter-dropdown .custom-dropdown-actions {
    padding: 20px 30px 12px 30px; /* add cushion to match Settings/Music */
    margin: 0 -30px;              /* full-bleed divider */
    background: #000000;
    border-top: 1px solid rgba(255,255,255,0.2);
}

/* Header spacing inside scrollable content for filter dropdown - match settings menu exactly */
.custom-dropdown-container.filter-dropdown .settings-header {
    margin: 0 0 12px 0;
    padding: 0 0 12px 0;
    text-align: center;
    border-bottom: none;
    position: relative;
}
.custom-dropdown-container.filter-dropdown .settings-header::after {
    content: '';
    position: absolute;
    left: 0; right: 0; bottom: 0;
    width: auto;
    height: 1px;
    background: rgba(255,255,255,0.3);
    border-radius: 1px;
}

/* Ensure settings modal and music player headers match dropdown headers exactly */
#settingsModal .settings-header,
#audioInfoModal .settings-header,
#explanationModal .settings-header,
#descriptionModal .settings-header {
    margin: 0 0 12px 0;
    padding: 0 0 12px 0;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #FFFFFF;
    border-bottom: 1px solid rgba(255, 255, 255, 0.3);
    text-align: center;
}
/* Modal subtitles: comfortable spacing and horizontal padding */
#settingsModal .settings-subtitle,
#audioInfoModal .settings-subtitle,
#explanationModal .settings-subtitle,
#descriptionModal .settings-subtitle {
    margin-top: 6px;
    margin-bottom: 20px; /* match og-item-finder comfort spacing */
    padding: 0 12px;
    line-height: 1.4;
}

/* Ensure scrollable content aligns with full-bleed dividers on sides */
#settingsModal .modal-scrollable-content,
#audioInfoModal .modal-scrollable-content,
#explanationModal .modal-scrollable-content,
#descriptionModal .modal-scrollable-content {
    box-sizing: border-box; /* keep earlier per-modal paddings intact */
}

/* Fine-tune settings sections spacing to mirror og */
#settingsModal .settings-section-new:first-of-type { margin-top: 0; }
#settingsModal .settings-section-new:last-of-type { margin-bottom: 15px; }
#settingsModal .setting-section-description { margin: 6px 0 12px; line-height: 1.4; color: #C0C0C0; }

/* Full-bleed action divider for settings/music/explanation modals */
/* Full-bleed action divider for settings/music/explanation modals */
#settingsModal .modal-actions-grid,
#audioInfoModal .modal-actions-grid,
#explanationModal .modal-actions-grid,
#descriptionModal .modal-actions-grid {
    padding: 20px 30px 12px 30px; /* give comfortable bottom cushion */
    margin: 0 -30px;              /* full-bleed divider */
    border-top: 1px solid rgba(255,255,255,0.2);
    background: #000000;
    gap: 15px;                    /* consistent gaps between buttons */
    /* no sticky for modals; let content padding control spacing from bottom */
}

#settingsModal .settings-header-icon,
#audioInfoModal .settings-header-icon,
#explanationModal .settings-header-icon,
#descriptionModal .settings-header-icon {
    font-size: 1.6em;
    margin-right: 12px;
    vertical-align: middle;
}

#settingsModal .settings-header h2,
#audioInfoModal .settings-header h2,
#explanationModal .settings-header h2,
#descriptionModal .settings-header h2 {
    margin: 0;
    font-size: 1.6rem;
    font-weight: 600;
}

#audioInfoModal .modal-actions-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
    gap: 15px;
}

.modal-actions-grid .modal-btn {
    background-color: #000;
    color: #ccc;
    border: 1px solid #333;
    transition: all 0.2s ease;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    border-radius: 6px;
    cursor: pointer;
    width: 100%;
    justify-content: center;
    font-size: 1em;
    font-weight: 600;
    padding: 12px;
    text-decoration: none;
    white-space: normal;
    text-align: center;
    min-width: 0;
    word-break: break-word;
}

#audioInfoModal .modal-actions-grid .modal-btn {
    width: 100%;
}

.modal-actions-grid .modal-btn:hover {
    border-color: #fff;
    color: #fff;
}
@media (max-width: 600px) {
    .modal-actions-grid {
        grid-template-columns: 1fr;
    }
    .custom-dropdown-actions {
        grid-template-columns: 1fr;
    }
    .modal-actions-grid .modal-btn {
        font-size: 0.9em;
        padding: 14px;
    }
}



/* --- End Settings Modal Styles --- */

/* --- Helper classes for settings --- */
body.settings-hide-explanation .value-explanation-container {
    display: none;
}
body.settings-hide-timestamp .update-timestamp {
    display: none;
}
body.settings-disable-glow .value-bubble:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
    border-color: rgba(255,255,255,0.2);
}
body.settings-hide-header #pageHeader {
    display: none;
}
body.settings-hide-header .top-navbar {
    background-color: rgba(0, 0, 0, 0.95);
    backdrop-filter: blur(10px);
    /* Match scrolled underline color for hidden-header mode */
    border-bottom: 1px solid var(--navbar-border-scrolled);
}
body.settings-hide-header .top-navbar .navbar-brand,
body.settings-hide-header .top-navbar .navbar-brand-text,
body.settings-hide-header .top-navbar .navbar-links-desktop > a,
body.settings-hide-header .top-navbar .navbar-links-desktop > .navbar-dropdown > .navbar-dropdown-toggle {
    color: var(--navbar-text-scrolled);
}
body.settings-hide-header .top-navbar .navbar-mobile-toggle,
body.settings-hide-header .top-navbar .navbar-dropdown > .navbar-dropdown-toggle i,
body.settings-hide-header .top-navbar .controls .input-icon {
    color: var(--navbar-icon-scrolled);
}
body.settings-hide-header .top-navbar .controls input[type="text"],
body.settings-hide-header .top-navbar .controls select,
body.settings-hide-header .top-navbar .controls .nav-input-style {
    color: var(--navbar-text-scrolled);
    border-color: var(--navbar-border-scrolled);
}
body.settings-hide-header .top-navbar .hamburger-inner,
body.settings-hide-header .top-navbar .hamburger-inner::before,
body.settings-hide-header .top-navbar .hamburger-inner::after {
    background-color: var(--navbar-icon-scrolled);
}
body.settings-hide-footer .main-app-footer {
    display: none;
}
body.settings-hide-status-badges .status-label {
    display: none;
}
/* --- End Helper classes --- */

/* === Improved Sort/Filter Scaling === */
/* Now handled by unified navigation styling above */

/* Removed old sort/filter select media queries - handled by unified styles */


/* Ensure audio player keeps appropriate width in all layouts */
.search-sort .nav-audio-player {
    width: auto !important;
    min-width: 100px !important;
    flex: 0 0 auto !important;
    height: 36px !important;
    box-sizing: border-box !important;
    padding: 0 8px !important;
    cursor: pointer !important;
}

/* Audio player icon-only sizing */
@media (max-width: 1079px) {
    .search-sort .nav-audio-player {
        width: 36px !important;
        min-width: 36px !important;
        padding: 0 !important;
    }
}

/* Prevent wrapping on menu buttons on larger screens */
@media (min-width: 1080px) {
  .search-sort #navAudioInfo,
  .search-sort #LISortButton,
  .search-sort #LIFilterButton {
      white-space: nowrap;
      min-width: 110px;
      max-width: none;
  }
}

/* Allow search input to size based on its text on larger screens */
@media (min-width: 769px) {
  .search-sort .input-icon-wrapper[data-nav-priority="1"] {
    max-width: none !important;
  }

  .search-sort .nav-item input[type="text"] {
    width: fit-content !important;
  }
}

/* --- Final Nav Outline Overrides (ensure consistency) --- */
.search-sort .input-icon-wrapper.disabled,
.search-sort .input-icon-wrapper:has(*:disabled) {
  border-color: rgba(255,255,255,0.2) !important;
  outline: none !important;
}
/* Beat focus-within/press/JS states when disabled */
.search-sort .input-icon-wrapper.disabled:focus-within,
.search-sort .input-icon-wrapper.disabled.pressing,
.search-sort .input-icon-wrapper.disabled.is-hover,
.search-sort .input-icon-wrapper.disabled.is-focus,
.search-sort .input-icon-wrapper.disabled.is-active,
.search-sort .input-icon-wrapper:has(*:disabled):focus-within,
.search-sort .input-icon-wrapper:has(*:disabled).pressing,
.search-sort .input-icon-wrapper:has(*:disabled).is-hover,
.search-sort .input-icon-wrapper:has(*:disabled).is-focus,
.search-sort .input-icon-wrapper:has(*:disabled).is-active {
  border-color: rgba(255,255,255,0.2) !important;
  outline: none !important;
  transform: none !important;
  box-shadow: none !important;
}
.search-sort .input-icon-wrapper.disabled:hover,
.search-sort .input-icon-wrapper:has(*:disabled):hover {
  border-color: rgba(255,255,255,0.2) !important;
  outline: none !important;
  transform: none !important;
  box-shadow: none !important;
}
.search-sort .input-icon-wrapper:not(.disabled):hover {
  border-color: rgba(255,255,255,0.8) !important;
}
.search-sort .input-icon-wrapper:not(.disabled):focus-within,
.search-sort .input-icon-wrapper:not(.disabled).pressing {
  border-color: rgba(255,255,255,0.85) !important;
  outline: 1px solid #1a73e8 !important;
  outline-offset: 0 !important;
}
/* Show focus outlines only for keyboard interactions (match control buttons UX) */
body.using-mouse .search-sort .input-icon-wrapper:focus-within,
body.using-mouse .search-sort .input-icon-wrapper.pressing,
body.using-mouse .search-sort .input-icon-wrapper.is-focus {
  /* Suppress blue ring and white border when using mouse */
  outline: none !important;
  border-color: rgba(255,255,255,0.2) !important;
}
body.using-mouse .search-sort .input-icon-wrapper:hover {
  /* Keep hover feedback with mouse */
  border-color: rgba(255,255,255,0.8) !important;
}
/* Body-level disabled state: keep grey base, no hover brighten */
body.controls-disabled .search-sort .input-icon-wrapper {
  border-color: rgba(255,255,255,0.2) !important;
  outline: none !important;
}
body.controls-disabled .search-sort .input-icon-wrapper:hover,
body.controls-disabled .search-sort .input-icon-wrapper.is-hover {
  border-color: rgba(255,255,255,0.2) !important;
  outline: none !important;
  transform: none !important;
  box-shadow: none !important;
}
body.controls-disabled .search-sort .input-icon-wrapper:focus-within,
body.controls-disabled .search-sort .input-icon-wrapper.pressing,
body.controls-disabled .search-sort .input-icon-wrapper.is-focus,
body.controls-disabled .search-sort .input-icon-wrapper.is-active {
  border-color: rgba(255,255,255,0.2) !important;
  outline: none !important;
  transform: none !important;
  box-shadow: none !important;
}
body.controls-disabled #LISortButton.nav-input-style,
body.controls-disabled #LIFilterButton.nav-input-style,
body.controls-disabled #LISortButton.nav-input-style:hover,
body.controls-disabled #LIFilterButton.nav-input-style:hover {
  outline: none !important;
}
/* JS-backed states to avoid relying on :has() support */
.search-sort .input-icon-wrapper.is-hover:not(.disabled) {
  border-color: rgba(255,255,255,0.8) !important;
}
.search-sort .input-icon-wrapper.is-focus:not(.disabled),
.search-sort .input-icon-wrapper.is-active:not(.disabled) {
  border-color: rgba(255,255,255,0.85) !important;
  outline: 1px solid #1a73e8 !important;
  outline-offset: 0 !important;
}
.search-sort .input-icon-wrapper.disabled.is-hover,
.search-sort .input-icon-wrapper.disabled.is-focus,
.search-sort .input-icon-wrapper.disabled.is-active {
  border-color: rgba(255,255,255,0.2) !important;
  outline: none !important;
}

/* === Value Dynamics-style Outlines for Search/Sort/Filter (final overrides) === */
/* Hover: subtle lift + brighter border */
.search-sort .input-icon-wrapper[data-nav-priority="1"]:hover,
.search-sort .input-icon-wrapper[data-nav-priority="2"]:hover,
.search-sort .input-icon-wrapper[data-nav-priority="3"]:hover {
  border-color: rgba(255,255,255,0.8) !important;
  transform: translateY(-2px) !important;
}
/* Focus/press: white border closest to control + blue outer ring (mirror Value Dynamics) */
.search-sort .input-icon-wrapper[data-nav-priority="1"]:focus-within,
.search-sort .input-icon-wrapper[data-nav-priority="1"].pressing,
body.using-mouse .search-sort .input-icon-wrapper[data-nav-priority="1"]:focus-within,
.search-sort .input-icon-wrapper[data-nav-priority="2"]:focus-within,
.search-sort .input-icon-wrapper[data-nav-priority="2"].pressing,
body.using-mouse .search-sort .input-icon-wrapper[data-nav-priority="2"]:focus-within,
.search-sort .input-icon-wrapper[data-nav-priority="3"]:focus-within,
.search-sort .input-icon-wrapper[data-nav-priority="3"].pressing,
body.using-mouse .search-sort .input-icon-wrapper[data-nav-priority="3"]:focus-within {
  border-color: rgba(255, 255, 255, 0.85) !important; /* white inner border */
  outline: 1px solid #1a73e8 !important;              /* blue outer ring */
  outline-offset: 0 !important;
}
/* Disabled states: no lift, no blue outline */
.search-sort .input-icon-wrapper[data-nav-priority="1"].disabled,
.search-sort .input-icon-wrapper[data-nav-priority="2"].disabled,
.search-sort .input-icon-wrapper[data-nav-priority="3"].disabled,
.search-sort .input-icon-wrapper[data-nav-priority="1"]:has(*:disabled),
.search-sort .input-icon-wrapper[data-nav-priority="2"]:has(*:disabled),
.search-sort .input-icon-wrapper[data-nav-priority="3"]:has(*:disabled) {
  border-color: rgba(255,255,255,0.2) !important;
  outline: none !important;
  box-shadow: none !important;
  transform: none !important;
}
.search-sort .input-icon-wrapper[data-nav-priority="1"].disabled:hover,
.search-sort .input-icon-wrapper[data-nav-priority="2"].disabled:hover,
.search-sort .input-icon-wrapper[data-nav-priority="3"].disabled:hover,
.search-sort .input-icon-wrapper[data-nav-priority="1"]:has(*:disabled):hover,
.search-sort .input-icon-wrapper[data-nav-priority="2"]:has(*:disabled):hover,
.search-sort .input-icon-wrapper[data-nav-priority="3"]:has(*:disabled):hover {
  border-color: rgba(255,255,255,0.2) !important;
  transform: none !important;
}

/* Control buttons press-hold outline to mirror wrappers, but only while inside */
#LIResetButton.pressing,
#navAudioInfo.pressing,
#LISettingsButton.pressing {
  border-color: rgba(255, 255, 255, 0.85) !important; /* white inner */
  outline: 1px solid #1a73e8 !important;              /* blue outer */
  outline-offset: 0 !important;
}
#LIResetButton:not(.pressing):focus,
#navAudioInfo:not(.pressing):focus,
#LISettingsButton:not(.pressing):focus {
  /* Avoid keeping focus outline on mouse click; keyboard users still get :focus-visible via browser */
  outline: none !important;
  box-shadow: none !important;
  border-color: rgba(255,255,255,0.2) !important;
}
#LIResetButton:not(.pressing):focus-visible,
#navAudioInfo:not(.pressing):focus-visible,
#LISettingsButton:not(.pressing):focus-visible {
  outline: none !important;
  box-shadow: none !important;
  border-color: rgba(255,255,255,0.2) !important;
}

/* Show white-only outline on hover (not pressed) for control buttons */
#LIResetButton:not(:disabled):hover:not(.pressing),
#navAudioInfo:not(:disabled):hover:not(.pressing),
#LISettingsButton:not(:disabled):hover:not(.pressing) {
  border-color: rgba(255, 255, 255, 0.85) !important; /* white border */
  outline: none !important;                            /* no blue ring on hover */
}
/* Ensure press state wins over hover so blue ring shows while holding */
#LIResetButton.pressing,
#LIResetButton.pressing:hover,
#navAudioInfo.pressing,
#navAudioInfo.pressing:hover,
#LISettingsButton.pressing,
#LISettingsButton.pressing:hover {
  border-color: rgba(255, 255, 255, 0.85) !important;
  outline: 1px solid #1a73e8 !important;
  outline-offset: 0 !important;
}

/* When disabled or during controls-disabled, suppress hover outlines on control buttons */
#LIResetButton:disabled,
#LIResetButton.disabled,
#navAudioInfo:disabled,
#navAudioInfo.disabled,
#LISettingsButton:disabled,
#LISettingsButton.disabled {
  pointer-events: none !important;
  outline: none !important;
  box-shadow: none !important;
  border-color: rgba(255,255,255,0.2) !important;
  transform: none !important;
}
#LIResetButton:disabled *,
#LIResetButton.disabled *,
#navAudioInfo:disabled *,
#navAudioInfo.disabled *,
#LISettingsButton:disabled *,
#LISettingsButton.disabled * {
  pointer-events: none !important;
}
#LIResetButton:disabled:hover,
#navAudioInfo:disabled:hover,
#LISettingsButton:disabled:hover,
body.controls-disabled #LIResetButton:hover,
body.controls-disabled #navAudioInfo:hover,
body.controls-disabled #LISettingsButton:hover {
  outline: none !important;
  border-color: rgba(255,255,255,0.2) !important;
  transform: none !important;
}
/* Never show press outline for disabled buttons */
#LIResetButton:disabled.pressing,
#navAudioInfo:disabled.pressing,
#LISettingsButton:disabled.pressing {
  outline: none !important;
  border-color: rgba(255,255,255,0.2) !important;
}

</style>
</head>
<body data-jbtn-spacing="manual">
<nav class="top-navbar" id="topNavbar">
<div class="navbar-container">
    <a href="/home.html" class="navbar-brand">
        <img src="https://blogger.googleusercontent.com/img/a/AVvXsEgNoZt3SENLS8hdeYEL4pH4qibyjZBKinJ1BLFrvX02gUhHFf2NlVSTTdCdFjVR_vofxvcs8-82Y7i1cjnioqvlhaR9UEWxjJ_N1HbnNoAZJHOcsW7w6-aBykVrqIh6i7_sxRmhOn9Q-zbKY8Xhcs2J5Jv0kflsWG6RxgQlcN2IZwZ3R0Db5H3LK4lEoqxA" alt="Jailbreak Trading Network Logo" class="navbar-logo">
        <span class="navbar-brand-text">Jailbreak Trading Network</span>
    </a>
    <div class="navbar-links-desktop" id="navbarLinksDesktop">
    </div>
    <div class="navbar-right-side">
        <button class="navbar-mobile-toggle" aria-label="Toggle menu" aria-expanded="false">
            <span class="hamburger-box">
                <span class="hamburger-inner"></span>
            </span>
        </button>
    </div>
</div>
<div class="navbar-mobile-menu" id="mobileMenu" aria-hidden="true">
    <div class="navbar-mobile-menu-overlay"></div>
    <div class="navbar-links-mobile" id="navbarLinksMobile">
    </div>
</div>
</nav>

<main>
<header id="pageHeader">
<div class="header-content-wrapper">
  <div class="header-title-container">
    <h1><span class="underline">All</span> Values</h1>
    <h2 data-value-type="All Values" style="display: none;">All Values</h2>
  </div>
  <div class="header-social-icons">
    <a href="https://www.roblox.com/communities/14854862" target="_blank" title="Jailbreak Trading Network on Roblox">
      <span>
        <img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj-coUV8k0Ph432sn55NyeVr9O_CKulNZ0XT_FVVI47SGQg4hCp8SzrwkPcvAnqn5AonLUQGzJxmjpPxEu9Ie0mB0fmCMIHx2PnzI5eJ7bBRgba-aKzq9nw-_AfvH14cgpUwEL0PkjN5LtkoLlL4vvXUgvXFxCvgBTr5dsXc5pKxfO0cEWkFNg22SMuVZlJ/s96/Roblox%20Logo%204.png" alt="Jailbreak Trading Network on Roblox">
      </span>
    </a>
    <a href="https://discord.jailbreaktradingnetwork.com" target="_blank" title="Join our Discord Community">
      <span>
        <img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiGkEw8Iz54k707PpygHYa0kKjeLGFEt18dlBSl08qvevBPfc1xov0Zdo7u__PDjkGNFN_qBVkZ3EVlqV2oUXm-RrNvVCgR7ND9llf-XOyrFOZJH7qeqNsks0l9wZ3S1-USpIcctPI2pdgn980vnHSRvVn1Ssk-o7PArHScwr1s9eFDKwAbQCNPQFGfOEGN/s96/Discord%20Logo.png" alt="Jailbreak Trading Network Discord Server">
      </span>
    </a>
    <a href="https://www.youtube.com/@JailbreakTradingNetwork" target="_blank" title="Our YouTube Channel">
      <span>
        <img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhBOIKwkAhljr81s3dJMDWbTZNGFteo5VB1rOHnlu2MgsEqDZl87tC6xU3PJK0rDw5-QhyIZql8Au2w8-F2oFVDD8x-zrQu-ZbLzCC5qadGWrr-TdFE_5h7GqvMZ0lBxjCGAB4do614E3cdVA9pZaSd-AojMm1rzAqJt6HJ8PbsGY0qkglHaFI8-vB9xyrb/s96/YouTube%20Logo.png" alt="Jailbreak Trading Network on YouTube">
      </span>
    </a>
    <a href="https://x.com/TradingWebsite" target="_blank" title="Follow us on X (Twitter)">
      <span>
        <img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgz79w5IjXhGw5bL3QDYaB2j5KHZUmTtdUwMGtukbuAHCFe3uQZo1s6Ar91u6q9xbfbbM6cAJAfQlXfX8A2cl8E5QQ324h66pogTz44cE8eMLJFlEUX9OwfdIcXTKbtxocrido-UG_K5gP8OPRuNQVj0ywdyNto4JDwf_RotLKMpoQM8SxjluwZRDASB8vh" alt="Jailbreak Trading Network on X (Twitter)">
      </span>
    </a>
    <a href="https://blog.jailbreaktradingnetwork.com/" target="_blank" title="Read our Blog">
      <span>
        <img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh3txXGt-KSa0zKAFEb-8ZyxGZfxQ0eDPKB3z0g4c7Hk4weZ5blaLV5McnM2X-dm3N9CtnonygbXVwgUwZa4tSjq0RqtECr5oZUtWWHNngaZAJv7N3kRvEQ_EGG5gRq7QaVUzBCOm3uLqOEGueB3DToImDDFaF-6QS8_bg2k8CEZerR69DWAlPKIwa2SNb7" alt="Jailbreak Trading Network Blog">
      </span>
    </a>
    <a href="https://appeal.gg/JailbreakTradingNetwork" target="_blank" title="Submit a Ban Appeal">
      <span>
        <img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj9mK-QtMo3SprqRnEBipnXxvNae2rwFRQfiUcI0KiTaPgXTe0Y-8S-w6jyzIAU9ER0W_ldxVrytxnuoDyOvAc7tyOQADOyROFRUGEHNIKk8Uk-aznL85zogOBAwQ8cWMBNSICy0kqJbGnQFaiD8mfO2-M-OTVlAHohOFmcycmBDAKSaY86ovhyphenhyphenJwxDQyOJ/s96/Ban%20Appeals%20Logo.jpg" alt="Ban Appeals for Jailbreak Trading Network">
      </span>
    </a>
  </div>
</div>
</header>

<div id="custom-loading-overlay">
<div id="loading-bubble-container">
    <div class="loading-bubble-logo-panel">
        <img src="https://blogger.googleusercontent.com/img/a/AVvXsEj13AnM5al59nnZUsyUzRFM7l0S33Nki9NOclqKwc0BFw4jRaI7Cgg4IhYWu_qJI0aknvKWGfjxGHSMGSIYTj8g1e5NMezXVU_a76ZwDFKYwslwthfHMjlPPwRSm1-AHPbPk3Ootp9ffHkeE8iWCf7rYFJOu1_-KY_i2jf6j9yHFvmLpIFQB1v_Ma3_PKL6" alt="Loading..." id="loading-gif">
    </div>
    <div class="loading-bubble-divider"></div>
    <div class="loading-bubble-console-panel">
        <p id="loading-message">Initializing...</p>
        <div id="progress-bar-container">
            <div id="progress-bar"></div>
        </div>
        <div id="loading-log-box"></div>
        <p class="loading-refresh-prompt">Experiencing loading issues? Please check our server status or refresh the page.</p>
        <div class="loading-social-icons">
          <a href="https://www.roblox.com/communities/14854862" target="_blank" class="loading-social-item">
            <img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj-coUV8k0Ph432sn55NyeVr9O_CKulNZ0XT_FVVI47SGQg4hCp8SzrwkPcvAnqn5AonLUQGzJxmjpPxEu9Ie0mB0fmCMIHx2PnzI5eJ7bBRgba-aKzq9nw-_AfvH14cgpUwEL0PkjN5LtkoLlL4vvXUgvXFxCvgBTr5dsXc5pKxfO0cEWkFNg22SMuVZlJ/s96/Roblox%20Logo%204.png" alt="Roblox Icon">
            <span class="loading-social-name">Roblox</span>
          </a>
          <a href="https://discord.jailbreaktradingnetwork.com" target="_blank" class="loading-social-item">
            <img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiGkEw8Iz54k707PpygHYa0kKjeLGFEt18dlBSl08qvevBPfc1xov0Zdo7u__PDjkGNFN_qBVkZ3EVlqV2oUXm-RrNvVCgR7ND9llf-XOyrFOZJH7qeqNsks0l9wZ3S1-USpIcctPI2pdgn980vnHSRvVn1Ssk-o7PArHScwr1s9eFDKwAbQCNPQFGfOEGN/s96/Discord%20Logo.png" alt="Discord Icon">
            <span class="loading-social-name">Discord</span>
          </a>
          <a href="https://www.youtube.com/@JailbreakTradingNetwork" target="_blank" class="loading-social-item">
            <img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhBOIKwkAhljr81s3dJMDWbTZNGFteo5VB1rOHnlu2MgsEqDZl87tC6xU3PJK0rDw5-QhyIZql8Au2w8-F2oFVDD8x-zrQu-ZbLzCC5qadGWrr-TdFE_5h7GqvMZ0lBxjCGAB4do614E3cdVA9pZaSd-AojMm1rzAqJt6HJ8PbsGY0qkglHaFI8-vB9xyrb/s96/YouTube%20Logo.png" alt="YouTube Icon">
            <span class="loading-social-name">YouTube</span>
          </a>
          <a href="https://x.com/TradingWebsite" target="_blank" class="loading-social-item">
            <img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgz79w5IjXhGw5bL3QDYaB2j5KHZUmTtdUwMGtukbuAHCFe3uQZo1s6Ar91u6q9xbfbbM6cAJAfQlXfX8A2cl8E5QQ324h66pogTz44cE8eMLJFlEUX9OwfdIcXTKbtxocrido-UG_K5gP8OPRuNQVj0ywdyNto4JDwf_RotLKMpoQM8SxjluwZRDASB8vh" alt="X Icon">
            <span class="loading-social-name">X</span>
          </a>
          <a href="https://blog.jailbreaktradingnetwork.com/" target="_blank" class="loading-social-item">
            <img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh3txXGt-KSa0zKAFEb-8ZyxGZfxQ0eDPKB3z0g4c7Hk4weZ5blaLV5McnM2X-dm3N9CtnonygbXVwgUwZa4tSjq0RqtECr5oZUtWWHNngaZAJv7N3kRvEQ_EGG5gRq7QaVUzBCOm3uLqOEGueB3DToImDDFaF-6QS8_bg2k8CEZerR69DWAlPKIwa2SNb7" alt="Blogger Icon">
            <span class="loading-social-name">Blogger</span>
          </a>
          <a href="https://appeal.gg/JailbreakTradingNetwork" target="_blank" class="loading-social-item">
            <img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj9mK-QtMo3SprqRnEBipnXxvNae2rwFRQfiUcI0KiTaPgXTe0Y-8S-w6jyzIAU9ER0W_ldxVrytxnuoDyOvAc7tyOQADOyROFRUGEHNIKk8Uk-aznL85zogOBAwQ8cWMBNSICy0kqJbGnQFaiD8mfO2-M-OTVlAHohOFmcycmBDAKSaY86ovhyphenhyphenJwxDQyOJ/s96/Ban%20Appeals%20Logo.jpg" alt="Ban Appeals Icon">
            <span class="loading-social-name">Appeals</span>
          </a>
        </div>
        <p id="error-message" style="display:none;"></p>
    </div>
</div>
</div>

<section class="controls" id="LIMenuContainer">
<div class="search-sort">
  <span class="input-icon-wrapper nav-item" data-nav-priority="1">
    <i class="fas fa-search input-icon" aria-hidden="true"></i>
    <input type="text" id="LISearchInput" placeholder="Search for Items" autocomplete="off" />
    <button id="LIClearSearch" class="search-clear" type="button" aria-label="Clear search"><i class="fas fa-times"></i></button>
  </span>
  <span class="input-icon-wrapper nav-item" data-nav-priority="2">
    <i class="fas fa-sort input-icon" aria-hidden="true"></i>
    <button id="LISortButton" class="nav-input-style" type="button"><span class="button-label">Sort Items</span><i class="fas fa-caret-down"></i></button>
  </span>
  <select id="LISortSelect" style="display:none;">
      <optgroup label="Sort by Name" data-description="Arrange items alphabetically.">
        <option value="name-asc">Sort: Name - A-Z</option>
        <option value="name-desc">Sort: Name - Z-A</option>
      </optgroup>
      <optgroup label="Sort by Price" data-description="Order items based on trading or duped value.">
        <option value="price-desc" selected>Sort: Current Value - High to Low</option>
        <option value="price-asc">Sort: Current Value - Low to High</option>
        <option value="duped-price-desc">Sort: Duped Value - High to Low</option>
        <option value="duped-price-asc">Sort: Duped Value - Low to High</option>
      </optgroup>
      <optgroup label="Sort by Demand" data-description="Sort using the demand rating.">
        <option value="demand-desc">Sort: Demand - High to Low</option>
        <option value="demand-asc">Sort: Demand - Low to High</option>
      </optgroup>
      <optgroup label="Sort by Reward Type" data-description="Order by safe tier, price or season reward.">
        <option value="safe-tier-desc">Sort: Safe Tier - High to Low</option>
        <option value="safe-tier-asc">Sort: Safe Tier - Low to High</option>
        <option value="obtainable-price-desc">Sort: Obtainable Price - High to Low</option>
        <option value="obtainable-price-asc">Sort: Obtainable Price - Low to High</option>
        <option value="season-reward-desc">Sort: Season Reward - High to Low</option>
        <option value="season-reward-asc">Sort: Season Reward - Low to High</option>
      </optgroup>
      <optgroup label="Sort by Statistics" data-description="Use distribution or trade count.">
        <option value="copies-desc">Sort: Distribution - High to Low</option>
        <option value="copies-asc">Sort: Distribution - Low to High</option>
        <option value="traded-desc">Sort: Times Traded - High to Low</option>
        <option value="traded-asc">Sort: Times Traded - Low to High</option>
      </optgroup>
      <optgroup label="Sort by Time" data-description="Order by most/least recently updated.">
        <option value="updated-desc">Sort: Latest Updates - Newest First</option>
        <option value="updated-asc">Sort: Latest Updates - Oldest First</option>
      </optgroup>
      <optgroup label="Sort by Special Properties" data-description="Sort by collector rarity and pity chance.">
        <option value="collector-rarity-desc">Sort: Collector Rarity - High to Low</option>
        <option value="collector-rarity-asc">Sort: Collector Rarity - Low to High</option>
        <option value="pity-chance-desc">Sort: Pity Chance - High to Low</option>
        <option value="pity-chance-asc">Sort: Pity Chance - Low to High</option>
      </optgroup>
      <optgroup label="Sort by Vehicle Stats" data-description="Sort by vehicle health, repair time, and top speed.">
        <option value="vehicle-health-desc">Sort: Vehicle Health - High to Low</option>
        <option value="vehicle-health-asc">Sort: Vehicle Health - Low to High</option>
        <option value="repair-time-desc">Sort: Repair Time - High to Low</option>
        <option value="repair-time-asc">Sort: Repair Time - Low to High</option>
        <option value="top-speed-desc">Sort: Top Speed - High to Low</option>
        <option value="top-speed-asc">Sort: Top Speed - Low to High</option>
      </optgroup>
    </select>
  <span class="input-icon-wrapper nav-item" data-nav-priority="3">
    <i class="fas fa-filter input-icon" aria-hidden="true"></i>
    <button id="LIFilterButton" class="nav-input-style" type="button"><span class="button-label">Filter Items</span><i class="fas fa-caret-down"></i></button>
  </span>
  <select id="LIFilterSelect" style="display:none;">
      <optgroup label="Filter by Type" data-description="Show items by how they are obtained.">
        <option value="all-items" selected>Filter: Show All Items</option>
        <option value="limited-only">Filter: Show Limited Items</option>
        <option value="retired-only">Filter: Show Retired Items</option>
        <option value="reference-only">Filter: Show Reference Items</option>
        <option value="obtainable-only">Filter: Show Obtainable Items</option>
        <option value="event-exclusive-only">Filter: Show Event-Exclusive Items</option>
        <option value="vault-exclusive-only">Filter: Show Vault-Exclusive Items</option>
        <option value="pass-exclusive-only">Filter: Show Pass-Exclusive Items</option>
      </optgroup>
      <optgroup label="Filter by Category" id="LICategoryFilterGroup" data-description="Show items from a specific category.">
        <option value="all-values" selected>Filter: Show All Values</option>
        <option value="category-vehicle">Filter: Vehicle Values</option>
        <option value="category-texture">Filter: Texture Values</option>
        <option value="category-color">Filter: Color Values</option>
        <option value="category-spoiler">Filter: Spoiler Values</option>
        <option value="category-rim">Filter: Rim Values</option>
        <option value="category-tire">Filter: Tire Values</option>
        <option value="category-furniture">Filter: Furniture Values</option>
        <option value="category-gun-texture">Filter: Gun Texture Values</option>
        <option value="category-vehicle-horn">Filter: Vehicle Horn Values</option>
        <option value="category-drift-particle">Filter: Drift Particle Values</option>
      </optgroup>
    </select>
  <button id="LIResetButton" class="control-button nav-item">
    <i class="fas fa-undo"></i>
    <span>Reset Options</span>
  </button>
  <button id="navAudioInfo" class="control-button nav-item" data-nav-priority="6">
    <i class="fas fa-music"></i>
    <span>Music Player</span>
  </button>
  <button id="LISettingsButton" class="control-button nav-item">
    <i class="fas fa-cog"></i>
    <span>Settings</span>
  </button>
</div>
</section>
<!-- Community CTA (mirrors OG Item Finder submission box) -->
<div class="discord-submission-info">
<div class="submission-info-content">
  <div class="submission-text">
    <h3>
      <i class="fab fa-discord submission-icon"></i>
      Looking for the Most Active Trading Community?
    </h3>
    <p>Join our community on Discord to trade, chat, and update values: <a href="https://discord.JailbreakTradingNetwork.com/" target="_blank">Jailbreak Trading Network</a></p>
  </div>
</div>
</div>
<div class="items-count hidden" id="ItemsCount" style="display:none" aria-hidden="true"></div>
<section class="value-bubbles-container" id="LIBubblesContainer" style="opacity: 0; transform: translateY(30px); transition: opacity 0.6s ease, transform 0.6s ease;">
</section>
<div class="fullscreen-overlay" id="LIFullscreenOverlay">
  <button class="jbtn-modal-close" id="LIFullscreenClose" type="button">&times;</button>
<img class="fullscreen-image" id="LIFullscreenImage" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==" alt="Fullscreen Image">
<div class="fullscreen-caption" id="LIFullscreenCaption"></div>
</div>
</main>
<footer class="main-app-footer">
<div class="footer-content-wrapper">
    <div class="footer-row">
        <p class="footer-summary-text">
            Jailbreak Trading Network is a fan-run initiative and is not affiliated with Badimo or Roblox Corporation.
        </p>
    </div>
    <div class="footer-row" id="footer-copyright-info-row">
        <p class="footer-copyright-text">
            <span> © <span id="footerYear"></span> Jailbreak Trading Network. All Rights Reserved.</span>
            <span class="footer-link-separator"> </span>
            <a href="#" class="footer-link" data-modal="about">
                <i class="fas fa-info-circle footer-link-icon"></i><span class="footer-link-text">About</span>
            </a>
            <span class="footer-link-separator"> </span>
            <a href="mailto:contact@JailbreakTradingNetwork.com" class="footer-link" target="_blank" rel="noopener noreferrer">
                <i class="fas fa-envelope footer-link-icon"></i><span class="footer-link-text">Contact Us</span>
            </a>
            <span class="footer-link-separator"> </span>
            <a href="/terms-of-service.html" class="footer-link">
                <i class="fas fa-file-alt footer-link-icon"></i><span class="footer-link-text">Terms of Service</span>
            </a>
            <span class="footer-link-separator"> </span>
            <a href="/privacy-policy.html" class="footer-link">
                <i class="fas fa-user-shield footer-link-icon"></i><span class="footer-link-text">Privacy Policy</span>
            </a>
        </p>
    </div>
</div>
</footer>

<div id="footer-modal-overlay" class="footer-modal-overlay jbtn-modal-overlay">
<button class="footer-modal-close jbtn-modal-close">&times;</button>
<div class="footer-modal-content jbtn-modal-content">
<section id="about-modal-content" class="modal-text-content" data-modal-id="about">
  <div class="settings-header">
    <i class="fas fa-info-circle settings-header-icon"></i>
    <h2>About Our Website</h2>
  </div>
  <p>
    The Jailbreak Trading Network offers accurate Roblox Jailbreak item values in a completely ad-free environment. Our detailed value list covers every limited vehicle, texture, and cosmetic so you can trade with confidence for both casual and competitive traders alike.
  </p>
  <p>
    Updated after each game patch, our community-driven database tracks the latest market prices and trends. Whether you need the worth of a new vehicle or complete historical data on rare rims, our guides help you stay ahead in the Jailbreak Trading scene.
  </p>
  <p>
    This is an independent fan project created by the community and has no official affiliation with Roblox Corporation or Badimo. For any account-related issues, please reach out through official support channels. We aim to provide accurate trading data and useful tools to help you make informed decisions in the Jailbreak marketplace.
  </p>
</section>
</div>
</div>

<div id="settingsModal" class="jbtn-modal-overlay">
<button class="jbtn-modal-close">&times;</button>
<div class="jbtn-modal-content">
<div class="modal-scrollable-content">
<div class="settings-header">
  <i class="fas fa-cogs settings-header-icon"></i>
  <h2>Display Settings</h2>
</div>
<p class="settings-subtitle">Customize your viewing experience to your liking.</p>

<div class="settings-section-new">
  <div class="settings-section-header">
    <i class="fas fa-desktop"></i>
    <h3>General Page Elements</h3>
  </div>
  <p class="setting-section-description">Control the visibility of main page components.</p>
  <div class="setting-option-new">
    <span>Hide Header</span>
    <label class="switch">
      <input type="checkbox" id="setting-hide-header" data-setting="hideHeader">
      <span class="slider round"></span>
    </label>
  </div>
  <div class="setting-option-new">
    <span>Hide Footer</span>
    <label class="switch">
      <input type="checkbox" id="setting-hide-footer" data-setting="hideFooter">
      <span class="slider round"></span>
    </label>
  </div>
  <div class="setting-option-new">
    <span>Hide Discord Info</span>
    <label class="switch">
      <input type="checkbox" id="setting-hide-submission-info" data-setting="hideSubmissionInfo">
      <span class="slider round"></span>
    </label>
  </div>
</div>


<div class="settings-section-new">
  <div class="settings-section-header">
    <i class="fas fa-id-card-alt"></i>
    <h3>Item Card Display</h3>
  </div>
  <p class="setting-section-description">Customize what details are shown on individual item cards.</p>
  <div class="setting-option-new">
    <span>Hide Item Explanations</span>
    <label class="switch">
      <input type="checkbox" id="setting-hide-explanation" data-setting="hideItemExplanations">
      <span class="slider round"></span>
    </label>
  </div>
  <div class="setting-option-new">
    <span>Hide Item Update Timestamps</span>
    <label class="switch">
      <input type="checkbox" id="setting-hide-timestamp" data-setting="hideItemTimestamps">
      <span class="slider round"></span>
    </label>
  </div>
  <div class="setting-option-new">
    <span>Hide Item Status Badges</span>
    <label class="switch">
      <input type="checkbox" id="setting-hide-status-badges" data-setting="hideStatusBadges">
      <span class="slider round"></span>
    </label>
  </div>
</div>


<div class="settings-section-new">
  <div class="settings-section-header">
    <i class="fas fa-magic"></i>
    <h3>Animation & Effects</h3>
  </div>
  <p class="setting-section-description">Control visual effects for performance or preference.</p>
  <div class="setting-option-new">
    <span>Disable Item Hover Glow</span>
    <label class="switch">
      <input type="checkbox" id="setting-toggle-hover-glow" data-setting="disableHoverGlow">
      <span class="slider round"></span>
    </label>
  </div>
  <div class="setting-option-new">
    <span>Disable Header Parallax Effect</span>
    <label class="switch">
      <input type="checkbox" id="setting-toggle-header-anim" data-setting="disableHeaderAnim">
      <span class="slider round"></span>
    </label>
  </div>
</div>

</div>


<div class="modal-actions-grid">
    <button id="saveSettingsButton" class="modal-btn save-btn"><i class="fas fa-save"></i>Save</button>
    <button id="resetSettingsButton" class="modal-btn reset-btn"><i class="fas fa-undo"></i>Reset Options</button>
</div>


</div>
</div>

<div id="explanationModal" class="jbtn-modal-overlay">
<button class="jbtn-modal-close">&times;</button>
<div class="jbtn-modal-content">
<div class="modal-scrollable-content">
  <div class="settings-header">
    <i class="fas fa-circle-question settings-header-icon"></i>
    <h2>Value Change Explanation</h2>
  </div>
<p class="settings-subtitle">Select an option to view information for this item.</p>
  <div class="explanation-section">
    <div class="explanation-section-header">
      <i class="fas fa-file-alt"></i>
      <h4>Value Change Explanation</h4>
    </div>
    <p class="explanation-section-description">See official posts explaining this item's value change.</p>
    <div class="explanation-options-container">
      <a id="explanation-x-post" href="#" target="_blank" class="explanation-option-button"><i class="fas fa-up-right-from-square"></i> View X Post</a>
      <a id="explanation-blog-post" href="#" target="_blank" class="explanation-option-button"><i class="fab fa-blogger-b"></i> View Blog Post</a>
    </div>
  </div>
  <div class="explanation-section">
    <div class="explanation-section-header">
      <i class="fas fa-clock-rotate-left"></i>
      <h4>Value Change History</h4>
    </div>
    <p class="explanation-section-description">See past posts detailing this item's value changes.</p>
    <div class="explanation-options-container">
      <a id="explanation-x-history" href="#" target="_blank" class="explanation-option-button"><i class="fas fa-up-right-from-square"></i> X Post History</a>
      <a id="explanation-blog-history" href="#" target="_blank" class="explanation-option-button"><i class="fab fa-blogger-b"></i> Blog Post History</a>
    </div>
  </div>
  <div class="explanation-section">
    <div class="explanation-section-header">
      <i class="fas fa-chart-line"></i>
      <h4>Historical Charts</h4>
    </div>
    <p class="explanation-section-description">Check charts of past value, demand, and other market trends.</p>
    <div class="explanation-options-container">
      <a id="explanation-value-history" href="#" target="_blank" class="explanation-option-button"><i class="fas fa-chart-line"></i> Value History</a>
      <a id="explanation-demand-history" href="#" target="_blank" class="explanation-option-button"><i class="fas fa-chart-area"></i> Demand History</a>
    </div>
  </div>
  <div class="explanation-section">
    <div class="explanation-section-header">
      <i class="fas fa-users"></i>
      <h4>Community Engagement</h4>
    </div>
    <p class="explanation-section-description">Request value changes or join community polls.</p>
    <div class="explanation-options-container">
      <a href="https://discord.com/channels/905907220477255740/1288298951761465396" target="_blank" class="explanation-option-button active">
        <i class="fas fa-pen-to-square"></i>
        Change Value
      </a>
      <a href="https://discord.com/channels/905907220477255740/1356217573514940507" target="_blank" class="explanation-option-button active">
        <i class="fas fa-square-poll-vertical"></i>
        Community Polls
      </a>
    </div>
  </div>
  <div class="explanation-section">
    <div class="explanation-section-header">
      <i class="fab fa-youtube"></i>
      <h4>YouTube Videos</h4>
    </div>
    <p class="explanation-section-description">Watch videos about this item or browse our channel.</p>
    <div class="explanation-options-container">
      <a id="youtube-search-videos" href="#" target="_blank" class="explanation-option-button active">
        <i class="fas fa-search"></i>
        Search Videos
      </a>
      <a href="https://www.youtube.com/@JailbreakTradingNetwork/videos" target="_blank" class="explanation-option-button active">
        <i class="fas fa-play"></i>
        View All Videos
      </a>
    </div>
  </div>
</div>
</div>
</div>

<div id="descriptionModal" class="jbtn-modal-overlay">
<button class="jbtn-modal-close">&times;</button>
<div class="jbtn-modal-content">
<div class="modal-scrollable-content">
  <div class="settings-header">
    <i class="fas fa-info-circle settings-header-icon"></i>
    <h2 id="descriptionModalTitle">Item Description</h2>
  </div>
  <p class="settings-subtitle">Learn more about this item and its details.</p>
  <div id="descriptionModalContent" class="description-modal-text">
    <!-- Description content will be inserted here -->
  </div>
  <div class="settings-divider-new"></div>
  <div class="explanation-section">
    <div class="explanation-section-header">
      <i class="fas fa-robot"></i>
      <h4>Need More Information?</h4>
    </div>
    <p class="explanation-section-description">Our AI can provide detailed insights, trading tips, and comprehensive information about any item in the game!</p>
    <div class="explanation-options-container">
      <a href="https://discord.com/channels/905907220477255740/1364429246172495982" target="_blank" class="explanation-option-button active">
        <i class="fab fa-discord"></i>
        Ask AI Assistant
      </a>
      <a href="https://discord.jailbreaktradingnetwork.com/" target="_blank" class="explanation-option-button active">
        <i class="fas fa-users"></i>
        Join Community
      </a>
    </div>
  </div>
  <div class="explanation-section">
    <div class="explanation-section-header">
      <i class="fab fa-youtube"></i>
      <h4>YouTube Videos</h4>
    </div>
    <p class="explanation-section-description">Watch videos about this item or browse our channel.</p>
    <div class="explanation-options-container">
      <a id="description-youtube-search-videos" href="#" target="_blank" class="explanation-option-button active">
        <i class="fas fa-search"></i>
        Search Videos
      </a>
      <a href="https://www.youtube.com/@JailbreakTradingNetwork/videos" target="_blank" class="explanation-option-button active">
        <i class="fas fa-play"></i>
        View All Videos
      </a>
    </div>
  </div>
</div>
</div>
</div>

<div id="audioInfoModal" class="jbtn-modal-overlay">
<button class="jbtn-modal-close">&times;</button>
<div class="jbtn-modal-content">
<div class="modal-scrollable-content">
  <div class="settings-header">
    <i class="fas fa-music settings-header-icon"></i>
    <h2>Music Player</h2>
  </div>
  <p class="settings-subtitle">Enjoy some background music while browsing values.</p>
  <div class="settings-section-new">
    <div class="settings-section-header">
      <i class="fas fa-play-circle"></i>
      <h3>Music Player</h3>
    </div>
    <p class="setting-section-description">Control playback of the background track.</p>
    <div class="settings-divider-new"></div>
    <div class="audio-player-container">
      <div class="audio-player-row">
        <span id="navAudioTime" class="audio-time">0:00/0:00</span>
        <button id="navAudioBack" aria-label="Rewind 10 seconds" class="audio-btn"><i class="fas fa-backward"></i></button>
        <button id="navAudioToggle" aria-label="Play or pause" class="audio-btn play-btn"><i class="fas fa-play"></i></button>
        <button id="navAudioForward" aria-label="Forward 10 seconds" class="audio-btn"><i class="fas fa-forward"></i></button>
        <input id="navAudioProgress" class="audio-progress" type="range" min="0" max="0" value="0" step="1" aria-label="Playback position">
      </div>
      <div class="audio-extra-controls">
        <button class="audio-control-preset" id="audioRestart" aria-label="Restart track"><i class="fas fa-undo"></i> Restart</button>
        <button class="audio-control-preset" id="audioShuffle" aria-label="Shuffle mode"><i class="fas fa-random"></i> Shuffle</button>
        <button class="audio-control-preset" id="audioLoop" aria-label="Loop track"><i class="fas fa-sync"></i> Loop</button>
        <button class="audio-control-preset" id="audioSpeed" aria-label="Playback speed"><i class="fas fa-tachometer-alt"></i> 1.0x</button>
        <button class="audio-control-preset" id="audioMute" aria-label="Mute audio"><i class="fas fa-volume-mute"></i> Mute</button>
      </div>
    </div>
  </div>
  <div class="settings-section-new">
    <div class="settings-section-header">
      <i class="fas fa-volume-up"></i>
      <h3>Volume Controls</h3>
    </div>
    <p class="setting-section-description">Adjust the music volume using presets or buttons.</p>
    <div class="settings-divider-new"></div>
    <div class="volume-controls">
      <div class="volume-slider-row">
        <button id="navVolumeDown" aria-label="Decrease volume" class="volume-btn"><i class="fas fa-volume-down"></i></button>
        <input id="navAudioVolume" class="audio-volume" type="range" min="0" max="100" value="100" aria-label="Volume">
        <span id="volumeDisplay" class="volume-display">100%</span>
        <button id="navVolumeUp" aria-label="Increase volume" class="volume-btn"><i class="fas fa-volume-up"></i></button>
      </div>
      <div class="volume-presets">
        <button class="volume-preset" data-vol="0"><i class="fas fa-volume-mute"></i> Mute</button>
        <button class="volume-preset" data-vol="25"><i class="fas fa-volume-down"></i> 25%</button>
        <button class="volume-preset" data-vol="50"><i class="fas fa-volume-up"></i> 50%</button>
        <button class="volume-preset" data-vol="75"><i class="fas fa-volume-up"></i> 75%</button>
        <button class="volume-preset" data-vol="100"><i class="fas fa-volume-up"></i> 100%</button>
      </div>
    </div>
  </div>
  <div class="settings-section-new">
    <div class="settings-section-header">
      <i class="fas fa-info-circle"></i>
      <h3>Attribution</h3>
    </div>
    <p class="setting-section-description audio-attribution">"Dreamy Ambient Background Music Loop" by Alexander Blu is licensed under CC BY 4.0. Please support the artist's work.</p>
  </div>
</div>
  <div class="modal-actions-grid">
    <button id="audioSourceButton" class="modal-btn save-btn"><i class="fas fa-link"></i>Source</button>
    <button id="audioLicenseButton" class="modal-btn reset-btn"><i class="fas fa-file-alt"></i>License</button>
  </div>
</div>
</div>
<script>

let frequencyData = {};
let vehicles = [];
let dataLoaded = false;
let isAnimating = false;
let isInitialLoad = true;
let isLoadingError = false;
// Forces the items count to animate from 0 on the next rebuild (used by Reset Options)
let __forceCountFromZero = false;

const nameMappings = {};
const excludedItems = [];

const apiEndpoints = {
"Vehicle Values": "https://system.jailbreaktradingnetwork.com/vehicles",
"Texture Values": "https://system.jailbreaktradingnetwork.com/textures",
"Color Values": "https://system.jailbreaktradingnetwork.com/colors",
"Spoiler Values": "https://system.jailbreaktradingnetwork.com/spoilers",
"Rim Values": "https://system.jailbreaktradingnetwork.com/rims",
"Tire Values": "https://system.jailbreaktradingnetwork.com/tires",
"Furniture Values": "https://system.jailbreaktradingnetwork.com/furniture",
"Gun Texture Values": "https://system.jailbreaktradingnetwork.com/guntextures",
"Vehicle Horn Values": "https://system.jailbreaktradingnetwork.com/vehiclehorns",
"Drift Particle Values": "https://system.jailbreaktradingnetwork.com/driftparticles"
};

const demandTypeMappings = {
"Vehicle Values": "Vehicle",
"Texture Values": "VehicleCustomization.Texture",
"Color Values": "VehicleCustomization.Color",
"Spoiler Values": "VehicleCustomization.Spoiler",
"Rim Values": "VehicleCustomization.Rim",
"Tire Values": ["VehicleCustomization.TireSticker", "VehicleCustomization.TireMesh"],
"Vehicle Horn Values": "VehicleCustomization.Horn",
"Drift Particle Values": "VehicleCustomization.Drift",
"Furniture Values": null,
"Gun Texture Values": null
};

const filterValueMappings = {
"Vehicle Values": "category-vehicle",
"Texture Values": "category-texture",
"Color Values": "category-color",
"Spoiler Values": "category-spoiler",
"Rim Values": "category-rim",
"Tire Values": "category-tire",
"Furniture Values": "category-furniture",
"Gun Texture Values": "category-gun-texture",
"Vehicle Horn Values": "category-vehicle-horn",
"Drift Particle Values": "category-drift-particle"
};

document.addEventListener('DOMContentLoaded', () => {
const headerH1 = document.querySelector('header h1');
const headerH2 = document.querySelector('header h2');
if (headerH1 && headerH2) {
  let titleText = headerH1.textContent.trim();
  if (!/values$/i.test(titleText)) {
    titleText = `${titleText} Values`;
  }
  headerH2.dataset.valueType = titleText;
  headerH2.textContent = titleText;
}
});

const customLoadingOverlay = document.getElementById('custom-loading-overlay');
const loadingMessageElement = document.getElementById('loading-message');
const progressBarElement = document.getElementById('progress-bar');
const errorMessageElement = document.getElementById('error-message');

// Navigation handler no longer needed - CSS handles everything
class AllItemsVisibleNav {
constructor() {}
init() {}
}

// Simplified dropdown sizer - no longer needed with fixed widths
class DynamicDropdownSizer {
constructor() {}
init() {}
updateAllSizes() {}
destroy() {}
}

// Initialize components
const responsiveNav = new AllItemsVisibleNav();
const dropdownSizer = new DynamicDropdownSizer();
const loadingLogBox = document.getElementById('loading-log-box');
const controlsElement = document.getElementById('LIMenuContainer');
const topNavbarElement = document.getElementById('topNavbar');
const pageHeaderElement = document.getElementById('pageHeader');


let currentSortCriteria = 'price-desc';
let currentFilterType = 'all-items';
let currentCategoryFilter = 'all-values';
const filterOptionValues = ["all-items", "limited-only", "retired-only", "reference-only", "obtainable-only", "event-exclusive-only", "vault-exclusive-only", "pass-exclusive-only"];

let originalSortOptionTexts = {};
let originalFilterOptionTexts = {};

const RENDER_BATCH_SIZE = 40;
let lazyList = [];
let lazyIndex = 0;
let lazyObserver;

const LISortSelectForEarlyInit = document.getElementById('LISortSelect');
if (LISortSelectForEarlyInit) {
  LISortSelectForEarlyInit.querySelectorAll('optgroup:not([label="Filter by Type"]) option').forEach(opt => {
      if (opt.value && opt.textContent) {
           originalSortOptionTexts[opt.value] = opt.textContent.trim();
      }
  });
} else {
  console.error("CRITICAL: LISortSelect element not found during initial script execution. Sort/filter display may be compromised.");
}

const LIFilterSelectForEarlyInit = document.getElementById('LIFilterSelect');
if (LIFilterSelectForEarlyInit) {
  LIFilterSelectForEarlyInit.querySelectorAll('option').forEach(opt => {
      if (opt.value && opt.textContent) {
           originalFilterOptionTexts[opt.value] = opt.textContent.trim();
      }
  });
}

// Function to update option text based on screen size and force layout reflow
function updateOptionTextForMobile() {
  const screenWidth = window.innerWidth;
  const searchInput = document.getElementById('LISearchInput');
  const sortSelect = document.getElementById('LISortSelect');
  const filterSelect = document.getElementById('LIFilterSelect');
  
  if (searchInput) {
      if (screenWidth >= 1401) {
          searchInput.placeholder = "Search for Items";
      } else {
          searchInput.placeholder = "Search";
      }
  }
  
  if (sortSelect && originalSortOptionTexts) {
      const sortContainer = sortSelect.parentElement;
      // Always use custom dropdown styling
      sortContainer.classList.remove('mobile-select');
      sortContainer.removeAttribute('data-mobile-text');
      // Ensure original option text is preserved for overlay
      sortSelect.querySelectorAll('option').forEach(opt => {
          if (originalSortOptionTexts[opt.value]) {
              opt.textContent = originalSortOptionTexts[opt.value];
          }
      });
  }
  
  if (filterSelect && originalFilterOptionTexts) {
      const filterContainer = filterSelect.parentElement;
      // Always use custom dropdown styling
      filterContainer.classList.remove('mobile-select');
      filterContainer.removeAttribute('data-mobile-text');
      // Ensure original option text is preserved for overlay
      filterSelect.querySelectorAll('option').forEach(opt => {
          if (originalFilterOptionTexts[opt.value]) {
              opt.textContent = originalFilterOptionTexts[opt.value];
          }
      });
  }
  
  // Force layout reflow by temporarily hiding and showing elements
  const searchSort = document.querySelector('.search-sort');
  if (searchSort) {
      // Trigger reflow by reading offsetHeight
      searchSort.offsetHeight;
      
      // Force repaint by toggling a class
      searchSort.classList.add('force-reflow');
      requestAnimationFrame(() => {
          searchSort.classList.remove('force-reflow');
      });
  }
}

// Debounced resize handler to avoid excessive calls
let resizeTimeout;
function handleResize() {
  clearTimeout(resizeTimeout);
  resizeTimeout = setTimeout(() => {
      updateOptionTextForMobile();
      updateButtonTextVisibility();
  }, 50);
}

// Call on page load and resize
window.addEventListener('resize', handleResize);
window.addEventListener('load', updateOptionTextForMobile);

  // Dynamic select sizing based on selected text and screen size
function adjustSelectWidth(selectElement) {
    if (!selectElement) return;
    
    const screenWidth = window.innerWidth;
    
    // Only auto-size on desktop screens; revert to CSS widths on mobile/tablet
    if (screenWidth <= 768) {
        selectElement.style.width = '';
        return;
    }
    
    // Create a temporary element to measure text width
    const temp = document.createElement('div');
    temp.style.cssText = `
        position: absolute;
        top: -9999px;
        left: -9999px;
        font-family: ${window.getComputedStyle(selectElement).fontFamily};
        font-size: ${window.getComputedStyle(selectElement).fontSize};
        font-weight: ${window.getComputedStyle(selectElement).fontWeight};
        padding: 0 2.2em 0 0;
        white-space: nowrap;
        visibility: hidden;
    `;
    
    const selectedOption = selectElement.options[selectElement.selectedIndex];
    temp.textContent = selectedOption ? selectedOption.textContent : '';
    
    document.body.appendChild(temp);
    const textWidth = temp.offsetWidth;
    document.body.removeChild(temp);
    
    // Responsive width calculation based on screen size - gradual scaling
    let minWidth, maxWidth;
    if (screenWidth >= 1300) {
        minWidth = 260;
        maxWidth = 450;
    } else if (screenWidth >= 1200) {
        minWidth = 250;
        maxWidth = 380;
    } else if (screenWidth >= 761) {
        // Gradual scaling from 1200px down to 761px
        const scaleFactor = (screenWidth - 761) / 439; // 0 to 1 (1200-761=439)
        minWidth = Math.round(160 + (90 * scaleFactor)); // 160 to 250
        maxWidth = Math.round(160 + (220 * scaleFactor)); // 160 to 380
    } else {
        minWidth = 160;
        maxWidth = 160;
    }
    
    const newWidth = Math.max(textWidth + 60, minWidth);
    const targetWidth = Math.min(newWidth, maxWidth);
    
    // Ensure smooth transition with easing
    selectElement.style.transition = 'width 0.2s cubic-bezier(0.25, 0.46, 0.45, 0.94)';
    selectElement.style.width = targetWidth + 'px';
}

// Dynamic button display text sizing - no longer needed
function adjustButtonDisplayTextWidth(buttonDisplayElement) {
    // Function kept for compatibility but does nothing
}

function adjustSearchWidth() {
  const searchInput = document.getElementById('LISearchInput');
  if (!searchInput) return;

  // Allow CSS to control the size for all screen widths
  searchInput.style.transition = '';
  searchInput.style.width = '';
  searchInput.style.minWidth = '';
  searchInput.style.maxWidth = '';
}

function adjustAllSelectWidths() {
  const sortSelect = document.getElementById('LISortSelect');
  const filterSelect = document.getElementById('LIFilterSelect');
  if (window.innerWidth <= 800) {
      // Reset to base widths on smaller screens  
      if (sortSelect) sortSelect.style.width = '';
      if (filterSelect) filterSelect.style.width = '';
      return;
  }
  // Large screens – dynamically size
  adjustSelectWidth(sortSelect);
  adjustSelectWidth(filterSelect);
  adjustSearchWidth();
}

// Add event listeners for select changes
document.addEventListener('DOMContentLoaded', () => {
  const sortSelect = document.getElementById('LISortSelect');
  const filterSelect = document.getElementById('LIFilterSelect');
  
  if (sortSelect) {
      sortSelect.addEventListener('change', () => adjustSelectWidth(sortSelect));
  }
  
  if (filterSelect) {
      filterSelect.addEventListener('change', () => adjustSelectWidth(filterSelect));
  }
  
  // Initial adjustment
  adjustAllSelectWidths();
});

// Adjust on window resize with improved debouncing
let adjustTimeout;
window.addEventListener('resize', () => {
  clearTimeout(adjustTimeout);
  adjustTimeout = setTimeout(adjustAllSelectWidths, 30);
});

// Update button text visibility based on screen size
function updateButtonTextVisibility() {
  const screenWidth = window.innerWidth;
  const showButtonText = screenWidth >= 1080; // Show text only on large desktop sizes
  const resetButton = document.getElementById('LIResetButton');
  const settingsButton = document.getElementById('LISettingsButton');
  
  [resetButton, settingsButton].forEach(button => {
      if (button) {
          const span = button.querySelector('span');
          if (span) {
              if (showButtonText) {
                  span.style.display = 'inline';
                  // Adjust margin based on screen size
                  if (screenWidth >= 1300) {
                      span.style.marginLeft = '6px';
                  } else if (screenWidth >= 1200) {
                      span.style.marginLeft = '5px';
                  } else if (screenWidth >= 1000) {
                      span.style.marginLeft = '5px';
                  } else {
                      span.style.marginLeft = '4px';
                  }
              } else {
                  span.style.display = 'none';
                  span.style.marginLeft = '0';
              }
          }
      }
  });
  
  // Make buttons equal width on desktop
  if (showButtonText && resetButton && settingsButton) {
      // Set optimal width for each button individually
      requestAnimationFrame(() => {
          resetButton.style.transition = 'min-width 0.2s ease';
          settingsButton.style.transition = 'min-width 0.2s ease';
          
          // Reset button should be more compact
          resetButton.style.minWidth = 'auto';
          resetButton.style.width = 'auto';
          resetButton.style.padding = '8px 12px';
          
          // Settings button can be slightly wider
          settingsButton.style.minWidth = 'auto';
          settingsButton.style.width = 'auto';
          settingsButton.style.padding = '8px 12px';
      });
  } else if (resetButton && settingsButton) {
      // Reset sizing on smaller screens so CSS can control icon-only width
      resetButton.style.minWidth = '';
      resetButton.style.width = '';
      resetButton.style.padding = '';
      settingsButton.style.minWidth = '';
      settingsButton.style.width = '';
      settingsButton.style.padding = '';
  }
  
  // Update sort/filter button sizing
  updateSortFilterButtonSizing();
}

// Function to handle sort/filter button sizing based on screen size
function updateSortFilterButtonSizing() {
  const sortButton = document.getElementById('LISortButton');
  const filterButton = document.getElementById('LIFilterButton');
  const sortWrapper = sortButton?.closest('.input-icon-wrapper');
  const filterWrapper = filterButton?.closest('.input-icon-wrapper');
  
  if (window.innerWidth >= 1401) {
      // Large desktop: Apply dynamic sizing with full text
      updateButtonText(); // This will recalculate and apply optimal widths
  } else if (window.innerWidth >= 1201) {
      // Medium desktop: Apply fixed sizing with shortened text
      if (sortWrapper) {
          sortWrapper.style.width = '';
          sortWrapper.style.minWidth = '';
          sortWrapper.style.maxWidth = '';
      }
      if (filterWrapper) {
          filterWrapper.style.width = '';
          filterWrapper.style.minWidth = '';
          filterWrapper.style.maxWidth = '';
      }
      updateButtonText(); // Will show shortened text
  } else {
      // Compact mode: Reset to CSS-controlled sizing (icon-only)
      if (sortWrapper) {
          sortWrapper.style.width = '';
          sortWrapper.style.minWidth = '';
          sortWrapper.style.maxWidth = '';
      }
      if (filterWrapper) {
          filterWrapper.style.width = '';
          filterWrapper.style.minWidth = '';
          filterWrapper.style.maxWidth = '';
      }
      // Update button text (will be hidden by CSS in compact mode)
      updateButtonText();
  }
}

// Update button text on resize with improved debouncing
let buttonResizeTimeout;
window.addEventListener('resize', () => {
  clearTimeout(buttonResizeTimeout);
  buttonResizeTimeout = setTimeout(() => {
      updateButtonTextVisibility();
  }, 30);
});

// Initial update
document.addEventListener('DOMContentLoaded', updateButtonTextVisibility);

// Show Filter by Category only on All Values page
function checkPageForCategoryFilter() {
  // Check if this is the All Values page by URL, title, or content
  const isAllValuesPage = 
      window.location.pathname === '/index' || window.location.pathname === '/index.html' || window.location.pathname === '/all-values' ||
      window.location.pathname === '/' ||
      document.title.toLowerCase().includes('all values') ||
      document.querySelector('h1, .page-title')?.textContent?.toLowerCase().includes('all values') ||
      // Default to showing it if we can't determine (fallback for main page)
      window.location.pathname === '';
  
  if (isAllValuesPage) {
      document.body.classList.add('page-all-values');
  } else {
      document.body.classList.remove('page-all-values');
  }
}

// Check on page load
document.addEventListener('DOMContentLoaded', checkPageForCategoryFilter);


const menuLinkData = [
{ text: "Home", href: "/home.html", icon: "fas fa-home" },
{ isSeparator: true },
{ text: "All Values", href: "/index.html", icon: "fas fa-th-list" },
{ text: "Vehicles", href: "/vehicles.html", icon: "fas fa-car-side" },
{ text: "Textures", href: "/textures.html", icon: "fas fa-paint-roller" },
{ text: "Colors", href: "/colors.html", icon: "fa-solid fa-fill-drip" },
{ text: "Spoilers", href: "/spoilers.html", icon: "fas fa-cogs" },
{ text: "Rims", href: "/rims.html", icon: "fas fa-compact-disc" },
{ text: "Tires", href: "/tires.html", icon: "fas fa-circle-dot" },
{
    text: "Other Values",
    icon: "fas fa-ellipsis-h",
    children: [
        { text: "Furniture", href: "/other-values/furniture.html", icon: "fas fa-couch"},
        { text: "Gun Textures", href: "/other-values/gun-textures.html", icon: "fas fa-gun"},
        { text: "Vehicle Horns", href: "/other-values/vehicle-horns.html", icon: "fas fa-bullhorn"},
        { text: "Drift Particles", href: "/other-values/drift-particles.html", icon: "fas fa-wind"},
    ]
},
{ isSeparator: true },
{ text: "Value Calculator", href: "/value-calculator.html", icon: "fas fa-calculator" },
{ text: "Dupe Calculator", href: "/dupe-calculator.html", icon: "fas fa-clone" },
{ text: "Stock Calculator", href: "/stock-calculator.html", icon: "fas fa-box-open" },
{ text: "Value Dynamics", href: "/value-dynamics.html", icon: "fas fa-chart-bar" },
{ text: "Demand Graph", href: "/demand-graph.html", icon: "fas fa-chart-area" },
{ isSeparator: true },
{ text: "OG Item Finder", href: "/og-item-finder.html", icon: "fas fa-search-dollar" },
{ text: "Vouches Index", href: "/vouches-index.html", icon: "fas fa-check-double" },
{ text: "Scammer List", href: "/scammer-list.html", icon: "fas fa-user-secret" },
{ text: "Archive Portal", href: "/archive-portal.html", icon: "fas fa-archive" },
{ text: "Trading Offers", href: "/trading-offers.html", icon: "fas fa-exchange-alt" },
{ text: "Private Servers", href: "/private-servers.html", icon: "fas fa-server" },
{ text: "Value Changes", href: "https://blog.jailbreaktradingnetwork.com/", icon: "fas fa-chart-line", external: true },
{ text: "Game Updates", href: "https://www.youtube.com/@JailbreakTradingNetwork/videos", icon: "fas fa-rocket", external: true },
{ isSeparator: true },
{
  text: "Legacy Features",
  icon: "fas fa-history",
  children: [
    { text: "Minecraft Server", href: "/legacy-features/minecraft-server.html", icon: "fas fa-cube" },
    { text: "Old OG Item Finder", href: "/legacy-features/old-og-item-finder.html", icon: "fas fa-search" },
    { text: "Old Scammer List", href: "/legacy-features/old-scammer-list.html", icon: "fas fa-list-alt" },
  ]
},
{
  text: "Our Social Media",
  icon: "fas fa-users",
  children: [
    { text: "Roblox Group", href: "https://www.roblox.com/communities/14854862", icon: "fas fa-gamepad", external: true },
    { text: "Discord Server", href: "https://discord.jailbreaktradingnetwork.com/", icon: "fab fa-discord", external: true },
    { text: "YouTube Videos", href: "https://www.youtube.com/@JailbreakTradingNetwork", icon: "fab fa-youtube", external: true },
    { text: "X/Twitter Account", href: "https://x.com/TradingWebsite", icon: "fab fa-twitter", external: true },
    { text: "Blogger Website", href: "https://blog.jailbreaktradingnetwork.com/", icon: "fab fa-blogger", external: true },
    { text: "Discord Appeals", href: "https://appeal.gg/JailbreakTradingNetwork", icon: "fas fa-gavel", external: true }
  ]
},
{ text: "Companion Apps", href: "/companion-apps.html", icon: "fas fa-window-restore" },
{ text: "Marketplace Info", href: "/marketplace-info.html", icon: "fas fa-store" },
{ isSeparator: true },
{ text: "Terms of Service", href: "/terms-of-service.html", icon: "fas fa-file-contract" },
{ text: "Privacy Policy", href: "/privacy-policy.html", icon: "fas fa-user-shield" }
];

const desktopLinksContainer = document.getElementById('navbarLinksDesktop');
const mobileLinksContainer = document.getElementById('navbarLinksMobile');
let moreDropdown = null;

function createDesktopLink(linkInfo, currentPath) {
const link = document.createElement('a');
link.href = linkInfo.href;
const externalIcon = linkInfo.external ? '<i class="fas fa-external-link-alt" style="margin-left: 5px; font-size: 0.8em; opacity: 0.8;"></i>' : '';
link.innerHTML = `<i class="${linkInfo.icon || 'fas fa-question-circle'} navbar-link-icon"></i><span class="navbar-link-text">${linkInfo.text}</span>${externalIcon}`;
if (linkInfo.external) {
  link.target = '_blank';
  link.rel = 'noopener noreferrer';
}
const linkHref = linkInfo.href;
let normalizedCurrentPath = currentPath.endsWith('/') ? currentPath.slice(0, -1) : currentPath;
if (normalizedCurrentPath.endsWith('.html')) normalizedCurrentPath = normalizedCurrentPath.slice(0, -5);
let normalizedLinkHref = linkHref.endsWith('/') ? linkHref.slice(0, -1) : linkHref;
if (normalizedLinkHref.endsWith('.html')) normalizedLinkHref = normalizedLinkHref.slice(0, -5);
const isRootPath = normalizedCurrentPath === '' || normalizedCurrentPath === '/';
const isHomeLink = normalizedLinkHref === '/home';
const isHomeMatch = isHomeLink && (normalizedCurrentPath === '/home' || normalizedCurrentPath.endsWith('/home'));
const isLegacyHomeLink = normalizedLinkHref === '/' || normalizedLinkHref === '';
const isLegacyHomeMatch = isLegacyHomeLink && (isRootPath || normalizedCurrentPath.endsWith('/index'));
const isAllValuesLink = normalizedLinkHref === '/index';
const isAllValuesMatch = isAllValuesLink && (isRootPath || normalizedCurrentPath.endsWith('/index') || normalizedCurrentPath.endsWith('/all-values'));
if (isHomeMatch || isLegacyHomeMatch) {
  link.classList.add('active');
} else if (isAllValuesMatch) {
  link.classList.add('active');
} else if (normalizedLinkHref !== '' && normalizedLinkHref !== '/' && normalizedCurrentPath.endsWith(normalizedLinkHref)) {
  link.classList.add('active');
}
link.addEventListener('click', () => {
  // Delay closing so navigation can occur before menu disappears
  setTimeout(() => closeAllDropdowns(), 100);
});
return link;
}

function populateNavbarLinks() {
if (!desktopLinksContainer || !mobileLinksContainer) return;

desktopLinksContainer.innerHTML = '';
mobileLinksContainer.innerHTML = '';
moreDropdown = null;

const currentPath = window.location.pathname;
const desktopElementsList = [];

function createDropdown(itemInfo, currentPath) {
    const dropdownElement = document.createElement('div');
    dropdownElement.className = 'navbar-dropdown';
    if (itemInfo.id) {
        dropdownElement.id = itemInfo.id;
    }
    const toggle = document.createElement('button');
    toggle.className = 'navbar-dropdown-toggle';
    toggle.innerHTML = `<i class="${itemInfo.icon || 'fas fa-question-circle'} navbar-link-icon"></i><span class="navbar-link-text">${itemInfo.text}</span> <i class="fas fa-caret-down"></i>`;
    const menu = document.createElement('div');
    menu.className = 'navbar-dropdown-menu';
    let isParentActive = false;

    if (itemInfo.children) {
        itemInfo.children.forEach(childInfo => {
            if (childInfo && childInfo.disabled) return;
            if (childInfo.children && childInfo.children.length > 0) {
                const nestedDropdown = createDropdown(childInfo, currentPath);
                if (nestedDropdown.querySelector('.active')) {
                    isParentActive = true;
                }
                menu.appendChild(nestedDropdown);
            } else {
                const childLink = createDesktopLink(childInfo, currentPath);
                if (childLink.classList.contains('active')) {
                    isParentActive = true;
                }
                menu.appendChild(childLink);
            }
        });
    }

    if (isParentActive) {
        toggle.classList.add('active');
    }
    dropdownElement.appendChild(toggle);
    dropdownElement.appendChild(menu);
    return dropdownElement;
}

function createSeparator() {
    const sep = document.createElement('span');
    sep.className = 'navbar-separator';
    sep.textContent = '|';
    return sep;
}

menuLinkData.forEach(itemInfo => {
    if (itemInfo && itemInfo.disabled) {
        return;
    }
    if (itemInfo.isSeparator) {
        desktopElementsList.push(createSeparator());
    } else if (itemInfo.children && itemInfo.children.length > 0) {
        desktopElementsList.push(createDropdown(itemInfo, currentPath));
    } else if (itemInfo.href) {
        desktopElementsList.push(createDesktopLink(itemInfo, currentPath));
    }
});

desktopElementsList.forEach(el => desktopLinksContainer.appendChild(el));

menuLinkData.forEach(itemInfo => {
    if (itemInfo && itemInfo.disabled) {
        return;
    }
    if (itemInfo.isSeparator) {
        const sep = document.createElement('div');
        sep.className = 'navbar-separator';
        mobileLinksContainer.appendChild(sep);
        return;
    }
    if (itemInfo.children && itemInfo.children.length > 0) {
        const mobileDropdown = createDropdown(itemInfo, currentPath);
        mobileLinksContainer.appendChild(mobileDropdown);
    } else if (itemInfo.href) {
        const mobileLink = createDesktopLink(itemInfo, currentPath);
        mobileLink.addEventListener('click', closeMobileMenu);
        mobileLinksContainer.appendChild(mobileLink);
    }
});

manageNavbarOverflow();
}

function manageNavbarOverflow() {
if (!desktopLinksContainer) return;
const top = document.getElementById('topNavbar');
if (top) top.classList.add('more-toggle-freeze');
// Reuse existing More dropdown: move its items back to the row but keep the element
let existingMoreDropdown = document.getElementById('navbarMoreDropdown');
let existingMenu = existingMoreDropdown ? existingMoreDropdown.querySelector('.navbar-dropdown-menu') : null;
if (existingMoreDropdown && existingMenu) {
    const itemsToRestore = Array.from(existingMenu.children);
    itemsToRestore.forEach(node => desktopLinksContainer.insertBefore(node, existingMoreDropdown));
}

const mobileToggleContainer = document.querySelector('.navbar-right-side');

if (window.innerWidth <= 991) {
    desktopLinksContainer.style.display = 'none';
    if (mobileToggleContainer) mobileToggleContainer.style.display = 'flex';
    return;
}
desktopLinksContainer.style.display = 'flex';
if (mobileToggleContainer) {
    if (mobileMenu && mobileMenu.classList.contains('open')) {
        mobileToggleContainer.style.display = 'flex';
    } else {
        mobileToggleContainer.style.display = 'none';
    }
}

requestAnimationFrame(() => {
    const container = desktopLinksContainer;
    if (container.scrollWidth <= container.clientWidth) {
    adjustLayoutForNavbar();
    if (top) {
        requestAnimationFrame(() => top.classList.remove('more-toggle-freeze'));
    }
        return; 
    }

    let moreDropdown = document.getElementById('navbarMoreDropdown');
    if (!moreDropdown) {
        moreDropdown = document.createElement('div');
        moreDropdown.className = 'navbar-dropdown navbar-more-dropdown';
        moreDropdown.id = 'navbarMoreDropdown';
        moreDropdown.innerHTML = '<button class="navbar-dropdown-toggle"><i class="fas fa-ellipsis-h navbar-link-icon"></i><span class="navbar-link-text">More</span> <i class="fas fa-caret-down"></i></button><div class="navbar-dropdown-menu"></div>';
        container.appendChild(moreDropdown);
    }
    let menu = moreDropdown.querySelector('.navbar-dropdown-menu');
    if (!menu) {
        menu = document.createElement('div');
        menu.className = 'navbar-dropdown-menu';
        moreDropdown.appendChild(menu);
    }

    while (container.scrollWidth > container.clientWidth && container.children.length > 1) {
        const itemToMove = moreDropdown.previousElementSibling;
        if (itemToMove) { 
            menu.insertBefore(itemToMove, menu.firstChild);
        } else {
            break; 
        }
    }
    
    if (menu.children.length > 0 && container.children.length === 1) {
        const itemToRestore = menu.firstElementChild;
        if (itemToRestore) {
            container.insertBefore(itemToRestore, moreDropdown);
        }
    }

    const toggle = moreDropdown.querySelector('.navbar-dropdown-toggle');
    if (menu.querySelector('.active') || menu.querySelector('a.active')) {
        toggle.classList.add('active');
    } else {
        toggle.classList.remove('active');
    }

    adjustLayoutForNavbar();
    if (top) {
        requestAnimationFrame(() => top.classList.remove('more-toggle-freeze'));
    }
});
}

function manageControlsOverflow() {
// No longer needed - CSS handles all responsive behavior
}
function handleGlobalResizeThrottled() {
// Close any open dropdowns on resize
closeAllDropdowns();
// Recalculate which navbar items should be visible
manageNavbarOverflow();
// Ensure the header title scales correctly when resizing
adjustHeaderTitleSize();
}


function closeAllDropdowns(exceptThisOne = null) {
document.querySelectorAll('.navbar-dropdown.open').forEach(openDropdown => {
    if (openDropdown !== exceptThisOne && !openDropdown.contains(exceptThisOne)) {
        openDropdown.classList.remove('open');
    }
});
}

function handleNavbarClick(event) {
  const toggle = event.target.closest('.navbar-dropdown-toggle');
  
  // Only close dropdowns for regular links (not dropdown toggles) and only in desktop context
  if (event.target.closest('a') && event.target.closest('.navbar-dropdown-menu') && 
      !event.target.closest('.navbar-dropdown-toggle') && 
      !event.target.closest('.navbar-links-mobile')) {
      closeAllDropdowns();
      return;
  }

  if (!toggle) {
      return;
  }

  const dropdown = toggle.parentElement;

  const isTopLevel = !dropdown.parentElement.closest('.navbar-dropdown-menu');
  
  // On desktop: top-level dropdowns are hover-only, nested dropdowns are click-only
  if (isTopLevel && window.innerWidth >= 992) {
      return; // Top-level dropdowns handled by hover
  }
  
  // For nested dropdowns on desktop, or all dropdowns on mobile, handle clicks

  event.preventDefault();
  const wasOpen = dropdown.classList.contains('open');

  // Allow multiple nested dropdowns to stay open - don't close siblings
  dropdown.classList.toggle('open', !wasOpen);
}

function adjustLayoutForNavbar() {}

const mobileMenu = document.getElementById('mobileMenu');
const mobileToggle = document.querySelector('.navbar-mobile-toggle');
const mobileMenuOverlay = document.querySelector('.navbar-mobile-menu-overlay');

function openMobileMenu() {
if (mobileMenu && mobileToggle) {
    mobileMenu.classList.add('open');
    mobileMenu.setAttribute('aria-hidden', 'false');
    mobileToggle.setAttribute('aria-expanded', 'true');
    document.body.classList.add('jbtn-modal-open');
    document.body.classList.add('mobile-menu-open');
    if (mobileMenuOverlay) mobileMenuOverlay.classList.add('open');
    const mobileLinksContainer = document.getElementById('navbarLinksMobile');
    if (mobileLinksContainer) {
        mobileLinksContainer.scrollTop = 0;
    }
}
}

function closeMobileMenu() {
if (mobileMenu && mobileToggle && mobileMenu.classList.contains('open')) {
    mobileMenu.classList.remove('open');
    mobileToggle.setAttribute('aria-expanded', 'false');
    mobileMenu.setAttribute('aria-hidden', 'true');
    if (mobileMenuOverlay) mobileMenuOverlay.classList.remove('open');
    if (mobileLinksContainer) {
        mobileLinksContainer.querySelectorAll('.is-pressing').forEach(el => el.classList.remove('is-pressing'));
    }

    setTimeout(() => {
        if (!document.querySelector('.fullscreen-overlay.active') &&
            (!customLoadingOverlay || customLoadingOverlay.style.opacity === '0')) {
             if (!mobileMenu.classList.contains('open')) {
                document.body.classList.remove('jbtn-modal-open');
                document.body.classList.remove('mobile-menu-open');
             }
        }
    }, 300);
    manageNavbarOverflow();
}
}

function setupNavbarInteractions() {
if (mobileToggle) {
    mobileToggle.addEventListener('click', () => {
        if (mobileMenu && mobileMenu.classList.contains('open')) {
            closeMobileMenu();
        } else {
            openMobileMenu();
        }
    });
}

// Close mobile menu when clicking on the overlay (background)
if (mobileMenuOverlay) {
    mobileMenuOverlay.addEventListener('click', closeMobileMenu);
}

if (desktopLinksContainer) desktopLinksContainer.addEventListener('click', handleNavbarClick);
if (mobileLinksContainer) mobileLinksContainer.addEventListener('click', handleNavbarClick);

const pressableSelector = '.navbar-links-mobile .navbar-dropdown > .navbar-dropdown-toggle, .navbar-links-mobile a';

function clearPressState(target) {
    if (!target) return;
    target.classList.remove('is-pressing');
    target.removeEventListener('pointerup', clearPressStateFromEvent);
    target.removeEventListener('pointercancel', clearPressStateFromEvent);
    target.removeEventListener('pointerleave', clearPressStateFromEvent);
}

function clearPressStateFromEvent(event) {
    clearPressState(event.currentTarget);
}

function handlePressStart(event) {
    if (!mobileMenu || !mobileMenu.classList.contains('open')) return;
    const pressTarget = event.target.closest(pressableSelector);
    if (!pressTarget) return;

    pressTarget.classList.add('is-pressing');
    pressTarget.addEventListener('pointerup', clearPressStateFromEvent);
    pressTarget.addEventListener('pointercancel', clearPressStateFromEvent);
    pressTarget.addEventListener('pointerleave', clearPressStateFromEvent);
}

function handlePressEnd(event) {
    const pressTarget = event.target.closest(pressableSelector);
    if (!pressTarget) return;
    clearPressState(pressTarget);
}

if (mobileLinksContainer) {
    mobileLinksContainer.addEventListener('pointerdown', handlePressStart);
    mobileLinksContainer.addEventListener('click', handlePressEnd, true);
}

document.addEventListener('click', (event) => {
    if (!event.target.closest('.top-navbar')) {
        closeAllDropdowns();
    }
});
window.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
      if (mobileMenu && mobileMenu.classList.contains('open')) closeMobileMenu();
      closeAllDropdowns();
    }
});

const closeTimeouts = new WeakMap();

desktopLinksContainer.addEventListener('mouseover', (event) => {
    const dropdown = event.target.closest('.navbar-dropdown');
    if (!dropdown) return;

    // Check if this is a nested dropdown (inside another dropdown menu)
    const isNested = dropdown.parentElement.closest('.navbar-dropdown-menu');
    
    // Only auto-open top-level dropdowns on hover
    if (isNested) {
        // For nested dropdowns, just cancel close timeouts but don't auto-open
        let currentDropdown = dropdown;
        while (currentDropdown) {
            if (closeTimeouts.has(currentDropdown)) {
                clearTimeout(closeTimeouts.get(currentDropdown));
                closeTimeouts.delete(currentDropdown);
            }
            // Move up to parent dropdown if it exists
            const parentMenu = currentDropdown.parentElement.closest('.navbar-dropdown-menu');
            currentDropdown = parentMenu ? parentMenu.parentElement : null;
        }
        return; // Don't auto-open nested dropdowns
    }

    // Cancel any pending close timeout for this dropdown and its ancestors
    let currentDropdown = dropdown;
    while (currentDropdown) {
        if (closeTimeouts.has(currentDropdown)) {
            clearTimeout(closeTimeouts.get(currentDropdown));
            closeTimeouts.delete(currentDropdown);
        }
        // Move up to parent dropdown if it exists
        const parentMenu = currentDropdown.parentElement.closest('.navbar-dropdown-menu');
        currentDropdown = parentMenu ? parentMenu.parentElement : null;
    }

    // Open the top-level dropdown if it's not already open
    if (!dropdown.classList.contains('open')) {
        const parent = dropdown.parentElement;
        if (parent) {
            // Only close sibling top-level dropdowns, not nested ones
            const isTopLevelParent = !parent.closest('.navbar-dropdown-menu');
            if (isTopLevelParent) {
                Array.from(parent.children).forEach(sibling => {
                    if (sibling !== dropdown && sibling.classList.contains('navbar-dropdown') && sibling.classList.contains('open')) {
                        sibling.classList.remove('open');
                        // Close nested dropdowns within the sibling top-level dropdown
                        sibling.querySelectorAll('.navbar-dropdown.open').forEach(d => d.classList.remove('open'));
                    }
                });
            }
        }
        dropdown.classList.add('open');
    }
});

desktopLinksContainer.addEventListener('mouseout', (event) => {
    const dropdown = event.target.closest('.navbar-dropdown');
    if (!dropdown) return;

    // Don't close if mouse is moving to a child element within the dropdown
    if (event.relatedTarget && dropdown.contains(event.relatedTarget)) {
        return;
    }

    // For nested dropdowns, they are click-to-open so be more lenient about closing
    const isNested = dropdown.parentElement.closest('.navbar-dropdown-menu');
    if (isNested) {
        const parentDropdown = dropdown.parentElement.closest('.navbar-dropdown-menu').parentElement;
        if (event.relatedTarget && parentDropdown && parentDropdown.contains(event.relatedTarget)) {
            // Mouse moved to parent dropdown area - don't close nested dropdown since it's click-controlled
            return;
        }
        
        // Only close nested dropdowns after a longer delay to avoid accidental closures
        const timeoutId = setTimeout(() => {
            // Double-check that mouse is truly outside the dropdown and parent areas
            if (!dropdown.matches(':hover') && !parentDropdown.matches(':hover')) {
                dropdown.classList.remove('open');
                dropdown.querySelectorAll('.navbar-dropdown.open').forEach(d => d.classList.remove('open'));
            }
            closeTimeouts.delete(dropdown);
        }, 500); // Longer delay for nested dropdowns
        closeTimeouts.set(dropdown, timeoutId);
        return;
    }

    // Standard close timeout
    const timeoutId = setTimeout(() => {
        dropdown.classList.remove('open');
        dropdown.querySelectorAll('.navbar-dropdown.open').forEach(d => d.classList.remove('open'));
        closeTimeouts.delete(dropdown);
    }, 200);
    closeTimeouts.set(dropdown, timeoutId);
});

if (topNavbarElement) {
    topNavbarElement.addEventListener('mouseleave', (event) => {
        if (event.relatedTarget && topNavbarElement.contains(event.relatedTarget)) {
            return;
        }
        closeAllDropdowns();
    });
}
}

function handleNavbarScrollStyle() {
if (!topNavbarElement || !pageHeaderElement) return;
const headerBottom = pageHeaderElement.offsetTop + pageHeaderElement.offsetHeight;
const navbarHeight = topNavbarElement.offsetHeight;

if (window.pageYOffset > (headerBottom - navbarHeight) ) {
    topNavbarElement.classList.add('scrolled');
} else {
    topNavbarElement.classList.remove('scrolled');
}
}

function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
    const context = this;
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(context, args), wait);
};
}

function adjustHeaderTitleSize() {
const h1 = document.querySelector('header h1');
const container = document.querySelector('.header-title-container');

if (!h1 || !container) {
    return;
}

h1.style.whiteSpace = 'nowrap';
h1.style.fontSize = '';

let computedStyleH1 = window.getComputedStyle(h1);
let currentFontSize = parseFloat(computedStyleH1.fontSize);

const MIN_FONT_SIZE_PX = 10;

const containerStyles = window.getComputedStyle(container);
const containerPaddingLeft = parseFloat(containerStyles.paddingLeft);
const containerPaddingRight = parseFloat(containerStyles.paddingRight);
const availableWidthForH1 = container.clientWidth - containerPaddingLeft - containerPaddingRight;

// If header is hidden or has no layout yet, skip resize to avoid tiny text
if (availableWidthForH1 <= 0) {
    h1.style.fontSize = '';
    return;
}

const buffer = 2;

while (h1.scrollWidth > (availableWidthForH1 - buffer) && currentFontSize > MIN_FONT_SIZE_PX) {
    currentFontSize -= 0.5;
    h1.style.fontSize = currentFontSize + 'px';
}

if (currentFontSize < MIN_FONT_SIZE_PX) {
    h1.style.fontSize = MIN_FONT_SIZE_PX + 'px';
}
}
const debouncedAdjustHeader = debounce(adjustHeaderTitleSize, 100);


function updateLoadingProgress(percentage, message, isError = false) {
if (isLoadingError && !isError) return;

const timestamp = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
const logEntry = document.createElement('p');
logEntry.textContent = `[${timestamp}] ${message}`;

if (isError) {
    isLoadingError = true;
    loadingMessageElement.textContent = "Error Occurred";
    errorMessageElement.textContent = message;
    errorMessageElement.style.display = 'block';

    logEntry.classList.add('log-error');

    if (progressBarElement) {
        progressBarElement.style.width = `${percentage}%`;
        progressBarElement.classList.add('error-state');
    }
} else {
    loadingMessageElement.textContent = message;
    if (progressBarElement) {
        progressBarElement.style.width = `${percentage}%`;
        progressBarElement.classList.remove('error-state');
    }
}

if (loadingLogBox) {
    loadingLogBox.appendChild(logEntry);
    loadingLogBox.scrollTop = loadingLogBox.scrollHeight;
}
}

function showCustomLoadingScreen(message) {
isLoadingError = false;
document.body.style.overflow = 'hidden';
try { document.body.classList.add('loading-active'); } catch(_) {}
// Navbar is already black by default, no need to add scrolled class
if (customLoadingOverlay) {
  customLoadingOverlay.style.display = 'flex';
  customLoadingOverlay.style.pointerEvents = 'none'; // keep header/dropdowns usable
  void customLoadingOverlay.offsetWidth;
  customLoadingOverlay.style.opacity = '1';
}
if (controlsElement) {
    controlsElement.classList.remove('loaded');
    controlsElement.style.visibility = 'hidden';
}
if (loadingLogBox) loadingLogBox.innerHTML = '';
updateLoadingProgress(0, message);
}

function hideCustomLoadingScreen() {
if (isLoadingError) {
    if (controlsElement) {
         controlsElement.classList.remove('loaded');
         controlsElement.style.visibility = 'hidden';
    }
    return false;
}

if (mobileMenu && !mobileMenu.classList.contains('open')) {
    document.body.style.overflow = '';
}

// Let handleNavbarScrollStyle determine the navbar state
if (topNavbarElement && !isLoadingError) {
    handleNavbarScrollStyle();
}

if (customLoadingOverlay) {
    customLoadingOverlay.style.opacity = '0';
    customLoadingOverlay.style.pointerEvents = 'none';
    setTimeout(() => {
        if (!isLoadingError) customLoadingOverlay.style.display = 'none';
        try { document.body.classList.remove('loading-active'); } catch(_) {}
    }, 500);
}
return true;
}

function isElementInViewport(el) {
const rect = el.getBoundingClientRect();
return rect.top < window.innerHeight && rect.bottom > 0;
}

function animateBubblesIn(containerSelector) {
const container = document.querySelector(containerSelector);
if (!container) return 0;

const bubblesInDom = container.querySelectorAll('.value-bubble, .no-items-found-message');
const staggerDelay = 24; // Slightly faster to reduce perceived lag
const transitionDuration = 250; // Corresponds to 0.25s in CSS
const maxDelay = 1000; // Prevent excessive delays for bubbles far down the list

const visibleBubbles = [];
bubblesInDom.forEach(bubble => {
    if (isElementInViewport(bubble)) {
        visibleBubbles.push(bubble);
    } else {
        bubble.classList.add('visible');
    }
});

visibleBubbles.forEach((bubble, index) => {
    const delay = Math.min(index * staggerDelay, maxDelay);
    setTimeout(() => {
        bubble.classList.add('visible');
    }, delay);
});

if (visibleBubbles.length === 0) {
    container.classList.remove('sorting');
    return 0;
}

container.classList.remove('sorting');
return ((visibleBubbles.length - 1) * staggerDelay) + transitionDuration;
}

function animateBubblesOut(containerSelector) {
const container = document.querySelector(containerSelector);
if (!container) return 350;

const itemsInDom = container.querySelectorAll('.value-bubble, .no-items-found-message');
// Row-based stagger to match OG item finder
const rowStagger = 60; // delay between rows (ms)
const transitionDuration = 350; // match CSS fade-out (0.35s)
const maxDelay = 600;

// Build rows of visible items using their top position
const rows = new Map();
const tolerance = 2; // px tolerance for grouping

itemsInDom.forEach(item => {
  const rect = item.getBoundingClientRect();
  // Immediately hide anything off-screen to avoid needless animation
  if (rect.top >= window.innerHeight || rect.bottom <= 0) {
    item.classList.remove('visible');
    return;
  }
  const top = Math.round(rect.top / tolerance) * tolerance;
  if (!rows.has(top)) rows.set(top, []);
  rows.get(top).push(item);
});

// Sort row keys by visual order (top ascending) and schedule fade-outs
const rowKeys = Array.from(rows.keys()).sort((a, b) => a - b);
rowKeys.forEach((key, rowIndex) => {
  const delay = Math.min(rowIndex * rowStagger, maxDelay);
  const rowItems = rows.get(key) || [];
  rowItems.forEach(item => {
    setTimeout(() => { item.classList.remove('visible'); }, delay);
  });
});

const rowsCount = rowKeys.length;
return rowsCount > 0 ? ((rowsCount - 1) * rowStagger) + transitionDuration : transitionDuration;
}

// Items count utilities (adapted from OG Item Finder)
const __itemsCountDefaultDuration = 350;
let __itemsCountRaf = 0;
const __itemsCountLast = { showing: 0, total: 0 };
function restartItemsCountAnimation() {
const el = document.getElementById('ItemsCount');
if (!el) return;
el.classList.remove('anim-fade-in');
void el.offsetWidth;
el.classList.add('anim-fade-in');
}
function __renderItemsCount(showing, total) {
const el = document.getElementById('ItemsCount');
if (!el) return;
el.innerHTML = `Showing <strong>${showing}</strong> out of <strong>${total}</strong> items.`;
try {
  el.style.setProperty('color', '#b0b0b0', 'important');
  el.querySelectorAll('strong').forEach(s => s.style.setProperty('color', '#b0b0b0', 'important'));
} catch (_) { /* no-op */ }
}
function updateItemsCount(targetShowing, targetTotal, duration = __itemsCountDefaultDuration) {
const el = document.getElementById('ItemsCount');
if (!el) return;
restartItemsCountAnimation();
if (__itemsCountRaf) { cancelAnimationFrame(__itemsCountRaf); __itemsCountRaf = 0; }
const start = performance.now();
const fromShowing = Number.isFinite(__itemsCountLast.showing) ? __itemsCountLast.showing : 0;
const fromTotal = Number.isFinite(__itemsCountLast.total) ? __itemsCountLast.total : 0;
const toShowing = Number.isFinite(targetShowing) ? targetShowing : 0;
const toTotal = Number.isFinite(targetTotal) ? targetTotal : 0;
if (fromShowing === toShowing && fromTotal === toTotal) {
  __renderItemsCount(toShowing, toTotal);
  return;
}
const step = (now) => {
  const t = Math.max(0, Math.min(1, (now - start) / duration));
  const curShowing = Math.round(fromShowing + (toShowing - fromShowing) * t);
  const curTotal = Math.round(fromTotal + (toTotal - fromTotal) * t);
  __renderItemsCount(curShowing, curTotal);
  __itemsCountLast.showing = curShowing;
  __itemsCountLast.total = curTotal;
  if (t < 1) {
    __itemsCountRaf = requestAnimationFrame(step);
  }
};
__itemsCountRaf = requestAnimationFrame(step);
}

function initiatePageReveal() {
if (!hideCustomLoadingScreen()) return;

const headerElement = document.getElementById('pageHeader');
const controlsElement = document.getElementById('LIMenuContainer');
const bubblesContainer = document.getElementById('LIBubblesContainer');
const topNavbar = document.getElementById('topNavbar');
const submissionInfoEl = document.querySelector('.discord-submission-info');


// Trigger header and navbar animations together after loading screen fades
if (headerElement && topNavbar) {
    setTimeout(() => {
        adjustHeaderTitleSize();
        headerElement.classList.add('loaded');
        topNavbar.classList.add('loaded');
    }, 500); // Wait for overlay fade-out and header image load
} else {
    if (!headerElement) console.error('pageHeader element not found!');
    if (!topNavbar) console.error('topNavbar element not found!');
}

// Trigger controls animation after header
if (controlsElement) {
    setTimeout(() => {
        controlsElement.style.visibility = 'visible';
        controlsElement.classList.add('loaded');
    }, 700);
} else {
    console.error('LIMenuContainer element not found!');
}

// Setup bubble animations and enable controls after controls are visible
setTimeout(() => {
    if (bubblesContainer) {
        bubblesContainer.style.opacity = '1';
        bubblesContainer.style.transform = 'translateY(0)';
    }
    if (submissionInfoEl && !(window.userSettings && window.userSettings.hideSubmissionInfo)) {
        submissionInfoEl.style.opacity = '1';
        submissionInfoEl.style.transform = 'translateY(0)';
    }
    // Allow items count to reveal only after components are in place
    try { document.body.classList.add('count-reveal-allowed'); } catch(_) {}
    setupBubbleAnimationObserver();
    setupImageClickEvents();
    setupDescriptionClickEvents();
    enableControls();
    isInitialLoad = false;
}, 700);
}
function normalizeName(name) {
return name.toLowerCase()
  .replace(/[\s-]/g, "")
  .replace("level", "lvl")
  .replace(/^og\|/, "");
}

async function fetchFrequencyData() {
updateLoadingProgress(10, "Connecting to server: Requesting latest demand statistics...");
let timeoutId;

const timeoutPromise = new Promise((_, reject) => {
  timeoutId = setTimeout(() => {
    reject(new Error("Timeout: Failed to load demand data within 30 seconds"));
  }, 30000);
});

try {
  const fetchPromise = fetch('https://system.jailbreaktradingnetwork.com/demand-data', {
    cache: 'no-store'
  }).then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status} (Demand Data)`);
    }
    return response.json();
  });

  const data = await Promise.race([fetchPromise, timeoutPromise]);
  clearTimeout(timeoutId);

  frequencyData = {};
  data.forEach(item => {
    if (item.Name && !excludedItems.includes(item.Name) && item.Type) {
      const key = `${normalizeName(item.Name)}|${item.Type}`;
      frequencyData[key] = {
        Name: item.Name,
        UniqueCirculation: item.UniqueCirculation || 0,
        TimesTraded: item.TimesTraded || 0,
        DemandMultiple: Math.min(item.DemandMultiple || 0, 10.00),
        Type: item.Type
      };
    }
  });
  updateLoadingProgress(40, "Connection successful: Demand statistics processed.");
} catch (error) {
  clearTimeout(timeoutId);
  console.error('Error fetching frequency data:', error);
  const errorMessage = error.message.includes("Timeout")
    ? "Error: Failed to load the database (Demand Data Timeout)."
    : `Error: Failed to load demand data. (${error.message})`;
  updateLoadingProgress(10, errorMessage, true);
  throw error;
}
}

async function fetchVehiclesData() {
const headerTitleElement = document.querySelector('header h2');
const headerTitle = headerTitleElement ? (headerTitleElement.dataset.valueType || headerTitleElement.textContent.trim()) : "Vehicle Values";

// Check if this is an "All Values" page
if (headerTitle === "All Values") {
  return await fetchAllValuesData();
}

const endpoint = apiEndpoints[headerTitle];

if (!endpoint) {
  console.error('No matching endpoint for header title:', headerTitle);
  const errorMsg = "Error: Invalid data endpoint.";
  updateLoadingProgress(40, errorMsg, true);
  throw new Error(errorMsg);
}

updateLoadingProgress(50, `Connecting to database: Fetching ${headerTitle.toLowerCase()} data...`);
let timeoutId;

const timeoutPromise = new Promise((_, reject) => {
  timeoutId = setTimeout(() => {
    reject(new Error(`Timeout: Failed to load ${headerTitle.toLowerCase()} data within 30 seconds`));
  }, 30000);
});

try {
  const fetchPromise = fetch(endpoint, {
    cache: 'no-store'
  }).then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status} (${headerTitle} Data)`);
    }
    return response.json();
  });

  const data = await Promise.race([fetchPromise, timeoutPromise]);
  clearTimeout(timeoutId);

  updateLoadingProgress(80, `Connection successful: ${headerTitle.toLowerCase()} data processed.`);
  return data.map(item => ({
    name: item.name || "Unknown",
    nickname: item.nickname || item.name,
    type: item.type || "unknown",
    image: item.image || "https://via.placeholder.com/250",
    originalPrice: item.originalPrice || "N/A",
    topSpeed: item.topSpeed || "N/A",
    vehicleHealth: item.vehicleHealth || "N/A",
    seasonPass: item.seasonPass || "N/A",
    robberyType: item.robberyType || "N/A",
    collectorRarity: item.collectorRarity || "N/A",
    dupedValue: item.dupedValue || "N/A",
    tradingValue: item.tradingValue || "N/A",
    explanation: item.explanation || item.description || "No description available.",
    blogPost: item.blogPost || "",
    writtenArticle: item.writtenArticle || "",
    wikiPage: item.wikiPage || "",
    timeStamp: item.timeStamp || null,
    category: headerTitle // Add category for identification
  }));
} catch (error) {
  clearTimeout(timeoutId);
  console.error('Error fetching vehicles data from', endpoint, ':', error);
  const errorMessage = error.message.includes("Timeout")
    ? `Error: Failed to load the database (${headerTitle} Data Timeout).`
    : `Error: Failed to load ${headerTitle.toLowerCase()} data. (${error.message})`;
  updateLoadingProgress(50, errorMessage, true);
  throw error;
}
}

async function fetchAllValuesData() {
updateLoadingProgress(50, "Connecting to database: Fetching all values data...");

const endpointEntries = Object.entries(apiEndpoints);
const totalEndpoints = endpointEntries.length;
let completedEndpoints = 0;
let allData = [];

const fetchPromises = endpointEntries.map(async ([category, endpoint]) => {
  try {
    const response = await fetch(endpoint, { cache: 'no-store' });
    if (!response.ok) {
      return [];
    }
    
    const data = await response.json();
    completedEndpoints++;
    
    // Update progress as each endpoint completes
    const progress = 50 + (completedEndpoints / totalEndpoints) * 30; // 50-80% range
    updateLoadingProgress(progress, `Loaded ${category.toLowerCase()}... (${completedEndpoints}/${totalEndpoints})`);
    
    return data.map(item => ({
      name: item.name || "Unknown",
      nickname: item.nickname || item.name,
      type: item.type || "unknown",
      image: item.image || "https://via.placeholder.com/250",
      originalPrice: item.originalPrice || "N/A",
      topSpeed: item.topSpeed || "N/A",
      vehicleHealth: item.vehicleHealth || "N/A",
      seasonPass: item.seasonPass || "N/A",
      robberyType: item.robberyType || "N/A",
      collectorRarity: item.collectorRarity || "N/A",
      dupedValue: item.dupedValue || "N/A",
      tradingValue: item.tradingValue || "N/A",
      explanation: item.explanation || item.description || "No description available.",
      blogPost: item.blogPost || "",
      writtenArticle: item.writtenArticle || "",
      wikiPage: item.wikiPage || "",
      timeStamp: item.timeStamp || null,
      category: category // Add category for identification
    }));
  } catch (error) {
    
    completedEndpoints++;
    const progress = 50 + (completedEndpoints / totalEndpoints) * 30;
    updateLoadingProgress(progress, `Failed to load ${category.toLowerCase()}... (${completedEndpoints}/${totalEndpoints})`);
    return [];
  }
});

try {
  const results = await Promise.all(fetchPromises);
  allData = results.flat();
  
  updateLoadingProgress(80, `Connection successful: All values data processed (${allData.length} items total).`);
  return allData;
} catch (error) {
  console.error('Error fetching all values data:', error);
  const errorMessage = `Error: Failed to load all values data. (${error.message})`;
  updateLoadingProgress(50, errorMessage, true);
  throw error;
}
}

function getDemandLabel(score) {
score = Math.min(score, 10.00);

// Format score to show 10.0 instead of 10.00
const formatScore = (num) => {
  if (num === 10) {
    return '10.0';
  }
  return num.toFixed(2);
};

if (score <= 1.5) {
    return ` ⭐ ${formatScore(score)} | Very Low`;
} else if (score <= 2.5) {
    return ` ⭐ ${formatScore(score)} | Low`;
} else if (score <= 5.0) {
    return ` ⭐ ${formatScore(score)} | Medium`;
} else if (score <= 6.0) {
    return ` ⭐ ${formatScore(score)} | High`;
} else {
    return ` ⭐ ${formatScore(score)} | Very High`;
}
}

function getStatusIcon(type) {
switch(type.toLowerCase()) {
  case "limited": return `<div class="status-label"><i class="fas fa-clock"></i> Season Limited</div>`;
  case "obtainable": return `<div class="status-label"><i class="fas fa-shopping-cart"></i> Obtainable Item</div>`;
  case "event-exclusive": return `<div class="status-label"><i class="fas fa-ticket-alt"></i> Event Exclusive</div>`;
  case "safe": return `<div class="status-label"><i class="fas fa-vault"></i> Vault Exclusive</div>`;
  case "retired": return `<div class="status-label"><i class="fas fa-archive"></i> Retired Item</div>`;
  case "reference": return `<div class="status-label"><i class="fas fa-book"></i> Reference Only</div>`;
  default: return `<div class="status-label"><i class="fas fa-question-circle"></i> Unknown Type</div>`;
}
}

function formatItemUpdateTime(isoTimestampString) {
  if (!isoTimestampString) {
      return "N/A (Not Available)";
  }

  const updatedDate = new Date(isoTimestampString);
  if (isNaN(updatedDate.getTime())) {
      return "N/A (Not Available)";
  }

  const now = new Date();
  const diffMilliseconds = now - updatedDate;

  const monthStr = (updatedDate.getMonth() + 1).toString().padStart(2, '0');
  const dayStr = updatedDate.getDate().toString().padStart(2, '0');
  const yearStr = updatedDate.getFullYear();
  const datePart = `${monthStr}/${dayStr}/${yearStr}`;

  let relativeTimePart;

  if (diffMilliseconds < 0) {
      relativeTimePart = "(Recently updated)";
  } else {
      const seconds = Math.floor(diffMilliseconds / 1000);
      const minutes = Math.floor(seconds / 60);
      const hours = Math.floor(minutes / 60);
      const days = Math.floor(hours / 24);

      const months = Math.floor(days / 30);
      const years = Math.floor(months / 12);

      if (years >= 1) {
          relativeTimePart = `(${years} year${years > 1 ? 's' : ''} ago)`;
      } else if (months >= 1) {
          relativeTimePart = `(${months} month${months > 1 ? 's' : ''} ago)`;
      } else if (days >= 1) {
          relativeTimePart = `(${days} day${days > 1 ? 's' : ''} ago)`;
      } else if (hours >= 1) {
          relativeTimePart = `(${hours} hour${hours > 1 ? 's' : ''} ago)`;
      } else {
          relativeTimePart = "(1 hour ago)";
      }
  }
  return `${datePart} ${relativeTimePart}`;
}



function replaceEmojisWithIcons(text) {
if (typeof text !== 'string') return text;

// First handle specific text-based replacements for contextual icons
let result = text
  // Handle specific Pass/Reward items
  .replace(/🎟️ Pass Exclusive/g, '<i class="fas fa-id-card" style="margin-right: 4px;"></i> Pass Exclusive')
  .replace(/🎟️ Free Reward/g, '<i class="fas fa-gift" style="margin-right: 4px;"></i> Free Reward')
  // Handle specific robbery/heist items
  .replace(/🏦 All Hyper 5's/g, '<i class="fas fa-layer-group" style="margin-right: 4px;"></i> All Hyper 5\'s')
  .replace(/🏦 All Hyper 4's/g, '<i class="fas fa-layer-group" style="margin-right: 4px;"></i> All Hyper 4\'s')
  .replace(/🏦 Cargo Plane/g, '<i class="fas fa-plane" style="margin-right: 4px;"></i> Cargo Plane')
  .replace(/🏦 Jewelry Store/g, '<i class="fas fa-gem" style="margin-right: 4px;"></i> Jewelry Store')
  .replace(/🏦 Crown Jewel/g, '<i class="fas fa-dice" style="margin-right: 4px;"></i> Crown Jewel')
  .replace(/🏦 Tomb Heist/g, '<i class="fas fa-gopuram" style="margin-right: 4px;"></i> Tomb Heist')
  .replace(/🏦 Power Plant/g, '<i class="fas fa-radiation" style="margin-right: 4px;"></i> Power Plant')
  .replace(/🏦 Museum Heist/g, '<i class="fas fa-university" style="margin-right: 4px;"></i> Museum Heist')
  .replace(/🏦 Bank Heist/g, '<i class="fas fa-university" style="margin-right: 4px;"></i> Bank Heist')
  .replace(/🏦 Train Heists/g, '<i class="fas fa-train" style="margin-right: 4px;"></i> Train Heists')
  // Handle remaining Unicode sequences
  // Bank/building (🏦) generic surrogate pair maps to money sack by default
  .replace(/\ud83c\udfe6/g, '<i class="fas fa-sack-dollar" style="margin-right: 4px;"></i>')
  .replace(/\ud83c\udf9f\ufe0f/g, '<i class="fas fa-ticket-alt" style="margin-right: 4px;"></i>')
  .replace(/\ud83c\udf9f/g, '<i class="fas fa-ticket-alt" style="margin-right: 4px;"></i>');

  const replacements = {
    '💰': '<i class="fas fa-dollar-sign" style="margin-right: 4px;"></i>',
    '💸': '<i class="fas fa-money-bill-wave" style="margin-right: 4px;"></i>',
  '🏎️': '<i class="fas fa-tachometer-alt" style="margin-right: 4px;"></i>',
  '⚠️': '<i class="fas fa-exclamation-triangle" style="margin-right: 4px; color: #f5c542;"></i>',
  '⚙️': '<i class="fas fa-cog" style="margin-right: 4px;"></i>',
  '🛡️': '<i class="fas fa-shield-alt" style="margin-right: 4px;"></i>',
  '❓': '<i class="fas fa-question-circle" style="margin-right: 4px;"></i>',
  '🤝': '<i class="fas fa-handshake" style="margin-right: 4px;"></i>',
  '🔁': '<i class="fas fa-sync-alt" style="margin-right: 4px;"></i>',
  '🌟': '<i class="fas fa-star" style="margin-right: 4px;"></i>',
  '🔎': '<i class="fas fa-search" style="margin-right: 4px;"></i>',
  '🛠️': '<i class="fas fa-tools" style="margin-right: 4px;"></i>',
  '🔍': '<i class="fas fa-search" style="margin-right: 4px;"></i>',
  '💥': '<i class="fas fa-fire" style="margin-right: 4px;"></i>',
  '🔥': '<i class="fas fa-fire" style="margin-right: 4px;"></i>',
  '🎟️': '<i class="fas fa-ticket-alt" style="margin-right: 4px;"></i>',
  '🎟': '<i class="fas fa-ticket-alt" style="margin-right: 4px;"></i>',
  '\ud83c\udf9f\ufe0f': '<i class="fas fa-ticket-alt" style="margin-right: 4px;"></i>',
  '\ud83c\udf9f': '<i class="fas fa-ticket-alt" style="margin-right: 4px;"></i>',
  // Bank emoji (🏦) defaults to money sack; vault icon applied contextually elsewhere
  '🏦': '<i class="fas fa-sack-dollar" style="margin-right: 4px;"></i>',
  '🖥️': '<i class="fas fa-desktop" style="margin-right: 4px;"></i>',
  '📊': '<i class="fas fa-chart-bar" style="margin-right: 4px;"></i>',
  '⭐': '<i class="fas fa-star" style="margin-right: 4px;"></i>'
};

const emojiRegex = /(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])\ufe0f?/g;

return result.replace(emojiRegex, (emoji) => {
  const key = emoji.replace(/\ufe0f/g, '');
  return replacements[emoji] || replacements[key] || emoji;
});
}

function getVehiclePriceLabel(item) {
if (!item) return "Original Price";
const price = item.originalPrice || "";
if (item.type && item.type.toLowerCase() === "safe") {
  return "Vault Reward";
} else if (price.includes("Level") || price.includes("%")) {
  return "Season Reward";
} else if (price.includes("*") || price.includes("FREE")) {
  return "Obtainable Price";
} else if (price.includes("CEO") || price.includes("NASCAR") ||
           price.includes("SWAT") || price.includes("F1") ||
           price.includes("BOSS") || price.includes("OG Live") ||
           price.includes("$1,000,000,000")) {
  return "Requirement";
}
return "Original Price";
}

function getTexturePriceLabel(item) {
if (!item) return "Original Price";
const price = item.originalPrice || "";
if (item.type && item.type.toLowerCase() === "safe") {
  return "Vault Reward";
} else if (price.includes("XP") || price.includes("Level 15") || price.includes("Level 25") || price.includes("Level 30") || price.includes("Level 45") || price.includes("Level 50") || price.includes("Level")) {
  return "Season Reward";
} else if (price.includes("*")) {
  return "Obtainable Price";
} else if (price.includes("Robux")) {
  return "Testing Access";
} else if (price.includes("Code") || price.includes("Beta") || price.includes("Graffiti")) {
  return "Requirement";
}
return "Original Price";
}

function getColorPriceLabel(item) {
if (!item) return "Original Price";
const price = item.originalPrice || "";
if (item.type && item.type.toLowerCase() === "safe") {
  return "Vault Reward";
} else if (price.includes("Level") || price.includes("%")) {
  return "Season Reward";
} else if (price.includes("Owner") || price.includes("%")) {
  return "Requirement";
} else if (price.includes("Heists") || price.includes("%")) {
  return "Pity Chance";
} else if (price.includes("Hyper") || price.includes("%")) {
  return "Requirements";
} else if (price.includes("Release") || price.includes("%")) {
  return "Requirement";
} else if (price.includes("to") || price.includes("%")) {
  return "Nuke Reward";
} else if (price.includes("*") || price.includes("%")) {
  return "Obtainable Price";
}
return "Original Price";
}

function getSpoilerPriceLabel(item) {
if (!item) return "Original Price";
const price = item.originalPrice || "";
if (item.type && item.type.toLowerCase() === "safe") {
  return "Vault Reward";
} else if (
  price.includes("XP") ||
  price.includes("Level 15") ||
  price.includes("Level 25") ||
  price.includes("Level 30") ||
  price.includes("Level 45") ||
  price.includes("Level 50") ||
  price.includes("Level") ||
  price.includes("%")
) {
  return "Season Reward";
} else if (price.includes("Event") || price.includes("Release") || price.includes("Storage") || price.includes("Redeem") || price.includes("CEO Reward") || price.includes("Tomb Reward")) {
  return "Requirement";
} else if (price.includes("Hyper")) {
  return "Requirements";
} else if (price.includes("*")) {
  return "Obtainable Price";
} else if (price.includes("to")) {
  return "Soccer Goal";
}
return "Original Price";
}

function getRimPriceLabel(item) {
if (!item) return "Original Price";
const price = item.originalPrice || "";
if (item.type && item.type.toLowerCase() === "safe") {
  return "Vault Reward";
} else if (
  price.includes("Level 15") ||
  price.includes("Level 25") ||
  price.includes("Level 30") ||
  price.includes("Level 45") ||
  price.includes("Level 50") ||
  price.includes("Level 40") ||
  price.includes("Level 20") ||
  price.includes("Level 10") ||
  price.includes("XP") ||
  price.includes("Level") ||
  price.includes("%")
) {
  return "Season Reward";
} else if (
  price.includes("5/'17 to 6/'17") ||
  price.includes("06/'18 to 6/'18") ||
  price.includes("4/'20 to 5/'21")
) {
  return "Vault Reward";
} else if (
  price.includes("MVP") ||
  price.includes("Event") ||
  price.includes("Release") ||
  price.includes("Storage") ||
  price.includes("Redeem") ||
  price.includes("CEO Reward") ||
  price.includes("Tomb Reward") ||
  price.includes("Scavenger")
) {
  return "Requirement";
} else if (price.includes("Hyper")) {
  return "Requirements";
} else if (price.includes("*")) {
  return "Obtainable Price";
} else if (price.includes("to")) {
  return "Soccer Goal";
}
return "Original Price";
}

function getTirePriceLabel(item) {
if (!item) return "Original Price";
const price = item.originalPrice || "";
if (item.type && item.type.toLowerCase() === "safe") {
  return "Vault Reward";
} else if (
  price.includes("Level 15") ||
  price.includes("Level 25") ||
  price.includes("Level 30") ||
  price.includes("Level 45") ||
  price.includes("Level 50") ||
  price.includes("Level 40") ||
  price.includes("Level 20") ||
  price.includes("Level 10") ||
  price.includes("XP") ||
  price.includes("Level") ||
  price.includes("%")
) {
  return "Season Reward";
} else if (
  price.includes("5/'17 to 6/'17") ||
  price.includes("06/'18 to 6/'18") ||
  price.includes("4/'20 to 5/'21")
) {
  return "Vault Reward";
} else if (price.includes("FREE Tires")) {
  return "Obtainable Price";
} else if (
  price.includes("MVP") ||
  price.includes("Event") ||
  price.includes("Release") ||
  price.includes("Storage") ||
  price.includes("Redeem") ||
  price.includes("CEO Reward") ||
  price.includes("Tomb Reward") ||
  price.includes("Scavenger") ||
  price.includes("SWAT Van Toy")
) {
  return "Requirement";
} else if (price.includes("Hyper")) {
  return "Requirements";
} else if (price.includes("*")) {
  return "Obtainable Price";
} else if (price.includes("to")) {
  return "Soccer Goal";
}
return "Original Price";
}

function getGunTexturePriceLabel(item) {
if (!item) return "Original Price";
const price = item.originalPrice || "";
if (item.type && item.type.toLowerCase() === "safe") {
  return "Vault Reward";
} else if (
  price.includes("Level 15") ||
  price.includes("Level 25") ||
  price.includes("Level 30") ||
  price.includes("Level 45") ||
  price.includes("Level 50") ||
  price.includes("Level 40") ||
  price.includes("Level 20") ||
  price.includes("Level 10") ||
  price.includes("XP") ||
  price.includes("Level") ||
  price.includes("%")
) {
  return "Season Reward";
} else if (
  price.includes("5/'17 to 6/'17") ||
  price.includes("06/'18 to 6/'18") ||
  price.includes("4/'20 to 5/'21")
) {
  return "Vault Reward";
} else if (price.includes("FREE Tires")) {
  return "Obtainable Price";
} else if (
  price.includes("MVP") ||
  price.includes("Event") ||
  price.includes("Release") ||
  price.includes("Storage") ||
  price.includes("Redeem") ||
  price.includes("CEO Reward") ||
  price.includes("Tomb Reward") ||
  price.includes("Scavenger") ||
  price.includes("VIP Pass")
) {
  return "Requirement";
} else if (price.includes("Hyper")) {
  return "Requirements";
} else if (price.includes("*")) {
  return "Obtainable Price";
} else if (price.includes("to")) {
  return "Soccer Goal";
}
return "Original Price";
}

function getVehicleHornPriceLabel(item) {
if (!item) return "Original Price";
const price = item.originalPrice || "";
if (item.type && item.type.toLowerCase() === "safe") {
  return "Vault Reward";
} else if (
  price.includes("Level 15") ||
  price.includes("Level 25") ||
  price.includes("Level 30") ||
  price.includes("Level 45") ||
  price.includes("Level 50") ||
  price.includes("Level 40") ||
  price.includes("Level 20") ||
  price.includes("Level 10") ||
  price.includes("XP") ||
  price.includes("Level") ||
  price.includes("%")
) {
  return "Season Reward";
} else if (
  price.includes("5/'17 to 6/'17") ||
  price.includes("06/'18 to 6/'18") ||
  price.includes("4/'20 to 5/'21")
) {
  return "Vault Reward";
} else if (
  price.includes("MVP") ||
  price.includes("Event") ||
  price.includes("Release") ||
  price.includes("Storage") ||
  price.includes("Redeem") ||
  price.includes("CEO Reward") ||
  price.includes("Injan") ||
  price.includes("VIP Pass")
) {
  return "Requirement";
} else if (
  price.includes("FREE Tires") ||
  price.includes("FREE") ||
  price.includes("*")
) {
  return "Obtainable Price";
} else if (price.includes("Hyper")) {
  return "Requirements";
} else if (price.includes("to")) {
  return "Soccer Goal";
}
return "Original Price";
}
function getFurniturePriceLabel(item) {
if (!item) return "Original Price";
const price = item.originalPrice || "";
if (item.type && item.type.toLowerCase() === "safe") {
  return "Vault Reward";
} else if (price.includes("Level") || price.includes("%")) {
  return "Season Reward";
} else if (price.includes("*") || price.includes("FREE")) {
  return "Obtainable Price";
} else if (
  price.includes("CEO") ||
  price.includes("NASCAR") ||
  price.includes("SWAT") ||
  price.includes("F1") ||
  price.includes("BOSS") ||
  price.includes("OG Live") ||
  price.includes("$1,000,000,000")
) {
  return "Requirement";
}
return "Original Price";
}

function getDriftParticlePriceLabel(item) {
if (!item) return "Original Price";
const price = item.originalPrice || "";
if (item.type && item.type.toLowerCase() === "safe") {
  return "Vault Reward";
} else if (
  price.includes("Level 15") ||
  price.includes("Level 25") ||
  price.includes("Level 30") ||
  price.includes("Level 45") ||
  price.includes("Level 50") ||
  price.includes("Level 40") ||
  price.includes("Level 20") ||
  price.includes("Level 10") ||
  price.includes("XP") ||
  price.includes("Level") ||
  price.includes("%")
) {
  return "Season Reward";
} else if (
  price.includes("5/'17 to 6/'17") ||
  price.includes("06/'18 to 6/'18") ||
  price.includes("4/'20 to 5/'21")
) {
  return "Vault Reward";
} else if (
  price.includes("MVP") ||
  price.includes("Event") ||
  price.includes("Release") ||
  price.includes("Storage") ||
  price.includes("Redeem") ||
  price.includes("CEO Reward") ||
  price.includes("Crew") ||
  price.includes("Minifigure") ||
  price.includes("Injan") ||
  price.includes("VIP Pass")
) {
  return "Requirement";
} else if (
  price.includes("FREE Tires") ||
  price.includes("FREE") ||
  price.includes("*")
) {
  return "Obtainable Price";
} else if (price.includes("Hyper")) {
  return "Requirements";
} else if (price.includes("to")) {
  return "Soccer Goal";
}
return "Original Price";
}
function createBubble(vehicle) {
let originalPriceDisplay = replaceEmojisWithIcons(vehicle.originalPrice === "N/A" ? "Not Available ❓" : vehicle.originalPrice);
let priceLabel;
if (vehicle.category && vehicle.category.includes("Gun Texture")) {
  priceLabel = getGunTexturePriceLabel(vehicle);
} else if (vehicle.category && vehicle.category.includes("Texture")) {
  priceLabel = getTexturePriceLabel(vehicle);
} else if (vehicle.category && vehicle.category.includes("Color")) {
  priceLabel = getColorPriceLabel(vehicle);
} else if (vehicle.category && vehicle.category.includes("Spoiler")) {
  priceLabel = getSpoilerPriceLabel(vehicle);
} else if (vehicle.category && vehicle.category.includes("Rim")) {
  priceLabel = getRimPriceLabel(vehicle);
} else if (vehicle.category && vehicle.category.includes("Tire")) {
  priceLabel = getTirePriceLabel(vehicle);
} else if (vehicle.category && vehicle.category.includes("Vehicle Horn")) {
  priceLabel = getVehicleHornPriceLabel(vehicle);
} else if (vehicle.category && vehicle.category.includes("Furniture")) {
  priceLabel = getFurniturePriceLabel(vehicle);
} else if (vehicle.category && vehicle.category.includes("Drift Particle")) {
  priceLabel = getDriftParticlePriceLabel(vehicle);
} else {
  priceLabel = getVehiclePriceLabel(vehicle);
}

if (priceLabel === "Season Reward") {
  originalPriceDisplay = originalPriceDisplay.replace('fa-search', 'fa-clock');
}

// If this item is marked as a Soccer Goal reward and the price text contains
// a date range like "5/'17 to 6/'17", ensure the leading icon is a soccer ball.
// Replace any existing leading icon or insert one if missing.
if (priceLabel === "Soccer Goal") {
  const hasToRange = typeof vehicle.originalPrice === 'string' && /\bto\b/i.test(vehicle.originalPrice);
  if (hasToRange) {
    const soccerIcon = '<i class="fas fa-futbol" style="margin-right: 4px;"></i>';
    // If there is already a leading <i> icon, replace just the first one; otherwise prepend
    if (/^\s*<i[^>]*><\/i>/.test(originalPriceDisplay)) {
      originalPriceDisplay = originalPriceDisplay.replace(/^\s*<i[^>]*><\/i>/, soccerIcon);
    } else if (!/fa-futbol/.test(originalPriceDisplay)) {
      originalPriceDisplay = soccerIcon + originalPriceDisplay;
    }
  }
}

// Contextual icon correction: for Vault Reward items only, if the value text mentions
// Tier 1-5 Safes, swap any money icons to a vault icon to avoid confusion.
try {
  if ((vehicle.type || '').toLowerCase() === 'safe' && /Tier\s*[1-5]\s*Safes?/i.test(originalPriceDisplay)) {
    originalPriceDisplay = originalPriceDisplay
      .replace(/fa-dollar-sign/g, 'fa-vault')
      .replace(/fa-sack-dollar/g, 'fa-vault');
  }
} catch(_) { /* no-op */ }


const statusBadge = getStatusIcon(vehicle.type);
const hasExplanation = (vehicle.blogPost && vehicle.blogPost.trim() !== "") || (vehicle.writtenArticle && vehicle.writtenArticle.trim() !== "");
const headerTitleElement = document.querySelector('header h2');
const currentHeaderTitleText = headerTitleElement ? (headerTitleElement.dataset.valueType || headerTitleElement.textContent.trim()) : "Vehicle Values";

const lookupName = normalizeName(vehicle.nickname || vehicle.name);

// For All Values page, use the item's category to determine the expected type
let expectedType;
if (currentHeaderTitleText === "All Values" && vehicle.category) {
  expectedType = demandTypeMappings[vehicle.category];
} else {
  expectedType = demandTypeMappings[currentHeaderTitleText];
}

let freqItem = null;
if (expectedType) {
  const key = Array.isArray(expectedType)
    ? expectedType.map(type => `${lookupName}|${type}`).find(k => frequencyData[k])
    : `${lookupName}|${expectedType}`;
  freqItem = frequencyData[key] || null;
}

const score = freqItem ? freqItem.DemandMultiple : 0;
const demandLabel = replaceEmojisWithIcons(freqItem ? getDemandLabel(score) : " 🌟 Unavailable");
const timesTraded = replaceEmojisWithIcons(freqItem && freqItem.TimesTraded ? ` 🤝 ${Number(freqItem.TimesTraded).toLocaleString('en-US')} Trades` : " 🤝 Unavailable");

const tradingValueDisplay = replaceEmojisWithIcons(vehicle.tradingValue === "N/A" ? " 💸 Not Available" : vehicle.tradingValue);
const dupedValueDisplay = replaceEmojisWithIcons(vehicle.dupedValue === "N/A" ? " ⚠️ Not Available" : vehicle.dupedValue);

let statsHtml;
const seasonPassVal = replaceEmojisWithIcons(vehicle.seasonPass);
const robberyTypeVal = replaceEmojisWithIcons(vehicle.robberyType);
const collectorRarityDisplay = replaceEmojisWithIcons(vehicle.collectorRarity === "N/A" ? "Not Available ❓" : vehicle.collectorRarity);

if (vehicle.category === "Color Values") {
    let detailsHtmlArray = [];

    if (seasonPassVal !== "N/A") {
        detailsHtmlArray.push(`<span>Season Pass: <span class="season-pass">${seasonPassVal}</span></span>`);
        if (robberyTypeVal !== "N/A") {
            detailsHtmlArray.push(`<span>Robbery Type: <span class="robbery-type">${robberyTypeVal}</span></span>`);
        }
    } else if (robberyTypeVal !== "N/A") {
        detailsHtmlArray.push(`<span>Robbery Type: <span class="robbery-type">${robberyTypeVal}</span></span>`);
    } else {
        detailsHtmlArray.push(`<span>Season Pass: <span class="season-pass">${replaceEmojisWithIcons("Not Available ❓")}</span></span>`);
    }
    detailsHtmlArray.push(`<span>Collector Rarity: <span class="collector-rarity">${collectorRarityDisplay}</span></span>`);
    statsHtml = detailsHtmlArray.join('\n          ');
} else if (vehicle.category === "Vehicle Values") {
    const topSpeedDisplay = replaceEmojisWithIcons(vehicle.topSpeed === "N/A" ? "Not Available ❓" : vehicle.topSpeed);
    const vehicleHealthDisplay = replaceEmojisWithIcons(vehicle.vehicleHealth === "N/A" ? "Not Available ❓" : vehicle.vehicleHealth);
    statsHtml = `
        <span>Top Speed: <span class="top-speed">${topSpeedDisplay}</span></span>
        <span>Health/Repair: <span class="vehicle-health">${vehicleHealthDisplay}</span></span>
    `;
} else {
    const displaySeasonPass = (seasonPassVal === "N/A") ? replaceEmojisWithIcons("Not Available ❓") : seasonPassVal;
    statsHtml = `
        <span>Season Pass: <span class="season-pass">${displaySeasonPass}</span></span>
        <span>Collector Rarity: <span class="collector-rarity">${collectorRarityDisplay}</span></span>
    `;
}

const updateTimeText = formatItemUpdateTime(vehicle.timeStamp);

const explanationButton = `
    <a class="explanation-button" data-x-post="${vehicle.blogPost || ''}" data-blog-post="${vehicle.writtenArticle || ''}"
       data-wiki-page="${vehicle.wikiPage || ''}" data-item-name="${vehicle.name}" data-item-nickname="${vehicle.nickname || ''}"
       title="${hasExplanation ? 'See value change explanation' : 'No explanation available'}">
      <i class="fas fa-file-alt"></i> Explanation
    </a>`;

// Add category tag for all pages (shows item type)
let categoryText = '';
if (vehicle.category) {
  categoryText = vehicle.category.replace(' Values', '');
} else {
  // Fallback: derive category from current page
  categoryText = currentHeaderTitleText.replace(' Values', '');
}

// Map category to appropriate icon
const categoryIcons = {
  'Vehicle': '<i class="fas fa-car-side"></i>',
  'Texture': '<i class="fas fa-paint-roller"></i>',
  'Color': '<i class="fa-solid fa-fill-drip"></i>',
  'Spoiler': '<i class="fas fa-cogs"></i>',
  'Rim': '<i class="fas fa-compact-disc"></i>',
  'Tire': '<i class="fas fa-circle-dot"></i>',
  'Furniture': '<i class="fas fa-couch"></i>',
  'Gun Texture': '<i class="fas fa-gun"></i>',
  'Vehicle Horn': '<i class="fas fa-bullhorn"></i>',
  'Drift Particle': '<i class="fas fa-wind"></i>'
};

const categoryIcon = categoryIcons[categoryText] || '';

const explanationContentHtml = `
  <p class="value-explanation clickable-description" data-description="${vehicle.explanation.replace(/"/g, '&quot;')}" data-item-name="${vehicle.name.replace(/"/g, '&quot;')}">${vehicle.explanation}</p>
`;

// Custom vehicle-specific icons
function getVehicleSpecificIcon(vehicleName) {
  const specificIcons = {
    'Sloop': '<i class="fas fa-sailboat"></i>',
    'Speed Yacht': '<i class="fas fa-ship"></i>',
    'Jet Ski': '<i class="fas fa-ship"></i>',
    'Cruiser': '<i class="fas fa-ship"></i>',
    'Little Bird': '<i class="fas fa-helicopter"></i>',
    'Escape Bot': '<i class="fas fa-helicopter"></i>',
    'Helicopter': '<i class="fas fa-helicopter"></i>',
    'Black Hawk': '<i class="fas fa-helicopter"></i>',
    'Drone': '<i class="fas fa-helicopter"></i>',
    'Celsior': '<i class="fas fa-helicopter"></i>',
    'Crew Capsule': '<i class="fas fa-helicopter"></i>',
    'UFO': '<i class="fas fa-helicopter"></i>',
    'Blade 2049': '<i class="fas fa-helicopter"></i>',
    "Lia's Ship": '<i class="fas fa-space-shuttle"></i>',
    'Jet Fighter': '<i class="fas fa-plane"></i>',
    'Stunt Plane': '<i class="fas fa-plane"></i>',
    'Jet': '<i class="fas fa-plane"></i>',
    'Volt Bike': '<i class="fas fa-motorcycle"></i>',
    'Falcon S': '<i class="fas fa-motorcycle"></i>',
    'ATV': '<i class="fas fa-motorcycle"></i>',
    'Patrol Bike': '<i class="fas fa-motorcycle"></i>',
    'Dirtbike': '<i class="fas fa-motorcycle"></i>',
    'Tank': '<i class="fas fa-car-side"></i>',
    'Sentinel': '<i class="fas fa-car-side"></i>',
    'Striker': '<i class="fas fa-car-side"></i>',
    'Goliath': '<i class="fas fa-car-side"></i>',
    'Celestial': '<i class="fas fa-car-side"></i>',
    'SWAT Van': '<i class="fas fa-car-side"></i>',
    'Cobra': '<i class="fas fa-car-side"></i>'
  };
  return specificIcons[vehicleName] || categoryIcon;
}

const vehicleIcon = getVehicleSpecificIcon(vehicle.name);

const bubble = document.createElement('div');
bubble.className = `value-bubble ${vehicle.type.toLowerCase()}-item`;
bubble.innerHTML = `
  <div class="value-bubble-content">
    <div class="image-container">
       <img src="${vehicle.image}"
            alt="${vehicle.name}"
            data-id="${vehicle.id}"
            data-category="${vehicle.category}"
            width="1280" height="720"
            decoding="async"
            loading="lazy">
       ${statusBadge}
       <h3>${vehicleIcon}${vehicleIcon ? ' ' : ''}${vehicle.name}</h3>
       <div class="image-border-overlay"></div>

    </div>
    <div class="value-category">
      <span>Current Value: <span class="jbt">${tradingValueDisplay}</span></span>
      <span>Duped Value: <span class="duped">${dupedValueDisplay}</span></span>
      <span>Demand Rating: <span class="demand">${demandLabel}</span></span>
      <span>${priceLabel}: <span class="price">${originalPriceDisplay}</span></span>
      <span>Distribution: <span class="copies">${replaceEmojisWithIcons(freqItem && freqItem.UniqueCirculation ? `🔁 ${Number(freqItem.UniqueCirculation).toLocaleString('en-US')} Copies` : "🔁 Unavailable")}</span></span>
      <span>Times Traded: <span class="traded">${timesTraded}</span></span>
      ${statsHtml}
    </div>
    <div class="value-explanation-container">
      ${explanationContentHtml}
    </div>
    <div class="update-timestamp">
      <span class="timestamp-text"><i class="fas fa-history"></i> ${updateTimeText}</span>
      ${explanationButton}
    </div>
  </div>
`;

const img = bubble.querySelector('img');
const imgWrap = bubble.querySelector('.image-container');
if (img && imgWrap) {
  const markLoaded = () => { try { imgWrap.classList.add('img-loaded'); } catch(_){} };
  if (img.complete && img.naturalWidth > 0) {
    // Image already cached/loaded
    markLoaded();
  } else {
    img.addEventListener('load', markLoaded, { once: true });
    img.addEventListener('error', () => { try { imgWrap.classList.add('img-loaded'); } catch(_){} }, { once: true });
  }
}

return bubble;
}

function loadNextBatch() {
const container = document.getElementById('LIBubblesContainer');
const sentinel = document.getElementById('LIValueSentinel');
if (!container || !sentinel) return;

const end = Math.min(lazyIndex + RENDER_BATCH_SIZE, lazyList.length);
const fragment = document.createDocumentFragment();
for (let i = lazyIndex; i < end; i++) {
  const bubble = createBubble(lazyList[i]);
  try { bubble.dataset.lazyIndex = String(i); } catch(_) {}
  // Prefer eager loading for the very first row to avoid visible pop-in
  if (lazyIndex === 0) {
    const img = bubble.querySelector('img');
    if (img) {
      try { img.setAttribute('loading', 'eager'); } catch(_) {}
      try { img.setAttribute('fetchpriority', 'high'); } catch(_) {}
    }
  }
  fragment.appendChild(bubble);
}
container.insertBefore(fragment, sentinel);

setupBubbleAnimationObserver();
setupUnloadRestoreObservers();
setupImagePriorityObserver && setupImagePriorityObserver();
setupImageClickEvents();
setupDescriptionClickEvents();

// Fallback: immediately reveal any cards already within/near viewport to avoid black top row
forceRevealNearViewport && forceRevealNearViewport();

lazyIndex = end;
if (lazyIndex >= lazyList.length) {
  if (lazyObserver) lazyObserver.disconnect();
  sentinel.remove();
}
}

// Ensure any bubbles already near viewport are marked visible quickly (fallback for IO race)
function forceRevealNearViewport() {
try {
  const thresholdTop = -100; // px above viewport
  const thresholdBottom = (window.innerHeight || 800) + 200; // px below viewport
  const candidates = document.querySelectorAll('#LIBubblesContainer .value-bubble:not(.visible)');
  candidates.forEach(el => {
    const rect = el.getBoundingClientRect();
    if (rect.bottom >= thresholdTop && rect.top <= thresholdBottom) {
      el.classList.add('visible');
      el.classList.remove('leaving');
      const wrap = el.querySelector('.image-container');
      const img = wrap && wrap.querySelector('img');
      if (img && (img.complete && img.naturalWidth > 0)) {
        wrap.classList.add('img-loaded');
      }
    }
  });
} catch (_) { /* no-op */ }
// Schedule a secondary pass after a short delay to catch late layout
try { setTimeout(() => forceRevealNearViewportPass2 && forceRevealNearViewportPass2(), 120); } catch(_) {}
}

function forceRevealNearViewportPass2() {
try {
  const thresholdTop = -100;
  const thresholdBottom = (window.innerHeight || 800) + 200;
  const candidates = document.querySelectorAll('#LIBubblesContainer .value-bubble:not(.visible)');
  candidates.forEach(el => {
    const rect = el.getBoundingClientRect();
    if (rect.bottom >= thresholdTop && rect.top <= thresholdBottom) {
      el.classList.add('visible');
      el.classList.remove('leaving');
      const wrap = el.querySelector('.image-container');
      const img = wrap && wrap.querySelector('img');
      if (img && (img.complete && img.naturalWidth > 0)) {
        wrap.classList.add('img-loaded');
      }
    }
  });
} catch (_) { /* no-op */ }
}

// Unload bubbles far off-screen and restore them when they approach viewport
let unloadObserver;
let restoreObserver;
function setupUnloadRestoreObservers() {
const container = document.getElementById('LIBubblesContainer');
if (!container) return;
try {
  if (unloadObserver) unloadObserver.disconnect();
  if (restoreObserver) restoreObserver.disconnect();

  // Detect bubbles that move far away from the viewport
  unloadObserver = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      const el = entry.target;
      if (!el || !el.classList.contains('value-bubble')) return;
      // Compute if element is far outside viewport beyond a buffer
      const rect = el.getBoundingClientRect();
      const vh = window.innerHeight || 800;
      const farBelow = rect.top > (vh + 5000);
      const farAbove = rect.bottom < (-5000);
      if ((farBelow || farAbove)) {
        const idx = parseInt(el.dataset.lazyIndex || '-1', 10);
        const h = el.offsetHeight || el.getBoundingClientRect().height || 420;
        const placeholder = document.createElement('div');
        placeholder.className = 'value-bubble-placeholder';
        placeholder.style.height = `${Math.max(200, Math.round(h))}px`;
        if (!Number.isNaN(idx)) placeholder.dataset.lazyIndex = String(idx);
        // Replace bubble with placeholder
        try {
          el.replaceWith(placeholder);
        } catch(_) { return; }
        // Observe placeholder to restore when it approaches viewport
        if (restoreObserver) restoreObserver.observe(placeholder);
      }
    });
  }, { root: null, rootMargin: '0px', threshold: 0 });

  // Restore placeholders into real bubbles before they enter viewport
  restoreObserver = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      const ph = entry.target;
      if (!entry.isIntersecting) return;
      if (!ph.classList.contains('value-bubble-placeholder')) return;
      const idx = parseInt(ph.dataset.lazyIndex || '-1', 10);
      if (Number.isNaN(idx) || !lazyList[idx]) { restoreObserver.unobserve(ph); return; }
      const bubble = createBubble(lazyList[idx]);
      try { bubble.dataset.lazyIndex = String(idx); } catch(_) {}
      // Immediately mark visible so contents render (avoids black/hidden content)
      try { bubble.classList.add('visible'); } catch(_) {}
      try { ph.replaceWith(bubble); } catch(_) { return; }
      // Observe for future unloads again
      try { unloadObserver && unloadObserver.observe(bubble); } catch(_) {}
      // Hook into reveal observer if present for consistency
      try { bubbleObserver && bubbleObserver.observe(bubble); } catch(_) {}
      // Ensure image priority + click handlers are restored for this bubble
      try {
        const img = bubble.querySelector('.image-container img');
        if (img) {
          // Promote priority immediately to ensure fast fetch when restoring
          try { img.setAttribute('fetchpriority', 'high'); } catch(_) {}
          try { img.setAttribute('loading', 'eager'); } catch(_) {}
          imagePriorityObserver && imagePriorityObserver.observe(img);
          // Bind fullscreen click if not yet bound
          if (img.dataset.fsBound !== '1') {
            img.dataset.fsBound = '1';
            img.addEventListener('click', () => {
              const overlay = document.getElementById('LIFullscreenOverlay');
              const fullscreenImage = document.getElementById('LIFullscreenImage');
              const fullscreenCaption = document.getElementById('LIFullscreenCaption');
              if (overlay && fullscreenImage && fullscreenCaption) {
                try { fullscreenImage.src = img.currentSrc || img.src; } catch(_) {}
                const itemName = img.alt || 'Item';
                const itemCategory = img.dataset.category || 'Item';
                const itemType = (itemCategory || '').replace(' Values', '') || 'Item';
                fullscreenCaption.innerHTML = `${itemName} (${itemType}) From Roblox Jailbreak | Sourced From <a href=\"https://jailbreaktradingnetwork.com\" target=\"_blank\" rel=\"noopener noreferrer\">Jailbreak Trading Network</a>.`;
                const wrap = img.closest('.image-container');
                if (wrap && !wrap.classList.contains('img-loaded')) wrap.classList.add('img-loaded');
                overlay.classList.add('active');
                document.body.classList.add('jbtn-modal-open');
              }
            });
          }
        }
      } catch(_) {}
      // Stop observing this placeholder
      try { restoreObserver.unobserve(ph); } catch(_) {}
    });
  }, { root: null, rootMargin: '3000px 0px 3000px 0px', threshold: 0 });

  // Start observing current bubbles
  container.querySelectorAll('.value-bubble').forEach(el => unloadObserver.observe(el));
  // Track scroll direction (bind once)
  if (!window.__scrollDirBound) {
    window.__scrollDirBound = true;
    window.addEventListener('scroll', () => {
      try {
        const y = window.pageYOffset || document.documentElement.scrollTop || 0;
        if (typeof window.__lastScrollY === 'number') {
          const down = y > window.__lastScrollY;
          document.body.classList.toggle('scrolling-down', down);
          document.body.classList.toggle('scrolling-up', !down);
        }
        window.__lastScrollY = y;
      } catch(_) {}
    }, { passive: true });
  }

  // Also wire up a scroll/resize fallback that force-restores placeholders near viewport
  const debouncedForce = (() => {
    let raf = 0; return () => { if (raf) return; raf = requestAnimationFrame(() => { raf = 0; try { forceRestoreNearViewport(); } catch(_) {} }); };
  })();
  window.addEventListener('scroll', debouncedForce, { passive: true });
  window.addEventListener('resize', debouncedForce, { passive: true });
} catch(_) { /* no-op */ }
}

// Fallback: quickly restore any placeholders near/within viewport to avoid visible blanks
function forceRestoreNearViewport() {
try {
  const topBuffer = -200;
  const bottomBuffer = (window.innerHeight || 800) + 400;
  const placeholders = document.querySelectorAll('#LIBubblesContainer .value-bubble-placeholder');
  placeholders.forEach(ph => {
    const rect = ph.getBoundingClientRect();
    if (rect.bottom >= topBuffer && rect.top <= bottomBuffer) {
      const idx = parseInt(ph.dataset.lazyIndex || '-1', 10);
      if (!Number.isNaN(idx) && lazyList[idx]) {
        const bubble = createBubble(lazyList[idx]);
        try { bubble.dataset.lazyIndex = String(idx); } catch(_) {}
        try { bubble.classList.add('visible'); } catch(_) {}
        const img = bubble.querySelector('.image-container img');
        if (img) {
          try { img.setAttribute('fetchpriority', 'high'); } catch(_) {}
          try { img.setAttribute('loading', 'eager'); } catch(_) {}
          imagePriorityObserver && imagePriorityObserver.observe(img);
        }
        try { ph.replaceWith(bubble); } catch(_) {}
      }
    }
  });
} catch(_) { /* no-op */ }
}

// Promote image priority for images approaching viewport to reduce pop-in during fast scroll
let imagePriorityObserver;
function setupImagePriorityObserver() {
try {
  if (imagePriorityObserver) imagePriorityObserver.disconnect();
  imagePriorityObserver = new IntersectionObserver((entries, obs) => {
    entries.forEach(entry => {
      const img = entry.target;
      if (entry.isIntersecting) {
        try { img.setAttribute('fetchpriority', 'high'); } catch(_) {}
        try { img.setAttribute('loading', 'eager'); } catch(_) {}
        obs.unobserve(img);
      }
    });
  }, { root: null, rootMargin: '1200px 0px 1200px 0px', threshold: 0 });

  document.querySelectorAll('#LIBubblesContainer .image-container img').forEach(img => {
    if (img) imagePriorityObserver.observe(img);
  });
} catch (_) { /* no-op */ }
}

function initLazyList(list) {
lazyList = list.slice();
lazyIndex = 0;
const container = document.getElementById('LIBubblesContainer');
if (!container) return;

const sentinel = document.createElement('div');
sentinel.id = 'LIValueSentinel';
container.appendChild(sentinel);

if (lazyObserver) lazyObserver.disconnect();
lazyObserver = new IntersectionObserver((entries) => {
  if (entries.some(entry => entry.isIntersecting)) {
    loadNextBatch();
  }
}, { rootMargin: '1000px' });
lazyObserver.observe(sentinel);

loadNextBatch();
}

function renderVehicles(list, shouldRefocus, isInitialSetup) {
const container = document.getElementById('LIBubblesContainer');
const searchInput = document.getElementById('LISearchInput');
const countElement = document.getElementById('ItemsCount');
isAnimating = true;
container.classList.add('sorting');

// Fade out the count to sync with outgoing cards
if (countElement) {
  countElement.classList.remove('anim-fade-in');
  countElement.classList.add('anim-fade-out');
}

if (lazyObserver) lazyObserver.disconnect();
lazyList = [];
lazyIndex = 0;
// Fade out only visible items in a stagger; off-screen items disappear immediately
const outDuration = animateBubblesOut('#LIBubblesContainer');

setTimeout(() => {
  container.innerHTML = '';

  if (list.length === 0) {
    // Mirror og-item-finder: render nothing when there are no results
    container.style.display = 'grid';
    container.style.alignItems = '';
    container.style.justifyContent = '';
    container.style.minHeight = '';
    container.style.padding = '0';
    container.style.gridTemplateColumns = '';
    container.style.width = '';
    container.style.marginTop = '';
    container.style.marginBottom = '';
    // Do not append any "no results" message or reset button
    // Update and reveal items count
    if (countElement) {
      countElement.style.display = '';
      countElement.removeAttribute('aria-hidden');
      countElement.classList.remove('hidden', 'anim-fade-out');
      requestAnimationFrame(() => {
        countElement.classList.add('anim-fade-in');
        const totalAll = Array.isArray(vehicles) ? vehicles.length : 0;
        // Animate both numbers from 0 -> target like OG
        __itemsCountLast.showing = 0;
        __itemsCountLast.total = 0;
        updateItemsCount(0, totalAll, 250);
      });
    }
  } else {
    container.style.display = 'grid';
    container.style.alignItems = '';
    container.style.minHeight = '';
    container.style.padding = '0';
    container.style.width = '';
    container.style.marginTop = '';
    container.style.marginBottom = '';

      initLazyList(list);

      // Update and reveal items count to new values
      if (countElement) {
        countElement.style.display = '';
        countElement.removeAttribute('aria-hidden');
        countElement.classList.remove('hidden', 'anim-fade-out');
        requestAnimationFrame(() => {
          countElement.classList.add('anim-fade-in');
          const totalAll = Array.isArray(vehicles) ? vehicles.length : list.length;
          // Always animate both numbers from 0 -> target on rebuild (matches OG feel)
          __itemsCountLast.showing = 0;
          __itemsCountLast.total = 0;
          updateItemsCount(list.length, totalAll, 300);
          __forceCountFromZero = false;
        });
      }
  }

    requestAnimationFrame(() => {
      requestAnimationFrame(() => {
        isAnimating = false;
        enableControls();
        if (shouldRefocus && searchInput) searchInput.focus();
      });
    });
}, outDuration);
}


let lastSortFilterDisable = 0;
function disableControls(source = 'general') {
// Only prevent rapid consecutive calls from sort/filter operations
if (source === 'sortfilter') {
  const now = Date.now();
  if (now - lastSortFilterDisable < 200) return; // Prevent double calls within 200ms
  lastSortFilterDisable = now;
}

const searchInput = document.getElementById('LISearchInput');
const sortSelect = document.getElementById('LISortSelect');
const filterSelect = document.getElementById('LIFilterSelect');
const sortButton = document.getElementById('LISortButton');
const filterButton = document.getElementById('LIFilterButton');
const audioButton = document.getElementById('navAudioInfo');
const audioContainer = audioButton ? audioButton.closest('.nav-audio-player') : null;
const searchWrapper = document.querySelector('.input-icon-wrapper[data-nav-priority="1"]');
const sortWrapper = document.querySelector('.input-icon-wrapper[data-nav-priority="2"]');
const filterWrapper = document.querySelector('.input-icon-wrapper[data-nav-priority="3"]');
if (searchInput) {
  // Clear focus so wrapper loses focus-within visuals immediately
  if (document.activeElement === searchInput) try { searchInput.blur(); } catch (e) {}
  searchInput.disabled = true;
}
if (sortSelect) sortSelect.disabled = true;
if (filterSelect) filterSelect.disabled = true;
if (sortButton) {
  try { sortButton.blur(); } catch (e) {}
  sortButton.disabled = true;
}
if (filterButton) {
  try { filterButton.blur(); } catch (e) {}
  filterButton.disabled = true;
}
if (audioButton) audioButton.disabled = true;
[searchWrapper, sortWrapper, filterWrapper].forEach(el => {
  if (!el) return;
  el.classList.add('disabled');
  // Clear any interactive states and force dimmed outline like control buttons while disabled
  el.classList.remove('is-hover', 'is-focus', 'is-active', 'pressing');
  try {
    el.style.borderColor = 'rgba(255,255,255,0.2)';
    el.style.outline = 'none';
    el.style.transform = 'none';
    // Drive the actual fade using opacity (matches control buttons feel)
    el.style.opacity = '0.5';
  } catch (e) {}
});
const resetButton = document.getElementById('LIResetButton');
if (resetButton) {
  resetButton.disabled = true;
  resetButton.classList.add('disabled');
}
const settingsButton = document.getElementById('LISettingsButton');
if (settingsButton) {
  settingsButton.disabled = true;
  settingsButton.classList.add('disabled');
}
if (audioButton) audioButton.classList.add('disabled');
if (audioContainer) audioContainer.classList.add('disabled');
document.body.classList.add('controls-disabled');
}

function enableControls() {
const searchInput = document.getElementById('LISearchInput');
const sortSelect = document.getElementById('LISortSelect');
const filterSelect = document.getElementById('LIFilterSelect');
const sortButton = document.getElementById('LISortButton');
const filterButton = document.getElementById('LIFilterButton');
const audioButton = document.getElementById('navAudioInfo');
const audioContainer = audioButton ? audioButton.closest('.nav-audio-player') : null;
const searchWrapper = document.querySelector('.input-icon-wrapper[data-nav-priority="1"]');
const sortWrapper = document.querySelector('.input-icon-wrapper[data-nav-priority="2"]');
const filterWrapper = document.querySelector('.input-icon-wrapper[data-nav-priority="3"]');
if (searchInput) searchInput.disabled = false;
if (sortSelect) sortSelect.disabled = false;
if (filterSelect) filterSelect.disabled = false;
if (sortButton) sortButton.disabled = false;
if (filterButton) filterButton.disabled = false;
if (audioButton) audioButton.disabled = false;
[searchWrapper, sortWrapper, filterWrapper].forEach(el => {
  if (!el) return;
  el.classList.remove('disabled');
  // Remove inline overrides so hover/focus works again
  try {
    el.style.borderColor = '';
    el.style.outline = '';
    el.style.transform = '';
    el.style.opacity = '';
  } catch (e) {}
});
const resetButton = document.getElementById('LIResetButton');
if (resetButton) {
  resetButton.disabled = false;
  resetButton.classList.remove('disabled');
}
const settingsButton = document.getElementById('LISettingsButton');
if (settingsButton) {
  settingsButton.disabled = false;
  settingsButton.classList.remove('disabled');
}
if (audioButton) audioButton.classList.remove('disabled');
if (audioContainer) audioContainer.classList.remove('disabled');
document.body.classList.remove('controls-disabled');

if (isInitialLoad) {
    document.querySelectorAll('.input-icon').forEach(icon => {
        icon.classList.add('activated');
        icon.addEventListener('animationend', () => {
            icon.classList.remove('activated');
        }, { once: true });
    });
}
}

function parseSafeTier(originalPriceString) {
if (typeof originalPriceString !== 'string') return Infinity;
const match = originalPriceString.match(/Tier (\d+)/i);
return match ? parseInt(match[1], 10) : Infinity;
}

function parseSeasonReward(originalPriceString) {
if (typeof originalPriceString !== 'string') return { season: Infinity, level: Infinity };
const seasonMatch = originalPriceString.match(/S(\d+)/i);
const levelMatch = originalPriceString.match(/Level (\d+)/i);
const season = seasonMatch ? parseInt(seasonMatch[1], 10) : Infinity;
const level = levelMatch ? parseInt(levelMatch[1], 10) : Infinity;
if (season === Infinity && level !== Infinity && originalPriceString.toLowerCase().includes("level")) {
  return { season: Infinity, level: level };
}
if (season === Infinity && level === Infinity) {
    return { season: Infinity, level: Infinity };
}
return { season, level };
}

function parseCurrency(str) {
if (typeof str !== 'string') return 0;
const cleanedStr = str.replace(/[^0-9.]/g, '');
const num = parseFloat(cleanedStr);
return isNaN(num) ? 0 : num;
}

function parseCollectorRarity(rarityString) {
if (typeof rarityString !== 'string' || rarityString === 'N/A' || rarityString.includes('Not Available')) return -1;

// Handle score format like "🔥 241/500 Score"
const scoreMatch = rarityString.match(/(\d+)\/(\d+)\s+Score/i);
if (scoreMatch) {
  const numerator = parseInt(scoreMatch[1]);
  const denominator = parseInt(scoreMatch[2]);
  if (denominator > 0) {
    return numerator / denominator; // Returns decimal between 0-1, higher = rarer
  }
}

// Fallback to traditional rarity names if no score found
const rarity = rarityString.toLowerCase().trim();
const rarityMap = {
  'common': 0.1,
  'uncommon': 0.2,
  'rare': 0.4,
  'epic': 0.6,
  'legendary': 0.8,
  'mythical': 0.9,
  'unobtainable': 1.0
};

for (const [key, value] of Object.entries(rarityMap)) {
  if (rarity.includes(key)) return value;
}

return -1; // For unknown rarities
}

function parsePityChance(originalPriceString) {
if (typeof originalPriceString !== 'string') return -1;

// Handle heists format like "🏦 ~ 750 Heists" or "🏦 ~ 1,500 Heists"
const heistsMatch = originalPriceString.match(/~?\s*([\d,]+)\s+Heists/i);
if (heistsMatch) {
  // Remove commas and parse the number
  const heistsRequired = parseInt(heistsMatch[1].replace(/,/g, ''));
  if (heistsRequired > 0) {
    // Convert to "pity chance" - fewer heists = higher chance (lower number = better)
    // Use inverse so higher numbers sort as "higher pity chance"
    return 1000000 / heistsRequired; // Arbitrary large number for inverse ranking
  }
}

// Look for percentage values that might represent pity chances
const percentMatch = originalPriceString.match(/(\d+(?:\.\d+)?)%/);
if (percentMatch) {
  return parseFloat(percentMatch[1]);
}

// Look for "1 in X" format
const oneInMatch = originalPriceString.match(/1\s+in\s+(\d+)/i);
if (oneInMatch) {
  const denominator = parseInt(oneInMatch[1]);
  return denominator > 0 ? (100 / denominator) : -1;
}

return -1; // No pity chance found
}

function parseVehicleHealth(vehicleHealthString) {
if (typeof vehicleHealthString !== 'string' || vehicleHealthString === 'N/A' || vehicleHealthString.includes('Not Available')) return -1;

// Handle format like "⚙️ 75 HP, 🛠️ 7.5s" - extract HP value
const hpMatch = vehicleHealthString.match(/(\d+(?:\.\d+)?)\s*HP/i);
if (hpMatch) {
  return parseFloat(hpMatch[1]);
}

return -1; // No HP value found
}

function parseRepairTime(vehicleHealthString) {
if (typeof vehicleHealthString !== 'string' || vehicleHealthString === 'N/A' || vehicleHealthString.includes('Not Available')) return -1;

// Handle format like "⚙️ 75 HP, 🛠️ 7.5s" - extract repair time value
const repairMatch = vehicleHealthString.match(/(\d+(?:\.\d+)?)\s*s/i);
if (repairMatch) {
  return parseFloat(repairMatch[1]);
}

return -1; // No repair time found
}

function parseTopSpeed(topSpeedString) {
if (typeof topSpeedString !== 'string' || topSpeedString === 'N/A' || topSpeedString.includes('Not Available')) return -1;

// Handle format like "🏎️ ~ 395 MPH" - extract speed value
const speedMatch = topSpeedString.match(/~?\s*(\d+(?:\.\d+)?)\s*MPH/i);
if (speedMatch) {
  return parseFloat(speedMatch[1]);
}

return -1; // No top speed found
}

function updateSortSelectDisplay() {
const LISortSelect = document.getElementById('LISortSelect');
if (LISortSelect) {
    LISortSelect.value = currentSortCriteria;
}
const LIFilterSelect = document.getElementById('LIFilterSelect');
if (LIFilterSelect) {
    LIFilterSelect.value = currentFilterType;
}
}

// Initialize default sort/filter values on DOM ready
function initializeDefaults() {
// Read actual values from select elements to ensure sync
const sortSelect = document.getElementById('LISortSelect');
const filterSelect = document.getElementById('LIFilterSelect');

// For sort select, get the actual selected value or default to price-desc
if (sortSelect) {
  // Check if there's a selected option in the HTML
  const selectedSortOption = sortSelect.querySelector('option[selected]');
  if (selectedSortOption) {
    currentSortCriteria = selectedSortOption.value;
    sortSelect.value = currentSortCriteria;
  } else if (sortSelect.value) {
    currentSortCriteria = sortSelect.value;
  } else {
    currentSortCriteria = 'price-desc';
    sortSelect.value = currentSortCriteria;
  }
} else {
  currentSortCriteria = 'price-desc';
}

// For filter select, get the actual selected value or default to all-items
if (filterSelect) {
  const selectedFilterOption = filterSelect.querySelector('option[selected]');
  if (selectedFilterOption) {
    const value = selectedFilterOption.value;
    if (value.startsWith('category-') || value === 'all-values') {
      currentCategoryFilter = value;
    } else {
      currentFilterType = value;
    }
    filterSelect.value = value;
  } else if (filterSelect.value) {
    const value = filterSelect.value;
    if (value.startsWith('category-') || value === 'all-values') {
      currentCategoryFilter = value;
    } else {
      currentFilterType = value;
    }
  } else {
    currentFilterType = 'all-items';
    currentCategoryFilter = 'all-values';
    filterSelect.value = currentFilterType;
  }
} else {
  currentFilterType = 'all-items';
  currentCategoryFilter = 'all-values';
}

const headerElement = document.querySelector('header h2');
const headerTitle = headerElement ? (headerElement.dataset.valueType || headerElement.textContent.trim()) : '';

// Check if this is the All Values page
const isAllValuesPage = window.location.pathname === '/index' || window.location.pathname === '/index.html' || window.location.pathname === '/all-values' || 
                       window.location.pathname === '/' || 
                       document.title.toLowerCase().includes('all values') ||
                       headerTitle === "All Values";

if (isAllValuesPage) {
  // For All Values page, allow both filters to be changed
  currentFilterType = 'all-items';
  currentCategoryFilter = 'all-values';
  if (filterSelect) filterSelect.value = currentFilterType;
} else {
  // For specific category pages, lock category filter to the active page
  currentFilterType = 'all-items';
  const mappedCategory = filterValueMappings[headerTitle] || 'all-values';
  currentCategoryFilter = mappedCategory;
  if (filterSelect) {
    filterSelect.value = currentFilterType;
    // Reflect the active category in the native select so custom UI mirrors it
    const categoryOptions = filterSelect.querySelectorAll('optgroup[label="Filter by Category"] option');
    categoryOptions.forEach(option => {
      option.selected = option.value === mappedCategory;
    });
  }
}


// Update display immediately
updateSortSelectDisplay();
updateButtonText();

// Initialize button sizing after a short delay to ensure elements are rendered
setTimeout(() => {
  updateSortFilterButtonSizing();
}, 100);

// Force initial update of displayed items if vehicles data is available
if (vehicles && vehicles.length > 0) {
  updateDisplayedItems(false, true);
}
}

// Function to calculate optimal button width based on text content
function calculateButtonWidth(button, text) {
// Create a temporary element to measure text width with exact same styling
const temp = document.createElement('div');
const buttonStyles = window.getComputedStyle(button);
temp.style.cssText = `
  position: absolute;
  top: -9999px;
  left: -9999px;
  font-family: ${buttonStyles.fontFamily};
  font-size: ${buttonStyles.fontSize};
  font-weight: ${buttonStyles.fontWeight};
  letter-spacing: ${buttonStyles.letterSpacing};
  white-space: nowrap;
  visibility: hidden;
  pointer-events: none;
  padding: 0;
  margin: 0;
  border: 0;
  line-height: normal;
`;
temp.textContent = text;

document.body.appendChild(temp);
const textWidth = temp.offsetWidth;
document.body.removeChild(temp);

// More precise calculations - reduced to minimize dead space
// Left padding for icon: 2.8em at 0.9em font size ≈ 45px
// Right padding for caret: just enough for the icon ≈ 18px  
// Base padding: minimal padding ≈ 8px
// Safety margin: small buffer ≈ 5px
const leftIconPadding = 45;
const rightCaretPadding = 18; // Reduced from 35px
const basePadding = 8; // Reduced from 20px
const safetyMargin = 5; // Reduced from 10px

const totalWidth = textWidth + leftIconPadding + rightCaretPadding + basePadding + safetyMargin;

// Constrain within min/max bounds - tighter minimum for shorter text
const calculatedWidth = Math.max(Math.min(totalWidth, 450), 100);

return calculatedWidth;
}

// Update button text to show currently selected options
function updateButtonText() {
const sortButton = document.getElementById('LISortButton');
const filterButton = document.getElementById('LIFilterButton');

if (sortButton && originalSortOptionTexts[currentSortCriteria]) {
  let sortText;
  
  if (window.innerWidth >= 1401) {
    // Large desktop: Full text
    sortText = originalSortOptionTexts[currentSortCriteria];
  } else if (window.innerWidth >= 1201) {
    // Medium desktop: Shortened text
    sortText = "Sort";
  } else {
    // Compact mode: Full text (will be hidden by CSS)
    sortText = originalSortOptionTexts[currentSortCriteria];
  }
  
  const sortLabel = sortButton.querySelector('.button-label');
  if (sortLabel) sortLabel.textContent = sortText;
  
  // Only apply dynamic sizing on large desktop screens
  if (window.innerWidth >= 1401) {
    // Use requestAnimationFrame to ensure the button is rendered before measuring
    requestAnimationFrame(() => {
      const optimalWidth = calculateButtonWidth(sortButton, sortText);
      const wrapper = sortButton.closest('.input-icon-wrapper');
      if (wrapper) {
        wrapper.style.width = `${optimalWidth}px`;
        wrapper.style.minWidth = `${optimalWidth}px`;
        wrapper.style.maxWidth = `${optimalWidth}px`;
      }
    });
  } else {
    // Reset to CSS-controlled sizing for medium/compact modes
    const wrapper = sortButton.closest('.input-icon-wrapper');
    if (wrapper) {
      wrapper.style.width = '';
      wrapper.style.minWidth = '';
      wrapper.style.maxWidth = '';
    }
  }
}

if (filterButton) {
  let filterText;
  
  // Check if we're on All Values page
  const headerTitleElement = document.querySelector('header h2');
  const headerTitle = headerTitleElement ? (headerTitleElement.dataset.valueType || headerTitleElement.textContent.trim()) : '';
  const isAllValuesPage = window.location.pathname === '/index' || window.location.pathname === '/index.html' || window.location.pathname === '/all-values' || 
                         window.location.pathname === '/' || 
                         document.title.toLowerCase().includes('all values') ||
                         headerTitle === "All Values";
  
  if (window.innerWidth >= 1401) {
    // Large desktop: Always show combined format "Filter: [Type] + [Category]"
    const typeText = currentFilterType !== 'all-items' ? 
      (originalFilterOptionTexts[currentFilterType] || currentFilterType).replace('Filter: Show ', '').replace('Filter: ', '') : 
      'All Items';
    
    const categoryText = isAllValuesPage ? 
      (currentCategoryFilter !== 'all-values' ? 
        (originalFilterOptionTexts[currentCategoryFilter] || currentCategoryFilter).replace('Filter: Show ', '').replace('Filter: ', '') : 
        'All Values') : 
      headerTitle; // On specific pages, show the current page category (e.g., "Vehicle Values")
    
    filterText = `Filter: ${typeText} + ${categoryText}`;
  } else if (window.innerWidth >= 1201) {
    // Medium desktop: Shortened text
    filterText = "Filter";
  } else {
    // Compact mode: Show active filter count or combined format
    const activeFilters = (currentFilterType !== 'all-items' ? 1 : 0) + (isAllValuesPage && currentCategoryFilter !== 'all-values' ? 1 : 0);
    if (activeFilters > 0) {
      filterText = `Filter (${activeFilters})`;
    } else {
      filterText = isAllValuesPage ? "Filter: All Items + All Values" : `Filter: All Items + ${headerTitle}`;
    }
  }
  
  const filterLabel = filterButton.querySelector('.button-label');
  if (filterLabel) filterLabel.textContent = filterText;
  
  // Only apply dynamic sizing on large desktop screens
  if (window.innerWidth >= 1401) {
    // Use requestAnimationFrame to ensure the button is rendered before measuring
    requestAnimationFrame(() => {
      const optimalWidth = calculateButtonWidth(filterButton, filterText);
      const wrapper = filterButton.closest('.input-icon-wrapper');
      if (wrapper) {
        wrapper.style.width = `${optimalWidth}px`;
        wrapper.style.minWidth = `${optimalWidth}px`;
        wrapper.style.maxWidth = `${optimalWidth}px`;
      }
    });
  } else {
    // Reset to CSS-controlled sizing for medium/compact modes
    const wrapper = filterButton.closest('.input-icon-wrapper');
    if (wrapper) {
      wrapper.style.width = '';
      wrapper.style.minWidth = '';
      wrapper.style.maxWidth = '';
    }
  }
}
}
// Function to show custom dropdown overlay
function showCustomDropdown(type, selectElement, optionTexts) {
// Remove any existing dropdown
const existingOverlay = document.querySelector('.custom-dropdown-overlay');
if (existingOverlay) {
  existingOverlay.remove();
}

// Don't disable controls just for opening the dropdown
// Only disable them when actually applying changes
const sortGroupIcons = {
  'Sort by Name': 'fas fa-font',
  'Sort by Price': 'fas fa-dollar-sign',
  'Sort by Demand': 'fas fa-chart-line',
  'Sort by Reward Type': 'fas fa-gift',
  'Sort by Statistics': 'fas fa-chart-bar',
  // Ensure these groups show icons as well
  'Sort by Time': 'fas fa-clock',
  'Sort by Special Properties': 'fas fa-star',
  'Sort by Vehicle Stats': 'fas fa-gauge'
};

const filterGroupIcons = {
  'Filter by Type': 'fas fa-tags',
  'Filter by Category': 'fas fa-th-list'
};

// Create overlay
const overlay = document.createElement('div');
overlay.className = 'custom-dropdown-overlay';

// Create container
const container = document.createElement('div');
container.className = type === 'sort' ? 'custom-dropdown-container sort-dropdown' : 'custom-dropdown-container filter-dropdown';

// Create close button
const closeBtn = document.createElement('button');
closeBtn.className = 'custom-dropdown-close';
closeBtn.innerHTML = '&times;';

// Create header
const header = document.createElement('div');
header.className = 'settings-header';
const headerIcon = document.createElement('i');
headerIcon.className = (type === 'sort' ? 'fas fa-sort' : 'fas fa-filter') + ' settings-header-icon';
const headerTitle = document.createElement('h2');
headerTitle.textContent = type === 'sort' ? 'Sort Options' : 'Filter Options';
header.appendChild(headerIcon);
header.appendChild(headerTitle);

let description;
if (type === 'sort') {
  description = document.createElement('p');
  description.className = 'settings-subtitle';
  description.textContent = 'Select how you want items ordered.';
} else if (type === 'filter') {
  description = document.createElement('p');
  description.className = 'settings-subtitle';
  description.textContent = 'Choose which items are shown.';
}

// Create content area
const content = document.createElement('div');
content.className = 'custom-dropdown-content';

// Track temporary selections
let tempValue = selectElement.value; // For sort functionality
let tempTypeFilter = currentFilterType;
let tempCategoryFilter = currentCategoryFilter;

// Add options
const optgroups = Array.from(selectElement.querySelectorAll('optgroup'));
optgroups.forEach((optgroup) => {
  const group = document.createElement('div');
  group.className = 'custom-dropdown-group';

  const headerWrap = document.createElement('div');
  headerWrap.className = 'custom-dropdown-group-header';

  if (optgroup.label) {
    const titleEl = document.createElement('h3');
    titleEl.className = 'custom-dropdown-group-title';
    let titleText = optgroup.label;
    const iconClass = type === 'sort' ? sortGroupIcons[optgroup.label] : filterGroupIcons[optgroup.label];
    if (iconClass) {
      titleEl.innerHTML = `<i class="${iconClass}"></i> ${titleText}`;
    } else {
      titleEl.textContent = titleText;
    }
    headerWrap.appendChild(titleEl);
  }

  const groupDescText = optgroup.getAttribute('data-description');
  if (groupDescText) {
    const descEl = document.createElement('p');
    descEl.className = 'custom-dropdown-group-desc';
    descEl.textContent = groupDescText;
    headerWrap.appendChild(descEl);
  }

  group.appendChild(headerWrap);

  const options = optgroup.querySelectorAll('option');
  options.forEach(option => {
    const optionDiv = document.createElement('div');
    optionDiv.className = 'custom-dropdown-option';
    
    // Check if this is a category filter option and if we're on a specific page
    const isCategoryOption = option.value.startsWith('category-') || option.value === 'all-values';
    const headerElement = document.querySelector('header h2');
    const headerTitle = headerElement ? (headerElement.dataset.valueType || headerElement.textContent.trim()) : '';
    const isAllValuesPage = window.location.pathname === '/index' || window.location.pathname === '/index.html' || window.location.pathname === '/all-values' || 
                           window.location.pathname === '/' || 
                           document.title.toLowerCase().includes('all values') ||
                           headerTitle === "All Values";
    
    if (isCategoryOption && !isAllValuesPage && optgroup.label === 'Filter by Category') {
      // On specific category pages, disable category filter options except current one
      const currentPageCategory = filterValueMappings[headerTitle];
      
      if (option.value !== currentPageCategory) {
        optionDiv.classList.add('disabled');
        optionDiv.style.opacity = '0.5';
        optionDiv.style.cursor = 'not-allowed';
        optionDiv.style.pointerEvents = 'none';
      }
    }
    
    const isSelected = type === 'sort' ? 
      option.value === currentSortCriteria :
      (option.value.startsWith('category-') || option.value === 'all-values') ? 
        option.value === currentCategoryFilter : 
        option.value === currentFilterType;
        
    if (option.selected || isSelected) {
      optionDiv.classList.add('selected');
    }
    const checkIcon = document.createElement('i');
    checkIcon.className = 'fas fa-check checkmark';
    checkIcon.setAttribute('aria-hidden', 'true');
    optionDiv.appendChild(checkIcon);
    const labelSpan = document.createElement('span');
    labelSpan.className = 'option-label';
    labelSpan.textContent = optionTexts[option.value] || option.textContent;
    optionDiv.appendChild(labelSpan);
    
    if (!optionDiv.classList.contains('disabled')) {
      optionDiv.addEventListener('click', () => {
        if (type === 'sort') {
          // For sort: clear ALL selections across all optgroups (single selection only)
          content.querySelectorAll('.custom-dropdown-option').forEach(opt => opt.classList.remove('selected'));
        } else {
          // For filter: only clear selections within the same optgroup (allows multiple selections across different groups)
          group.querySelectorAll('.custom-dropdown-option').forEach(opt => opt.classList.remove('selected'));
        }
        optionDiv.classList.add('selected');
        
        // Update the appropriate temporary variable
        if (type === 'sort') {
          // Sort handling (unchanged)
          tempValue = option.value;
        } else {
          // Filter handling - determine if it's category or type filter
          if (option.value.startsWith('category-') || option.value === 'all-values') {
            tempCategoryFilter = option.value;
          } else {
            tempTypeFilter = option.value;
          }
        }
      });
    }
    
    group.appendChild(optionDiv);
  });

  content.appendChild(group);
});

// Assemble and show
overlay.appendChild(closeBtn);

// Both sort and filter dropdowns: put header inside scrollable content
content.insertBefore(header, content.firstChild);
if (description) {
  content.insertBefore(description, content.children[1]);
}
container.appendChild(content);

// Action buttons
const actions = document.createElement('div');
actions.className = 'custom-dropdown-actions modal-actions-grid';

const applyBtn = document.createElement('button');
applyBtn.className = 'modal-btn save-btn';
applyBtn.innerHTML = type === 'sort' ? '<i class="fas fa-sort"></i>Sort' : '<i class="fas fa-filter"></i>Filter';
actions.appendChild(applyBtn);

const resetBtn = document.createElement('button');
resetBtn.className = 'modal-btn reset-btn';
resetBtn.innerHTML = '<i class="fas fa-undo"></i>Reset';
actions.appendChild(resetBtn);

applyBtn.addEventListener('click', () => {
  // Apply button now just closes the dropdown - changes are auto-applied
  closeDropdown();
});

resetBtn.addEventListener('click', () => {
  // Only disable controls when actually applying changes
  disableControls();
  resetAllFilters();
  closeDropdown();
});

container.appendChild(actions);
overlay.appendChild(container);
document.body.appendChild(overlay);
document.body.classList.add('jbtn-modal-open');

// Show with animation - force reflow for consistent behavior across browsers
requestAnimationFrame(() => {
  void overlay.offsetWidth; // trigger reflow to ensure animation
  overlay.classList.add('show');
  // Move focus into the dropdown to clear any outline on trigger buttons
  try { closeBtn.focus({ preventScroll: true }); } catch (e) {}
  // Also clear any focus/pressing classes on wrappers
  try {
    const sortBtn = document.getElementById('LISortButton');
    const filterBtn = document.getElementById('LIFilterButton');
    const sortWrap = sortBtn ? sortBtn.closest('.input-icon-wrapper') : null;
    const filterWrap = filterBtn ? filterBtn.closest('.input-icon-wrapper') : null;
    if (sortBtn) sortBtn.blur();
    if (filterBtn) filterBtn.blur();
    if (sortWrap) sortWrap.classList.remove('is-focus', 'is-active', 'pressing');
    if (filterWrap) filterWrap.classList.remove('is-focus', 'is-active', 'pressing');
  } catch (e) {}
});

function closeDropdown() {
  // Apply changes before closing if this is a filter dropdown
  if (type === 'filter') {
    // Apply both type and category filters
    const filtersChanged = currentFilterType !== tempTypeFilter || currentCategoryFilter !== tempCategoryFilter;
    
    if (filtersChanged) {
      disableControls('sortfilter');
      currentFilterType = tempTypeFilter;
      currentCategoryFilter = tempCategoryFilter;
      
      // Set the select element to the type filter value for compatibility
      selectElement.value = tempTypeFilter;
      selectElement.dispatchEvent(new Event('change'));
    }
  } else if (type === 'sort') {
    // Apply sort changes if different
    if (tempValue && tempValue !== selectElement.value) {
      disableControls('sortfilter');
      selectElement.value = tempValue;
      selectElement.dispatchEvent(new Event('change'));
    }
  }
  
  overlay.classList.remove('show');
  overlay.addEventListener('transitionend', function handler(e) {
    if (e.target === overlay && e.propertyName === 'opacity') {
      overlay.removeEventListener('transitionend', handler);
      overlay.remove();
      // Don't automatically enable controls - they'll be enabled after filtering completes
      const isOtherOverlayActive =
        document.querySelector('.fullscreen-overlay.active') ||
        document.querySelector('.jbtn-modal-overlay.active') ||
        (mobileMenu && mobileMenu.classList.contains('open')) ||
        (customLoadingOverlay && customLoadingOverlay.style.opacity !== '0');
      if (!isOtherOverlayActive) {
        document.body.classList.remove('jbtn-modal-open');
      }
    }
  });
  document.removeEventListener('keydown', escHandler);
}

function escHandler(e) {
  if (e.key === 'Escape') {
    // Changes will be auto-applied in closeDropdown()
    closeDropdown();
  }
}

// Close handlers
closeBtn.addEventListener('click', () => {
  // Changes will be auto-applied in closeDropdown()
  closeDropdown();
});
overlay.addEventListener('click', (e) => {
  if (e.target === overlay) {
    // Changes will be auto-applied in closeDropdown()
    closeDropdown();
  }
});
document.addEventListener('keydown', escHandler);
}


function updateDisplayedItems(shouldRefocusSearch = false, isInitialRender = false) {
if (isAnimating && !isInitialRender) return;
disableControls();

let processedList = [...vehicles];

const searchInput = document.getElementById('LISearchInput');
const query = searchInput.value.trim().toLowerCase();
if (query) {
    processedList = processedList.filter(vehicle =>
    vehicle.name.toLowerCase().includes(query)
    );
}

// Apply type filtering (limited, retired, etc.)
if (currentFilterType !== 'all-items') {
    let category = currentFilterType.replace("-only", "");
    if (category === "vault-exclusive") category = "safe";
    if (category === "pass-exclusive") {
        processedList = processedList.filter(vehicle => 
            vehicle.seasonPass && vehicle.seasonPass.toLowerCase().includes("pass exclusive")
        );
    } else {
        processedList = processedList.filter(vehicle => vehicle.type.trim().toLowerCase() === category);
    }
}

// Apply category filtering (vehicle, texture, etc.) - only on All Values page
const headerTitleElement = document.querySelector('header h2');
const headerTitle = headerTitleElement ? (headerTitleElement.dataset.valueType || headerTitleElement.textContent.trim()) : '';
const isAllValuesPage = window.location.pathname === '/index' || window.location.pathname === '/index.html' || window.location.pathname === '/all-values' || 
                       window.location.pathname === '/' || 
                       document.title.toLowerCase().includes('all values') ||
                       headerTitle === "All Values";

if (isAllValuesPage && currentCategoryFilter !== 'all-values' && currentCategoryFilter.startsWith('category-')) {
    const categoryType = currentCategoryFilter.replace('category-', '').replace('-', ' ');
    const categoryMap = {
        'vehicle': 'Vehicle Values',
        'texture': 'Texture Values',
        'color': 'Color Values',
        'spoiler': 'Spoiler Values',
        'rim': 'Rim Values',
        'tire': 'Tire Values',
        'furniture': 'Furniture Values',
        'gun texture': 'Gun Texture Values',
        'vehicle horn': 'Vehicle Horn Values',
        'drift particle': 'Drift Particle Values'
    };
    const targetCategory = categoryMap[categoryType];
    if (targetCategory) {
        processedList = processedList.filter(vehicle => vehicle.category === targetCategory);
    }
}

const expectedType = demandTypeMappings[headerTitle];

if (currentSortCriteria === "name-asc") {
    processedList.sort((a, b) => a.name.localeCompare(b.name));
} else if (currentSortCriteria === "name-desc") {
    processedList.sort((a, b) => b.name.localeCompare(a.name));
} else if (currentSortCriteria === "price-asc") {
    processedList.sort((a, b) => {
    const aVal = parseCurrency(a.tradingValue);
    const bVal = parseCurrency(b.tradingValue);
    return aVal - bVal || a.name.localeCompare(b.name);
    });
} else if (currentSortCriteria === "price-desc") {
    processedList.sort((a, b) => {
    const aVal = parseCurrency(a.tradingValue);
    const bVal = parseCurrency(b.tradingValue);
    return bVal - aVal || a.name.localeCompare(b.name);
    });
} else if (currentSortCriteria === "duped-price-desc") {
    processedList.sort((a, b) => {
        const aVal = parseCurrency(a.dupedValue);
        const bVal = parseCurrency(b.dupedValue);
        return bVal - aVal || a.name.localeCompare(b.name);
    });
} else if (currentSortCriteria === "duped-price-asc") {
    processedList.sort((a, b) => {
        const aVal = parseCurrency(a.dupedValue);
        const bVal = parseCurrency(b.dupedValue);
        return aVal - bVal || a.name.localeCompare(b.name);
    });
} else if (currentSortCriteria === "obtainable-price-desc") {
    processedList.sort((a, b) => {
        const aVal = parseCurrency(a.originalPrice);
        const bVal = parseCurrency(b.originalPrice);
        return bVal - aVal || a.name.localeCompare(b.name);
    });
} else if (currentSortCriteria === "obtainable-price-asc") {
    processedList.sort((a, b) => {
        const aVal = parseCurrency(a.originalPrice);
        const bVal = parseCurrency(b.originalPrice);
        return aVal - bVal || a.name.localeCompare(b.name);
    });
} else if (currentSortCriteria === "safe-tier-desc") {
    processedList.sort((a, b) => {
        const aTier = parseSafeTier(a.originalPrice);
        const bTier = parseSafeTier(b.originalPrice);
        if (aTier === Infinity && bTier !== Infinity) return 1;
        if (aTier !== Infinity && bTier === Infinity) return -1;
        if (aTier === Infinity && bTier === Infinity) return a.name.localeCompare(b.name);
        return bTier - aTier || a.name.localeCompare(b.name);
    });
} else if (currentSortCriteria === "safe-tier-asc") {
    processedList.sort((a, b) => {
        const aTier = parseSafeTier(a.originalPrice);
        const bTier = parseSafeTier(b.originalPrice);
        if (aTier === Infinity && bTier !== Infinity) return 1;
        if (aTier !== Infinity && bTier === Infinity) return -1;
        if (aTier === Infinity && bTier === Infinity) return a.name.localeCompare(b.name);
        return aTier - bTier || a.name.localeCompare(b.name);
    });
} else if (currentSortCriteria === "season-reward-desc") {
    processedList.sort((a, b) => {
        const aReward = parseSeasonReward(a.originalPrice);
        const bReward = parseSeasonReward(b.originalPrice);
        if (aReward.season === Infinity && bReward.season !== Infinity) return 1;
        if (aReward.season !== Infinity && bReward.season === Infinity) return -1;
        if (aReward.season === Infinity && bReward.season === Infinity) return a.name.localeCompare(b.name);
        if (bReward.season !== aReward.season) return bReward.season - aReward.season;
        return bReward.level - aReward.level || a.name.localeCompare(b.name);
    });
} else if (currentSortCriteria === "season-reward-asc") {
    processedList.sort((a, b) => {
        const aReward = parseSeasonReward(a.originalPrice);
        const bReward = parseSeasonReward(b.originalPrice);
        if (aReward.season === Infinity && bReward.season !== Infinity) return 1;
        if (aReward.season !== Infinity && bReward.season === Infinity) return -1;
        if (aReward.season === Infinity && bReward.season === Infinity) return a.name.localeCompare(b.name);
        if (aReward.season !== bReward.season) return aReward.season - bReward.season;
        return aReward.level - bReward.level || a.name.localeCompare(b.name);
    });
} else if (currentSortCriteria === "demand-desc") {
  processedList.sort((a, b) => {
    const aKey = normalizeName(a.nickname || a.name);
    const bKey = normalizeName(b.nickname || b.name);
    
    // For All Values page, use the item's category to determine the expected type
    let aExpectedType, bExpectedType;
    if (headerTitle === "All Values") {
      aExpectedType = a.category ? demandTypeMappings[a.category] : expectedType;
      bExpectedType = b.category ? demandTypeMappings[b.category] : expectedType;
    } else {
      aExpectedType = bExpectedType = expectedType;
    }
    
    const aFreqKey = Array.isArray(aExpectedType) ? aExpectedType.map(type => `${aKey}|${type}`).find(k => frequencyData[k]) : `${aKey}|${aExpectedType}`;
    const bFreqKey = Array.isArray(bExpectedType) ? bExpectedType.map(type => `${bKey}|${type}`).find(k => frequencyData[k]) : `${bKey}|${bExpectedType}`;
    const aFreq = frequencyData[aFreqKey] || null;
    const bFreq = frequencyData[bFreqKey] || null;
    const aDemand = aFreq ? aFreq.DemandMultiple : 0;
    const bDemand = bFreq ? bFreq.DemandMultiple : 0;
    return bDemand - aDemand || a.name.localeCompare(b.name);
  });
} else if (currentSortCriteria === "demand-asc") {
  processedList.sort((a, b) => {
    const aKey = normalizeName(a.nickname || a.name);
    const bKey = normalizeName(b.nickname || b.name);
    
    // For All Values page, use the item's category to determine the expected type
    let aExpectedType, bExpectedType;
    if (headerTitle === "All Values") {
      aExpectedType = a.category ? demandTypeMappings[a.category] : expectedType;
      bExpectedType = b.category ? demandTypeMappings[b.category] : expectedType;
    } else {
      aExpectedType = bExpectedType = expectedType;
    }
    
    const aFreqKey = Array.isArray(aExpectedType) ? aExpectedType.map(type => `${aKey}|${type}`).find(k => frequencyData[k]) : `${aKey}|${aExpectedType}`;
    const bFreqKey = Array.isArray(bExpectedType) ? bExpectedType.map(type => `${bKey}|${type}`).find(k => frequencyData[k]) : `${bKey}|${bExpectedType}`;
    const aFreq = frequencyData[aFreqKey] || null;
    const bFreq = frequencyData[bFreqKey] || null;
    const aDemand = aFreq ? aFreq.DemandMultiple : 0;
    const bDemand = bFreq ? bFreq.DemandMultiple : 0;
    return aDemand - bDemand || a.name.localeCompare(b.name);
  });
} else if (currentSortCriteria === "copies-desc") {
  processedList.sort((a, b) => {
    const aKey = normalizeName(a.nickname || a.name);
    const bKey = normalizeName(b.nickname || b.name);
    
    // For All Values page, use the item's category to determine the expected type
    let aExpectedType, bExpectedType;
    if (headerTitle === "All Values") {
      aExpectedType = a.category ? demandTypeMappings[a.category] : expectedType;
      bExpectedType = b.category ? demandTypeMappings[b.category] : expectedType;
    } else {
      aExpectedType = bExpectedType = expectedType;
    }
    
    const aFreqKey = Array.isArray(aExpectedType) ? aExpectedType.map(type => `${aKey}|${type}`).find(k => frequencyData[k]) : `${aKey}|${aExpectedType}`;
   const bFreqKey = Array.isArray(bExpectedType) ? bExpectedType.map(type => `${bKey}|${type}`).find(k => frequencyData[k]) : `${bKey}|${bExpectedType}`;
    const aFreq = frequencyData[aFreqKey] || null;
    const bFreq = frequencyData[bFreqKey] || null;
    const aCopies = aFreq && aFreq.UniqueCirculation ? Number(aFreq.UniqueCirculation) : 0;
    const bCopies = bFreq && bFreq.UniqueCirculation ? Number(bFreq.UniqueCirculation) : 0;
    return bCopies - aCopies || a.name.localeCompare(b.name);
  });
} else if (currentSortCriteria === "copies-asc") {
  processedList.sort((a, b) => {
    const aKey = normalizeName(a.nickname || a.name);
    const bKey = normalizeName(b.nickname || b.name);
    
    // For All Values page, use the item's category to determine the expected type
    let aExpectedType, bExpectedType;
    if (headerTitle === "All Values") {
      aExpectedType = a.category ? demandTypeMappings[a.category] : expectedType;
      bExpectedType = b.category ? demandTypeMappings[b.category] : expectedType;
    } else {
      aExpectedType = bExpectedType = expectedType;
    }
    
    const aFreqKey = Array.isArray(aExpectedType) ? aExpectedType.map(type => `${aKey}|${type}`).find(k => frequencyData[k]) : `${aKey}|${aExpectedType}`;
    const bFreqKey = Array.isArray(bExpectedType) ? bExpectedType.map(type => `${bKey}|${type}`).find(k => frequencyData[k]) : `${bKey}|${bExpectedType}`;
    const aFreq = frequencyData[aFreqKey] || null;
    const bFreq = frequencyData[bFreqKey] || null;
    const aCopies = aFreq && aFreq.UniqueCirculation ? Number(aFreq.UniqueCirculation) : 0;
    const bCopies = bFreq && bFreq.UniqueCirculation ? Number(bFreq.UniqueCirculation) : 0;
    return aCopies - bCopies || a.name.localeCompare(b.name);
  });
} else if (currentSortCriteria === "traded-desc") {
  processedList.sort((a, b) => {
    const aKey = normalizeName(a.nickname || a.name);
    const bKey = normalizeName(b.nickname || b.name);
    
    // For All Values page, use the item's category to determine the expected type
    let aExpectedType, bExpectedType;
    if (headerTitle === "All Values") {
      aExpectedType = a.category ? demandTypeMappings[a.category] : expectedType;
      bExpectedType = b.category ? demandTypeMappings[b.category] : expectedType;
    } else {
      aExpectedType = bExpectedType = expectedType;
    }
    
    const aFreqKey = Array.isArray(aExpectedType) ? aExpectedType.map(type => `${aKey}|${type}`).find(k => frequencyData[k]) : `${aKey}|${aExpectedType}`;
    const bFreqKey = Array.isArray(bExpectedType) ? bExpectedType.map(type => `${bKey}|${type}`).find(k => frequencyData[k]) : `${bKey}|${bExpectedType}`;
    const aFreq = frequencyData[aFreqKey] || null;
    const bFreq = frequencyData[bFreqKey] || null;
    const aTraded = aFreq && aFreq.TimesTraded ? Number(aFreq.TimesTraded) : 0;
    const bTraded = bFreq && bFreq.TimesTraded ? Number(bFreq.TimesTraded) : 0;
    return bTraded - aTraded || a.name.localeCompare(b.name);
  });
} else if (currentSortCriteria === "traded-asc") {
  processedList.sort((a, b) => {
    const aKey = normalizeName(a.nickname || a.name);
    const bKey = normalizeName(b.nickname || b.name);
    
    // For All Values page, use the item's category to determine the expected type
    let aExpectedType, bExpectedType;
    if (headerTitle === "All Values") {
      aExpectedType = a.category ? demandTypeMappings[a.category] : expectedType;
      bExpectedType = b.category ? demandTypeMappings[b.category] : expectedType;
    } else {
      aExpectedType = bExpectedType = expectedType;
    }
    
    const aFreqKey = Array.isArray(aExpectedType) ? aExpectedType.map(type => `${aKey}|${type}`).find(k => frequencyData[k]) : `${aKey}|${aExpectedType}`;
    const bFreqKey = Array.isArray(bExpectedType) ? bExpectedType.map(type => `${bKey}|${type}`).find(k => frequencyData[k]) : `${bKey}|${bExpectedType}`;
    const aFreq = frequencyData[aFreqKey] || null;
    const bFreq = frequencyData[bFreqKey] || null;
    const aTraded = aFreq && aFreq.TimesTraded ? Number(aFreq.TimesTraded) : 0;
    const bTraded = bFreq && bFreq.TimesTraded ? Number(bFreq.TimesTraded) : 0;
    return aTraded - bTraded || a.name.localeCompare(b.name);
  });
} else if (currentSortCriteria === "updated-desc") {
  processedList.sort((a, b) => {
    const aTime = a.timeStamp ? new Date(a.timeStamp).getTime() : -Infinity;
    const bTime = b.timeStamp ? new Date(b.timeStamp).getTime() : -Infinity;
    return (bTime - aTime) || a.name.localeCompare(b.name);
  });
} else if (currentSortCriteria === "updated-asc") {
  processedList.sort((a, b) => {
    const aTime = a.timeStamp ? new Date(a.timeStamp).getTime() : Infinity;
    const bTime = b.timeStamp ? new Date(b.timeStamp).getTime() : Infinity;
    return (aTime - bTime) || a.name.localeCompare(b.name);
  });
} else if (currentSortCriteria === "collector-rarity-desc") {
  processedList.sort((a, b) => {
    const aRarity = parseCollectorRarity(a.collectorRarity);
    const bRarity = parseCollectorRarity(b.collectorRarity);
    
    // Handle items without rarity data (-1) - put them at the end for desc
    if (aRarity === -1 && bRarity !== -1) return 1;
    if (aRarity !== -1 && bRarity === -1) return -1;
    if (aRarity === -1 && bRarity === -1) return a.name.localeCompare(b.name);
    
    return bRarity - aRarity || a.name.localeCompare(b.name);
  });
} else if (currentSortCriteria === "collector-rarity-asc") {
  processedList.sort((a, b) => {
    const aRarity = parseCollectorRarity(a.collectorRarity);
    const bRarity = parseCollectorRarity(b.collectorRarity);
    
    // Handle items without rarity data (-1) - put them at the end for asc
    if (aRarity === -1 && bRarity !== -1) return 1;
    if (aRarity !== -1 && bRarity === -1) return -1;
    if (aRarity === -1 && bRarity === -1) return a.name.localeCompare(b.name);
    
    return aRarity - bRarity || a.name.localeCompare(b.name);
  });
} else if (currentSortCriteria === "pity-chance-desc") {
  processedList.sort((a, b) => {
    const aPity = parsePityChance(a.originalPrice);
    const bPity = parsePityChance(b.originalPrice);
    const aIsColor = a.category === "Color Values";
    const bIsColor = b.category === "Color Values";
    
    // Prioritize Color Values items with pity data first
    if (aIsColor && aPity !== -1 && (!bIsColor || bPity === -1)) return -1;
    if (bIsColor && bPity !== -1 && (!aIsColor || aPity === -1)) return 1;
    
    // Among Color Values items with pity data, sort by pity value
    if (aIsColor && bIsColor && aPity !== -1 && bPity !== -1) {
      return bPity - aPity || a.name.localeCompare(b.name);
    }
    
    // Handle all remaining items without pity data - put them at the end, sorted alphabetically
    if (aPity === -1 && bPity !== -1) return 1;
    if (aPity !== -1 && bPity === -1) return -1;
    if (aPity === -1 && bPity === -1) return a.name.localeCompare(b.name);
    
    // For items with pity data, sort by pity value, then alphabetically
    return bPity - aPity || a.name.localeCompare(b.name);
  });
} else if (currentSortCriteria === "pity-chance-asc") {
  processedList.sort((a, b) => {
    const aPity = parsePityChance(a.originalPrice);
    const bPity = parsePityChance(b.originalPrice);
    const aIsColor = a.category === "Color Values";
    const bIsColor = b.category === "Color Values";
    
    // Prioritize Color Values items with pity data first
    if (aIsColor && aPity !== -1 && (!bIsColor || bPity === -1)) return -1;
    if (bIsColor && bPity !== -1 && (!aIsColor || aPity === -1)) return 1;
    
    // Among Color Values items with pity data, sort by pity value
    if (aIsColor && bIsColor && aPity !== -1 && bPity !== -1) {
      return aPity - bPity || a.name.localeCompare(b.name);
    }
    
    // Handle all remaining items without pity data - put them at the end, sorted alphabetically
    if (aPity === -1 && bPity !== -1) return 1;
    if (aPity !== -1 && bPity === -1) return -1;
    if (aPity === -1 && bPity === -1) return a.name.localeCompare(b.name);
    
    // For items with pity data, sort by pity value, then alphabetically
    return aPity - bPity || a.name.localeCompare(b.name);
  });
} else if (currentSortCriteria === "vehicle-health-desc") {
  processedList.sort((a, b) => {
    const aHealth = parseVehicleHealth(a.vehicleHealth);
    const bHealth = parseVehicleHealth(b.vehicleHealth);
    
    // Handle items without health data (-1) - put them at the end, sorted alphabetically
    if (aHealth === -1 && bHealth !== -1) return 1;
    if (aHealth !== -1 && bHealth === -1) return -1;
    if (aHealth === -1 && bHealth === -1) return a.name.localeCompare(b.name);
    
    return bHealth - aHealth || a.name.localeCompare(b.name);
  });
} else if (currentSortCriteria === "vehicle-health-asc") {
  processedList.sort((a, b) => {
    const aHealth = parseVehicleHealth(a.vehicleHealth);
    const bHealth = parseVehicleHealth(b.vehicleHealth);
    
    // Handle items without health data (-1) - put them at the end, sorted alphabetically
    if (aHealth === -1 && bHealth !== -1) return 1;
    if (aHealth !== -1 && bHealth === -1) return -1;
    if (aHealth === -1 && bHealth === -1) return a.name.localeCompare(b.name);
    
    return aHealth - bHealth || a.name.localeCompare(b.name);
  });
} else if (currentSortCriteria === "repair-time-desc") {
  processedList.sort((a, b) => {
    const aRepair = parseRepairTime(a.vehicleHealth);
    const bRepair = parseRepairTime(b.vehicleHealth);
    
    // Handle items without repair time data (-1) - put them at the end, sorted alphabetically
    if (aRepair === -1 && bRepair !== -1) return 1;
    if (aRepair !== -1 && bRepair === -1) return -1;
    if (aRepair === -1 && bRepair === -1) return a.name.localeCompare(b.name);
    
    return bRepair - aRepair || a.name.localeCompare(b.name);
  });
} else if (currentSortCriteria === "repair-time-asc") {
  processedList.sort((a, b) => {
    const aRepair = parseRepairTime(a.vehicleHealth);
    const bRepair = parseRepairTime(b.vehicleHealth);
    
    // Handle items without repair time data (-1) - put them at the end, sorted alphabetically
    if (aRepair === -1 && bRepair !== -1) return 1;
    if (aRepair !== -1 && bRepair === -1) return -1;
    if (aRepair === -1 && bRepair === -1) return a.name.localeCompare(b.name);
    
    return aRepair - bRepair || a.name.localeCompare(b.name);
  });
} else if (currentSortCriteria === "top-speed-desc") {
  processedList.sort((a, b) => {
    const aSpeed = parseTopSpeed(a.topSpeed);
    const bSpeed = parseTopSpeed(b.topSpeed);
    
    // Handle items without top speed data (-1) - put them at the end, sorted alphabetically
    if (aSpeed === -1 && bSpeed !== -1) return 1;
    if (aSpeed !== -1 && bSpeed === -1) return -1;
    if (aSpeed === -1 && bSpeed === -1) return a.name.localeCompare(b.name);
    
    return bSpeed - aSpeed || a.name.localeCompare(b.name);
  });
} else if (currentSortCriteria === "top-speed-asc") {
  processedList.sort((a, b) => {
    const aSpeed = parseTopSpeed(a.topSpeed);
    const bSpeed = parseTopSpeed(b.topSpeed);
    
    // Handle items without top speed data (-1) - put them at the end, sorted alphabetically
    if (aSpeed === -1 && bSpeed !== -1) return 1;
    if (aSpeed !== -1 && bSpeed === -1) return -1;
    if (aSpeed === -1 && bSpeed === -1) return a.name.localeCompare(b.name);
    
    return aSpeed - bSpeed || a.name.localeCompare(b.name);
  });
}

updateSortSelectDisplay();
renderVehicles(processedList, shouldRefocusSearch, isInitialRender);
}

const LISearchInput = document.getElementById("LISearchInput");
if (LISearchInput) {
LISearchInput.addEventListener("input", debounce(updateDisplayedItems, 600));
// Show/hide clear button as user types
const _updateClearBtn = () => {
  const btn = document.getElementById('LIClearSearch');
  if (!btn) return;
  const hasText = !!(LISearchInput.value && LISearchInput.value.trim());
  btn.style.display = hasText ? 'inline-flex' : 'none';
};
LISearchInput.addEventListener('input', _updateClearBtn);
// Initial state
setTimeout(_updateClearBtn, 0);
LISearchInput.addEventListener("keydown", function(event) {
  if (event.key === "Enter") {
    event.preventDefault();
    const searchInput = document.getElementById('LISearchInput');
    updateDisplayedItems(document.activeElement === searchInput, false);
  } else if (event.key === 'Escape' && LISearchInput.value) {
    // Mirror og-item-finder: ESC clears and updates
    event.stopPropagation();
    LISearchInput.value = '';
    try {
      const btn = document.getElementById('LIClearSearch');
      if (btn) btn.style.display = 'none';
    } catch(_) {}
    try { updateDisplayedItems(true, false); } catch(_) {}
  }
});
}

// Map clear (x) press interactions to wrapper for consistent outlines
(function mapClearButtonToWrapper() {
document.addEventListener('DOMContentLoaded', () => {
  const clearBtn = document.getElementById('LIClearSearch');
  const inputWrap = clearBtn ? clearBtn.closest('.input-icon-wrapper') : null;
  if (!clearBtn || !inputWrap) return;
  const add = () => inputWrap.classList.add('pressing');
  const remove = () => inputWrap.classList.remove('pressing');
  clearBtn.addEventListener('pointerdown', add);
  clearBtn.addEventListener('pointerup', remove);
  clearBtn.addEventListener('pointercancel', remove);
  clearBtn.addEventListener('pointerleave', remove);
  clearBtn.addEventListener('blur', remove);
});
})();


const LISortSelect = document.getElementById("LISortSelect");
if (LISortSelect) {
LISortSelect.addEventListener("change", function(event) {
    currentSortCriteria = event.target.value;
    const searchInput = document.getElementById('LISearchInput');
    updateButtonText();
    updateDisplayedItems(document.activeElement === searchInput, false);
});
}

const LIFilterSelect = document.getElementById("LIFilterSelect");
if (LIFilterSelect) {
LIFilterSelect.addEventListener("change", function(event) {
    const value = event.target.value;
    if (value.startsWith('category-') || value === 'all-values') {
        currentCategoryFilter = value;
    } else {
        currentFilterType = value;
    }
    const searchInput = document.getElementById('LISearchInput');
    updateButtonText();
    updateDisplayedItems(document.activeElement === searchInput, false);
});
}

// Add click handlers for new sort/filter buttons to show menus
const sortButton = document.getElementById('LISortButton');
const filterButton = document.getElementById('LIFilterButton');

if (sortButton) {
sortButton.addEventListener('click', () => {
  // Prevent focus ring from sticking on mouse interactions
  try { sortButton.blur(); } catch (e) {}
  const wrap = sortButton.closest('.input-icon-wrapper');
  if (wrap) wrap.classList.remove('is-focus', 'is-active', 'pressing');
  showCustomDropdown('sort', LISortSelect, originalSortOptionTexts);
});
sortButton.addEventListener('keydown', e => {
  if (e.key === 'Enter' || e.key === ' ') {
    e.preventDefault();
    showCustomDropdown('sort', LISortSelect, originalSortOptionTexts);
  }
});
}

// Clear search button behavior
(function setupClearSearch() {
const clearBtn = document.getElementById('LIClearSearch');
const input = document.getElementById('LISearchInput');
if (!clearBtn || !input) return;
clearBtn.addEventListener('click', () => {
  input.value = '';
  try { updateDisplayedItems(true, false); } catch(_) {}
  // Hide the button and refocus input
  clearBtn.style.display = 'none';
  try { input.focus(); } catch(_) {}
});
})();

if (filterButton) {
filterButton.addEventListener('click', () => {
  // Prevent focus ring from sticking on mouse interactions
  try { filterButton.blur(); } catch (e) {}
  const wrap = filterButton.closest('.input-icon-wrapper');
  if (wrap) wrap.classList.remove('is-focus', 'is-active', 'pressing');
  showCustomDropdown('filter', LIFilterSelect, originalFilterOptionTexts);
});
filterButton.addEventListener('keydown', e => {
  if (e.key === 'Enter' || e.key === ' ') {
    e.preventDefault();
    showCustomDropdown('filter', LIFilterSelect, originalFilterOptionTexts);
  }
});
}

document.addEventListener('click', function(event) {
const searchInput = document.getElementById('LISearchInput');
if (searchInput && !searchInput.contains(event.target) && document.activeElement === searchInput) {
  searchInput.blur();
}
});

// Input modality tracking to control when outlines appear (keyboard vs mouse)
(function trackInputModality() {
const onPointer = () => {
  document.body.classList.add('using-mouse');
};
const onKey = (e) => {
  if (e.key === 'Tab' || e.key === 'ArrowUp' || e.key === 'ArrowDown' || e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
    document.body.classList.remove('using-mouse');
  }
};
window.addEventListener('pointerdown', onPointer, { passive: true });
window.addEventListener('keydown', onKey, { passive: true });
})();

function throttle(func, limit) {
let inThrottle;
return function(...args) {
  const context = this;
  if (!inThrottle) {
    func.apply(context, args);
    inThrottle = true;
    setTimeout(() => inThrottle = false, limit);
  }
};
}

function setupAnnouncement() {
const announcementClose = document.getElementById("LIAnnouncementClose");
const announcementBar = document.getElementById("LIAnnouncementBar");

if (!announcementClose || !announcementBar) return;

function setCookie(name, value, days) {
  let expires = "";
  if (days) {
    const date = new Date();
    date.setTime(date.getTime() + (days*24*60*60*1000));
    expires = "; expires=" + date.toUTCString();
  }
  document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}
function getCookie(name) {
  const nameEQ = name + "=";
  const ca = document.cookie.split(';');
  for(let i=0;i < ca.length;i++) {
    let c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

if (getCookie('announcementClosed') === 'true') {
  announcementBar.classList.add('hidden');
}

announcementClose.addEventListener("click", () => {
  announcementBar.classList.add("hidden");
  setCookie('announcementClosed', 'true', 30); 
});
}

function setupImageClickEvents() {
const images = document.querySelectorAll('.value-bubble img');
const overlay = document.getElementById('LIFullscreenOverlay');
const fullscreenImage = document.getElementById('LIFullscreenImage');
const closeButton = document.getElementById('LIFullscreenClose');
const fullscreenCaption = document.getElementById('LIFullscreenCaption');

if (!overlay || !fullscreenImage || !closeButton || !fullscreenCaption) return;

// Bind direct listeners for currently present images (legacy path)
images.forEach(img => {
  if (img.dataset.fsBound === '1') return;
  img.dataset.fsBound = '1';
  img.addEventListener('click', () => {
    if (overlay.classList.contains('active')) return;
    try {
      fullscreenImage.src = img.currentSrc || img.src;
      const itemName = img.alt || 'Item';
      const itemCategory = img.dataset.category || 'Item';
      const itemType = itemCategory.replace(' Values', '') || 'Item';
      fullscreenCaption.innerHTML = `${itemName} (${itemType}) From Roblox Jailbreak | Sourced From <a href="https://jailbreaktradingnetwork.com" target="_blank" rel="noopener noreferrer">Jailbreak Trading Network</a>.`;
      const wrap = img.closest('.image-container');
      if (wrap && !wrap.classList.contains('img-loaded')) wrap.classList.add('img-loaded');
    } catch(_) {}
    overlay.classList.add('active');
    document.body.classList.add('jbtn-modal-open');
  });
});

// Add delegated listener so newly restored/inserted images work without rebinding
const container = document.getElementById('LIBubblesContainer');
if (container && container.dataset.fsDelegated !== '1') {
  container.dataset.fsDelegated = '1';
  container.addEventListener('click', (e) => {
    const targetImg = e.target && e.target.closest ? e.target.closest('.image-container img') : null;
    if (!targetImg || !container.contains(targetImg)) return;
    if (overlay.classList.contains('active')) return;
    try {
      fullscreenImage.src = targetImg.currentSrc || targetImg.src;
      const itemName = targetImg.alt || 'Item';
      const itemCategory = targetImg.dataset.category || 'Item';
      const itemType = itemCategory.replace(' Values', '') || 'Item';
      fullscreenCaption.innerHTML = `${itemName} (${itemType}) From Roblox Jailbreak | Sourced From <a href="https://jailbreaktradingnetwork.com" target="_blank" rel="noopener noreferrer">Jailbreak Trading Network</a>.`;
      const wrap = targetImg.closest('.image-container');
      if (wrap && !wrap.classList.contains('img-loaded')) wrap.classList.add('img-loaded');
    } catch(_) {}
    overlay.classList.add('active');
    document.body.classList.add('jbtn-modal-open');
  });
}

function closeOverlay() {
  overlay.classList.remove('active');
  if ((!mobileMenu || !mobileMenu.classList.contains('open')) &&
      (!customLoadingOverlay || customLoadingOverlay.style.opacity === '0')) {
      document.body.classList.remove('jbtn-modal-open');
  }
}

if (!closeButton.dataset.listenerAttached) {
    closeButton.addEventListener('click', closeOverlay);
    closeButton.dataset.listenerAttached = 'true';
}
if (!overlay.dataset.listenerAttached) {
    overlay.addEventListener('click', (e) => {
      if (e.target === overlay) {
        closeOverlay();
      }
    });
    overlay.dataset.listenerAttached = 'true';
}
}

function setupDescriptionClickEvents() {
const modal = document.getElementById('descriptionModal');
const modalTitle = document.getElementById('descriptionModalTitle');
const modalContent = document.getElementById('descriptionModalContent');
const closeButton = modal ? modal.querySelector('.jbtn-modal-close') : null;
const youtubeSearchLink = document.getElementById('description-youtube-search-videos');
if (!modal || !modalTitle || !modalContent || !closeButton) return;

// Delegate click handling so dynamically added items work without cloning
if (!window.__descDelegated) {
  window.__descDelegated = true;
  document.addEventListener('click', (e) => {
    const target = e.target.closest('.clickable-description');
    if (!target) return;
    e.stopPropagation();
    const description = target.dataset.description;
    const itemName = target.dataset.itemName;
    const itemNickname = target.dataset.itemNickname;
    modalTitle.textContent = `${itemName} - Description`;
    modalContent.textContent = description || '';
    if (youtubeSearchLink) {
      if (itemName) {
        const searchName = (itemNickname && itemNickname.trim() !== '') ? itemNickname : itemName;
        youtubeSearchLink.href = `https://www.youtube.com/@JailbreakTradingNetwork/search?query=${encodeURIComponent(searchName)}`;
        youtubeSearchLink.classList.remove('inactive');
        youtubeSearchLink.classList.add('active');
      } else {
        youtubeSearchLink.href = '#';
        youtubeSearchLink.classList.add('inactive');
        youtubeSearchLink.classList.remove('active');
      }
    }
    modal.classList.add('active');
    document.body.classList.add('jbtn-modal-open');
  });
}

function closeDescriptionModal() {
  modal.classList.remove('active');
  if ((!mobileMenu || !mobileMenu.classList.contains('open')) &&
      (!customLoadingOverlay || customLoadingOverlay.style.opacity === '0')) {
    document.body.classList.remove('jbtn-modal-open');
  }
}
if (!closeButton.dataset.listenerAttached) {
  closeButton.addEventListener('click', closeDescriptionModal);
  closeButton.dataset.listenerAttached = 'true';
}
if (!modal.dataset.listenerAttached) {
  modal.addEventListener('click', (e) => { if (e.target === modal) closeDescriptionModal(); });
  modal.dataset.listenerAttached = 'true';
}
}

function createTopFadeEffectElement() {
  if (document.getElementById('top-fade-effect')) return;

  const topFadeEffectElement = document.createElement('div');
  topFadeEffectElement.id = 'top-fade-effect';
  topFadeEffectElement.style.position = 'fixed';
  topFadeEffectElement.style.top = 'var(--top-navbar-height)';
  topFadeEffectElement.style.left = '0';
  topFadeEffectElement.style.right = '0';
  topFadeEffectElement.style.height = '10px';
  topFadeEffectElement.style.background = 'linear-gradient(to bottom, rgba(0,0,0,0.4) 0%, rgba(0,0,0,0) 100%)';
  topFadeEffectElement.style.zIndex = '998';
  topFadeEffectElement.style.pointerEvents = 'none';
  document.body.appendChild(topFadeEffectElement);
}

const headerBannerElement = document.getElementById('pageHeader');
let rafPending = false;

function scrollHandler() {
  if (!rafPending) {
      rafPending = true;
      window.requestAnimationFrame(() => {
          if (headerBannerElement) {
              const scrollY = window.pageYOffset;
              headerBannerElement.style.backgroundPosition = `center calc(50% + ${scrollY * 0.4}px)`;
          }
          handleNavbarScrollStyle();
          rafPending = false;
      });
  }
}

window.addEventListener('scroll', scrollHandler, { passive: true });


function handleGlobalResizeThrottledLegacy() {
// This function is now deprecated - using the improved version above
closeAllDropdowns();
manageNavbarOverflow();
updateSortSelectDisplay();
adjustHeaderTitleSize();
}
const throttledResize = throttle(handleGlobalResizeThrottled, 50);
window.addEventListener('resize', throttledResize);

// Close mobile menu when resizing to desktop
window.addEventListener('resize', () => {
if (window.innerWidth >= 992 && mobileMenu && mobileMenu.classList.contains('open')) {
  closeMobileMenu();
}
});


document.addEventListener('DOMContentLoaded', () => {
populateNavbarLinks();
setupNavbarInteractions();
adjustLayoutForNavbar();
handleNavbarScrollStyle();

// Ensure navbar responsiveness is set up correctly
manageNavbarOverflow();

// Initialize responsive navigation and dynamic dropdowns
setTimeout(() => {
  responsiveNav.init();
  dropdownSizer.init();
  // Run navbar management again after a short delay to ensure everything is set up
  manageNavbarOverflow();
}, 100);

// Fallback animation trigger if window load fails
setTimeout(() => {
  const topNavbar = document.getElementById('topNavbar');
  const headerElement = document.getElementById('pageHeader');
  const controlsElement = document.getElementById('LIMenuContainer');

  if (!isLoadingError && dataLoaded && topNavbar && !topNavbar.classList.contains('loaded')) {
    initiatePageReveal();
  }
}, 3000); // 3 second fallback

document.addEventListener('click', (event) => {
    if (!event.target.closest('.navbar-dropdown')) {
        closeAllDropdowns();
    }
});

document.querySelectorAll('.collapsible-footer-section .collapsible-header').forEach(header => {
  header.addEventListener('click', () => {
    const section = header.parentElement;
    section.classList.toggle('active');
  });
});

});


window.addEventListener('load', async () => {
// Ensure body is ready for animation
document.body.style.animationDelay = '0.2s';

adjustLayoutForNavbar();
manageNavbarOverflow();
manageControlsOverflow();

// Extra safety check for mobile navigation after a delay
setTimeout(() => {
  manageNavbarOverflow();
}, 200);

createTopFadeEffectElement();
loadSettings();
showCustomLoadingScreen("Initializing application components...");

try {
  await fetchFrequencyData();
  vehicles = await fetchVehiclesData();
  dataLoaded = true;

  // Show category filters if this is an All Values page
  const headerTitleElement = document.querySelector('header h2');
  const headerTitle = headerTitleElement ? (headerTitleElement.dataset.valueType || headerTitleElement.textContent.trim()) : "Vehicle Values";
  const categoryFilterGroup = document.getElementById('LICategoryFilterGroup');
  const isAllValuesPage = headerTitle === "All Values" || 
                         headerTitle.toLowerCase().includes('all values') ||
                         window.location.pathname === '/index' || window.location.pathname === '/index.html' || window.location.pathname === '/all-values' || 
                         window.location.pathname === '/';
  
  if (categoryFilterGroup && isAllValuesPage) {
    categoryFilterGroup.style.display = 'block';
  } else if (categoryFilterGroup) {
    categoryFilterGroup.style.display = 'none';
  }

  initializeDefaults();
  setupAnnouncement();

  if (!isLoadingError) {
      updateLoadingProgress(100, "All data loaded. Application is ready!");
      setTimeout(() => {
        initiatePageReveal();
        // Ensure button sizing is applied after page is fully loaded
        setTimeout(updateSortFilterButtonSizing, 200);
      }, 300);
  }

} catch (error) {
  console.error('Error during initial load:', error);
  if (!isLoadingError) {
    updateLoadingProgress(0, `Error: ${error.message || "An unexpected critical error occurred."}`, true);
  }
  if (customLoadingOverlay && customLoadingOverlay.style.opacity === '1' && controlsElement) {
      controlsElement.style.visibility = 'hidden';
  }
}
});

// Mobile labels no longer needed - using consistent labels

const modalOverlay = document.getElementById('footer-modal-overlay');
if (modalOverlay) {
  const modalClose = modalOverlay.querySelector('.footer-modal-close');
  const modalLinks = document.querySelectorAll('a.footer-link[data-modal]');
  const modalContents = modalOverlay.querySelectorAll('.modal-text-content');

  const openModal = (modalId) => {
      modalContents.forEach(content => {
          content.classList.toggle('active', content.dataset.modalId === modalId);
      });
      modalOverlay.classList.add('active');
      document.body.classList.add('jbtn-modal-open');
  };

  const closeModal = () => {
      modalOverlay.classList.remove('active');
      const isOtherOverlayActive = document.querySelector('.fullscreen-overlay.active') ||
                                  (customLoadingOverlay && customLoadingOverlay.style.opacity !== '0') ||
                                  (mobileMenu && mobileMenu.classList.contains('open'));
      if (!isOtherOverlayActive) {
          document.body.classList.remove('jbtn-modal-open');
      }
  };

  modalLinks.forEach(link => {
      link.addEventListener('click', (e) => {
          e.preventDefault();
          openModal(link.dataset.modal);
      });
  });

  if (modalClose) modalClose.addEventListener('click', closeModal);
  modalOverlay.addEventListener('click', (e) => {
      if (e.target === modalOverlay) closeModal();
  });
  window.addEventListener('keydown', (e) => {
      if (e.key === 'Escape' && modalOverlay.classList.contains('active')) {
          closeModal();
      }
  });
}


const LIResetButton = document.getElementById("LIResetButton");
if (LIResetButton) {
  LIResetButton.addEventListener('click', resetAllFilters);
}

const defaultSettings = {
  hideHeader: false,
  hideFooter: false,
  hideSubmissionInfo: false,
  hideItemExplanations: false,
  hideItemTimestamps: false,
  hideStatusBadges: false,
  disableHoverGlow: false,
  disableHeaderAnim: false
};
let userSettings = { ...defaultSettings };

function applySettings() {
// Community box visibility
try {
  const submissionInfo = document.querySelector('.discord-submission-info');
  if (submissionInfo) submissionInfo.style.display = userSettings.hideSubmissionInfo ? 'none' : '';
  document.body.classList.toggle('submission-hidden', !!userSettings.hideSubmissionInfo);
} catch (_) { /* no-op */ }

document.body.classList.toggle('settings-hide-explanation', userSettings.hideItemExplanations);
document.body.classList.toggle('settings-hide-timestamp', userSettings.hideItemTimestamps);
document.body.classList.toggle('settings-disable-glow', userSettings.disableHoverGlow);
document.body.classList.toggle('settings-hide-header', userSettings.hideHeader);
document.body.classList.toggle('settings-hide-footer', userSettings.hideFooter);

document.body.classList.toggle('settings-hide-status-badges', userSettings.hideStatusBadges);
manageScrollHandler();

// Update navbar style immediately when header visibility changes
if (userSettings.hideHeader) {
  // Force navbar to scrolled state when header is hidden
  if (topNavbarElement) {
    topNavbarElement.classList.add('scrolled');
  }
} else {
  // Let normal scroll handler determine navbar state when header is shown
  handleNavbarScrollStyle();
  // Recalculate header title size when header is re-enabled
  setTimeout(() => {
    const h1 = document.querySelector('header h1');
    const container = document.querySelector('.header-title-container');
    if (h1 && container) {
      // Force a reflow to ensure proper layout calculations
      container.offsetHeight;
      // Reset any previous inline font-size and recalculate
      h1.style.fontSize = '';
      adjustHeaderTitleSize();
    }
  }, 150); // Slightly longer delay to ensure proper layout
}
}

function loadSettings() {
  const savedSettings = localStorage.getItem('jbtnSettings');
  if (savedSettings) {
      try {
          const parsedSettings = JSON.parse(savedSettings);
          userSettings = { ...userSettings, ...parsedSettings };
      } catch (e) {
          console.error("Failed to parse settings from localStorage", e);
      }
  }
  
  document.querySelectorAll('#settingsModal input[type="checkbox"]').forEach(checkbox => {
      const settingKey = checkbox.dataset.setting;
      if (settingKey in userSettings) {
          checkbox.checked = userSettings[settingKey];
      }
  });

  applySettings();
}

function saveSettings() {
  document.querySelectorAll('#settingsModal input[type="checkbox"]').forEach(checkbox => {
      const settingKey = checkbox.dataset.setting;
      if (settingKey in userSettings) {
          userSettings[settingKey] = checkbox.checked;
      }
  });
  localStorage.setItem('jbtnSettings', JSON.stringify(userSettings));
  applySettings();
}

// Initialize settings modal when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
const settingsModal = document.getElementById('settingsModal');
if (settingsModal) {
const openBtn = document.getElementById('LISettingsButton');
const closeBtn = settingsModal.querySelector('.jbtn-modal-close');
const saveAndCloseBtn = document.getElementById('saveSettingsButton');
const resetBtn = document.getElementById('resetSettingsButton');
let settingsStateOnOpen = {};

function getCurrentSettingsState() {
    const state = {};
    document.querySelectorAll('#settingsModal input[type="checkbox"]').forEach(checkbox => {
        const settingKey = checkbox.dataset.setting;
        if (settingKey) {
            state[settingKey] = checkbox.checked;
        }
    });
    return state;
}

function openSettingsModal() {
    loadSettings();
    settingsStateOnOpen = getCurrentSettingsState();
    settingsModal.classList.add('active');
    document.body.classList.add('jbtn-modal-open');
}
function closeSettingsModal() {
    settingsModal.classList.remove('active');
    document.body.classList.remove('jbtn-modal-open');
}

if(openBtn) openBtn.addEventListener('click', openSettingsModal);
if(closeBtn) closeBtn.addEventListener('click', closeSettingsModal);

function resetSettings() {
    localStorage.removeItem('jbtnSettings');
    userSettings = { ...defaultSettings };
    document.querySelectorAll('#settingsModal input[type="checkbox"]').forEach(checkbox => {
        const settingKey = checkbox.dataset.setting;
        if (settingKey in userSettings) {
            checkbox.checked = userSettings[settingKey];
        }
    });
    applySettings();
}

if(resetBtn) resetBtn.addEventListener('click', resetSettings);

if(saveAndCloseBtn) {
    saveAndCloseBtn.addEventListener('click', () => {
        saveSettings();
        closeSettingsModal();
    });
}

settingsModal.addEventListener('click', (e) => {
  if (e.target === settingsModal) {
    const currentState = getCurrentSettingsState();
    if (JSON.stringify(settingsStateOnOpen) !== JSON.stringify(currentState)) {
        saveSettings();
    }
    closeSettingsModal();
  }
});

loadSettings();
}
});

// Scroll handler for navbar styling only (when header parallax is disabled)
let navbarRafPending = false;
function navbarOnlyScrollHandler() {
  if (!navbarRafPending) {
      navbarRafPending = true;
      window.requestAnimationFrame(() => {
          handleNavbarScrollStyle();
          navbarRafPending = false;
      });
  }
}

function manageScrollHandler() {
if (headerBannerElement && !userSettings.disableHeaderAnim) {
    window.addEventListener('scroll', scrollHandler, { passive: true });
    window.removeEventListener('scroll', navbarOnlyScrollHandler);
} else {
    window.removeEventListener('scroll', scrollHandler);
    if (headerBannerElement) {
      headerBannerElement.style.backgroundPosition = `center center`;
    }
    // Still need navbar color changes even without header parallax
    window.addEventListener('scroll', navbarOnlyScrollHandler, { passive: true });
}
}

let bubbleObserver;


function setupBubbleAnimationObserver() {
if (bubbleObserver) {
    bubbleObserver.disconnect();
}

const options = {
    root: null,
    rootMargin: '400px 0px 400px 0px',
    threshold: [0, 0.01, 0.1]
};

const observerCallback = (entries, observer) => {
    const candidates = [];
    for (const entry of entries) {
        const el = entry.target;
        if (!el || !el.classList) continue;
        if (entry.isIntersecting) {
          // entering viewport: ensure leaving removed and reveal if needed
          el.classList.remove('leaving');
          if (!el.classList.contains('visible')) candidates.push(el);
        } else {
          // exiting viewport: do not toggle visibility here to avoid content flicker
          // Keep card visible; unloading logic will handle far-offscreen elements
          // Optionally clear transient leaving state
          el.classList.remove('leaving');
        }
    }
    if (!candidates.length) return;

    // Group by visual row (based on rounded top position)
    const rows = new Map();
    candidates.forEach(el => {
        const rect = el.getBoundingClientRect();
        const key = Math.round(rect.top / 8) * 8; // normalize to reduce tiny drift
        if (!rows.has(key)) rows.set(key, []);
        rows.get(key).push(el);
    });

    // Reveal rows from top to bottom; within a row, reveal left-to-right
    const sortedRowKeys = Array.from(rows.keys()).sort((a, b) => a - b);
    let rowIndex = 0;
    sortedRowKeys.forEach(rowKey => {
        const rowEls = rows.get(rowKey) || [];
        // sort by DOM order for stable left-to-right
        rowEls.sort((a, b) => (a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING) ? -1 : 1);
        const baseDelay = rowIndex * 60; // ms per row
        rowEls.forEach((el, i) => {
            const perElDelay = i * 20; // small intra-row stagger
            const totalDelay = baseDelay + perElDelay;
            el.style.transitionDelay = `${totalDelay}ms`;
            el.classList.add('visible');
            setTimeout(() => { try { el.style.transitionDelay = '0ms'; } catch(_){} }, totalDelay + 300);
            observer.unobserve(el);
        });
        rowIndex += 1;
    });
};

bubbleObserver = new IntersectionObserver(observerCallback, options);

  const elementsToAnimate = document.querySelectorAll('#LIBubblesContainer .value-bubble, #LIBubblesContainer .no-items-found-message');
  elementsToAnimate.forEach(el => {
    // Only observe elements not yet visible; prevents flicker during rapid scroll
    if (!el.classList.contains('visible')) {
      bubbleObserver.observe(el);
    }
  });

const container = document.getElementById('LIBubblesContainer');
if (container) {
    container.classList.remove('sorting');
}
}

function resetAllFilters() {
  const searchInput = document.getElementById('LISearchInput');
  const sortSelect = document.getElementById('LISortSelect');
  const filterSelect = document.getElementById('LIFilterSelect');

  if (searchInput) searchInput.value = '';
  
  currentSortCriteria = 'price-desc';
  if (sortSelect) sortSelect.value = currentSortCriteria;

  currentFilterType = 'all-items';
  currentCategoryFilter = 'all-values';
  if (filterSelect) filterSelect.value = currentFilterType;
  
  // On reset, animate the count from 0 back up to the full set
  __forceCountFromZero = true;

  // Update button text and sizing after reset
  updateButtonText();
  
  updateDisplayedItems(false, false);
}

const explanationModal = document.getElementById('explanationModal');
if (explanationModal) {
  const closeBtn = explanationModal.querySelector('.jbtn-modal-close');
  const xPostLink = document.getElementById('explanation-x-post');
  const blogPostLink = document.getElementById('explanation-blog-post');
  const xHistoryLink = document.getElementById('explanation-x-history');
  const blogHistoryLink = document.getElementById('explanation-blog-history');
  const valueHistoryLink = document.getElementById('explanation-value-history');
  const demandHistoryLink = document.getElementById('explanation-demand-history');
  const youtubeSearchLink = document.getElementById('youtube-search-videos');

  const openModal = (xPostUrl, blogPostUrl, itemName, itemNickname) => {
      if (xPostLink) {
          if (xPostUrl && xPostUrl.trim() !== "") {
              xPostLink.href = xPostUrl;
              xPostLink.classList.remove('inactive');
              xPostLink.classList.add('active');
          } else {
              xPostLink.removeAttribute('href');
              xPostLink.classList.add('inactive');
              xPostLink.classList.remove('active');
          }
      }
      if (blogPostLink) {
          if (blogPostUrl && blogPostUrl.trim() !== "") {
              blogPostLink.href = blogPostUrl;
              blogPostLink.classList.remove('inactive');
              blogPostLink.classList.add('active');
          } else {
              blogPostLink.removeAttribute('href');
              blogPostLink.classList.add('inactive');
              blogPostLink.classList.remove('active');
          }
      }
      if (xHistoryLink) {
          if (itemName && xPostUrl && xPostUrl.trim() !== "") {
              const encodedName = encodeURIComponent(itemName);
              xHistoryLink.href = `https://x.com/search?q=from%3ATradingWebsite%20${encodedName}&f=live`;
              xHistoryLink.classList.remove('inactive');
              xHistoryLink.classList.add('active');
          } else {
              xHistoryLink.removeAttribute('href');
              xHistoryLink.classList.add('inactive');
              xHistoryLink.classList.remove('active');
          }
      }
      if (blogHistoryLink) {
          if (itemName && blogPostUrl && blogPostUrl.trim() !== "") {
              const encodedName = encodeURIComponent(itemName);
              blogHistoryLink.href = `https://blog.jailbreaktradingnetwork.com/search?q=${encodedName}`;
              blogHistoryLink.classList.remove('inactive');
              blogHistoryLink.classList.add('active');
          } else {
              blogHistoryLink.removeAttribute('href');
              blogHistoryLink.classList.add('inactive');
              blogHistoryLink.classList.remove('active');
          }
      }
      if (valueHistoryLink) {
          if (itemName) {
              valueHistoryLink.href = `value-dynamics.html?item=${encodeURIComponent(itemName)}`;
              valueHistoryLink.classList.remove('inactive');
              valueHistoryLink.classList.add('active');
          } else {
              valueHistoryLink.href = '#';
              valueHistoryLink.classList.add('inactive');
              valueHistoryLink.classList.remove('active');
          }
      }
      if (demandHistoryLink) {
          if (itemName) {
              const demandName = (itemNickname && itemNickname.trim() !== '') ? itemNickname : itemName;
              demandHistoryLink.href = `demand-graph.html?item=${encodeURIComponent(demandName)}`;
              demandHistoryLink.classList.remove('inactive');
              demandHistoryLink.classList.add('active');
          } else {
              demandHistoryLink.href = '#';
              demandHistoryLink.classList.add('inactive');
              demandHistoryLink.classList.remove('active');
          }
      }
      if (youtubeSearchLink) {
          if (itemName) {
              const searchName = (itemNickname && itemNickname.trim() !== '') ? itemNickname : itemName;
              youtubeSearchLink.href = `https://www.youtube.com/@JailbreakTradingNetwork/search?query=${encodeURIComponent(searchName)}`;
              youtubeSearchLink.classList.remove('inactive');
              youtubeSearchLink.classList.add('active');
          } else {
              youtubeSearchLink.href = '#';
              youtubeSearchLink.classList.add('inactive');
              youtubeSearchLink.classList.remove('active');
          }
      }
      explanationModal.classList.add('active');
      document.body.classList.add('jbtn-modal-open');
  };

  const closeModal = () => {
      explanationModal.classList.remove('active');
      document.body.classList.remove('jbtn-modal-open');
  };

  closeBtn.addEventListener('click', closeModal);
  explanationModal.addEventListener('click', (e) => {
      if (e.target === explanationModal) {
          closeModal();
      }
  });
  
  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape' && explanationModal.classList.contains('active')) {
      closeModal();
    }
  });

  document.getElementById('LIBubblesContainer').addEventListener('click', (e) => {
      const button = e.target.closest('.explanation-button');
      if (button) {
          e.preventDefault();
          const xPost = button.dataset.xPost;
          const blogPost = button.dataset.blogPost;
          const itemName = button.dataset.itemName;
          const itemNickname = button.dataset.itemNickname;
          openModal(xPost, blogPost, itemName, itemNickname);
      }
  });

  explanationModal.addEventListener('click', (e) => {
      const inactiveLink = e.target.closest('.explanation-option-button.inactive');
      if (inactiveLink) {
          e.preventDefault();
      }
  });
}


// All Values page functionality
(function initAllValuesSupport() {
// Toggle category filter visibility based on page type
function toggleCategoryFilters() {
  const headerTitleElement = document.querySelector('header h2');
  const headerTitle = headerTitleElement ? (headerTitleElement.dataset.valueType || headerTitleElement.textContent.trim()) : "Vehicle Values";
  const categoryFilterGroup = document.getElementById('LICategoryFilterGroup');
  
  if (categoryFilterGroup) {
    const isAllValuesPage = headerTitle === "All Values" || 
                           headerTitle.toLowerCase().includes('all values') ||
                           window.location.pathname === '/index' || window.location.pathname === '/index.html' || window.location.pathname === '/all-values' || 
                           window.location.pathname === '/';
    
    if (isAllValuesPage) {
      categoryFilterGroup.style.display = 'block';
    } else {
      categoryFilterGroup.style.display = 'none';
      // Reset category filter to default and type filter to all-items
      currentCategoryFilter = 'all-values';
      currentFilterType = 'all-items';
      const filterSelect = document.getElementById('LIFilterSelect');
      if (filterSelect) filterSelect.value = 'all-items';
    }
  }
}

// Initialize category filters when DOM is ready
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', toggleCategoryFilters);
} else {
  toggleCategoryFilters();
}

// Also initialize when page loads
window.addEventListener('load', () => {
  setTimeout(toggleCategoryFilters, 100);
});
})();

</script>
<div id="hiddenAudioPlayer" style="display:none;"></div>
<script src="https://www.youtube.com/iframe_api"></script>
<script>
(function() {
const ytScript = document.querySelector('script[src="https://www.youtube.com/iframe_api"]');
if (ytScript) {
ytScript.addEventListener('error', function(e) {
  console.error('[All Values] Failed to load YouTube IFrame API:', e);
});
}
setTimeout(function() {
if (!window.YT || !window.YT.Player) {
  console.error('[All Values] YouTube API not available after loading.');
}
}, 5000);
})();
</script>
<script>

(function() {
const playerElement = document.getElementById('hiddenAudioPlayer');
let player;
let isPlaying = false;
// Guard: only allow automatic resume on new pages if previously playing
let canAutoResume = false;
// Set when user explicitly hit play this session (prevents our guard from pausing)
let userInitiatedPlay = false;
let saveTimer = null;
let progressSlider;
let volumeSlider;
let volumeDisplay;
let volDownBtn;
let volUpBtn;
let presetButtons;

const AUDIO_KEY = 'jbtnAudio';
function loadAudioState() {
try {
  const raw = localStorage.getItem(AUDIO_KEY);
  if (!raw) return null;
  return JSON.parse(raw);
} catch (_) { return null; }
}
function saveAudioState(extra = {}) {
try {
  const base = loadAudioState() || {};
  const curTime = (player && typeof player.getCurrentTime === 'function') ? player.getCurrentTime() : base.currentTime || 0;
  const vol = (player && typeof player.getVolume === 'function') ? player.getVolume() : (volumeSlider ? parseInt(volumeSlider.value, 10) : (base.volume || 100));
  const data = {
    videoId: 'lwo2bSAOePE',
    currentTime: curTime,
    volume: vol,
    isPlaying: isPlaying,
    hasInteracted: base.hasInteracted || false,
    lastUpdated: Date.now(),
    ...extra,
  };
  localStorage.setItem(AUDIO_KEY, JSON.stringify(data));
} catch (_) { /* ignore */ }
}
function markInteracted() {
const st = loadAudioState() || {};
if (!st.hasInteracted) {
  saveAudioState({ hasInteracted: true });
}
}
function startAutoSave() {
if (saveTimer) return;
saveTimer = setInterval(() => { if (isPlaying) saveAudioState(); }, 3000);
}
function stopAutoSave() {
if (saveTimer) { clearInterval(saveTimer); saveTimer = null; }
}

function updateToggleIcon() {
const icon = document.querySelector('#navAudioToggle i');
if (!icon) return;
icon.classList.toggle('fa-play', !isPlaying);
icon.classList.toggle('fa-pause', isPlaying);
}

function updateProgress() {
if (!player || typeof player.getCurrentTime !== 'function') return;
const timeElem = document.getElementById('navAudioTime');
const current = player.getCurrentTime();
const duration = player.getDuration() || 0;
if (timeElem && duration > 0) {
  const minutes = Math.floor(current / 60);
  const seconds = Math.floor(current % 60).toString().padStart(2, '0');
  const durMin = Math.floor(duration / 60);
  const durSec = Math.floor(duration % 60).toString().padStart(2, '0');
  timeElem.textContent = `${minutes}:${seconds}/${durMin}:${durSec}`;
}
if (progressSlider && duration > 0) {
  progressSlider.max = duration;
  progressSlider.value = current;
}
}

function updateActivePreset(vol) {
if (!presetButtons) return;
const val = parseInt(vol, 10);
presetButtons.forEach(btn => {
  const btnVol = parseInt(btn.dataset.vol, 10);
  if (!isNaN(btnVol) && btnVol === val) {
    btn.classList.add('active');
  } else {
    btn.classList.remove('active');
  }
});
}

function setVolume(vol) {
if (volumeDisplay) volumeDisplay.textContent = `${vol}%`;
if (volumeSlider) volumeSlider.value = vol;
if (player && typeof player.setVolume === 'function') player.setVolume(vol);
updateActivePreset(vol);
}

document.addEventListener('DOMContentLoaded', function() {
const toggleBtn = document.getElementById('navAudioToggle');
const backBtn = document.getElementById('navAudioBack');
const forwardBtn = document.getElementById('navAudioForward');
const infoBtn = document.getElementById('navAudioInfo');
volumeSlider = document.getElementById('navAudioVolume');
volDownBtn = document.getElementById('navVolumeDown');
volUpBtn = document.getElementById('navVolumeUp');
volumeDisplay = document.getElementById('volumeDisplay');
progressSlider = document.getElementById('navAudioProgress');
presetButtons = document.querySelectorAll('.volume-preset');
if (volumeSlider) setVolume(volumeSlider.value);
const infoModal = document.getElementById('audioInfoModal');
const infoClose = infoModal ? infoModal.querySelector('.jbtn-modal-close') : null;

if (playerElement) {
  const initPlayer = function() {
    player = new YT.Player('hiddenAudioPlayer', {
      height: '0',
      width: '0',
      videoId: 'lwo2bSAOePE',
      playerVars: { autoplay: 0, controls: 0, loop: 1, playlist: 'lwo2bSAOePE' },
      events: {
        'onReady': function() {
          // Restore from saved state only if user has interacted before
          const saved = loadAudioState();
          if (saved && saved.hasInteracted) {
            // Always require a fresh manual play when returning to the page
            canAutoResume = false;
            // Apply volume
            const vol = Number.isFinite(saved.volume) ? saved.volume : (volumeSlider ? parseInt(volumeSlider.value, 10) : 100);
            if (volumeSlider) setVolume(vol);
            // Seek near last position, accounting for elapsed time if it was playing
            try {
              const elapsed = (Date.now() - (saved.lastUpdated || Date.now())) / 1000;
              let target = saved.currentTime || 0;
              if (saved.isPlaying) target += Math.max(0, Math.min(elapsed, 30)); // cap drift
              if (player && typeof player.seekTo === 'function') player.seekTo(target, true);
            } catch(_) {}
            // Do not auto resume playback on load; wait for explicit user action
            isPlaying = false;
            updateToggleIcon();
            saveAudioState();
          } else {
            if (volumeSlider) setVolume(volumeSlider.value);
          }
          setInterval(updateProgress, 500);
        },
        'onError': function(error) {
          console.error('[All Values] Player error:', error);
        },
        'onStateChange': function(event) {
          if (event.data === YT.PlayerState.ENDED) {
            if (player && typeof player.playVideo === 'function') {
              player.seekTo(0);
              player.playVideo();
            }
            isPlaying = true;
          } else if (event.data === YT.PlayerState.PLAYING) {
            // Prevent unintended auto-play when entering a new subpage if previously paused
            if (!userInitiatedPlay && !canAutoResume) {
              try { player.pauseVideo(); } catch(_) {}
              isPlaying = false;
              updateToggleIcon();
              saveAudioState();
              return;
            }
            isPlaying = true;
            // After first PLAYING, future state changes can proceed normally
            canAutoResume = true;
            userInitiatedPlay = false;
            startAutoSave();
            saveAudioState();
          } else if (event.data === YT.PlayerState.PAUSED) {
            isPlaying = false;
            saveAudioState();
          }
          updateToggleIcon();
        }
      }
    });
  };
  if (window.YT && YT.Player) {
    initPlayer();
  } else {
    window.onYouTubeIframeAPIReady = initPlayer;
  }
}

if (toggleBtn) {
  toggleBtn.addEventListener('click', function() {
    if (!player) return;
    markInteracted();
    const state = player.getPlayerState();
    if (state !== YT.PlayerState.PLAYING) {
      userInitiatedPlay = true;
      player.playVideo();
      isPlaying = true;
    } else {
      player.pauseVideo();
      isPlaying = false;
      // Once user explicitly pauses, prevent auto-resume on next page load
      canAutoResume = false;
    }
    updateToggleIcon();
    saveAudioState();
  });
}

if (backBtn) {
  backBtn.addEventListener('click', function() {
    if (player) {
      player.seekTo(Math.max(player.getCurrentTime() - 10, 0), true);
      saveAudioState();
    }
  });
}

if (forwardBtn) {
  forwardBtn.addEventListener('click', function() {
    if (player && !isNaN(player.getDuration())) {
      player.seekTo(Math.min(player.getCurrentTime() + 10, player.getDuration()), true);
      saveAudioState();
    }
  });
}

// New audio control buttons
const restartBtn = document.getElementById('audioRestart');
const shuffleBtn = document.getElementById('audioShuffle');
const loopBtn = document.getElementById('audioLoop');
const speedBtn = document.getElementById('audioSpeed');
const muteBtn = document.getElementById('audioMute');

let isLooping = false;
let playbackSpeeds = [1.0, 1.25, 1.5, 2.0];
let currentSpeedIndex = 0;
let isMuted = false;
let previousVolume = 100;

if (restartBtn) {
  restartBtn.addEventListener('click', function() {
    if (player) {
      player.seekTo(0, true);
      saveAudioState();
    }
  });
}

if (shuffleBtn) {
  shuffleBtn.addEventListener('click', function() {
    shuffleBtn.classList.toggle('active');
  });
}

if (loopBtn) {
  loopBtn.addEventListener('click', function() {
    isLooping = !isLooping;
    loopBtn.classList.toggle('active', isLooping);
    if (player && typeof player.setLoop === 'function') {
      player.setLoop(isLooping);
    }
  });
}

if (speedBtn) {
  speedBtn.addEventListener('click', function() {
    currentSpeedIndex = (currentSpeedIndex + 1) % playbackSpeeds.length;
    const newSpeed = playbackSpeeds[currentSpeedIndex];
    speedBtn.innerHTML = `<i class="fas fa-tachometer-alt"></i> ${newSpeed}x`;
    
    if (player && typeof player.setPlaybackRate === 'function') {
      player.setPlaybackRate(newSpeed);
    }
    markInteracted();
    saveAudioState();
  });
}

if (muteBtn) {
  muteBtn.addEventListener('click', function() {
    if (player && typeof player.getVolume === 'function') {
      if (isMuted) {
        player.setVolume(previousVolume);
        if (volumeSlider) volumeSlider.value = previousVolume;
        muteBtn.classList.remove('active');
        muteBtn.innerHTML = '<i class="fas fa-volume-up"></i> Mute';
      } else {
        previousVolume = player.getVolume();
        player.setVolume(0);
        if (volumeSlider) volumeSlider.value = 0;
        muteBtn.classList.add('active');
        muteBtn.innerHTML = '<i class="fas fa-volume-mute"></i> Muted';
      }
      isMuted = !isMuted;
      if (volumeDisplay) {
        volumeDisplay.textContent = `${isMuted ? 0 : Math.round(previousVolume)}%`;
      }
      markInteracted();
      saveAudioState();
    }
  });
}

if (volumeSlider) {
  volumeSlider.addEventListener('input', function() {
    setVolume(this.value);
    markInteracted();
    saveAudioState();
  });
}

if (volDownBtn) {
  volDownBtn.addEventListener('click', () => {
    let vol = Math.max(parseInt(volumeSlider.value, 10) - 5, 0);
    setVolume(vol);
  });
}

if (volUpBtn) {
  volUpBtn.addEventListener('click', () => {
    let vol = Math.min(parseInt(volumeSlider.value, 10) + 5, 100);
    setVolume(vol);
  });
}

if (presetButtons.length) {
  presetButtons.forEach(btn => {
    btn.addEventListener('click', () => {
      const vol = parseInt(btn.dataset.vol, 10);
      if (!isNaN(vol)) {
        setVolume(vol);
      }
      markInteracted();
      saveAudioState();
    });
  });
}

if (progressSlider) {
  progressSlider.addEventListener('input', function() {
    if (player) {
      player.seekTo(this.value, true);
      saveAudioState();
    }
  });
}

const sourceBtn = document.getElementById('audioSourceButton');
const licenseBtn = document.getElementById('audioLicenseButton');
if (sourceBtn) {
  sourceBtn.addEventListener('click', () => {
    window.open('http://www.orangefreesounds.com/dreamy-ambient-background-music-loop/', '_blank', 'noopener');
  });
}
if (licenseBtn) {
  licenseBtn.addEventListener('click', () => {
    window.open('https://creativecommons.org/licenses/by/4.0/', '_blank', 'noopener');
  });
}


if (infoBtn && infoModal) {
  const openInfo = () => {
    infoModal.classList.add('active');
    document.body.classList.add('jbtn-modal-open');
  };
  const closeInfo = () => {
    infoModal.classList.remove('active');
    document.body.classList.remove('jbtn-modal-open');
  };
  infoBtn.addEventListener('click', openInfo);
  if (infoClose) infoClose.addEventListener('click', closeInfo);
  infoModal.addEventListener('click', (e) => {
    if (e.target === infoModal) closeInfo();
  });
  window.addEventListener('keydown', (e) => {
    if (e.key === 'Escape' && infoModal.classList.contains('active')) {
      closeInfo();
    }
  });
}
});
// Save on page hide
window.addEventListener('pagehide', () => { try { saveAudioState(); } catch(_) {} });
})();
</script>
<script>
// Persist white + blue outlines while press-holding on Search/Sort/Filter
(function attachPressingOutline() {
const addPressing = (el) => el && el.classList.add('pressing');
const removePressing = (el) => el && el.classList.remove('pressing');
const onUp = (wrap) => () => removePressing(wrap);
document.addEventListener('DOMContentLoaded', () => {
  const wrappers = Array.from(document.querySelectorAll(
    '.search-sort .input-icon-wrapper[data-nav-priority="1"],' +
    '.search-sort .input-icon-wrapper[data-nav-priority="2"],' +
    '.search-sort .input-icon-wrapper[data-nav-priority="3"]'
  ));
  const sortButton = document.getElementById('LISortButton');
  const filterButton = document.getElementById('LIFilterButton');
  const sortWrapper = sortButton ? sortButton.closest('.input-icon-wrapper') : null;
  const filterWrapper = filterButton ? filterButton.closest('.input-icon-wrapper') : null;
  wrappers.forEach((wrap) => {
    wrap.addEventListener('pointerdown', () => addPressing(wrap));
    // Keep pressing highlight until release/cancel; do not clear on focusin so press-hold shows outline
    wrap.addEventListener('pointerup', onUp(wrap));
    wrap.addEventListener('pointercancel', onUp(wrap));
  });
  // Global safety: always clear transient states and blur triggers on release
  document.addEventListener('pointerup', () => {
    wrappers.forEach((w) => w && w.classList.remove('pressing','is-focus','is-active','is-hover'));
    if (sortButton) { try { sortButton.blur(); } catch (err) {} }
    if (filterButton) { try { filterButton.blur(); } catch (err) {} }
  }, { capture: true, passive: true });
  document.addEventListener('pointercancel', () => wrappers.forEach(removePressing), { capture: true, passive: true });
  window.addEventListener('scroll', () => wrappers.forEach(removePressing), { passive: true });
});
})();
</script>
<script src="scripts/menus.js"></script>
<script>
// Make Reset/Music/Settings mimic wrapper press behavior without accidental clicks
(function wireControlButtonPressStates() {
document.addEventListener('DOMContentLoaded', () => {
  const ids = ['LIResetButton', 'navAudioInfo', 'LISettingsButton'];
  const buttons = ids.map(id => document.getElementById(id)).filter(Boolean);
  if (!buttons.length) return;

  const onPointerDown = (e) => {
    const btn = e.currentTarget;
    if (btn.disabled) return;
    btn.dataset.pressed = '1';
    btn.classList.add('pressing');
    // Start a new press cycle; ensure any stale cancel flag is cleared
    delete btn.dataset.cancelClick;
  };
  const onPointerUp = (e) => {
    const btn = e.currentTarget;
    btn.classList.remove('pressing');
    delete btn.dataset.pressed;
    // Note: do not clear cancelClick here; click handler will respect it and clear
  };
  const onPointerCancel = onPointerUp;
  const onPointerLeave = (e) => {
    const btn = e.currentTarget;
    if (btn.dataset.pressed === '1') {
      // While holding and leaving, remove highlight
      btn.classList.remove('pressing');
      // And cancel the ensuing click if release occurs off-button
      btn.dataset.cancelClick = '1';
    }
  };
  const onPointerEnter = (e) => {
    const btn = e.currentTarget;
    if (btn.dataset.pressed === '1' && !btn.disabled) {
      // While holding and re-entering, restore highlight
      btn.classList.add('pressing');
      // Since cursor is back over the button, allow the click again
      delete btn.dataset.cancelClick;
    }
  };

  buttons.forEach((btn) => {
    btn.addEventListener('pointerdown', onPointerDown);
    btn.addEventListener('pointerup', onPointerUp);
    btn.addEventListener('pointercancel', onPointerCancel);
    btn.addEventListener('pointerleave', onPointerLeave);
    btn.addEventListener('pointerenter', onPointerEnter);
    // Cancel accidental clicks if pointer left while pressed and released off-button
    btn.addEventListener('click', (ev) => {
      if (btn.dataset.cancelClick === '1') {
        ev.preventDefault();
        ev.stopPropagation();
        delete btn.dataset.cancelClick;
      }
    }, true);
    // After legitimate click, drop focus to avoid lingering white border
    btn.addEventListener('click', () => {
      try { btn.blur(); } catch (e) {}
      btn.classList.remove('pressing');
      delete btn.dataset.pressed;
    });
  });

  // Global safety: clear any press states on release anywhere
  document.addEventListener('pointerup', () => {
    buttons.forEach((btn) => {
      btn.classList.remove('pressing');
      delete btn.dataset.pressed;
      // leave cancelClick intact for the immediate click phase; browser dispatches click after pointerup
    });
  }, { capture: true, passive: true });
});
})();
</script>
<script>
// Cross-browser hover/focus/active outline for Search/Sort/Filter wrappers
(function wireNavWrapperInteractions() {
function isDisabledWrapper(wrap) {
  return wrap.classList.contains('disabled') || wrap.querySelector(':disabled') !== null;
}
function addState(wrap, cls) {
  if (!wrap) return;
  if (isDisabledWrapper(wrap)) return;
  wrap.classList.add(cls);
}
function removeState(wrap, cls) {
  if (!wrap) return;
  wrap.classList.remove(cls);
}
function clearStates(wrap) {
  if (!wrap) return;
  wrap.classList.remove('is-hover', 'is-focus', 'is-active', 'pressing');
}
document.addEventListener('DOMContentLoaded', () => {
  const wrappers = Array.from(document.querySelectorAll(
    '.search-sort .input-icon-wrapper[data-nav-priority="1"],'+
    '.search-sort .input-icon-wrapper[data-nav-priority="2"],'+
    '.search-sort .input-icon-wrapper[data-nav-priority="3"]'
  ));
  wrappers.forEach((wrap) => {
    // Hover
    wrap.addEventListener('mouseenter', () => addState(wrap, 'is-hover'));
    wrap.addEventListener('mouseleave', () => removeState(wrap, 'is-hover'));
    // Focus
    wrap.addEventListener('focusin', () => addState(wrap, 'is-focus'));
    wrap.addEventListener('focusout', () => removeState(wrap, 'is-focus'));
    // Active
    wrap.addEventListener('pointerdown', () => addState(wrap, 'is-active'));
    wrap.addEventListener('pointerup', () => removeState(wrap, 'is-active'));
    wrap.addEventListener('pointercancel', () => removeState(wrap, 'is-active'));
  });

  // Integrate with existing enable/disable to clear states
  const originalDisable = window.disableControls;
  const originalEnable = window.enableControls;
  window.disableControls = function patchedDisableControls() {
    try { wrappers.forEach(clearStates); } catch (e) {}
    return originalDisable.apply(this, arguments);
  };
  window.enableControls = function patchedEnableControls() {
    const ret = originalEnable.apply(this, arguments);
    try { wrappers.forEach(clearStates); } catch (e) {}
    return ret;
  };
});
})();
</script>
<script>
// Lock-in nav bar below top menu (mirror og-item-finder)
(function setupControlsLockIn() {
document.addEventListener('DOMContentLoaded', () => {
  const cont = document.getElementById('LIMenuContainer');
  if (!cont || !cont.classList.contains('controls')) return;

  const spacer = document.createElement('div');
  spacer.style.display = 'none';
  cont.parentNode.insertBefore(spacer, cont.nextSibling);

  let origTop = 0;
  const recompute = () => {
    spacer.style.height = cont.offsetHeight + 'px';
    if (!cont.classList.contains('fixed')) {
      origTop = cont.getBoundingClientRect().top + window.scrollY;
    } else {
      origTop = spacer.getBoundingClientRect().top + window.scrollY;
    }
  };

  const onScroll = () => {
    const isDesktop = window.matchMedia('(min-width: 768px)').matches;
    if (!isDesktop) {
      cont.classList.remove('fixed');
      spacer.style.display = 'none';
      cont.style.left = '';
      cont.style.right = '';
      cont.style.width = '';
      return;
    }
    if (!cont.classList.contains('fixed')) {
      origTop = cont.getBoundingClientRect().top + window.scrollY;
    }
    const topOffset = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--top-navbar-height')) || 0;
    if (window.scrollY + topOffset >= origTop) {
      if (!cont.classList.contains('fixed')) {
        const heightBefore = cont.offsetHeight;
        cont.classList.add('fixed');
        spacer.style.display = 'block';
        spacer.style.height = heightBefore + 'px';
        cont.style.left = '';
        cont.style.right = '';
        cont.style.width = '';
      }
    } else {
      if (cont.classList.contains('fixed')) {
        cont.classList.remove('fixed');
        spacer.style.display = 'none';
        cont.style.left = '';
        cont.style.right = '';
        cont.style.width = '';
      }
    }
  };

  window.addEventListener('scroll', onScroll, { passive: true });
  window.addEventListener('resize', recompute);
  window.addEventListener('load', recompute);
  recompute();
  onScroll();
});
})();
</script>
<script>
document.addEventListener('DOMContentLoaded', function() {
const yearElem = document.getElementById('footerYear');
if (yearElem) {
  yearElem.textContent = new Date().getFullYear();
}
});
</script>
</body>
</html>

/* Inventory modal specific tweaks */
.inventory-grid .controls {
position: sticky;
top: 0;
z-index: 10;
margin: 0 0 15px;
padding: 10px 16px;
background: rgba(0,0,0,0.5);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
border-style: solid;
border-color: rgba(255,255,255,0.2);
border-width: 1px 0;
box-sizing: border-box;
box-shadow: none;
}

.inventory-grid .controls .search-sort {
justify-content: flex-start;
gap: 8px;
max-width: none;
}

.inventory-grid .input-icon-wrapper {
border: 1px solid rgba(255,255,255,0.2);
background: rgba(0,0,0,0.3);
}

.inventory-grid .control-button {
background: rgba(0,0,0,0.3);
border: 1px solid rgba(255,255,255,0.2);
}

@media (max-width: 768px) {
.inventory-grid .controls {
padding: 8px 12px;
}
.inventory-grid .controls .search-sort {
flex-wrap: wrap;
justify-content: space-between;
}
}