/* ============================================
   NEXIVOSIGNAL FOOTBALL - COMPLETE STYLESHEET
   v2.0 - Improved UX, SEO-friendly, Accessible
   ============================================ */

/* ---- FONTS & RESET ---- */
*, *::before, *::after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

:root {
  --primary: #00ff88;
  --secondary: #ff6b00;
  --accent: #ffdd00;
  --bg-dark: #0a0e1a;
  --bg-mid: #111827;
  --bg-card: #1a2235;
  --text-primary: #e8f4f8;
  --text-dim: #7fa0b8;
  --pixel-green: #22c55e;
  --pixel-red: #ef4444;
  --pixel-blue: #3b82f6;
  --pixel-yellow: #eab308;
  --pixel-orange: #f97316;
  --pixel-purple: #a855f7;
  --pixel-cyan: #06b6d4;
  --border-glow: 0 0 10px var(--primary), 0 0 20px rgba(0,255,136,0.3);
  --font-pixel: 'Press Start 2P', monospace;
  --font-retro: 'VT323', monospace;
  --hud-height: 60px;
  --commentary-height: 36px;
  --cookie-banner-height: 0px;
}

html {
  scroll-behavior: smooth;
  font-size: 16px;
}

body {
  background: var(--bg-dark);
  color: var(--text-primary);
  font-family: var(--font-pixel);
  overflow-x: hidden;
  min-height: 100vh;
}

/* ---- SKIP LINK (Accessibility) ---- */
.skip-link {
  position: absolute;
  top: -100px;
  left: 0;
  background: var(--primary);
  color: var(--bg-dark);
  font-family: var(--font-pixel);
  font-size: 10px;
  padding: 10px 20px;
  z-index: 99999;
  text-decoration: none;
  transition: top 0.2s;
}
.skip-link:focus {
  top: 0;
}

/* ---- PAGE SYSTEM ---- */
.page {
  display: none;
  min-height: 100vh;
}
.page.active {
  display: block;
}

.page-section {
  display: none;
  min-height: calc(100vh - 140px);
  padding: 40px 20px;
}
.page-section.active {
  display: block;
}

/* ---- CRT EFFECTS ---- */
#crt-overlay {
  position: fixed;
  top: 0; left: 0; right: 0; bottom: 0;
  pointer-events: none;
  z-index: 9999;
  background: radial-gradient(ellipse at center, transparent 60%, rgba(0,0,0,0.5) 100%);
  animation: crtFlicker 8s infinite;
}

#scanlines {
  position: fixed;
  top: 0; left: 0; right: 0; bottom: 0;
  pointer-events: none;
  z-index: 9998;
  background: repeating-linear-gradient(
    0deg,
    transparent,
    transparent 2px,
    rgba(0,0,0,0.07) 2px,
    rgba(0,0,0,0.07) 4px
  );
}

@keyframes crtFlicker {
  0%, 100% { opacity: 1; }
  92% { opacity: 1; }
  93% { opacity: 0.95; }
  94% { opacity: 1; }
  97% { opacity: 0.97; }
  98% { opacity: 1; }
}

/* ---- BACKGROUND CANVAS ---- */
#bg-canvas {
  position: fixed;
  top: 0; left: 0;
  width: 100%; height: 100%;
  z-index: -1;
  opacity: 0.3;
}

/* ---- PIXEL PARTICLES ---- */
#pixel-particles {
  position: fixed;
  top: 0; left: 0; right: 0; bottom: 0;
  pointer-events: none;
  z-index: 0;
  overflow: hidden;
}

.pixel-particle {
  position: absolute;
  width: 4px;
  height: 4px;
  background: var(--primary);
  animation: pixelFloat linear infinite;
  image-rendering: pixelated;
}

@keyframes pixelFloat {
  0% { transform: translateY(100vh) rotate(0deg); opacity: 0; }
  10% { opacity: 1; }
  90% { opacity: 1; }
  100% { transform: translateY(-100px) rotate(360deg); opacity: 0; }
}

/* ---- HEADER ---- */
#site-header {
  position: fixed;
  top: 0; left: 0; right: 0;
  z-index: 1000;
  background: rgba(10,14,26,0.97);
  border-bottom: 2px solid var(--primary);
  box-shadow: 0 2px 20px rgba(0,255,136,0.2);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
}

.header-inner {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 70px;
  max-width: 1400px;
  margin: 0 auto;
}

#logo {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  text-decoration: none;
  padding: 4px 8px;
  border: 1px solid transparent;
  transition: border-color 0.2s;
}

#logo:hover, #logo:focus {
  border-color: rgba(0,255,136,0.3);
  outline: none;
}

.logo-pixel {
  font-size: 24px;
  animation: ballSpin 3s linear infinite;
  display: inline-block;
}

@keyframes ballSpin {
  0% { transform: rotate(0deg) scale(1); }
  50% { transform: rotate(180deg) scale(1.1); }
  100% { transform: rotate(360deg) scale(1); }
}

.logo-text {
  font-family: var(--font-pixel);
  font-size: 12px;
  color: var(--primary);
  letter-spacing: 2px;
}

.logo-accent {
  color: var(--secondary);
}

.logo-sub {
  font-size: 8px;
  color: var(--text-dim);
  display: block;
}

#main-nav {
  display: flex;
  gap: 2px;
}

.nav-link {
  font-family: var(--font-pixel);
  font-size: 7px;
  color: var(--text-dim);
  text-decoration: none;
  padding: 8px 9px;
  border: 1px solid transparent;
  transition: all 0.2s;
  letter-spacing: 0.5px;
  cursor: pointer;
  border-radius: 2px;
}

.nav-link:hover,
.nav-link.active,
.nav-link:focus {
  color: var(--primary);
  border-color: var(--primary);
  box-shadow: 0 0 10px rgba(0,255,136,0.3);
  background: rgba(0,255,136,0.05);
  outline: none;
}

#nav-toggle {
  display: none;
  background: none;
  border: 1px solid var(--primary);
  color: var(--primary);
  font-size: 20px;
  cursor: pointer;
  padding: 6px 12px;
  transition: background 0.2s;
}

#nav-toggle:hover {
  background: rgba(0,255,136,0.1);
}

#nav-toggle:focus {
  outline: 2px solid var(--primary);
  outline-offset: 2px;
}

/* ---- BUTTONS ---- */
.btn {
  font-family: var(--font-pixel);
  font-size: 10px;
  letter-spacing: 1px;
  padding: 12px 20px;
  border: 2px solid;
  cursor: pointer;
  transition: all 0.15s;
  text-transform: uppercase;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  position: relative;
  overflow: hidden;
  image-rendering: pixelated;
  text-decoration: none;
  line-height: 1.4;
}

.btn:focus {
  outline: 3px solid var(--accent);
  outline-offset: 2px;
}

.btn::before {
  content: '';
  position: absolute;
  top: 0; left: -100%;
  width: 100%; height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255,255,255,0.1), transparent);
  transition: left 0.3s;
  pointer-events: none;
}

.btn:hover::before {
  left: 100%;
}

.btn-primary {
  background: var(--primary);
  border-color: var(--primary);
  color: var(--bg-dark);
  box-shadow: 0 0 15px rgba(0,255,136,0.5);
}

.btn-primary:hover {
  background: #00ffaa;
  box-shadow: 0 0 25px rgba(0,255,136,0.8);
  transform: translateY(-2px);
}

.btn-primary:active {
  transform: translateY(0);
}

.btn-secondary {
  background: transparent;
  border-color: var(--secondary);
  color: var(--secondary);
}

.btn-secondary:hover {
  background: var(--secondary);
  color: var(--bg-dark);
  box-shadow: 0 0 15px rgba(255,107,0,0.5);
  transform: translateY(-2px);
}

.btn-huge {
  font-size: 14px;
  padding: 18px 32px;
}

.btn-back {
  background: transparent;
  border-color: var(--text-dim);
  color: var(--text-dim);
  font-size: 9px;
}

.btn-back:hover {
  border-color: var(--text-primary);
  color: var(--text-primary);
}

.btn-danger {
  background: transparent;
  border-color: var(--pixel-red);
  color: var(--pixel-red);
}

.btn-danger:hover {
  background: var(--pixel-red);
  color: white;
}

/* ---- HERO SECTION ---- */
#home {
  padding-top: 90px;
}

.hero {
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-height: calc(100vh - 90px);
  max-width: 1400px;
  margin: 0 auto;
  padding: 40px;
  gap: 40px;
}

.hero-content {
  flex: 1;
  max-width: 600px;
}

.hero-badge {
  display: inline-block;
  background: rgba(255,221,0,0.15);
  border: 1px solid var(--accent);
  color: var(--accent);
  font-size: 8px;
  padding: 8px 16px;
  margin-bottom: 24px;
  animation: badgePulse 2s ease-in-out infinite;
}

@keyframes badgePulse {
  0%, 100% { box-shadow: 0 0 5px rgba(255,221,0,0.3); }
  50% { box-shadow: 0 0 15px rgba(255,221,0,0.7); }
}

.hero-title {
  line-height: 1.2;
  margin-bottom: 20px;
}

.title-line-1 {
  display: block;
  font-size: clamp(28px, 5vw, 56px);
  color: var(--primary);
  text-shadow: 0 0 20px rgba(0,255,136,0.8), 3px 3px 0 rgba(0,255,136,0.3);
}

.title-line-2 {
  display: block;
  font-size: clamp(28px, 5vw, 56px);
  color: var(--secondary);
  text-shadow: 0 0 20px rgba(255,107,0,0.8), 3px 3px 0 rgba(255,107,0,0.3);
}

.title-line-3 {
  display: block;
  font-size: clamp(16px, 3vw, 32px);
  color: var(--accent);
  text-shadow: 0 0 15px rgba(255,221,0,0.8);
  letter-spacing: 4px;
}

.hero-subtitle {
  color: var(--text-dim);
  font-size: 9px;
  letter-spacing: 2px;
  margin-bottom: 32px;
}

.hero-stats {
  display: flex;
  gap: 24px;
  margin-bottom: 40px;
  flex-wrap: wrap;
}

.stat-item {
  text-align: center;
  border: 1px solid rgba(0,255,136,0.2);
  padding: 12px 16px;
  background: rgba(0,255,136,0.05);
  transition: border-color 0.2s;
}

.stat-item:hover {
  border-color: rgba(0,255,136,0.5);
}

.stat-num {
  display: block;
  font-size: 20px;
  color: var(--primary);
  text-shadow: 0 0 10px var(--primary);
}

.stat-label {
  display: block;
  font-size: 7px;
  color: var(--text-dim);
  margin-top: 4px;
}

.hero-buttons {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.hero-visual {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  max-width: 450px;
}

#hero-canvas {
  border: 2px solid var(--primary);
  box-shadow: 0 0 30px rgba(0,255,136,0.4), inset 0 0 30px rgba(0,255,136,0.1);
  image-rendering: pixelated;
  image-rendering: crisp-edges;
  max-width: 100%;
  height: auto;
}

/* ---- SECTIONS ---- */
.section-title {
  font-size: clamp(12px, 2vw, 18px);
  color: var(--primary);
  text-align: center;
  margin-bottom: 40px;
  text-shadow: 0 0 15px rgba(0,255,136,0.5);
  position: relative;
}

.section-title::after {
  content: '';
  display: block;
  width: 60px;
  height: 3px;
  background: var(--primary);
  margin: 12px auto 0;
  box-shadow: 0 0 10px var(--primary);
}

.section-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 80px 20px 40px;
}

/* ---- FEATURES ---- */
.features-section {
  padding: 80px 40px;
  max-width: 1400px;
  margin: 0 auto;
}

.features-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
}

.feature-card {
  background: var(--bg-card);
  border: 1px solid rgba(0,255,136,0.2);
  padding: 28px 24px;
  transition: all 0.3s;
  position: relative;
  overflow: hidden;
}

.feature-card::before {
  content: '';
  position: absolute;
  top: 0; left: 0;
  width: 100%; height: 2px;
  background: var(--primary);
  transform: scaleX(0);
  transition: transform 0.3s;
}

.feature-card:hover::before {
  transform: scaleX(1);
}

.feature-card:hover {
  border-color: var(--primary);
  box-shadow: 0 0 20px rgba(0,255,136,0.2);
  transform: translateY(-4px);
}

.feature-icon {
  font-size: 32px;
  margin-bottom: 16px;
  display: block;
}

.feature-card h3 {
  font-size: 10px;
  color: var(--primary);
  margin-bottom: 12px;
}

.feature-card p {
  font-family: var(--font-retro);
  font-size: 15px;
  color: var(--text-dim);
  line-height: 1.8;
}

/* ---- MODES SECTION ---- */
.modes-section {
  padding: 60px 40px;
  max-width: 1400px;
  margin: 0 auto;
  background: rgba(0,0,0,0.3);
}

.modes-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  gap: 16px;
}

.mode-card {
  background: var(--bg-card);
  border: 1px solid rgba(255,107,0,0.3);
  padding: 24px 20px;
  cursor: pointer;
  transition: all 0.2s;
  text-align: center;
}

.mode-card:hover,
.mode-card:focus {
  border-color: var(--secondary);
  box-shadow: 0 0 15px rgba(255,107,0,0.4);
  transform: translateY(-4px);
  outline: none;
}

.mode-card:focus {
  box-shadow: 0 0 0 3px var(--accent);
}

.mode-num {
  font-size: 24px;
  color: rgba(255,107,0,0.4);
  font-family: var(--font-retro);
  margin-bottom: 8px;
}

.mode-card h3 {
  font-size: 9px;
  color: var(--secondary);
  margin-bottom: 8px;
}

.mode-card p {
  font-size: 14px;
  color: var(--text-dim);
  font-family: var(--font-retro);
}

/* ---- PLAY MODES ---- */
.play-modes {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
  gap: 12px;
}

.play-mode-btn {
  display: flex;
  align-items: center;
  gap: 20px;
  background: var(--bg-card);
  border: 2px solid rgba(0,255,136,0.2);
  padding: 20px 24px;
  cursor: pointer;
  transition: all 0.2s;
  color: var(--text-primary);
  text-align: left;
  width: 100%;
}

.play-mode-btn:hover {
  border-color: var(--primary);
  box-shadow: 0 0 20px rgba(0,255,136,0.3);
  transform: translateX(4px);
}

.play-mode-btn:focus {
  outline: 3px solid var(--primary);
  outline-offset: 2px;
}

.mode-icon {
  font-size: 32px;
  min-width: 48px;
  text-align: center;
  pointer-events: none;
}

.mode-info h3 {
  font-family: var(--font-pixel);
  font-size: 10px;
  color: var(--primary);
  margin-bottom: 6px;
  pointer-events: none;
}

.mode-info p {
  font-family: var(--font-retro);
  font-size: 14px;
  color: var(--text-dim);
  pointer-events: none;
}

/* ---- TEAM SELECT SCREEN ---- */
#team-select-screen {
  background: var(--bg-dark);
  padding-top: 20px;
  min-height: 100vh;
}

#team-select-bg {
  position: fixed;
  top: 0; left: 0; right: 0; bottom: 0;
  background: linear-gradient(135deg, #0a0e1a 0%, #111827 50%, #0a1a0f 100%);
  z-index: -1;
}

.screen-title {
  font-size: 16px;
  text-align: center;
  color: var(--primary);
  padding: 20px;
  text-shadow: 0 0 20px rgba(0,255,136,0.7);
}

.team-select-layout {
  display: flex;
  align-items: flex-start;
  justify-content: center;
  gap: 20px;
  padding: 10px 20px;
  flex-wrap: wrap;
}

.team-panel {
  width: 220px;
  text-align: center;
}

.team-panel h3 {
  font-size: 10px;
  color: var(--text-dim);
  margin-bottom: 12px;
}

.selected-team-display {
  background: var(--bg-card);
  border: 2px solid var(--primary);
  padding: 20px;
  min-height: 140px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  box-shadow: var(--border-glow);
}

.team-logo-big {
  font-size: 48px;
  margin-bottom: 8px;
  display: block;
}

.team-name-big {
  font-size: 9px;
  color: var(--primary);
}

.team-rating {
  font-size: 7px;
  color: var(--text-dim);
  margin-top: 6px;
}

.vs-divider {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  min-width: 200px;
}

.vs-divider > span {
  font-size: 28px;
  color: var(--accent);
  text-shadow: 0 0 15px var(--accent);
}

.match-settings {
  width: 100%;
  background: var(--bg-card);
  border: 1px solid rgba(0,255,136,0.2);
  padding: 12px;
}

.setting-row {
  display: flex;
  flex-direction: column;
  gap: 4px;
  margin-bottom: 8px;
}

.setting-row label {
  font-size: 7px;
  color: var(--text-dim);
}

.setting-row select,
.setting-row input {
  background: var(--bg-dark);
  border: 1px solid var(--primary);
  color: var(--primary);
  font-family: var(--font-pixel);
  font-size: 8px;
  padding: 6px;
  width: 100%;
}

.setting-row select:focus,
.setting-row input:focus {
  outline: 2px solid var(--accent);
}

#current-mode-display {
  font-size: 8px;
  color: var(--secondary);
  background: var(--bg-dark);
  padding: 6px;
  border: 1px solid var(--secondary);
}

.team-grid-hint {
  text-align: center;
  font-family: var(--font-retro);
  font-size: 15px;
  color: var(--text-dim);
  margin-bottom: 12px;
  padding: 0 20px;
}

.team-grid-hint strong {
  color: var(--primary);
}

.teams-grid-container {
  padding: 10px 20px 20px;
  overflow-y: auto;
  max-height: 320px;
}

.teams-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 8px;
  max-width: 1200px;
  margin: 0 auto;
}

.team-card {
  background: var(--bg-card);
  border: 2px solid rgba(0,255,136,0.15);
  padding: 10px 8px;
  cursor: pointer;
  transition: all 0.15s;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.team-card:hover,
.team-card:focus {
  border-color: var(--primary);
  box-shadow: 0 0 10px rgba(0,255,136,0.3);
  transform: scale(1.05);
  outline: none;
}

.team-card.selected-home {
  border-color: #3b82f6;
  box-shadow: 0 0 15px rgba(59,130,246,0.5);
  background: rgba(59,130,246,0.1);
}

.team-card.selected-away {
  border-color: #ef4444;
  box-shadow: 0 0 15px rgba(239,68,68,0.5);
  background: rgba(239,68,68,0.1);
}

.team-card-logo {
  font-size: 28px;
  display: block;
}

.team-card-name {
  font-size: 7px;
  color: var(--text-primary);
  line-height: 1.3;
}

.team-card-rating {
  font-size: 7px;
  color: var(--accent);
}

/* ---- GAME SCREEN ---- */
#game-screen {
  background: #000;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  position: relative;
  overflow: hidden;
}

#game-canvas {
  display: block;
  image-rendering: pixelated;
  image-rendering: crisp-edges;
  max-width: 100%;
}

#game-canvas:focus {
  outline: 2px solid var(--primary);
  outline-offset: 2px;
}

/* ---- HUD ---- */
#game-hud {
  position: fixed;
  top: 0; left: 0; right: 0;
  height: var(--hud-height);
  background: linear-gradient(180deg, rgba(10,14,26,0.97) 0%, rgba(10,14,26,0.75) 100%);
  border-bottom: 2px solid var(--primary);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  z-index: 500;
  gap: 10px;
}

#hud-left, #hud-right {
  flex: 1;
}

#hud-right {
  display: flex;
  justify-content: flex-end;
}

.hud-team {
  display: flex;
  align-items: center;
  gap: 10px;
}

.hud-team-logo {
  font-size: 24px;
}

.hud-team-name {
  font-size: 8px;
  color: var(--text-dim);
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.hud-score {
  font-size: 26px;
  color: var(--primary);
  text-shadow: 0 0 10px var(--primary);
  min-width: 32px;
  text-align: center;
  font-variant-numeric: tabular-nums;
}

#hud-center {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}

#hud-time {
  font-size: 18px;
  color: var(--accent);
  text-shadow: 0 0 10px var(--accent);
  font-family: var(--font-pixel);
  min-width: 80px;
  text-align: center;
  font-variant-numeric: tabular-nums;
}

#hud-period {
  font-size: 7px;
  color: var(--text-dim);
}

#hud-weather-icon {
  font-size: 14px;
}

#pause-btn {
  background: rgba(0,255,136,0.1);
  border: 1px solid var(--primary);
  color: var(--primary);
  font-size: 16px;
  cursor: pointer;
  padding: 6px 10px;
  transition: all 0.2s;
}

#pause-btn:hover {
  background: rgba(0,255,136,0.25);
}

#pause-btn:focus {
  outline: 2px solid var(--accent);
}

/* ---- COMMENTARY BAR ---- */
#commentary-bar {
  position: fixed;
  bottom: 0; left: 0; right: 0;
  height: var(--commentary-height);
  background: rgba(10,14,26,0.92);
  border-top: 1px solid rgba(0,255,136,0.3);
  display: flex;
  align-items: center;
  padding: 0 16px;
  z-index: 500;
  overflow: hidden;
}

#commentary-text {
  font-family: var(--font-retro);
  font-size: 18px;
  color: var(--primary);
  white-space: nowrap;
  animation: commentaryScroll 14s linear infinite;
}

@keyframes commentaryScroll {
  0% { transform: translateX(100vw); }
  100% { transform: translateX(-100%); }
}

/* ---- MINIMAP ---- */
#minimap {
  position: fixed;
  bottom: 44px;
  right: 10px;
  z-index: 501;
  border: 1px solid rgba(0,255,136,0.4);
  background: rgba(0,20,10,0.85);
  border-radius: 2px;
}

#minimap-canvas {
  display: block;
}

/* ---- MOBILE CONTROLS ---- */
#mobile-controls {
  position: fixed;
  bottom: 44px;
  left: 0; right: 0;
  display: none;
  justify-content: space-between;
  align-items: flex-end;
  padding: 10px 20px;
  z-index: 502;
  pointer-events: none;
}

#joystick-area {
  pointer-events: all;
}

#joystick-base {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background: rgba(0,255,136,0.1);
  border: 2px solid rgba(0,255,136,0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  touch-action: none;
  user-select: none;
  -webkit-user-select: none;
}

#joystick-knob {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  background: rgba(0,255,136,0.6);
  border: 2px solid var(--primary);
  position: absolute;
  touch-action: none;
  pointer-events: none;
  will-change: transform;
}

#action-buttons {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
  pointer-events: all;
}

.action-btn {
  width: 52px;
  height: 52px;
  border-radius: 8px;
  background: rgba(0,0,0,0.75);
  border: 2px solid rgba(0,255,136,0.5);
  color: white;
  font-size: 20px;
  cursor: pointer;
  transition: all 0.1s;
  display: flex;
  align-items: center;
  justify-content: center;
  touch-action: manipulation;
  -webkit-tap-highlight-color: transparent;
  user-select: none;
  -webkit-user-select: none;
}

.action-btn:active {
  background: rgba(0,255,136,0.3);
  transform: scale(0.92);
}

/* ---- PAUSE MENU ---- */
#pause-menu {
  position: fixed;
  top: 0; left: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.88);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 600;
}

#pause-menu.hidden { display: none; }

.pause-panel {
  background: var(--bg-card);
  border: 2px solid var(--primary);
  padding: 40px;
  text-align: center;
  min-width: 300px;
  max-width: 420px;
  width: 90%;
  box-shadow: var(--border-glow);
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.pause-panel h2 {
  font-size: 16px;
  color: var(--primary);
  margin-bottom: 8px;
}

.pause-stats {
  background: rgba(0,0,0,0.3);
  padding: 12px;
  margin-bottom: 8px;
}

.pause-stat {
  display: flex;
  justify-content: space-between;
  font-size: 8px;
  color: var(--text-dim);
  padding: 4px 0;
  border-bottom: 1px solid rgba(255,255,255,0.05);
}

/* ---- OVERLAY SCREENS ---- */
#goal-overlay {
  position: fixed;
  top: 0; left: 0; right: 0; bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 700;
  pointer-events: none;
  background: rgba(0,0,0,0.3);
}

#goal-overlay.hidden { display: none; }

#goal-text {
  font-size: clamp(40px, 10vw, 80px);
  color: var(--accent);
  text-shadow: 0 0 30px var(--accent), 0 0 60px rgba(255,221,0,0.5), 4px 4px 0 var(--secondary);
  animation: goalPop 0.5s cubic-bezier(0.36, 0.07, 0.19, 0.97);
  letter-spacing: 4px;
}

#goal-scorer-text {
  font-size: 14px;
  color: var(--primary);
  margin-top: 12px;
  text-shadow: 0 0 10px var(--primary);
}

#goal-assist-text {
  font-size: 10px;
  color: var(--text-dim);
  margin-top: 4px;
}

@keyframes goalPop {
  0% { transform: scale(0) rotate(-10deg); opacity: 0; }
  50% { transform: scale(1.3) rotate(5deg); opacity: 1; }
  100% { transform: scale(1) rotate(0deg); opacity: 1; }
}

.halftime-panel,
.fulltime-panel {
  background: var(--bg-card);
  border: 2px solid var(--primary);
  padding: 40px;
  text-align: center;
  max-width: 520px;
  width: 90%;
  box-shadow: var(--border-glow);
}

#halftime-overlay,
#fulltime-overlay {
  position: fixed;
  top: 0; left: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.88);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 600;
}

#halftime-overlay.hidden,
#fulltime-overlay.hidden { display: none; }

.halftime-panel h2,
.fulltime-panel h2 {
  font-size: 16px;
  color: var(--primary);
  margin-bottom: 20px;
}

#halftime-score,
#fulltime-score {
  font-size: 36px;
  color: var(--accent);
  text-shadow: 0 0 15px var(--accent);
  margin-bottom: 16px;
  font-variant-numeric: tabular-nums;
}

.halftime-stats,
.fulltime-stats {
  margin-bottom: 20px;
}

.stat-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 0;
  border-bottom: 1px solid rgba(255,255,255,0.05);
  font-size: 8px;
  color: var(--text-dim);
}

#match-mvp {
  background: rgba(255,221,0,0.1);
  border: 1px solid var(--accent);
  padding: 12px;
  margin-bottom: 16px;
  font-size: 9px;
  color: var(--accent);
}

#achievement-earned {
  background: rgba(168,85,247,0.1);
  border: 1px solid var(--pixel-purple);
  padding: 12px;
  margin-bottom: 16px;
  font-size: 9px;
  color: var(--pixel-purple);
}

#achievement-earned.hidden { display: none; }

/* ---- REPLAY ---- */
#replay-overlay {
  position: fixed;
  top: 10px; left: 50%;
  transform: translateX(-50%);
  z-index: 800;
}

#replay-overlay.hidden { display: none; }

#replay-label {
  background: var(--secondary);
  color: white;
  font-size: 10px;
  padding: 8px 20px;
  border: 2px solid white;
  animation: blinkReplay 0.8s ease-in-out infinite;
}

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

/* ---- PENALTY ---- */
#penalty-overlay {
  position: fixed;
  top: 0; left: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.82);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 650;
}

#penalty-overlay.hidden { display: none; }

.penalty-panel {
  background: var(--bg-card);
  border: 2px solid var(--accent);
  padding: 32px;
  text-align: center;
  max-width: 400px;
  width: 90%;
  box-shadow: 0 0 30px rgba(255,221,0,0.4);
}

.penalty-panel h2 {
  color: var(--accent);
  font-size: 14px;
  margin-bottom: 16px;
}

#penalty-score-display {
  font-size: 28px;
  color: var(--primary);
  margin-bottom: 12px;
}

#penalty-kicks-display {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-bottom: 12px;
  font-size: 20px;
}

#penalty-instruction {
  font-family: var(--font-retro);
  font-size: 16px;
  color: var(--text-dim);
  margin-bottom: 12px;
}

#penalty-result-msg {
  font-size: 12px;
  color: var(--accent);
  min-height: 20px;
}

/* ---- CARD DISPLAY ---- */
#card-display {
  position: fixed;
  top: 80px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 750;
  text-align: center;
  animation: cardSlideIn 0.4s ease-out;
}

#card-display.hidden { display: none; }

@keyframes cardSlideIn {
  0% { transform: translateX(-50%) translateY(-60px); opacity: 0; }
  100% { transform: translateX(-50%) translateY(0); opacity: 1; }
}

#card-visual {
  width: 40px;
  height: 60px;
  margin: 0 auto 8px;
  border: 3px solid rgba(0,0,0,0.5);
  border-radius: 4px;
}

#card-player-name {
  font-size: 9px;
  color: white;
  text-shadow: 1px 1px 0 black;
}

/* ---- SUBSTITUTION ---- */
#sub-overlay {
  position: fixed;
  bottom: 100px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 750;
  animation: subSlideUp 0.4s ease-out;
}

#sub-overlay.hidden { display: none; }

@keyframes subSlideUp {
  0% { transform: translateX(-50%) translateY(60px); opacity: 0; }
  100% { transform: translateX(-50%) translateY(0); opacity: 1; }
}

.sub-panel {
  background: var(--bg-card);
  border: 2px solid var(--pixel-green);
  padding: 16px 24px;
  text-align: center;
  font-size: 9px;
}

.sub-panel h3 {
  color: var(--pixel-green);
  margin-bottom: 8px;
}

#sub-out { color: var(--pixel-red); margin-bottom: 4px; }
#sub-in { color: var(--pixel-green); }

/* ---- MODALS ---- */
.modal {
  position: fixed;
  top: 0; left: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.92);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9000;
  padding: 20px;
  overflow-y: auto;
}

.modal.hidden { display: none; }

.modal-panel {
  background: var(--bg-card);
  border: 2px solid var(--primary);
  padding: 32px;
  max-width: 700px;
  width: 100%;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: var(--border-glow);
  position: relative;
}

.modal-legal {
  max-width: 800px;
}

.modal-panel h2 {
  font-size: 14px;
  color: var(--primary);
  margin-bottom: 24px;
  text-align: center;
}

/* ---- SETTINGS ---- */
.settings-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.setting-group {
  background: rgba(0,0,0,0.3);
  padding: 16px;
  border: 1px solid rgba(0,255,136,0.1);
}

.setting-group h3 {
  font-size: 9px;
  color: var(--text-dim);
  margin-bottom: 16px;
  border-bottom: 1px solid rgba(255,255,255,0.1);
  padding-bottom: 8px;
}

.slider-row {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 12px;
  flex-wrap: wrap;
}

.slider-row label {
  font-size: 8px;
  color: var(--text-dim);
  min-width: 80px;
}

.slider-row input[type="range"] {
  flex: 1;
  accent-color: var(--primary);
  min-width: 80px;
}

.slider-row span {
  font-size: 8px;
  color: var(--primary);
  min-width: 24px;
}

.toggle-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
  gap: 8px;
}

.toggle-row label {
  font-size: 8px;
  color: var(--text-dim);
}

.toggle-row input[type="checkbox"] {
  accent-color: var(--primary);
  width: 16px;
  height: 16px;
  cursor: pointer;
}

.select-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  margin-bottom: 12px;
  flex-wrap: wrap;
}

.select-row label {
  font-size: 8px;
  color: var(--text-dim);
}

.select-row select {
  background: var(--bg-dark);
  border: 1px solid var(--primary);
  color: var(--primary);
  font-family: var(--font-pixel);
  font-size: 8px;
  padding: 4px 8px;
}

.modal-buttons {
  display: flex;
  gap: 10px;
  justify-content: center;
  flex-wrap: wrap;
  padding-top: 8px;
}

/* ---- ACHIEVEMENTS ---- */
#achievements-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 12px;
  margin-bottom: 20px;
}

.achievement-item {
  background: rgba(0,0,0,0.4);
  border: 2px solid;
  padding: 16px;
  text-align: center;
  transition: all 0.2s;
}

.achievement-item.unlocked {
  border-color: var(--accent);
  box-shadow: 0 0 10px rgba(255,221,0,0.3);
}

.achievement-item.locked {
  border-color: rgba(255,255,255,0.1);
  opacity: 0.6;
  filter: grayscale(1);
}

.achievement-icon {
  font-size: 28px;
  margin-bottom: 8px;
}

.achievement-name {
  font-size: 8px;
  color: var(--accent);
  margin-bottom: 4px;
}

.achievement-desc {
  font-family: var(--font-retro);
  font-size: 14px;
  color: var(--text-dim);
}

/* ---- ACHIEVEMENT TOAST ---- */
#achievement-toast {
  position: fixed;
  top: 80px;
  right: 20px;
  background: var(--bg-card);
  border: 2px solid var(--accent);
  padding: 16px 20px;
  display: flex;
  align-items: center;
  gap: 12px;
  z-index: 9500;
  box-shadow: 0 0 20px rgba(255,221,0,0.5);
  animation: toastSlideIn 0.4s ease-out;
  max-width: 320px;
}

#achievement-toast.hidden { display: none; }

@keyframes toastSlideIn {
  0% { transform: translateX(120%); opacity: 0; }
  100% { transform: translateX(0); opacity: 1; }
}

.toast-icon { font-size: 28px; }

.toast-title {
  font-size: 8px;
  color: var(--accent);
  margin-bottom: 4px;
}

.toast-desc {
  font-family: var(--font-retro);
  font-size: 14px;
  color: var(--text-dim);
}

/* ---- LEADERBOARD ---- */
.leaderboard-tabs {
  display: flex;
  gap: 8px;
  margin-bottom: 24px;
  flex-wrap: wrap;
  justify-content: center;
}

.tab-btn {
  background: transparent;
  border: 2px solid rgba(0,255,136,0.3);
  color: var(--text-dim);
  font-family: var(--font-pixel);
  font-size: 8px;
  padding: 10px 16px;
  cursor: pointer;
  transition: all 0.2s;
}

.tab-btn.active,
.tab-btn:hover,
.tab-btn:focus {
  border-color: var(--primary);
  color: var(--primary);
  background: rgba(0,255,136,0.1);
  outline: none;
}

.tab-btn:focus {
  box-shadow: 0 0 0 3px var(--accent);
}

#leaderboard-table {
  max-width: 700px;
  margin: 0 auto;
}

.lb-entry {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  border-bottom: 1px solid rgba(255,255,255,0.05);
  background: var(--bg-card);
  margin-bottom: 4px;
  transition: all 0.2s;
}

.lb-entry:hover {
  border-color: rgba(0,255,136,0.3);
  background: rgba(0,255,136,0.05);
}

.lb-rank {
  font-size: 12px;
  color: var(--text-dim);
  min-width: 32px;
}

.lb-rank-1 { color: var(--accent); font-size: 14px; }
.lb-rank-2 { color: #c0c0c0; }
.lb-rank-3 { color: #cd7f32; }

.lb-name {
  flex: 1;
  font-size: 9px;
  color: var(--text-primary);
}

.lb-value {
  font-size: 10px;
  color: var(--primary);
}

/* ---- CAREER ---- */
.career-overview {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 24px;
}

.career-profile {
  display: flex;
  align-items: center;
  gap: 24px;
  background: var(--bg-card);
  border: 1px solid rgba(0,255,136,0.2);
  padding: 24px;
  width: 100%;
  max-width: 600px;
  flex-wrap: wrap;
}

.career-avatar {
  font-size: 64px;
}

.career-details h3 {
  font-size: 10px;
  color: var(--primary);
  margin-bottom: 8px;
}

.career-details p {
  font-family: var(--font-retro);
  font-size: 15px;
  color: var(--text-dim);
  margin-bottom: 4px;
}

.career-actions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  justify-content: center;
}

.career-stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 12px;
  width: 100%;
  max-width: 700px;
}

.career-stat-box {
  background: var(--bg-card);
  border: 1px solid rgba(0,255,136,0.15);
  padding: 16px;
  text-align: center;
}

.career-stat-val {
  font-size: 24px;
  color: var(--primary);
  text-shadow: 0 0 10px var(--primary);
}

.career-stat-label {
  font-size: 7px;
  color: var(--text-dim);
  margin-top: 4px;
}

/* ---- TOURNAMENT ---- */
.tournament-setup {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 24px;
}

.tournament-info {
  text-align: center;
}

.tournament-info h3 {
  font-size: 16px;
  color: var(--accent);
  margin-bottom: 8px;
  text-shadow: 0 0 10px var(--accent);
}

.tournament-info p {
  font-family: var(--font-retro);
  font-size: 18px;
  color: var(--text-dim);
}

.tournament-btn-group {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  justify-content: center;
}

#tournament-bracket {
  width: 100%;
  max-width: 900px;
  overflow-x: auto;
}

.bracket-match {
  background: var(--bg-card);
  border: 1px solid rgba(0,255,136,0.2);
  padding: 12px;
  display: flex;
  gap: 12px;
  align-items: center;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.bracket-match:hover {
  border-color: rgba(0,255,136,0.5);
  background: rgba(0,255,136,0.05);
}

/* ---- CAREER SETUP ---- */
.career-setup-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-bottom: 24px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-size: 8px;
  color: var(--text-dim);
}

.form-group input[type="text"],
.form-group select,
.form-group textarea {
  width: 100%;
  background: var(--bg-dark);
  border: 2px solid rgba(0,255,136,0.3);
  color: var(--text-primary);
  font-family: var(--font-pixel);
  font-size: 9px;
  padding: 10px;
}

.form-group input[type="text"]:focus,
.form-group select:focus,
.form-group textarea:focus {
  outline: none;
  border-color: var(--primary);
  box-shadow: 0 0 10px rgba(0,255,136,0.2);
}

.form-note {
  font-family: var(--font-retro);
  font-size: 13px;
  color: var(--text-dim);
  background: rgba(0,0,0,0.3);
  border-left: 2px solid var(--text-dim);
  padding: 8px 12px;
  margin: 8px 0;
  line-height: 1.6;
}

.career-team-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  gap: 8px;
  max-height: 200px;
  overflow-y: auto;
}

.career-team-option {
  background: var(--bg-dark);
  border: 2px solid rgba(0,255,136,0.2);
  padding: 8px;
  cursor: pointer;
  text-align: center;
  transition: all 0.2s;
  font-size: 8px;
}

.career-team-option:hover,
.career-team-option.selected,
.career-team-option:focus {
  border-color: var(--primary);
  background: rgba(0,255,136,0.1);
  color: var(--primary);
  outline: none;
}

.career-team-option .team-emoji {
  display: block;
  font-size: 24px;
  margin-bottom: 4px;
}

/* ---- CONTROLS PAGE ---- */
.controls-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.controls-card {
  background: var(--bg-card);
  border: 1px solid rgba(0,255,136,0.2);
  padding: 24px;
}

.controls-card h3 {
  font-size: 10px;
  color: var(--primary);
  margin-bottom: 16px;
  border-bottom: 1px solid rgba(0,255,136,0.2);
  padding-bottom: 8px;
}

.control-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.control-item {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 9px;
}

.control-item kbd {
  background: rgba(0,0,0,0.5);
  border: 1px solid rgba(0,255,136,0.4);
  color: var(--primary);
  padding: 4px 8px;
  font-family: var(--font-pixel);
  font-size: 7px;
  min-width: 80px;
  text-align: center;
  border-radius: 2px;
  flex-shrink: 0;
}

.control-item span {
  color: var(--text-dim);
  font-family: var(--font-retro);
  font-size: 15px;
}

/* ---- NEWS ---- */
.news-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.news-card {
  background: var(--bg-card);
  border: 1px solid rgba(0,255,136,0.2);
  padding: 24px;
  transition: all 0.3s;
}

.news-card.featured {
  border-color: var(--accent);
  box-shadow: 0 0 15px rgba(255,221,0,0.2);
}

.news-card:hover {
  transform: translateY(-4px);
  border-color: var(--primary);
}

.news-date {
  font-size: 8px;
  color: var(--text-dim);
  margin-bottom: 8px;
}

.news-card h3 {
  font-size: 9px;
  color: var(--primary);
  margin-bottom: 12px;
  line-height: 1.6;
}

.news-card p {
  font-family: var(--font-retro);
  font-size: 14px;
  color: var(--text-dim);
  line-height: 1.7;
  margin-bottom: 12px;
}

.news-tag {
  display: inline-block;
  background: rgba(0,255,136,0.15);
  border: 1px solid var(--primary);
  color: var(--primary);
  font-size: 7px;
  padding: 4px 8px;
}

/* ---- ABOUT ---- */
.about-content {
  max-width: 700px;
  margin: 0 auto;
  background: var(--bg-card);
  border: 1px solid rgba(0,255,136,0.2);
  padding: 32px;
}

.about-text p {
  font-family: var(--font-retro);
  font-size: 16px;
  color: var(--text-dim);
  line-height: 1.8;
  margin-bottom: 16px;
}

.about-text h3 {
  font-size: 10px;
  color: var(--primary);
  margin: 20px 0 10px;
}

.about-text ul {
  list-style: none;
  padding: 0;
}

.about-text ul li {
  font-family: var(--font-retro);
  font-size: 15px;
  color: var(--text-dim);
  padding: 4px 0;
  padding-left: 20px;
  position: relative;
  line-height: 1.6;
}

.about-text ul li::before {
  content: '▶';
  position: absolute;
  left: 0;
  color: var(--primary);
  font-size: 10px;
}

/* ---- CREDITS ---- */
.credits-content {
  max-width: 600px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.credits-section {
  background: var(--bg-card);
  border: 1px solid rgba(0,255,136,0.15);
  padding: 24px;
  text-align: center;
}

.credits-section h3 {
  font-size: 10px;
  color: var(--primary);
  margin-bottom: 12px;
}

.credits-section p {
  font-family: var(--font-retro);
  font-size: 16px;
  color: var(--text-dim);
  line-height: 1.6;
}

/* ---- LEGAL CONTENT ---- */
.legal-content {
  font-family: var(--font-retro);
  font-size: 15px;
  color: var(--text-dim);
  line-height: 1.9;
  margin-bottom: 24px;
}

.legal-content h3 {
  font-family: var(--font-pixel);
  font-size: 9px;
  color: var(--primary);
  margin: 20px 0 10px;
  padding-bottom: 4px;
  border-bottom: 1px solid rgba(0,255,136,0.15);
}

.legal-content ul {
  padding-left: 20px;
  margin-bottom: 12px;
}

.legal-content ul li {
  margin-bottom: 6px;
}

.legal-content p {
  margin-bottom: 12px;
}

.legal-content em {
  color: var(--text-dim);
  font-size: 13px;
}

.legal-content strong {
  color: var(--text-primary);
}

/* Cookie table */
.cookie-table {
  width: 100%;
  border-collapse: collapse;
  margin: 16px 0;
  font-size: 13px;
}

.cookie-table th,
.cookie-table td {
  text-align: left;
  padding: 8px 10px;
  border: 1px solid rgba(0,255,136,0.15);
}

.cookie-table th {
  background: rgba(0,255,136,0.1);
  color: var(--primary);
  font-family: var(--font-pixel);
  font-size: 7px;
}

.cookie-table td {
  color: var(--text-dim);
}

.cookie-table tr:hover td {
  background: rgba(0,255,136,0.03);
}

/* ---- CONTACT ---- */
.contact-content {
  margin-bottom: 20px;
}

.contact-content p {
  font-family: var(--font-retro);
  font-size: 15px;
  color: var(--text-dim);
  margin-bottom: 12px;
  line-height: 1.7;
}

.contact-content textarea {
  width: 100%;
  background: var(--bg-dark);
  border: 2px solid rgba(0,255,136,0.3);
  color: var(--text-primary);
  font-family: var(--font-retro);
  font-size: 15px;
  padding: 10px;
  resize: vertical;
  min-height: 100px;
}

.contact-content textarea:focus {
  outline: none;
  border-color: var(--primary);
}

/* ---- FOOTER ---- */
#site-footer {
  background: rgba(0,0,0,0.85);
  border-top: 2px solid rgba(0,255,136,0.2);
  padding: 48px 20px 32px;
  margin-top: 40px;
}

.footer-inner {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 24px;
  text-align: center;
}

.footer-logo {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 10px;
  color: var(--primary);
}

.footer-links {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  justify-content: center;
  list-style: none;
}

.footer-links a {
  color: var(--text-dim);
  text-decoration: none;
  font-size: 8px;
  cursor: pointer;
  transition: color 0.2s;
  padding: 4px 0;
  border-bottom: 1px solid transparent;
}

.footer-links a:hover,
.footer-links a:focus {
  color: var(--primary);
  border-bottom-color: var(--primary);
  outline: none;
}

.footer-copy p {
  font-family: var(--font-retro);
  font-size: 13px;
  color: var(--text-dim);
  margin-bottom: 4px;
  line-height: 1.6;
}

.footer-legal-note {
  font-size: 12px !important;
  color: rgba(127,160,184,0.7) !important;
  margin-top: 8px !important;
}

/* ---- 404 ---- */
#page-404 {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
}

.error-404 {
  text-align: center;
  padding: 40px;
}

.error-ball {
  font-size: 80px;
  animation: bounce404 1s ease-in-out infinite;
  display: block;
}

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

.error-404 h1 {
  font-size: clamp(40px, 10vw, 60px);
  color: var(--secondary);
  text-shadow: 0 0 20px var(--secondary);
  margin: 20px 0;
}

.error-404 h2 {
  font-size: 16px;
  color: var(--primary);
  margin-bottom: 16px;
}

.error-404 p {
  font-family: var(--font-retro);
  font-size: 18px;
  color: var(--text-dim);
  margin-bottom: 32px;
}

/* ---- LOADING SCREEN ---- */
#loading-screen {
  position: fixed;
  top: 0; left: 0; right: 0; bottom: 0;
  background: var(--bg-dark);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 99999;
  transition: opacity 0.5s, visibility 0.5s;
}

#loading-screen.hidden {
  opacity: 0;
  visibility: hidden;
  pointer-events: none;
}

.loading-content {
  text-align: center;
  padding: 20px;
}

.loading-ball {
  font-size: 60px;
  animation: loadingBounce 0.8s ease-in-out infinite;
  display: block;
  margin-bottom: 24px;
}

@keyframes loadingBounce {
  0%, 100% { transform: translateY(0) rotate(0deg); }
  50% { transform: translateY(-30px) rotate(180deg); }
}

.loading-title {
  font-size: clamp(12px, 3vw, 18px);
  color: var(--primary);
  text-shadow: 0 0 20px var(--primary);
  margin-bottom: 32px;
  letter-spacing: 3px;
}

.loading-bar-wrap {
  width: 300px;
  max-width: 80vw;
  height: 12px;
  background: rgba(0,255,136,0.1);
  border: 2px solid rgba(0,255,136,0.3);
  margin: 0 auto 16px;
  overflow: hidden;
}

.loading-bar {
  height: 100%;
  background: var(--primary);
  width: 0%;
  transition: width 0.2s ease-out;
  box-shadow: 0 0 10px var(--primary);
}

.loading-text {
  font-family: var(--font-retro);
  font-size: 15px;
  color: var(--text-dim);
}

/* ===================================================
   COOKIE CONSENT BANNER
   =================================================== */
#cookie-banner {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(10, 14, 26, 0.98);
  border-top: 2px solid var(--primary);
  box-shadow: 0 -4px 24px rgba(0,255,136,0.25);
  z-index: 99000;
  padding: 16px 20px;
  transform: translateY(0);
  transition: transform 0.4s ease;
  backdrop-filter: blur(12px);
  -webkit-backdrop-filter: blur(12px);
}

#cookie-banner.cookie-hidden {
  transform: translateY(120%);
  pointer-events: none;
}

.cookie-banner-inner {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 20px;
  flex-wrap: wrap;
}

.cookie-banner-text {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  flex: 1;
  min-width: 200px;
}

.cookie-icon {
  font-size: 28px;
  flex-shrink: 0;
  line-height: 1;
}

.cookie-banner-text p {
  font-family: var(--font-retro);
  font-size: 15px;
  color: var(--text-dim);
  line-height: 1.7;
  margin: 0;
}

.cookie-banner-text a {
  color: var(--primary);
  text-decoration: underline;
  cursor: pointer;
}

.cookie-banner-text a:hover {
  color: #00ffaa;
}

.cookie-banner-actions {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  align-items: center;
  flex-shrink: 0;
}

.btn-cookie-accept {
  font-size: 9px;
  padding: 10px 18px;
}

.btn-cookie-essential {
  font-size: 8px;
  padding: 10px 14px;
}

.btn-cookie-settings {
  font-size: 8px;
  padding: 10px 14px;
}

/* ---- SCROLLBAR ---- */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background: var(--bg-dark);
}

::-webkit-scrollbar-thumb {
  background: var(--primary);
  border-radius: 0;
}

::-webkit-scrollbar-thumb:hover {
  background: #00ffaa;
}

/* ---- FORM ELEMENTS ---- */
input[type="range"] {
  -webkit-appearance: none;
  appearance: none;
  background: rgba(0,255,136,0.1);
  border: 1px solid rgba(0,255,136,0.3);
  height: 6px;
  border-radius: 0;
}

input[type="range"]::-webkit-slider-thumb {
  -webkit-appearance: none;
  width: 16px;
  height: 16px;
  background: var(--primary);
  border: 2px solid var(--bg-dark);
  cursor: pointer;
}

input[type="range"]:focus {
  outline: 2px solid var(--accent);
}

select {
  cursor: pointer;
}

/* ---- HIGH CONTRAST MODE ---- */
body.high-contrast {
  --bg-dark: #000000;
  --bg-mid: #000000;
  --bg-card: #111111;
  --text-primary: #ffffff;
  --text-dim: #cccccc;
  --primary: #00ff88;
  --secondary: #ff6b00;
  --accent: #ffff00;
}

body.high-contrast .feature-card,
body.high-contrast .mode-card,
body.high-contrast .news-card {
  border-width: 2px;
}

/* ---- LARGE TEXT MODE ---- */
body.large-text {
  --font-retro: 'VT323', monospace;
}

body.large-text .feature-card p,
body.large-text .about-text p,
body.large-text .legal-content,
body.large-text .control-item span {
  font-size: 19px;
}

body.large-text .mode-info p {
  font-size: 17px;
}

/* ---- RESPONSIVE ---- */
@media (max-width: 1024px) {
  .hero {
    flex-direction: column;
    text-align: center;
    padding: 20px;
    min-height: auto;
    padding-top: 90px;
  }
  .hero-stats { justify-content: center; }
  .hero-buttons { justify-content: center; }
  .hero-visual { max-width: 320px; }
  #hero-canvas { width: 300px; height: 300px; }
}

@media (max-width: 768px) {
  #main-nav {
    display: none;
    position: fixed;
    top: 70px; left: 0; right: 0;
    background: rgba(10,14,26,0.98);
    flex-direction: column;
    border-top: 1px solid var(--primary);
    z-index: 999;
    padding: 8px 0;
    max-height: calc(100vh - 70px);
    overflow-y: auto;
  }
  #main-nav.open {
    display: flex;
  }
  .nav-link {
    padding: 14px 20px;
    border-bottom: 1px solid rgba(0,255,136,0.08);
    font-size: 9px;
  }
  #nav-toggle { display: block; }
  .title-line-1, .title-line-2 { font-size: 28px; }
  .title-line-3 { font-size: 16px; }
  .team-select-layout { flex-direction: column; align-items: center; }
  .team-panel { width: 100%; max-width: 300px; }
  .vs-divider { width: 100%; max-width: 300px; }
  #mobile-controls { display: flex; }
  #minimap { display: none; }
  .features-grid { grid-template-columns: 1fr; }
  .modes-grid { grid-template-columns: repeat(2, 1fr); }
  .settings-grid { grid-template-columns: 1fr; }
  .cookie-banner-inner { flex-direction: column; }
  .cookie-banner-actions { width: 100%; justify-content: center; }
  .modal-panel { padding: 20px; }
  .cookie-table { font-size: 11px; }
  .cookie-table th, .cookie-table td { padding: 6px; }
}

@media (max-width: 480px) {
  .btn-huge { font-size: 10px; padding: 14px 20px; }
  .hero-stats { gap: 12px; }
  .stat-num { font-size: 16px; }
  .section-title { font-size: 12px; }
  .play-modes { grid-template-columns: 1fr; }
  .modes-grid { grid-template-columns: 1fr; }
  .hero-buttons { flex-direction: column; align-items: center; }
  .hero-buttons .btn { width: 100%; justify-content: center; max-width: 280px; }
  .loading-title { font-size: 12px; letter-spacing: 1px; }
  .cookie-banner-text p { font-size: 14px; }
  .btn-cookie-accept, .btn-cookie-essential, .btn-cookie-settings {
    font-size: 8px; padding: 9px 12px;
  }
}

/* ---- LANDSCAPE MOBILE ---- */
@media (max-height: 500px) and (orientation: landscape) {
  #game-hud { height: 44px; }
  .hud-score { font-size: 20px; }
  #hud-time { font-size: 16px; }
  #mobile-controls { bottom: 30px; }
  .action-btn { width: 44px; height: 44px; font-size: 16px; }
  #joystick-base { width: 80px; height: 80px; }
  #joystick-knob { width: 36px; height: 36px; }
}

/* ---- PRINT STYLES ---- */
@media print {
  #site-header,
  #loading-screen,
  #cookie-banner,
  #pixel-particles,
  #crt-overlay,
  #scanlines,
  #bg-canvas {
    display: none !important;
  }
  body {
    background: white;
    color: black;
  }
  .page-section.active {
    display: block;
    padding-top: 20px;
  }
}

/* ---- ANIMATIONS ---- */
@keyframes shimmer {
  0% { background-position: -200% 0; }
  100% { background-position: 200% 0; }
}

.shimmer {
  background: linear-gradient(90deg, transparent 25%, rgba(0,255,136,0.1) 50%, transparent 75%);
  background-size: 200% 100%;
  animation: shimmer 2s infinite;
}

@keyframes pulse-green {
  0%, 100% { box-shadow: 0 0 5px rgba(0,255,136,0.3); }
  50% { box-shadow: 0 0 20px rgba(0,255,136,0.8); }
}

/* ---- UTILITIES ---- */
.hidden { display: none !important; }
.text-center { text-align: center; }
.text-primary { color: var(--primary); }
.text-dim { color: var(--text-dim); }
.mt-8 { margin-top: 8px; }
.mt-16 { margin-top: 16px; }
.mb-16 { margin-bottom: 16px; }
.visually-hidden {
  position: absolute;
  width: 1px; height: 1px;
  padding: 0; margin: -1px;
  overflow: hidden;
  clip: rect(0,0,0,0);
  white-space: nowrap;
  border: 0;
}

/* ---- FOCUS VISIBLE (keyboard nav) ---- */
:focus-visible {
  outline: 3px solid var(--accent);
  outline-offset: 3px;
}

/* Suppress outline for mouse users */
:focus:not(:focus-visible) {
  outline: none;
}
/* ENDFILE -->

<!-- FILE: ui.js -->
/**
 * NEXIVOSIGNAL FOOTBALL - UI ENGINE v2
 * Improved: proper nav flow, cookie consent, modal management, security
 */

'use strict';

const UI = (() => {

  // ── State ────────────────────────────────────────────────────────────────────
  let currentPage = 'home';
  let selectedHomeTeam = null;
  let selectedAwayTeam = null;
  let currentGameMode = 'quickmatch';
  let settings = {
    musicVol: 70, sfxVol: 80, crt: true, particles: true,
    shake: true, scanlines: true, difficulty: 'normal',
    fullscreen: false, offside: true, autoswitch: true,
    highContrast: false, largeText: false, lang: 'en'
  };
  let careerData = null;
  let tournamentData = null;
  let leaderboardData = { wins: [], goals: [], fastest: [], streak: [] };
  let achievements = [];
  let cookieConsent = null; // null | 'all' | 'essential'

  // ── Security: sanitize user text input ───────────────────────────────────────
  function sanitize(str) {
    if (typeof str !== 'string') return '';
    return str
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#039;')
      .slice(0, 200);
  }

  // ── Safe localStorage wrapper ────────────────────────────────────────────────
  const Store = {
    get(key) {
      try { return localStorage.getItem(key); } catch (e) { return null; }
    },
    set(key, val) {
      try { localStorage.setItem(key, val); return true; } catch (e) { return false; }
    },
    remove(key) {
      try { localStorage.removeItem(key); } catch (e) {}
    },
    getJSON(key, fallback = null) {
      try {
        const val = localStorage.getItem(key);
        return val ? JSON.parse(val) : fallback;
      } catch (e) { return fallback; }
    },
    setJSON(key, obj) {
      try { localStorage.setItem(key, JSON.stringify(obj)); return true; }
      catch (e) { return false; }
    }
  };

  // ── Init ─────────────────────────────────────────────────────────────────────
  function init() {
    loadSettings();
    loadSaveData();
    setupNav();
    setupLanding();
    setupTeamSelect();
    setupGameButtons();
    setupModals();
    setupFooter();
    setupLeaderboard();
    setupCareer();
    setupTournament();
    buildParticles();
    startBgCanvas();
    startHeroCanvas();
    initAchievements();
    setupCookieBanner();
    runLoadingScreen();
  }

  // ── Loading Screen ───────────────────────────────────────────────────────────
  function runLoadingScreen() {
    const bar = document.getElementById('loading-bar');
    const text = document.getElementById('loading-text');
    const screen = document.getElementById('loading-screen');
    const progressWrap = document.getElementById('loading-progress');
    const messages = [
      'Loading game engine...', 'Initializing physics...',
      'Building teams...', 'Setting up AI...', 'Loading sound engine...',
      'Preparing stadiums...', 'Almost ready...'
    ];
    let progress = 0;
    let msgIdx = 0;
    const interval = setInterval(() => {
      progress += Math.random() * 18 + 5;
      if (progress >= 100) progress = 100;
      bar.style.width = progress + '%';
      if (progressWrap) progressWrap.setAttribute('aria-valuenow', Math.round(progress));
      if (msgIdx < messages.length) {
        text.textContent = messages[msgIdx++];
      }
      if (progress >= 100) {
        clearInterval(interval);
        setTimeout(() => {
          screen.classList.add('hidden');
          Sound.init();
          Sound.startMusic('menu', 140);
        }, 400);
      }
    }, 180);
  }

  // ── Cookie Consent ────────────────────────────────────────────────────────────
  function setupCookieBanner() {
    const saved = Store.get('nf_cookie_consent');
    if (saved === 'all' || saved === 'essential') {
      cookieConsent = saved;
      hideCookieBanner();
      return;
    }

    const banner = document.getElementById('cookie-banner');
    if (!banner) return;
    banner.classList.remove('cookie-hidden');

    const acceptBtn = document.getElementById('cookie-accept-btn');
    const essentialBtn = document.getElementById('cookie-essential-btn');
    const settingsLink = document.getElementById('cookie-settings-link');
    const learnMore = document.getElementById('cookie-learn-more');

    if (acceptBtn) {
      acceptBtn.addEventListener('click', () => {
        cookieConsent = 'all';
        Store.set('nf_cookie_consent', 'all');
        hideCookieBanner();
        Sound.sfx.menuSelect();
      });
    }

    if (essentialBtn) {
      essentialBtn.addEventListener('click', () => {
        cookieConsent = 'essential';
        Store.set('nf_cookie_consent', 'essential');
        hideCookieBanner();
        Sound.sfx.menuSelect();
      });
    }

    if (settingsLink) {
      settingsLink.addEventListener('click', () => {
        openModal('cookies-modal');
      });
    }

    if (learnMore) {
      learnMore.addEventListener('click', (e) => {
        e.preventDefault();
        openModal('cookies-modal');
      });
    }
  }

  function hideCookieBanner() {
    const banner = document.getElementById('cookie-banner');
    if (banner) banner.classList.add('cookie-hidden');
  }

  // ── Navigation ───────────────────────────────────────────────────────────────
  function setupNav() {
    document.querySelectorAll('.nav-link').forEach(link => {
      link.addEventListener('click', e => {
        e.preventDefault();
        const page = link.dataset.page;
        if (page) navigateTo(page);
        Sound.sfx.menuSelect();
        // Close mobile nav
        const nav = document.getElementById('main-nav');
        nav.classList.remove('open');
        const toggle = document.getElementById('nav-toggle');
        if (toggle) toggle.setAttribute('aria-expanded', 'false');
      });
    });

    // Mobile toggle
    const toggle = document.getElementById('nav-toggle');
    if (toggle) {
      toggle.addEventListener('click', () => {
        const nav = document.getElementById('main-nav');
        const isOpen = nav.classList.toggle('open');
        toggle.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
      });
    }

    // Logo click → home
    const logo = document.getElementById('logo');
    if (logo) {
      logo.addEventListener('click', () => navigateTo('home'));
      logo.addEventListener('keydown', e => {
        if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); navigateTo('home'); }
      });
    }

    // Mode cards on home section
    document.querySelectorAll('.mode-card').forEach(card => {
      card.addEventListener('click', () => {
        const mode = card.dataset.mode;
        if (mode === 'career') navigateTo('career-page');
        else if (mode === 'tournament') navigateTo('tournament-page');
        else {
          currentGameMode = mode;
          navigateTo('play');
        }
        Sound.sfx.menuSelect();
      });
      card.addEventListener('keydown', e => {
        if (e.key === 'Enter' || e.key === ' ') {
          e.preventDefault();
          card.click();
        }
      });
    });
  }

  function navigateTo(pageId) {
    const sections = ['home', 'play', 'career-page', 'tournament-page',
      'leaderboard-page', 'about-page', 'controls-page', 'news-page',
      'credits-page'];

    if (sections.includes(pageId)) {
      // Show landing page
      document.querySelectorAll('.page').forEach(p => p.classList.remove('active'));
      document.getElementById('landing-page').classList.add('active');

      // Show correct section
      document.querySelectorAll('.page-section').forEach(s => s.classList.remove('active'));
      const sec = document.getElementById(pageId);
      if (sec) {
        sec.classList.add('active');
        // Focus main heading for screen readers
        const heading = sec.querySelector('h1, h2');
        if (heading) {
          heading.setAttribute('tabindex', '-1');
          heading.focus();
        }
      }

      // Update nav links
      document.querySelectorAll('.nav-link').forEach(l => {
        const isActive = l.dataset.page === pageId;
        l.classList.toggle('active', isActive);
        l.setAttribute('aria-current', isActive ? 'page' : 'false');
      });

      currentPage = pageId;
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
  }

  // ── Landing page buttons ─────────────────────────────────────────────────────
  function setupLanding() {
    const playNow = document.getElementById('play-now-btn');
    if (playNow) {
      playNow.addEventListener('click', () => {
        currentGameMode = 'quickmatch';
        navigateTo('play');
        Sound.sfx.menuSelect();
      });
    }

    const howTo = document.getElementById('how-to-play-btn');
    if (howTo) {
      howTo.addEventListener('click', () => {
        navigateTo('controls-page');
        Sound.sfx.menuSelect();
      });
    }

    // Play mode buttons
    document.querySelectorAll('.play-mode-btn').forEach(btn => {
      btn.addEventListener('click', () => {
        const mode = btn.dataset.mode;
        currentGameMode = mode;
        Sound.sfx.menuSelect();
        if (mode === 'career') {
          navigateTo('career-page');
        } else if (mode === 'tournament') {
          navigateTo('tournament-page');
        } else {
          openTeamSelect(mode);
        }
      });
      btn.addEventListener('mouseenter', () => Sound.sfx.menuHover());
    });
  }

  // ── Team Selection ───────────────────────────────────────────────────────────
  function setupTeamSelect() {
    const teamsGrid = document.getElementById('teams-grid');
    if (!teamsGrid) return;
    const teams = PlayersData.getTeams();

    teams.forEach(team => {
      const card = document.createElement('div');
      card.className = 'team-card';
      card.dataset.teamId = team.id;
      card.setAttribute('role', 'listitem');
      card.setAttribute('tabindex', '0');
      card.setAttribute('aria-label', `${team.name}, rating ${team.rating}, formation ${team.formation}`);
      card.innerHTML = `
        <span class="team-card-logo" aria-hidden="true">${team.emoji}</span>
        <span class="team-card-name">${sanitize(team.name)}</span>
        <span class="team-card-rating">★ ${team.rating}</span>
      `;
      card.addEventListener('click', () => selectTeam(team, card));
      card.addEventListener('keydown', e => {
        if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); selectTeam(team, card); }
      });
      card.addEventListener('mouseenter', () => Sound.sfx.menuHover());
      teamsGrid.appendChild(card);
    });

    const backBtn = document.getElementById('back-from-select');
    if (backBtn) {
      backBtn.addEventListener('click', () => {
        navigateTo('play');
        Sound.sfx.menuBack();
      });
    }

    const kickOff = document.getElementById('kick-off-btn');
    if (kickOff) {
      kickOff.addEventListener('click', () => {
        if (!selectedHomeTeam || !selectedAwayTeam) {
          flashMessage('Please select both teams!');
          return;
        }
        startGame();
        Sound.sfx.menuSelect();
      });
    }
  }

  function selectTeam(team, card) {
    Sound.sfx.menuSelect();
    const allCards = document.querySelectorAll('.team-card');

    if (!selectedHomeTeam || (selectedHomeTeam && selectedAwayTeam)) {
      selectedHomeTeam = team;
      selectedAwayTeam = null;
      allCards.forEach(c => {
        c.classList.remove('selected-home', 'selected-away');
        c.removeAttribute('aria-pressed');
      });
      card.classList.add('selected-home');
      card.setAttribute('aria-pressed', 'true');
      updateTeamDisplay('home', team);
    } else if (team.id !== selectedHomeTeam.id) {
      selectedAwayTeam = team;
      card.classList.add('selected-away');
      card.setAttribute('aria-pressed', 'true');
      updateTeamDisplay('away', team);
    } else {
      // Re-clicking home team — deselect
      selectedHomeTeam = null;
      card.classList.remove('selected-home');
      card.removeAttribute('aria-pressed');
    }
  }

  function updateTeamDisplay(side, team) {
    const logoEl = document.getElementById(`${side}-logo-big`);
    const nameEl = document.getElementById(`${side}-name-big`);
    const ratingEl = document.getElementById(`${side}-rating`);
    if (logoEl) logoEl.textContent = team.emoji;
    if (nameEl) nameEl.textContent = sanitize(team.name);
    if (ratingEl) ratingEl.textContent = `★ ${team.rating} | ${team.formation}`;
  }

  function openTeamSelect(mode) {
    currentGameMode = mode;
    const modeDisplay = document.getElementById('current-mode-display');
    if (modeDisplay) modeDisplay.textContent = mode.toUpperCase().replace(/_/g, ' ');

    if (!selectedHomeTeam) {
      const home = PlayersData.getRandomTeam();
      selectedHomeTeam = home;
      updateTeamDisplay('home', home);
      document.querySelectorAll('.team-card').forEach(c => {
        c.classList.remove('selected-home', 'selected-away');
        if (c.dataset.teamId === home.id) c.classList.add('selected-home');
      });
    }
    if (!selectedAwayTeam) {
      const away = PlayersData.getRandomTeam(selectedHomeTeam.id);
      selectedAwayTeam = away;
      updateTeamDisplay('away', away);
      document.querySelectorAll('.team-card').forEach(c => {
        if (c.dataset.teamId === away.id) c.classList.add('selected-away');
      });
    }

    document.querySelectorAll('.page').forEach(p => p.classList.remove('active'));
    document.getElementById('team-select-screen').classList.add('active');
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }

  function startGame() {
    const diffEl = document.getElementById('difficulty-select');
    const timeEl = document.getElementById('time-select');
    const weatherEl = document.getElementById('weather-select');

    const difficulty = diffEl ? diffEl.value : 'normal';
    const timeVal = timeEl ? parseInt(timeEl.value) : 5;
    const weather = weatherEl ? weatherEl.value : 'sunny';

    const config = {
      homeTeam: selectedHomeTeam,
      awayTeam: selectedAwayTeam,
      difficulty,
      matchTime: timeVal * 60,
      weather: weather === 'random' ? randomWeather() : weather,
      mode: currentGameMode
    };

    document.querySelectorAll('.page').forEach(p => p.classList.remove('active'));
    document.getElementById('game-screen').classList.add('active');

    Sound.stopMusic();
    if (typeof Game !== 'undefined') {
      Game.start(config);
    }

    // Focus canvas for keyboard accessibility
    setTimeout(() => {
      const canvas = document.getElementById('game-canvas');
      if (canvas) canvas.focus();
    }, 100);
  }

  function randomWeather() {
    const weathers = ['sunny', 'sunny', 'sunny', 'night', 'rain', 'snow', 'fog'];
    return weathers[Math.floor(Math.random() * weathers.length)];
  }

  // ── Game Buttons ─────────────────────────────────────────────────────────────
  function setupGameButtons() {
    const pauseBtn = document.getElementById('pause-btn');
    if (pauseBtn) {
      pauseBtn.addEventListener('click', () => {
        if (typeof Game !== 'undefined') Game.togglePause();
      });
    }

    const resumeBtn = document.getElementById('resume-btn');
    if (resumeBtn) {
      resumeBtn.addEventListener('click', () => {
        if (typeof Game !== 'undefined') Game.togglePause();
        Sound.sfx.menuSelect();
      });
    }

    const restartBtn = document.getElementById('restart-btn');
    if (restartBtn) {
      restartBtn.addEventListener('click', () => {
        if (typeof Game !== 'undefined') Game.restart();
        Sound.sfx.menuSelect();
      });
    }

    const settingsBtn = document.getElementById('settings-in-game-btn');
    if (settingsBtn) {
      settingsBtn.addEventListener('click', () => openSettings());
    }

    const quitBtn = document.getElementById('quit-to-menu-btn');
    if (quitBtn) {
      quitBtn.addEventListener('click', () => {
        if (typeof Game !== 'undefined') Game.stop();
        returnToMenu();
        Sound.sfx.menuBack();
      });
    }

    const playAgainBtn = document.getElementById('play-again-btn');
    if (playAgainBtn) {
      playAgainBtn.addEventListener('click', () => {
        document.getElementById('fulltime-overlay').classList.add('hidden');
        if (typeof Game !== 'undefined') Game.restart();
        Sound.sfx.menuSelect();
      });
    }

    const ftMenuBtn = document.getElementById('fulltime-menu-btn');
    if (ftMenuBtn) {
      ftMenuBtn.addEventListener('click', () => {
        document.getElementById('fulltime-overlay').classList.add('hidden');
        if (typeof Game !== 'undefined') Game.stop();
        returnToMenu();
        Sound.sfx.menuBack();
      });
    }

    const htBtn = document.getElementById('continue-halftime-btn');
    if (htBtn) {
      htBtn.addEventListener('click', () => {
        document.getElementById('halftime-overlay').classList.add('hidden');
        if (typeof Game !== 'undefined') Game.continueAfterHalftime();
        Sound.sfx.menuSelect();
      });
    }

    // ESC key
    document.addEventListener('keydown', e => {
      if (e.key === 'Escape') {
        const gameScreen = document.getElementById('game-screen');
        if (gameScreen && gameScreen.classList.contains('active')) {
          if (typeof Game !== 'undefined') Game.togglePause();
        }
      }
    });
  }

  function returnToMenu() {
    document.querySelectorAll('.page').forEach(p => p.classList.remove('active'));
    document.getElementById('landing-page').classList.add('active');
    document.querySelectorAll('.page-section').forEach(s => s.classList.remove('active'));
    document.getElementById('home').classList.add('active');
    document.querySelectorAll('.nav-link').forEach(l => {
      const isActive = l.dataset.page === 'home';
      l.classList.toggle('active', isActive);
      l.setAttribute('aria-current', isActive ? 'page' : 'false');
    });
    Sound.startMusic('menu', 140);
    currentPage = 'home';
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }

  // ── Modals ───────────────────────────────────────────────────────────────────
  function setupModals() {
    // Settings
    const saveBtn = document.getElementById('save-settings-btn');
    if (saveBtn) saveBtn.addEventListener('click', saveSettings);
    const resetBtn = document.getElementById('reset-settings-btn');
    if (resetBtn) resetBtn.addEventListener('click', resetSettings);
    const closeSettingsBtn = document.getElementById('close-settings-btn');
    if (closeSettingsBtn) closeSettingsBtn.addEventListener('click', () => closeModal('settings-modal'));

    const musicVol = document.getElementById('music-vol');
    if (musicVol) musicVol.addEventListener('input', e => {
      document.getElementById('music-vol-val').textContent = e.target.value;
      Sound.setMusicVolume(parseInt(e.target.value));
    });

    const sfxVol = document.getElementById('sfx-vol');
    if (sfxVol) sfxVol.addEventListener('input', e => {
      document.getElementById('sfx-vol-val').textContent = e.target.value;
      Sound.setSfxVolume(parseInt(e.target.value));
    });

    const crtToggle = document.getElementById('crt-toggle');
    if (crtToggle) crtToggle.addEventListener('change', e => {
      document.getElementById('crt-overlay').style.display = e.target.checked ? 'block' : 'none';
    });

    const scanlinesToggle = document.getElementById('scanlines-toggle');
    if (scanlinesToggle) scanlinesToggle.addEventListener('change', e => {
      document.getElementById('scanlines').style.display = e.target.checked ? 'block' : 'none';
    });

    const fullscreenToggle = document.getElementById('fullscreen-toggle');
    if (fullscreenToggle) fullscreenToggle.addEventListener('change', e => {
      if (e.target.checked) document.documentElement.requestFullscreen?.().catch(() => {});
      else document.exitFullscreen?.().catch(() => {});
    });

    // Achievements
    const closeAchBtn = document.getElementById('close-achievements-btn');
    if (closeAchBtn) closeAchBtn.addEventListener('click', () => closeModal('achievements-modal'));

    // Career setup
    const confirmCareerBtn = document.getElementById('confirm-career-btn');
    if (confirmCareerBtn) confirmCareerBtn.addEventListener('click', startCareer);
    const cancelCareerBtn = document.getElementById('cancel-career-btn');
    if (cancelCareerBtn) cancelCareerBtn.addEventListener('click', () => closeModal('career-setup-modal'));

    // Legal modals
    const closePrivacy = document.getElementById('close-privacy-btn');
    if (closePrivacy) closePrivacy.addEventListener('click', () => closeModal('privacy-modal'));
    const closeTerms = document.getElementById('close-terms-btn');
    if (closeTerms) closeTerms.addEventListener('click', () => closeModal('terms-modal'));
    const closeCookies = document.getElementById('close-cookies-btn');
    if (closeCookies) closeCookies.addEventListener('click', () => closeModal('cookies-modal'));
    const closeContact = document.getElementById('close-contact-btn');
    if (closeContact) closeContact.addEventListener('click', () => closeModal('contact-modal'));

    // Privacy → cookies link inside privacy modal
    const privToCookies = document.getElementById('privacy-to-cookies');
    if (privToCookies) privToCookies.addEventListener('click', (e) => {
      e.preventDefault();
      closeModal('privacy-modal');
      openModal('cookies-modal');
    });

    const sendContactBtn = document.getElementById('send-contact-btn');
    if (sendContactBtn) {
      sendContactBtn.addEventListener('click', () => {
        const msg = document.getElementById('contact-message');
        if (msg && msg.value.trim()) {
          flashMessage('Thank you! Your message has been noted. 📨');
          msg.value = '';
          const nameEl = document.getElementById('contact-name');
          if (nameEl) nameEl.value = '';
          closeModal('contact-modal');
        } else {
          flashMessage('Please enter a message first.');
        }
      });
    }

    // 404
    const back404 = document.getElementById('back-to-home-404');
    if (back404) back404.addEventListener('click', () => returnToMenu());

    // Close modals on backdrop click
    document.querySelectorAll('.modal').forEach(modal => {
      modal.addEventListener('click', e => {
        if (e.target === modal) closeModal(modal.id);
      });
    });

    // ESC closes topmost modal
    document.addEventListener('keydown', e => {
      if (e.key === 'Escape') {
        const openModals = Array.from(document.querySelectorAll('.modal:not(.hidden)'));
        if (openModals.length > 0) {
          e.stopPropagation();
          closeModal(openModals[openModals.length - 1].id);
        }
      }
    });
  }

  function openModal(id) {
    const modal = document.getElementById(id);
    if (!modal) return;
    modal.classList.remove('hidden');
    // Focus first focusable element inside
    const focusable = modal.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');
    if (focusable) setTimeout(() => focusable.focus(), 50);
    Sound.sfx.menuSelect();
  }

  function closeModal(id) {
    const modal = document.getElementById(id);
    if (!modal) return;
    modal.classList.add('hidden');
    Sound.sfx.menuBack();
  }

  function openSettings() {
    document.getElementById('music-vol').value = settings.musicVol;
    document.getElementById('music-vol-val').textContent = settings.musicVol;
    document.getElementById('sfx-vol').value = settings.sfxVol;
    document.getElementById('sfx-vol-val').textContent = settings.sfxVol;
    document.getElementById('crt-toggle').checked = settings.crt;
    document.getElementById('particles-toggle').checked = settings.particles;
    document.getElementById('shake-toggle').checked = settings.shake;
    document.getElementById('scanlines-toggle').checked = settings.scanlines;
    document.getElementById('settings-difficulty').value = settings.difficulty;
    document.getElementById('offside-toggle').checked = settings.offside;
    document.getElementById('autoswitch-toggle').checked = settings.autoswitch;
    document.getElementById('hc-toggle').checked = settings.highContrast;
    document.getElementById('lt-toggle').checked = settings.largeText;
    document.getElementById('lang-select').value = settings.lang;
    openModal('settings-modal');
  }

  function saveSettings() {
    settings.musicVol = parseInt(document.getElementById('music-vol').value);
    settings.sfxVol = parseInt(document.getElementById('sfx-vol').value);
    settings.crt = document.getElementById('crt-toggle').checked;
    settings.particles = document.getElementById('particles-toggle').checked;
    settings.shake = document.getElementById('shake-toggle').checked;
    settings.scanlines = document.getElementById('scanlines-toggle').checked;
    settings.difficulty = document.getElementById('settings-difficulty').value;
    settings.offside = document.getElementById('offside-toggle').checked;
    settings.autoswitch = document.getElementById('autoswitch-toggle').checked;
    settings.highContrast = document.getElementById('hc-toggle').checked;
    settings.largeText = document.getElementById('lt-toggle').checked;
    settings.lang = document.getElementById('lang-select').value;

    Store.setJSON('nf_settings', settings);
    applySettings();
    closeModal('settings-modal');
    Sound.sfx.achievement();
    flashMessage('Settings saved! ✓');
  }

  function resetSettings() {
    settings = {
      musicVol: 70, sfxVol: 80, crt: true, particles: true,
      shake: true, scanlines: true, difficulty: 'normal', fullscreen: false,
      offside: true, autoswitch: true, highContrast: false, largeText: false, lang: 'en'
    };
    applySettings();
    openSettings();
  }

  function loadSettings() {
    const saved = Store.getJSON('nf_settings');
    if (saved) {
      try { settings = { ...settings, ...saved }; } catch (e) {}
    }
    applySettings();
  }

  function applySettings() {
    const crtEl = document.getElementById('crt-overlay');
    const scanlinesEl = document.getElementById('scanlines');
    if (crtEl) crtEl.style.display = settings.crt ? 'block' : 'none';
    if (scanlinesEl) scanlinesEl.style.display = settings.scanlines ? 'block' : 'none';
    if (typeof Sound !== 'undefined' && Sound.initialized) {
      Sound.setMusicVolume(settings.musicVol);
      Sound.setSfxVolume(settings.sfxVol);
    }
    document.body.classList.toggle('high-contrast', !!settings.highContrast);
    document.body.classList.toggle('large-text', !!settings.largeText);
  }

  // ── Footer ───────────────────────────────────────────────────────────────────
  function setupFooter() {
    const privacyLink = document.getElementById('privacy-link');
    if (privacyLink) privacyLink.addEventListener('click', e => { e.preventDefault(); openModal('privacy-modal'); });

    const termsLink = document.getElementById('terms-link');
    if (termsLink) termsLink.addEventListener('click', e => { e.preventDefault(); openModal('terms-modal'); });

    const cookiesLink = document.getElementById('cookies-link');
    if (cookiesLink) cookiesLink.addEventListener('click', e => { e.preventDefault(); openModal('cookies-modal'); });

    const contactLink = document.getElementById('contact-link');
    if (contactLink) contactLink.addEventListener('click', e => { e.preventDefault(); openModal('contact-modal'); });

    document.querySelectorAll('.footer-links a[data-page]').forEach(a => {
      a.addEventListener('click', e => {
        e.preventDefault();
        navigateTo(a.dataset.page);
      });
    });
  }

  // ── Leaderboard ───────────────────────────────────────────────────────────────
  function setupLeaderboard() {
    document.querySelectorAll('.tab-btn').forEach(btn => {
      btn.addEventListener('click', () => {
        document.querySelectorAll('.tab-btn').forEach(b => {
          b.classList.remove('active');
          b.setAttribute('aria-selected', 'false');
        });
        btn.classList.add('active');
        btn.setAttribute('aria-selected', 'true');
        // Update tabpanel label
        const table = document.getElementById('leaderboard-table');
        if (table) table.setAttribute('aria-labelledby', btn.id);
        renderLeaderboard(btn.dataset.tab);
        Sound.sfx.menuHover();
      });
    });
    generateSampleLeaderboard();
    renderLeaderboard('wins');
  }

  function generateSampleLeaderboard() {
    const names = ['PixelKing', 'GoalMachine', 'NexivoAce', 'RetroStriker', 'PixelGoal',
      'ChampionFC', 'UltimateGK', 'SkillMaster', 'NetBuster', 'TacticalPro'];
    const teams = PlayersData.getTeams();

    leaderboardData.wins = names.map((n, i) => ({
      name: n, team: teams[i % teams.length].name, value: Math.floor(Math.random() * 200 + 50)
    })).sort((a, b) => b.value - a.value);

    leaderboardData.goals = names.map((n, i) => ({
      name: n, team: teams[i % teams.length].name, value: Math.floor(Math.random() * 500 + 100)
    })).sort((a, b) => b.value - a.value);

    leaderboardData.fastest = names.map((n, i) => ({
      name: n, team: teams[i % teams.length].name,
      value: (10 + Math.random() * 50).toFixed(1) + 's'
    }));

    leaderboardData.streak = names.map((n, i) => ({
      name: n, team: teams[i % teams.length].name, value: Math.floor(Math.random() * 20 + 3)
    })).sort((a, b) => b.value - a.value);
  }

  function renderLeaderboard(tab) {
    const container = document.getElementById('leaderboard-table');
    if (!container) return;
    const data = leaderboardData[tab] || [];
    container.innerHTML = '';

    const list = document.createElement('div');
    list.setAttribute('role', 'list');
    list.setAttribute('aria-label', `Leaderboard: ${tab}`);

    data.slice(0, 10).forEach((entry, i) => {
      const div = document.createElement('div');
      div.className = 'lb-entry';
      div.setAttribute('role', 'listitem');
      const rankClass = i === 0 ? 'lb-rank-1' : i === 1 ? 'lb-rank-2' : i === 2 ? 'lb-rank-3' : '';
      const medal = i === 0 ? '🥇' : i === 1 ? '🥈' : i === 2 ? '🥉' : `#${i + 1}`;
      div.innerHTML = `
        <span class="lb-rank ${rankClass}" aria-hidden="true">${medal}</span>
        <span class="lb-name">${sanitize(entry.name)}<br><small style="color:var(--text-dim);font-size:10px;">${sanitize(entry.team)}</small></span>
        <span class="lb-value">${sanitize(String(entry.value))}</span>
      `;
      list.appendChild(div);
    });

    container.appendChild(list);
  }

  // ── Career ────────────────────────────────────────────────────────────────────
  function setupCareer() {
    const startBtn = document.getElementById('start-career-btn');
    const continueBtn = document.getElementById('continue-career-btn');

    if (startBtn) startBtn.addEventListener('click', () => {
      buildCareerTeamGrid();
      openModal('career-setup-modal');
    });

    if (continueBtn) continueBtn.addEventListener('click', () => {
      if (careerData) {
        loadCareerDisplay();
        flashMessage('Career loaded! ✓');
      } else {
        flashMessage('No career save found!');
      }
    });

    updateCareerDisplay();
  }

  function buildCareerTeamGrid() {
    const grid = document.getElementById('career-team-grid');
    if (!grid) return;
    grid.innerHTML = '';
    PlayersData.getTeams().forEach(team => {
      const div = document.createElement('div');
      div.className = 'career-team-option';
      div.dataset.teamId = team.id;
      div.setAttribute('role', 'option');
      div.setAttribute('tabindex', '0');
      div.setAttribute('aria-selected', 'false');
      div.setAttribute('aria-label', `${team.name} - Rating ${team.rating}`);
      div.innerHTML = `<span class="team-emoji" aria-hidden="true">${team.emoji}</span><span>${sanitize(team.name)}</span>`;
      div.addEventListener('click', () => {
        document.querySelectorAll('.career-team-option').forEach(o => {
          o.classList.remove('selected');
          o.setAttribute('aria-selected', 'false');
        });
        div.classList.add('selected');
        div.setAttribute('aria-selected', 'true');
        Sound.sfx.menuHover();
      });
      div.addEventListener('keydown', e => {
        if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); div.click(); }
      });
      grid.appendChild(div);
    });
  }

  function startCareer() {
    const nameInput = document.getElementById('manager-name-input');
    const name = nameInput ? sanitize(nameInput.value.trim()) || 'MANAGER' : 'MANAGER';
    const selectedTeamEl = document.querySelector('.career-team-option.selected');
    if (!selectedTeamEl) { flashMessage('Please select a team!'); return; }
    const teamId = selectedTeamEl.dataset.teamId;
    const team = PlayersData.getTeamById(teamId);
    if (!team) { flashMessage('Invalid team selection.'); return; }
    const difficulty = document.getElementById('career-difficulty').value;

    careerData = {
      managerName: name.toUpperCase().slice(0, 20),
      teamId,
      teamName: team.name,
      season: 1,
      budget: 10000000,
      difficulty,
      wins: 0, losses: 0, draws: 0,
      goals: 0, trophies: 0,
      matches: [],
      created: new Date().toISOString()
    };

    Store.setJSON('nf_career', careerData);
    closeModal('career-setup-modal');
    updateCareerDisplay();
    flashMessage(`Career started! Welcome, ${careerData.managerName}! ⭐`);
    Sound.sfx.victory();
  }

  function updateCareerDisplay() {
    if (careerData) loadCareerDisplay();
  }

  function loadCareerDisplay() {
    if (!careerData) return;
    const el = id => document.getElementById(id);
    if (el('career-manager-name')) el('career-manager-name').textContent = `MANAGER: ${sanitize(careerData.managerName)}`;
    if (el('career-team-name')) el('career-team-name').textContent = `TEAM: ${sanitize(careerData.teamName)}`;
    if (el('career-season')) el('career-season').textContent = `SEASON: ${careerData.season}`;
    if (el('career-budget')) el('career-budget').textContent = `BUDGET: $${(careerData.budget / 1000000).toFixed(1)}M`;

    const statsGrid = el('career-stats-display');
    if (statsGrid) {
      statsGrid.innerHTML = `
        <div class="career-stat-box"><div class="career-stat-val">${careerData.wins}</div><div class="career-stat-label">WINS</div></div>
        <div class="career-stat-box"><div class="career-stat-val">${careerData.draws}</div><div class="career-stat-label">DRAWS</div></div>
        <div class="career-stat-box"><div class="career-stat-val">${careerData.losses}</div><div class="career-stat-label">LOSSES</div></div>
        <div class="career-stat-box"><div class="career-stat-val">${careerData.goals}</div><div class="career-stat-label">GOALS</div></div>
        <div class="career-stat-box"><div class="career-stat-val">${careerData.trophies}</div><div class="career-stat-label">TROPHIES</div></div>
      `;
    }
  }

  function loadSaveData() {
    careerData = Store.getJSON('nf_career', null);
    updateCareerDisplay();
  }

  // ── Tournament ────────────────────────────────────────────────────────────────
  function setupTournament() {
    const startBtn = document.getElementById('start-tournament-btn');
    const continueBtn = document.getElementById('continue-tournament-btn');

    if (startBtn) startBtn.addEventListener('click', () => {
      initTournament();
      Sound.sfx.menuSelect();
    });
    if (continueBtn) continueBtn.addEventListener('click', () => {
      if (tournamentData) renderBracket();
      else flashMessage('No tournament in progress!');
    });
  }

  function initTournament() {
    const teams = PlayersData.getTeams();
    const shuffled = [...teams].sort(() => Math.random() - 0.5).slice(0, 8);
    tournamentData = {
      teams: shuffled,
      round: 1,
      matches: [],
      winners: []
    };
    for (let i = 0; i < 4; i++) {
      tournamentData.matches.push({
        home: shuffled[i * 2],
        away: shuffled[i * 2 + 1],
        homeScore: null, awayScore: null, played: false
      });
    }
    renderBracket();
  }

  function renderBracket() {
    const container = document.getElementById('tournament-bracket');
    if (!container || !tournamentData) return;

    container.innerHTML = '';
    const heading = document.createElement('h3');
    heading.style.cssText = 'color:var(--accent);font-size:10px;margin-bottom:16px;text-align:center;';
    heading.textContent = 'QUARTER FINALS';
    container.appendChild(heading);

    tournamentData.matches.forEach((match) => {
      const div = document.createElement('div');
      div.className = 'bracket-match';
      const score = match.played ? `${match.homeScore} - ${match.awayScore}` : 'VS';
      div.setAttribute('role', 'button');
      div.setAttribute('tabindex', match.played ? '-1' : '0');
      div.setAttribute('aria-label', `${match.home.name} vs ${match.away.name}${match.played ? ` — Result: ${score}` : ' — Click to play this match'}`);
      div.innerHTML = `
        <span style="font-size:20px;" aria-hidden="true">${match.home.emoji}</span>
        <span style="flex:1;font-size:8px;color:var(--text-primary);">${sanitize(match.home.name)}</span>
        <span style="font-size:10px;color:var(--accent);padding:0 12px;">${score}</span>
        <span style="flex:1;font-size:8px;color:var(--text-primary);text-align:right;">${sanitize(match.away.name)}</span>
        <span style="font-size:20px;" aria-hidden="true">${match.away.emoji}</span>
      `;

      if (!match.played) {
        div.style.borderColor = 'rgba(0,255,136,0.4)';
        div.addEventListener('click', () => {
          selectedHomeTeam = match.home;
          selectedAwayTeam = match.away;
          currentGameMode = 'tournament';
          startGame();
        });
        div.addEventListener('keydown', e => {
          if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); div.click(); }
        });
      } else {
        div.style.borderColor = 'rgba(255,221,0,0.3)';
        div.style.cursor = 'default';
      }

      container.appendChild(div);
    });
  }

  // ── Achievements ──────────────────────────────────────────────────────────────
  function initAchievements() {
    achievements = [
      { id: 'first_goal', name: 'FIRST BLOOD', desc: 'Score your first goal', icon: '⚽', unlocked: false },
      { id: 'hat_trick', name: 'HAT TRICK HERO', desc: 'Score 3 goals in one match', icon: '🎩', unlocked: false },
      { id: 'clean_sheet', name: 'CLEAN SHEET', desc: 'Win without conceding', icon: '🛡️', unlocked: false },
      { id: 'comeback', name: 'COMEBACK KING', desc: 'Win from 2 goals down', icon: '👑', unlocked: false },
      { id: 'penalty_king', name: 'PENALTY KING', desc: 'Score 5 penalties', icon: '🎯', unlocked: false },
      { id: 'first_win', name: 'FIRST WIN', desc: 'Win your first match', icon: '🏆', unlocked: false },
      { id: 'tour_win', name: 'TOURNAMENT WINNER', desc: 'Win a tournament', icon: '🥇', unlocked: false },
      { id: 'worldclass', name: 'WORLD CLASS', desc: 'Beat a Legend team', icon: '⭐', unlocked: false },
      { id: 'speedster', name: 'LIGHTNING FAST', desc: 'Score in under 10 seconds', icon: '⚡', unlocked: false },
      { id: 'veteran', name: 'VETERAN', desc: 'Play 50 matches', icon: '🎖️', unlocked: false },
    ];

    const saved = Store.getJSON('nf_achievements', null);
    if (saved && Array.isArray(saved)) {
      achievements.forEach(a => {
        const s = saved.find(x => x.id === a.id);
        if (s) a.unlocked = !!s.unlocked;
      });
    }
  }

  function unlockAchievement(id) {
    const ach = achievements.find(a => a.id === id);
    if (!ach || ach.unlocked) return;
    ach.unlocked = true;
    Store.setJSON('nf_achievements', achievements);
    showAchievementToast(ach);
    Sound.sfx.achievement();
  }

  function showAchievementToast(ach) {
    const toast = document.getElementById('achievement-toast');
    const desc = document.getElementById('toast-desc');
    if (!toast || !desc) return;
    desc.textContent = `${ach.name}: ${ach.desc}`;
    toast.classList.remove('hidden');
    setTimeout(() => toast.classList.add('hidden'), 4000);
  }

  // ── Background Canvas ─────────────────────────────────────────────────────────
  function startBgCanvas() {
    const canvas = document.getElementById('bg-canvas');
    if (!canvas) return;
    const ctx = canvas.getContext('2d');

    function resize() {
      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight;
    }
    resize();
    let resizeTimer;
    window.addEventListener('resize', () => {
      clearTimeout(resizeTimer);
      resizeTimer = setTimeout(resize, 100);
    });

    let t = 0;
    function draw() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.fillStyle = '#0a0e1a';
      ctx.fillRect(0, 0, canvas.width, canvas.height);

      ctx.strokeStyle = 'rgba(0,255,136,0.04)';
      ctx.lineWidth = 1;
      const gridSize = 60;
      for (let x = 0; x < canvas.width; x += gridSize) {
        ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, canvas.height); ctx.stroke();
      }
      for (let y = 0; y < canvas.height; y += gridSize) {
        ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(canvas.width, y); ctx.stroke();
      }

      for (let i = 0; i < 5; i++) {
        const x = (Math.sin(t * 0.3 + i * 2) * 0.5 + 0.5) * canvas.width;
        const y = (Math.cos(t * 0.2 + i * 1.5) * 0.5 + 0.5) * canvas.height;
        const r = 40 + Math.sin(t + i) * 20;
        const grad = ctx.createRadialGradient(x, y, 0, x, y, r);
        grad.addColorStop(0, 'rgba(0,255,136,0.07)');
        grad.addColorStop(1, 'transparent');
        ctx.fillStyle = grad;
        ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill();
      }

      t += 0.008;
      requestAnimationFrame(draw);
    }
    draw();
  }

  // ── Hero Canvas ────────────────────────────────────────────────────────────────
  function startHeroCanvas() {
    const canvas = document.getElementById('hero-canvas');
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    canvas.width = 400;
    canvas.height = 400;
    ctx.imageSmoothingEnabled = false;

    let t = 0;
    const ball = { x: 200, y: 200, vx: 2, vy: 1.3, rotation: 0 };

    function drawField() {
      ctx.fillStyle = '#0a1a0f';
      ctx.fillRect(0, 0, 400, 400);
      for (let i = 0; i < 8; i++) {
        ctx.fillStyle = i % 2 === 0 ? 'rgba(0,80,30,0.5)' : 'rgba(0,60,20,0.5)';
        ctx.fillRect(i * 50, 0, 50, 400);
      }
      ctx.strokeStyle = 'rgba(255,255,255,0.4)';
      ctx.lineWidth = 2;
      ctx.strokeRect(20, 20, 360, 360);
      ctx.beginPath(); ctx.moveTo(200, 20); ctx.lineTo(200, 380); ctx.stroke();
      ctx.beginPath(); ctx.arc(200, 200, 50, 0, Math.PI * 2); ctx.stroke();
      ctx.strokeRect(20, 130, 70, 140);
      ctx.strokeRect(310, 130, 70, 140);
      ctx.fillStyle = 'rgba(255,255,255,0.15)';
      ctx.fillRect(5, 160, 20, 80);
      ctx.fillRect(375, 160, 20, 80);
      // Score board
      ctx.fillStyle = 'rgba(0,0,0,0.7)';
      ctx.fillRect(140, 8, 120, 24);
      ctx.strokeStyle = 'rgba(0,255,136,0.5)';
      ctx.strokeRect(140, 8, 120, 24);
      ctx.fillStyle = '#fff';
      ctx.font = '12px "Press Start 2P", monospace';
      ctx.textAlign = 'center';
      ctx.fillText('1 - 0', 200, 25);
      ctx.font = '6px "Press Start 2P", monospace';
      ctx.fillStyle = 'rgba(0,255,136,0.8)';
      const mins = Math.floor(t * 0.2) % 90;
      const secs = Math.floor(t * 2) % 60;
      ctx.fillText(`${String(mins).padStart(2,'0')}:${String(secs).padStart(2,'0')}`, 200, 37);
    }

    function drawPixelPlayer(x, y, color) {
      ctx.save();
      ctx.translate(Math.round(x), Math.round(y));
      const bob = Math.abs(Math.sin(t * 6 + x)) * 2;
      ctx.fillStyle = 'rgba(0,0,0,0.25)';
      ctx.fillRect(-8, 10, 16, 4);
      ctx.fillStyle = color;
      ctx.fillRect(-6, -8 + bob * 0.3, 12, 10);
      ctx.fillStyle = '#fff';
      ctx.fillRect(-5, 2 + bob * 0.3, 10, 5);
      ctx.fillStyle = '#222';
      ctx.fillRect(-5, 7, 4, 5);
      ctx.fillRect(1, 7, 4, 5);
      ctx.fillStyle = '#f5d5a0';
      ctx.fillRect(-4, -16 + bob, 8, 8);
      ctx.fillStyle = '#222';
      ctx.fillRect(-4, -16 + bob, 8, 3);
      ctx.restore();
    }

    const players = [
      { x: 80, y: 200, color: '#cc0000', side: 'home' },
      { x: 140, y: 140, color: '#cc0000', side: 'home' },
      { x: 140, y: 260, color: '#cc0000', side: 'home' },
      { x: 320, y: 200, color: '#0044cc', side: 'away' },
      { x: 260, y: 140, color: '#0044cc', side: 'away' },
      { x: 260, y: 260, color: '#0044cc', side: 'away' },
    ];

    function animatePlayers() {
      players.forEach((p, i) => {
        const angle = t * 0.5 + i * 1.0;
        if (p.side === 'home') {
          p.x = 100 + Math.sin(angle) * 30;
          p.y = 200 + Math.cos(angle * 0.7) * 60;
        } else {
          p.x = 300 + Math.sin(angle + Math.PI) * 30;
          p.y = 200 + Math.cos(angle * 0.7 + Math.PI) * 60;
        }
      });
    }

    function update() {
      ball.x += ball.vx;
      ball.y += ball.vy;
      ball.rotation += 0.1;
      if (ball.x < 20 || ball.x > 380) ball.vx *= -1;
      if (ball.y < 20 || ball.y > 380) ball.vy *= -1;
      players.forEach(p => {
        const dx = p.x - ball.x, dy = p.y - ball.y;
        const d = Math.sqrt(dx * dx + dy * dy);
        if (d < 20) {
          ball.vx = -ball.vx * 1.1 + (Math.random() - 0.5);
          ball.vy = -ball.vy * 1.1 + (Math.random() - 0.5);
          const spd = Math.sqrt(ball.vx * ball.vx + ball.vy * ball.vy);
          if (spd > 4) { ball.vx = (ball.vx / spd) * 4; ball.vy = (ball.vy / spd) * 4; }
        }
      });
    }

    function render() {
      drawField();
      animatePlayers();
      update();
      players.forEach(p => drawPixelPlayer(p.x, p.y, p.color));
      PlayersData.drawBall(ctx, ball.x, ball.y, 0, ball.rotation, 0);
      t += 0.02;
      requestAnimationFrame(render);
    }

    render();
  }

  // ── Pixel Particles ───────────────────────────────────────────────────────────
  function buildParticles() {
    const container = document.getElementById('pixel-particles');
    if (!container) return;
    const colors = ['#00ff88', '#ff6b00', '#ffdd00', '#3b82f6', '#ef4444'];
    for (let i = 0; i < 20; i++) {
      const p = document.createElement('div');
      p.className = 'pixel-particle';
      p.setAttribute('aria-hidden', 'true');
      p.style.left = Math.random() * 100 + '%';
      p.style.animationDuration = (8 + Math.random() * 12) + 's';
      p.style.animationDelay = -(Math.random() * 15) + 's';
      p.style.background = colors[Math.floor(Math.random() * colors.length)];
      const size = (2 + Math.floor(Math.random() * 4)) + 'px';
      p.style.width = size;
      p.style.height = size;
      container.appendChild(p);
    }
  }

  // ── HUD Updates ───────────────────────────────────────────────────────────────
  function updateHUD(homeScore, awayScore, time, period, weather) {
    const homeEl = document.getElementById('hud-score-home');
    const awayEl = document.getElementById('hud-score-away');
    const timeEl = document.getElementById('hud-time');
    const periodEl = document.getElementById('hud-period');
    const weatherEl = document.getElementById('hud-weather-icon');

    if (homeEl) homeEl.textContent = homeScore;
    if (awayEl) awayEl.textContent = awayScore;
    if (timeEl) timeEl.textContent = formatTime(time);
    if (periodEl) periodEl.textContent = period;
    if (weatherEl) {
      const icons = { sunny: '☀️', night: '🌙', rain: '🌧️', snow: '❄️', fog: '🌫️' };
      weatherEl.textContent = icons[weather] || '☀️';
      weatherEl.title = weather ? weather.charAt(0).toUpperCase() + weather.slice(1) : 'Sunny';
    }
  }

  function setHUDTeams(homeTeam, awayTeam) {
    const hlEl = document.getElementById('hud-home-logo');
    const hnEl = document.getElementById('hud-home-name');
    const alEl = document.getElementById('hud-away-logo');
    const anEl = document.getElementById('hud-away-name');
    if (hlEl) hlEl.textContent = homeTeam.emoji;
    if (hnEl) hnEl.textContent = sanitize(homeTeam.name);
    if (alEl) alEl.textContent = awayTeam.emoji;
    if (anEl) anEl.textContent = sanitize(awayTeam.name);
  }

  function formatTime(seconds) {
    const s = Math.max(0, Math.floor(seconds));
    const m = Math.floor(s / 60);
    const sec = s % 60;
    return `${String(m).padStart(2, '0')}:${String(sec).padStart(2, '0')}`;
  }

  // ── Commentary ────────────────────────────────────────────────────────────────
  function setCommentary(text) {
    const el = document.getElementById('commentary-text');
    if (el) {
      el.textContent = sanitize(text);
      // Re-trigger scroll animation
      el.style.animation = 'none';
      void el.offsetHeight;
      el.style.animation = '';
    }
  }

  // ── Goal Overlay ──────────────────────────────────────────────────────────────
  function showGoal(scorerName, assistName) {
    const overlay = document.getElementById('goal-overlay');
    const scorer = document.getElementById('goal-scorer-text');
    const assist = document.getElementById('goal-assist-text');
    if (!overlay) return;
    overlay.classList.remove('hidden');
    if (scorer) scorer.textContent = scorerName ? `⚽ ${sanitize(scorerName)}` : '';
    if (assist) assist.textContent = assistName ? `🅰️ ASSIST: ${sanitize(assistName)}` : '';
    setTimeout(() => overlay.classList.add('hidden'), 3000);
  }

  // ── Halftime / Fulltime ────────────────────────────────────────────────────────
  function showHalftime(homeScore, awayScore, stats) {
    const overlay = document.getElementById('halftime-overlay');
    const scoreEl = document.getElementById('halftime-score');
    const statsEl = document.getElementById('halftime-stats');
    if (!overlay) return;
    if (scoreEl) scoreEl.textContent = `${homeScore} - ${awayScore}`;
    if (statsEl) statsEl.innerHTML = renderStats(stats);
    overlay.classList.remove('hidden');
    Sound.sfx.halfTime();
  }

  function showFulltime(homeTeam, awayTeam, homeScore, awayScore, stats) {
    const overlay = document.getElementById('fulltime-overlay');
    if (!overlay) return;

    const resultTitle = document.getElementById('fulltime-result-title');
    const scoreEl = document.getElementById('fulltime-score');
    const statsEl = document.getElementById('fulltime-stats');
    const mvpEl = document.getElementById('match-mvp');

    const result = homeScore > awayScore ? `${sanitize(homeTeam.name)} WIN!` :
      awayScore > homeScore ? `${sanitize(awayTeam.name)} WIN!` : 'IT\'S A DRAW!';

    if (resultTitle) resultTitle.textContent = result;
    if (scoreEl) scoreEl.textContent = `${homeScore} - ${awayScore}`;
    if (statsEl) statsEl.innerHTML = renderStats(stats);
    if (mvpEl && stats && stats.mvp) mvpEl.textContent = `⭐ MVP: ${sanitize(stats.mvp)}`;

    overlay.classList.remove('hidden');
    Sound.sfx.fullTime();

    if (homeScore !== awayScore) {
      setTimeout(() => Sound.sfx.victory(), 1000);
    }

    updateLeaderboardEntry(homeTeam, awayTeam, homeScore, awayScore, stats);

    if (homeScore > awayScore || awayScore > homeScore) unlockAchievement('first_win');
    if (homeScore === 0 || awayScore === 0) unlockAchievement('clean_sheet');
    if (stats && (stats.homeGoals >= 3 || stats.awayGoals >= 3)) unlockAchievement('hat_trick');
  }

  function updateLeaderboardEntry(ht, at, hs, as_) {
    const existing = leaderboardData.wins.find(e => e.name === ht.name);
    if (existing && hs > as_) existing.value++;
    leaderboardData.wins.sort((a, b) => b.value - a.value);
  }

  function renderStats(stats) {
    if (!stats) return '';
    return `
      <div class="stat-row"><span>POSSESSION</span><span>${stats.homePoss || 50}% — ${stats.awayPoss || 50}%</span></div>
      <div class="stat-row"><span>SHOTS</span><span>${stats.homeShots || 0} — ${stats.awayShots || 0}</span></div>
      <div class="stat-row"><span>SHOTS ON TARGET</span><span>${stats.homeShotsOT || 0} — ${stats.awayShotsOT || 0}</span></div>
      <div class="stat-row"><span>PASSES</span><span>${stats.homePasses || 0} — ${stats.awayPasses || 0}</span></div>
      <div class="stat-row"><span>FOULS</span><span>${stats.homeFouls || 0} — ${stats.awayFouls || 0}</span></div>
      <div class="stat-row"><span>CORNERS</span><span>${stats.homeCorners || 0} — ${stats.awayCorners || 0}</span></div>
    `;
  }

  // ── Card Display ──────────────────────────────────────────────────────────────
  function showCard(playerName, cardType) {
    const display = document.getElementById('card-display');
    const visual = document.getElementById('card-visual');
    const nameEl = document.getElementById('card-player-name');
    if (!display) return;
    if (visual) visual.style.background = cardType === 'red' ? '#ef4444' : '#eab308';
    if (nameEl) nameEl.textContent = sanitize(playerName);
    display.classList.remove('hidden');
    display.setAttribute('aria-label', `${cardType === 'red' ? 'Red' : 'Yellow'} card shown to ${playerName}`);
    setTimeout(() => display.classList.add('hidden'), 2500);
    if (cardType === 'red') Sound.sfx.redCard();
    else Sound.sfx.yellowCard();
  }

  // ── Pause menu stats ──────────────────────────────────────────────────────────
  function updatePauseStats(stats) {
    const poss = document.getElementById('pause-possession');
    const shots = document.getElementById('pause-shots');
    const passes = document.getElementById('pause-passes');
    if (poss) poss.textContent = `${stats.homePoss || 50}% / ${stats.awayPoss || 50}%`;
    if (shots) shots.textContent = `${stats.homeShots || 0} / ${stats.awayShots || 0}`;
    if (passes) passes.textContent = `${stats.homePasses || 0} / ${stats.awayPasses || 0}`;
  }

  // ── Flash Message ─────────────────────────────────────────────────────────────
  function flashMessage(msg) {
    const existing = document.getElementById('flash-msg');
    if (existing) existing.remove();
    const div = document.createElement('div');
    div.id = 'flash-msg';
    div.setAttribute('role', 'alert');
    div.setAttribute('aria-live', 'polite');
    div.style.cssText = `
      position:fixed;top:88px;left:50%;transform:translateX(-50%);
      background:var(--bg-card);border:2px solid var(--secondary);
      color:var(--secondary);font-family:var(--font-pixel);font-size:9px;
      padding:12px 24px;z-index:9800;
      animation:toastSlideIn 0.3s ease-out;
      max-width:90vw;text-align:center;word-break:break-word;
      box-shadow:0 4px 20px rgba(255,107,0,0.3);
    `;
    div.textContent = msg;
    document.body.appendChild(div);
    setTimeout(() => { if (div.parentNode) div.remove(); }, 3000);
  }

  // ── Public API ────────────────────────────────────────────────────────────────
  return {
    init,
    navigateTo,
    openTeamSelect,
    returnToMenu,
    openSettings,
    openModal,
    closeModal,
    updateHUD,
    setHUDTeams,
    setCommentary,
    showGoal,
    showHalftime,
    showFulltime,
    showCard,
    updatePauseStats,
    flashMessage,
    unlockAchievement,
    formatTime,
    sanitize,
    getSettings: () => settings,
    updateCareerDisplay,
    renderBracket,
    get selectedHomeTeam() { return selectedHomeTeam; },
    get selectedAwayTeam() { return selectedAwayTeam; },
    get currentGameMode() { return currentGameMode; },
    get cookieConsent() { return cookieConsent; }
  };

})();

// Auto-initialize when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
  UI.init();
});