﻿:root {
  /* Color Palette */
  --primary: #0071e3; /* Apple's signature blue */
  --primary-light: #47a9ff;
  --primary-dark: #0058b0;
  --secondary: #fa5252; /* Vibrant red for attention */
  --accent: #9866ff; /* Light purple for accent */
  --success: #30d158; /* Apple's green */
  --warning: #ff9f0a; /* Apple's orange */
  --error: #ff453a; /* Apple's red */
  /* Background and Surface */
  --background: #f5f5f7; /* Apple's light gray background */
  --surface: #ffffff; /* Clean white for surfaces */
  --surface-secondary: #f8f8fa; /* Subtle off-white for secondary surfaces */
  /* Text Colors */
  --text-primary: #1d1d1f; /* Almost black for primary text */
  --text-secondary: #6e6e73; /* Medium gray for secondary text */
  --text-tertiary: #86868b; /* Light gray for tertiary text */
  /* Feedback Colors */
  --feedback-correct-bg: #e6f4ea; /* Light green */
  --feedback-correct-text: #0a3d1d; /* Dark green */
  --feedback-incorrect-bg: #fce8e6; /* Light red */
  --feedback-incorrect-text: #5f1c15; /* Dark red */
  /* Borders and Shadows */
  --border-radius-sm: 8px;
  --border-radius-md: 12px;
  --border-radius-lg: 18px;
  --border-radius-xl: 22px;
  --shadow-sm: 0 2px 6px rgba(0, 0, 0, 0.05);
  --shadow-md: 0 4px 12px rgba(0, 0, 0, 0.08);
  --shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.12);
  /* Transitions */
  --transition-fast: 200ms cubic-bezier(0.25, 0.46, 0.45, 0.94);
  --transition-normal: 300ms cubic-bezier(0.25, 0.46, 0.45, 0.94);
  /* Typography */
  --font-primary: -apple-system, BlinkMacSystemFont, 'SF Pro Text', 'SF Pro Display', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  /* Spacing */
  --spacing-xs: 4px;
  --spacing-sm: 8px;
  --spacing-md: 16px;
  --spacing-lg: 24px;
  --spacing-xl: 32px;
  --spacing-xxl: 48px;
}
/* Base styles and resets - Apple style */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: var(--font-primary);
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
html {
    font-size: 16px;
    scroll-behavior: smooth;
}
body {
    font-family: var(--font-primary);
    background-color: var(--background);
    color: var(--text-primary);
    line-height: 1.6;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    height: 100vh;
    width: 100%;
    padding: 0;
    margin: 0;
    overscroll-behavior: none;
    touch-action: manipulation;
    letter-spacing: -0.01em;
    /* --- MODIFIED FOR BACKGROUND IMAGES & CENTERING --- */
    background-size: cover;
    background-position: center center;
    background-repeat: no-repeat;
    transition: background-image 0.8s ease-in-out, background-color 0.5s ease;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
}
.container {
    /* --- MODIFIED: This now acts as the main viewport for the centered app pane --- */
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 1rem;
    position: relative; /* For overlay effects */
}
/* NEW: Cracked screen effect for incorrect answers */
.container.cracked::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: radial-gradient(circle at 50% 50%, transparent, rgba(0,0,0,0.1) 70%),
                linear-gradient(105deg, transparent 49.5%, red 49.5%, red 50.5%, transparent 50.5%),
                linear-gradient(175deg, transparent 49.5%, red 49.5%, red 50.5%, transparent 50.5%);
    opacity: 0;
    animation: crackle 0.4s ease-out forwards;
    pointer-events: none;
    z-index: 10000;
}
@keyframes crackle {
    0% { opacity: 0; transform: scale(0.8); }
    50% { opacity: 0.3; }
    100% { opacity: 0; transform: scale(1.2); }
}
h1, h2, h3, h4, h5, h6 {
    font-weight: 600;
    line-height: 1.2;
    margin-bottom: var(--spacing-md);
    color: var(--text-primary);
}
h1 {
    font-size: 2.8rem;
    font-weight: 600;
    letter-spacing: -0.025em;
    line-height: 1.1;
}
h2 {
    font-size: 2rem;
    font-weight: 600;
    letter-spacing: -0.02em;
    line-height: 1.2;
    margin-top: var(--spacing-xxl);
}
h3 {
    font-size: 1.5rem;
}
p {
    margin-bottom: var(--spacing-md);
    color: var(--text-secondary);
    font-size: 1.0625rem;
    line-height: 1.47059;
}
strong {
    font-weight: 600;
    color: var(--text-primary);
}
a {
    color: var(--primary);
    text-decoration: none;
    transition: color var(--transition-fast);
}
a:hover {
    color: var(--primary-dark);
    text-decoration: underline;
}
.btn {
    display: inline-block;
    background-color: var(--primary);
    color: white;
    border: none;
    border-radius: var(--border-radius-md);
    padding: var(--spacing-md) var(--spacing-lg);
    font-size: 17px;
    font-weight: 500;
    cursor: pointer;
    box-shadow: var(--shadow-sm);
    transition: all var(--transition-fast);
    text-decoration: none;
    text-align: center;
    -webkit-tap-highlight-color: transparent;
    letter-spacing: -0.01em;
    width: 100%;
    margin: var(--spacing-sm) 0;
}
.btn:hover {
    background-color: var(--primary-light);
    text-decoration: none;
    transform: translateY(-2px);
    box-shadow: var(--shadow-md);
}
.btn:active {
    transform: scale(0.98) translateY(0);
    box-shadow: 0 0 0 3px rgba(0, 125, 250, 0.15);
}
.btn-secondary {
    background-color: var(--surface);
    color: var(--primary);
    border: 1px solid rgba(0, 0, 0, 0.1);
}
.btn-secondary:hover {
    background-color: var(--surface-secondary);
}
.btn-icon {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: var(--spacing-sm);
  border-radius: 50%;
  color: var(--text-secondary);
  -webkit-tap-highlight-color: transparent;
  transition: background-color var(--transition-fast);
}
.btn-icon:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

/* --- Dark Mode Base Styles --- */
@media (prefers-color-scheme: dark) {
    :root {
        --primary: #0a84ff;
        --primary-light: #64aaff;
        --primary-dark: #0060cc;
        --secondary: #ff375f;
        --accent: #bf5af2;
        --success: #30d158;
        --warning: #ffd60a;
        --error: #ff453a;
        --background: #000000;
        --surface: #1c1c1e;
        --surface-secondary: #2c2c2e;
        --text-primary: #ffffff;
        --text-secondary: #ebebf5;
        --text-tertiary: #ebebf599;
        --shadow-sm: 0 2px 6px rgba(255, 255, 255, 0.05);
        --shadow-md: 0 4px 12px rgba(255, 255, 255, 0.08);
        --feedback-correct-bg: #1a3d23;
        --feedback-correct-text: #c2f0d1;
        --feedback-incorrect-bg: #4d1a16;
        --feedback-incorrect-text: #f8cfc9;
    }
    .btn-secondary {
        border-color: rgba(255,255,255,0.15);
        color: var(--primary-light);
    }
    .btn-secondary:hover {
        background-color: #2c2c2e;
    }
}

/* --- Mobile Typography & Layout --- */
@media (max-width: 768px) {
    h1 { font-size: 2.2rem; }
    h2 { font-size: 1.75rem; }
    p { font-size: 1.1rem; }
}

/* --- Dynamic background for streaks --- */
body.streak-active {
  background: linear-gradient(135deg, var(--background), #eef5ff);
}
@media (prefers-color-scheme: dark) {
    body.streak-active {
        background: linear-gradient(135deg, var(--background), #0a1a33);
    }
}

/* --- REWRITTEN & ENHANCED: Glassmorphism Core --- */
#landing-screen, #game-screen, #paywall, #end-screen, #loading-screen {
  display: flex;
  flex-direction: column;
  overflow-y: auto; /* Allow scrolling on content-heavy screens */
  /* SIZING & SPACING: This makes it a centered pane instead of a full screen overlay */
  width: 100%;
  max-width: 480px; /* Optimal for mobile-first view */
  height: 95vh;
  max-height: 950px;
  padding: var(--spacing-lg);
  /* --- LIVELY GLASSMORPHISM EFFECT --- */
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0.1));
  backdrop-filter: blur(25px) saturate(180%);
  -webkit-backdrop-filter: blur(25px) saturate(180%);
  border-radius: 24px;
  border: 1px solid rgba(255, 255, 255, 0.18);
  box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.2);
  transition: transform 0.4s cubic-bezier(0.16, 1, 0.3, 1), opacity 0.4s cubic-bezier(0.16, 1, 0.3, 1);
}
/* Hide screens based on JS inline style */
#game-screen, #paywall, #end-screen, #loading-screen {
    display: none;
}

/* --- Landing Screen --- */
#landing-screen {
  justify-content: center;
  align-items: center;
  gap: var(--spacing-sm); /* Reduced gap */
  padding: var(--spacing-xl);
}
#landing-screen h1 {
  font-size: 32px;
  margin-bottom: var(--spacing-md);
  text-align: center;
  color: var(--text-primary);
}
/* START: NEW CSS FOR AUTH FORMS */
#auth-container {
    width: 100%;
}
#auth-container input[type="email"],
#auth-container input[type="password"] {
  width: 100%;
  padding: var(--spacing-md) var(--spacing-lg);
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: var(--border-radius-md);
  font-size: 17px;
  background-color: rgba(255, 255, 255, 0.5); /* Translucent input */
  margin-bottom: var(--spacing-md);
  transition: border var(--transition-fast);
  color: var(--text-primary);
}
#auth-container input::placeholder {
    color: var(--text-secondary);
}
#auth-container input:focus {
  outline: none;
  border-color: var(--primary);
  box-shadow: 0 0 0 3px rgba(0, 125, 250, 0.15);
}
.form-switcher {
    font-size: 14px;
    text-align: center;
    margin-top: var(--spacing-md);
    color: var(--text-secondary);
}
.form-switcher a {
    font-weight: 500;
}
/* END: NEW CSS FOR AUTH FORMS */

#google-signin-btn,
#microsoft-signin-btn {
  background-color: white;
  color: var(--text-primary);
  border: 1px solid rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--spacing-sm);
}
#google-signin-btn:hover,
#microsoft-signin-btn:hover {
  background-color: var(--surface-secondary);
}
#google-signin-btn::before {
  content: "G";
  background: linear-gradient(45deg, #4285F4, #34A853, #FBBC05, #EA4335);
  color: white;
  border-radius: 50%;
  height: 24px;
  width: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
}
/* START: NEW ICON FOR MICROSOFT BUTTON */
#microsoft-signin-btn::before {
  content: "";
  background-image: url('data:image/svg+xml;charset=UTF-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 12"><path fill="%23f25022" d="M0 0h5.7v5.7H0z"/><path fill="%2300a4ef" d="M0 6.3h5.7V12H0z"/><path fill="%237fba00" d="M6.3 0H12v5.7H6.3z"/><path fill="%23ffb900" d="M6.3 6.3H12V12H6.3z"/></svg>');
  background-repeat: no-repeat;
  background-position: center;
  background-size: 18px;
  height: 24px;
  width: 24px;
}
/* END: NEW ICON FOR MICROSOFT BUTTON */

#support-email {
  margin-top: var(--spacing-lg);
  font-size: 14px;
  color: var(--text-secondary);
}
.footer-nav {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: var(--spacing-md);
  margin-top: var(--spacing-lg);
}
.footer-nav a {
  font-size: 14px;
  color: var(--text-secondary);
  text-decoration: none;
  transition: color var(--transition-fast);
}
.footer-nav a:hover {
  color: var(--primary);
}

/* --- Loading Screen --- */
#loading-screen {
  justify-content: center;
  align-items: center;
}
#loading-tip {
  text-align: center;
  font-size: 17px;
  max-width: 85%;
  position: relative;
  padding-top: 100px;
  color: var(--text-secondary);
}
#loading-tip:before {
  content: "";
  position: absolute;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40px;
  height: 40px;
  border: 3px solid rgba(0, 0, 0, 0.08);
  border-top: 3px solid var(--primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}
@keyframes spin {
  0% { transform: translateX(-50%) rotate(0deg); }
  100% { transform: translateX(-50%) rotate(360deg); }
}

/* --- Game Screen --- */
#game-screen {
  justify-content: space-between;
  gap: var(--spacing-md);
}
#header {
    width: 100%;
    flex-shrink: 0;
    /* REDUCED SPACING: Add a small gap for the elements below the header bar */
    display: flex;
    flex-direction: column;
    gap: var(--spacing-sm);
}
.stats-bar {
    display: flex;
    justify-content: space-between; /* Pushes left, center, and right groups apart */
    align-items: center;
    width: 100%;
    gap: var(--spacing-sm);
    font-size: 15px; /* Slightly smaller font for compactness */
    font-weight: 600;
    color: var(--text-secondary);
    padding: 0 var(--spacing-sm); /* Add a little horizontal padding */
}
/* Remove the old secondary bar styles */
.stats-bar-secondary {
    display: none;
}
/* NEW: Group for left-side stats */
.stat-group-left {
    display: flex;
    align-items: center;
    gap: var(--spacing-md); /* Space between individual stats */
}
/* NEW: Group for right-side actions */
.game-actions {
    display: flex;
    align-items: center;
    gap: 0; /* Let padding/margin on children handle spacing */
}
/* Adjust individual stat items to be compact */
#upgrade-link, #level-indicator, #score-indicator, #lives-indicator {
    background-color: transparent;
    padding: 0;
    box-shadow: none;
    font-size: inherit;
    color: inherit;
    display: flex;
    align-items: center;
    gap: 3px; /* Small gap between emoji and number */
}
/* Specific styling for the upgrade link to make it compact */
#upgrade-link {
    font-weight: 600;
    font-size: 14px;
    color: var(--primary);
    text-decoration: none;
    padding: var(--spacing-xs) var(--spacing-sm);
    border-radius: var(--border-radius-sm);
    transition: background-color var(--transition-fast);
}
#upgrade-link:hover {
    background-color: rgba(0, 0, 0, 0.05);
    text-decoration: none;
}
#premium-indicator {
    line-height: 1;
    margin-left: 4px;
}
#lives-indicator {
    position: relative;
    overflow: hidden;
    transition: color 0.2s ease;
}
#streak-counter {
    font-size: 15px; /* Match the bar font size */
    font-weight: 700;
    color: var(--warning);
    background-color: transparent;
    padding: 0;
    box-shadow: none;
    opacity: 0;
    transform: scale(0.5);
    transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
    flex-shrink: 0; /* Prevent it from being squished */
}
#streak-counter.visible {
    opacity: 1;
    transform: scale(1);
    animation: glow 1.5s ease-in-out infinite alternate;
}
@keyframes glow {
  from { text-shadow: 0 0 4px rgba(255, 159, 10, 0.5); }
  to { text-shadow: 0 0 16px rgba(255, 159, 10, 0.9); }
}
#level-title {
    text-align: center;
    font-size: 18px;
    font-weight: 600;
    color: var(--text-primary);
    /* REDUCED SPACING: Removed top margin, reduced bottom margin */
    margin: 0 0 var(--spacing-sm) 0;
    animation: fadeIn 0.5s ease;
}
#character-question-area {
    flex-grow: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    width: 100%;
    margin: var(--spacing-md) 0;
}
#funny-character {
  display: flex;
  align-items: flex-start;
  gap: var(--spacing-md);
  margin-bottom: var(--spacing-lg);
  justify-content: center;
  text-align: center;
}
.character-img {
  font-size: 30px;
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  box-shadow: var(--shadow-sm);
  transition: transform 0.3s ease;
  flex-shrink: 0;
  position: relative; /* For aura positioning */
}
/* NEW: Character aura for streaks */
#character-aura {
    position: absolute;
    top: -10px;
    left: -10px;
    right: -10px;
    bottom: -10px;
    border-radius: 50%;
    opacity: 0;
    transition: opacity 0.5s ease;
}
#character-aura.on-fire {
    opacity: 1;
    animation: fire-aura 2s ease-in-out infinite alternate;
}
@keyframes fire-aura {
    0% { box-shadow: 0 0 10px #ff9f0a, 0 0 20px #ff9f0a, 0 0 30px #ff453a, inset 0 0 5px #ff9f0a; transform: scale(1); }
    100% { box-shadow: 0 0 15px #ff9f0a, 0 0 25px #ff9f0a, 0 0 40px #ff453a, inset 0 0 8px #ff9f0a; transform: scale(1.05); }
}
.character-img.bounce-big {
    animation: bounce-big 0.6s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}
@keyframes bounce-big {
    0%, 100% { transform: scale(1); }
    50% { transform: scale(1.25); }
}
.character-img.shake {
    animation: shake 0.5s ease-in-out;
}
@keyframes shake {
    0%, 100% { transform: translateX(0); }
    20% { transform: translateX(-8px) rotate(-5deg); }
    40% { transform: translateX(8px) rotate(5deg); }
    60% { transform: translateX(-8px) rotate(-5deg); }
    80% { transform: translateX(8px) rotate(5deg); }
}
/* NEW: Lightbulb moment animation */
.character-img.lightbulb::after {
    content: '💡';
    position: absolute;
    top: -20px;
    right: -10px;
    font-size: 24px;
    opacity: 0;
    animation: lightbulb-pop 1s ease-out forwards;
}
@keyframes lightbulb-pop {
    0% { transform: translateY(10px) scale(0.5); opacity: 0; }
    50% { transform: translateY(-5px) scale(1.2); opacity: 1; }
    100% { transform: translateY(0) scale(1); opacity: 1; }
}
#character-image {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    object-fit: cover;
    /* NEW: Sunglasses effect */
    filter: none;
    transition: filter 0.5s ease;
}
#character-image.sunglasses {
    filter: drop-shadow(0px 5px 0px rgba(29, 29, 31, 1)); /* Simulates sunglasses */
}
.character-img img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}
.character-msg {
  background-color: var(--surface);
  padding: var(--spacing-md) var(--spacing-lg);
  border-radius: var(--border-radius-md);
  border-top-left-radius: 4px;
  max-width: 80%;
  box-shadow: var(--shadow-sm);
  font-size: 15px;
  line-height: 1.4;
  position: relative;
  transition: background-color 0.3s ease, color 0.3s ease, transform 0.3s ease;
  margin: 0;
}
.character-msg.correct {
    background-color: var(--feedback-correct-bg);
    color: var(--feedback-correct-text);
    transform: scale(1.02);
}
.character-msg.incorrect {
    background-color: var(--feedback-incorrect-bg);
    color: var(--feedback-incorrect-text);
}
.character-msg:before {
  content: "";
  position: absolute;
  left: -8px;
  top: 10px;
  width: 15px;
  height: 15px;
  background: var(--surface); /* Default background */
  transform: rotate(45deg);
  border-radius: 3px;
  transition: background-color 0.3s ease;
}
.character-msg.correct:before {
    background-color: var(--feedback-correct-bg);
}
.character-msg.incorrect:before {
    background-color: var(--feedback-incorrect-bg);
}
.progress-container {
  width: 100%;
}
#progress-bar {
  height: 8px;
  background-color: rgba(0, 0, 0, 0.08);
  border-radius: 4px;
  overflow: hidden;
  position: relative;
}
#progress {
  height: 100%;
  background-color: var(--primary);
  border-radius: 4px;
  transition: width 0.8s cubic-bezier(0.16, 1, 0.3, 1);
  width: 0%;
}
#progress.progress-update {
    animation: progress-glow 1.5s ease-out;
}
@keyframes progress-glow {
  from {
    box-shadow: 0 0 4px var(--primary-light), 0 0 8px var(--primary-light);
  }
  to {
    box-shadow: 0 0 16px var(--primary-light), 0 0 24px var(--primary-light), 0 0 32px var(--primary);
  }
}
#badge-container {
  display: flex;
  gap: var(--spacing-sm);
  margin-top: var(--spacing-md);
  overflow-x: auto;
  padding-bottom: var(--spacing-xs);
  scrollbar-width: none;
}
#badge-container::-webkit-scrollbar {
  display: none;
}
#question-container {
  background-color: rgba(255, 255, 255, 0.5);
  border: 1px solid rgba(255, 255, 255, 0.2);
  padding: var(--spacing-lg);
  border-radius: var(--border-radius-lg);
  box-shadow: none;
  position: relative;
  margin: 0 auto;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  transition: transform 0.4s ease, opacity 0.4s ease;
}
#question-container.slide-out {
    opacity: 0;
    transform: translateX(-50px) scale(0.95);
}
#question-container.slide-in {
    opacity: 1;
    transform: translateX(0) scale(1);
}
#topic-display {
    font-size: 14px;
    font-weight: 600;
    color: var(--primary);
    text-align: center;
    margin-bottom: var(--spacing-sm);
    text-transform: uppercase;
    letter-spacing: 0.05em;
}
#difficulty-display {
    text-align: center;
    font-size: 16px;
    color: var(--warning);
    margin-bottom: var(--spacing-md);
}
#question-text {
  font-size: 20px;
  font-weight: 600;
  text-align: center;
  line-height: 1.3;
  margin-bottom: 0;
  letter-spacing: -0.02em;
}
#share-question {
  position: absolute;
  top: var(--spacing-md);
  right: var(--spacing-md);
  height: 40px;
  width: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--text-secondary);
  background-color: transparent;
  transition: background-color var(--transition-fast);
}
#share-question:hover {
  background-color: rgba(0, 0, 0, 0.05);
}
#answer-buttons {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: var(--spacing-md);
  margin-top: var(--spacing-lg);
  margin-bottom: var(--spacing-lg);
}
#yes-btn, #no-btn {
  min-height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  font-weight: 500;
  border-radius: var(--border-radius-md);
  transition: transform var(--transition-fast), background-color var(--transition-fast), box-shadow var(--transition-fast);
  box-shadow: var(--shadow-sm);
  animation: button-breath 2s ease-in-out infinite;
}
#yes-btn.powered-up, #no-btn.powered-up {
    background-size: 200% 200%;
    animation: button-breath 2s ease-in-out infinite, shimmer 3s linear infinite;
}
@keyframes shimmer {
    0% { background-position: 0% 50%; }
    50% { background-position: 100% 50%; }
    100% { background-position: 0% 50%; }
}
#yes-btn.powered-up {
    background-image: linear-gradient(120deg, var(--success) 0%, #39e663 50%, var(--success) 100%);
}
#no-btn.powered-up {
    background-image: linear-gradient(120deg, var(--error) 0%, #ff5e54 50%, var(--error) 100%);
}
@keyframes button-breath {
    0%, 100% { transform: scale(1); }
    50% { transform: scale(1.03); }
}
#yes-btn:active, #no-btn:active {
  transform: scale(0.95);
  box-shadow: var(--shadow-sm);
}
#yes-btn {
  background-color: var(--success);
}
#yes-btn:hover {
  background-color: #26b84a;
}
#no-btn {
  background-color: var(--error);
}
#no-btn:hover {
  background-color: #e13c31;
}
.correct-answer-highlight {
    box-shadow: 0 0 0 4px var(--success), 0 0 20px var(--success);
    transform: scale(1.05);
}
#continue-btn {
    grid-column: 1 / -1; /* Make the button span both columns */
    background-color: var(--primary);
    animation: none; /* Disable breathing animation for this button */
}
/* NEW: Viral Share Buttons */
#viral-share-container {
    margin-top: var(--spacing-md);
    display: flex;
    flex-direction: column;
    gap: var(--spacing-sm);
}
.btn-viral {
    background: linear-gradient(135deg, var(--accent), #7a42e6);
    font-weight: 600;
    animation: fadeIn 0.5s ease;
}
.btn-viral:hover {
    transform: translateY(-2px) scale(1.02);
    box-shadow: var(--shadow-lg);
}
.btn-stumped {
    background: linear-gradient(135deg, var(--warning), #e68a00);
}

/* --- Paywall Screen --- */
#paywall {
  justify-content: center;
  align-items: center;
  padding: var(--spacing-xl);
  gap: var(--spacing-lg);
}
#paywall h2 {
  font-size: 28px;
  margin-bottom: var(--spacing-md);
  color: var(--text-primary);
  text-align: center;
  letter-spacing: -0.02em;
}
#paywall ul {
  list-style: none;
  margin-bottom: var(--spacing-lg);
  width: 100%;
}
#paywall li {
  padding: var(--spacing-md) 0;
  font-size: 17px;
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}
#paywall li:before {
  content: "✓";
  color: var(--success);
  font-weight: bold;
  font-size: 18px;
}

/* --- ================================== --- */
/* --- REWARD ROUND / END SCREEN STYLES --- */
/* --- ================================== --- */
#end-screen {
  padding: var(--spacing-xl);
  overflow-y: auto;
  text-align: center;
  position: relative; /* Needed for pep-talk overlay */
}
#end-screen-title {
    font-size: 2.5rem;
    color: var(--text-primary);
    margin-bottom: var(--spacing-xs);
    letter-spacing: -0.02em;
    opacity: 0;
    transform: scale(1.5);
    transition: opacity 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275), transform 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}
#end-screen-title.visible {
    opacity: 1;
    transform: scale(1);
}
#end-screen-dynamic-title {
    font-size: 1.2rem;
    font-weight: 500;
    color: var(--text-secondary);
    margin-bottom: var(--spacing-lg);
}

.end-screen-element {
    opacity: 0;
    transform: translateY(20px);
    transition: opacity 0.6s ease-out, transform 0.6s ease-out, filter 0.4s ease;
}
#end-screen.pep-talk-active .end-screen-element {
    filter: blur(8px);
    opacity: 0.5;
}

#level-summary-container, #topic-performance-container, #achievements-container {
    background-color: rgba(255, 255, 255, 0.4);
    border: 1px solid rgba(255, 255, 255, 0.2);
    padding: var(--spacing-lg);
    border-radius: var(--border-radius-lg);
    margin-bottom: var(--spacing-lg);
    box-shadow: none;
    text-align: left;
}
#topic-performance-container h3, #achievements-container h3, #level-summary-container h3 {
    text-align: center;
    font-size: 1.1rem;
    margin-bottom: var(--spacing-lg);
}

/* Performance Summary Card Redesign */
#score-container {
    text-align: center;
    margin-bottom: var(--spacing-lg);
}
#final-score-value {
    font-size: 4rem;
    font-weight: 700;
    line-height: 1;
    color: var(--primary);
    display: block;
}
#score-buildup-list {
    list-style: none;
    padding: 0;
    font-size: 0.9rem;
    color: var(--text-secondary);
    margin-top: var(--spacing-sm);
}
#score-buildup-list li {
    opacity: 0;
    transform: translateY(10px);
    animation: fadeInUp 0.5s ease-out forwards;
}
#score-buildup-list li:nth-child(2) { animation-delay: 0.2s; }
#score-buildup-list li:nth-child(3) { animation-delay: 0.4s; }

@keyframes fadeInUp {
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

#gauge-and-difficulty-container {
    display: flex;
    justify-content: space-around;
    align-items: center;
    gap: var(--spacing-md);
    margin-top: var(--spacing-lg);
}
#accuracy-gauge-container, #difficulty-meter-container {
    text-align: center;
}
#accuracy-gauge-container p, #difficulty-meter-container p {
    font-size: 0.8rem;
    color: var(--text-secondary);
    margin: var(--spacing-sm) 0 0 0;
}
#accuracy-gauge {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    display: grid;
    place-items: center;
    background: conic-gradient(var(--gauge-color, var(--success)) calc(var(--value, 0) * 1%), #e0e0e0 0);
    transition: --value 1.5s ease-in-out, background-color 1.5s ease;
}
#accuracy-gauge::before {
    content: "";
    position: absolute;
    width: 65px;
    height: 65px;
    background: var(--surface);
    border-radius: 50%;
}
#accuracy-gauge-value {
    position: relative;
    font-size: 1.2rem;
    font-weight: 600;
}
#difficulty-meter {
    font-size: 1.8rem;
    color: var(--warning);
}

/* Topic Performance Chart */
#topic-performance-chart {
  height: 250px;
  width: 100%;
}
#performanceChart {
  width: 100% !important;
  height: 100% !important;
}

/* Achievements Card Redesign: "THE TROPHY WALL" */
#achievements-container {
    perspective: 1000px;
}
#newly-unlocked-achievement .achievement-medal {
    animation: fly-in-flip 1s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
}
@keyframes fly-in-flip {
    0% { transform: translateY(50px) rotateX(-90deg) scale(0.8); opacity: 0; }
    100% { transform: translateY(0) rotateX(0deg) scale(1); opacity: 1; }
}

#trophy-wall {
    display: flex;
    justify-content: center;
    gap: var(--spacing-md);
    flex-wrap: wrap;
}
.achievement-medal {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: var(--spacing-sm);
    text-align: center;
    position: relative;
}
.achievement-medal-icon {
    font-size: 4rem;
    line-height: 1;
    filter: drop-shadow(0 4px 6px rgba(0,0,0,0.2));
    position: relative;
    z-index: 1;
}
/* Medal Gradients for that metallic feel */
.medal-bronze { text-shadow: 0 2px 2px rgba(0,0,0,0.3); color: #CD7F32; }
.medal-silver { text-shadow: 0 2px 2px rgba(0,0,0,0.3); color: #C0C0C0; }
.medal-gold { text-shadow: 0 2px 2px rgba(0,0,0,0.3); color: #FFD700; }

.achievement-medal-text h4 {
    font-size: 0.9rem;
    margin: 0;
    color: var(--text-primary);
}
.achievement-medal-text p {
    font-size: 0.8rem;
    margin: 0;
    color: var(--text-secondary);
}

/* States */
.achievement-medal.not-yet-unlocked .achievement-medal-icon {
    filter: grayscale(1) drop-shadow(0 2px 3px rgba(0,0,0,0.1));
    opacity: 0.5;
}
.achievement-medal.not-yet-unlocked .achievement-medal-text {
    opacity: 0.7;
}
.achievement-medal.newly-unlocked::after {
    content: 'NEW!';
    position: absolute;
    top: -5px;
    right: -10px;
    background: var(--accent);
    color: white;
    font-size: 0.7rem;
    font-weight: bold;
    padding: 2px 8px;
    border-radius: 10px;
    transform: rotate(15deg);
    animation: pop-in 0.5s 1s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards;
    opacity: 0;
}
@keyframes pop-in {
    0% { transform: scale(0.5) rotate(15deg); opacity: 0; }
    100% { transform: scale(1) rotate(15deg); opacity: 1; }
}

/* Button Hierarchy */
.btn-container {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-sm);
    margin-top: var(--spacing-md);
}
.btn.btn-primary-action {
    background: linear-gradient(135deg, var(--primary), var(--primary-dark));
    color: white;
    font-size: 1.1rem;
    padding: 18px var(--spacing-lg);
    animation: pulse 2s infinite;
}
.btn.btn-primary-action:hover {
    animation-play-state: paused;
    transform: translateY(-2px) scale(1.02);
}
@keyframes pulse {
    0% { box-shadow: 0 0 0 0 rgba(0, 113, 227, 0.7); }
    70% { box-shadow: 0 0 0 10px rgba(0, 113, 227, 0); }
    100% { box-shadow: 0 0 0 0 rgba(0, 113, 227, 0); }
}
.btn.btn-secondary-action {
    background: var(--primary);
}
.btn.btn-social-action {
    background: #1DA1F2; /* Twitter Blue */
}
.btn.btn-utility-action {
    background-color: transparent;
    color: var(--text-secondary);
    border: 1px solid var(--text-tertiary);
}
.btn.btn-utility-action:hover {
    background: rgba(128, 128, 128, 0.1);
}

/* --- NEW: PEP TALK STYLES --- */
#pep-talk-container {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    backdrop-filter: blur(5px);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 100;
    opacity: 0;
    animation: fadeIn 0.5s ease-out forwards;
}
.pep-talk-content {
    background-color: var(--surface);
    padding: var(--spacing-xl);
    border-radius: var(--border-radius-lg);
    width: 90%;
    max-width: 420px;
    box-shadow: var(--shadow-lg);
    text-align: center;
    transform: scale(0.8);
    opacity: 0;
    animation: zoomIn 0.5s 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards;
}
@keyframes zoomIn {
    to { transform: scale(1); opacity: 1; }
}
#pep-talk-character-img {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    box-shadow: 0 4px 15px rgba(0,0,0,0.2);
    margin: -64px auto var(--spacing-md) auto;
    display: block;
    border: 4px solid var(--surface);
}
#pep-talk-opener {
    font-size: 1.8rem;
    font-weight: 700;
    color: var(--text-primary);
    margin-bottom: var(--spacing-sm);
}
#pep-talk-body {
    font-size: 1.1rem;
    color: var(--text-secondary);
    line-height: 1.5;
    margin-bottom: var(--spacing-lg);
}
#pep-talk-body strong.strong-topic {
    color: var(--success);
}
#pep-talk-body strong.weak-topic {
    color: var(--warning);
}
#pep-talk-cta {
    font-size: 1rem;
    font-weight: 500;
    color: var(--text-tertiary);
    margin-bottom: var(--spacing-lg);
}
#pep-talk-actions {
    display: flex;
    flex-direction: column;
    gap: var(--spacing-sm);
}
.btn-practice-drill {
    background: linear-gradient(135deg, var(--warning), #e68a00);
    animation: pulse 2s infinite;
}
/* --- END PEP TALK STYLES --- */

/* --- HISTORY SECTION / TUTOR PLAN --- */
#history-section {
    background-color: transparent;
    border: none;
    padding: 0;
    box-shadow: none;
    display: flex;
    flex-direction: column;
    gap: var(--spacing-lg);
}
.history-section-title {
    font-size: 1.2rem;
    font-weight: 600;
    text-align: center;
    margin-bottom: var(--spacing-sm);
}
#tutor-priority-card {
    background-color: var(--surface);
    border-radius: var(--border-radius-lg);
    padding: var(--spacing-lg);
    border: 1px solid rgba(0,0,0,0.05);
    box-shadow: var(--shadow-md);
    text-align: center;
}
#tutor-priority-card h4 {
    font-size: 1rem;
    color: var(--text-secondary);
    margin: 0;
    text-transform: uppercase;
    letter-spacing: 0.05em;
}
#tutor-priority-card .topic-name {
    font-size: 2rem;
    font-weight: 700;
    color: var(--primary);
    margin: var(--spacing-xs) 0;
}
#tutor-priority-card .topic-accuracy {
    font-size: 1.2rem;
    font-weight: 600;
    color: var(--warning);
    margin-bottom: var(--spacing-md);
}
#tutor-priority-card .tutor-message {
    font-size: 1rem;
    color: var(--text-secondary);
    margin-bottom: var(--spacing-lg);
}
#skill-building-list .skill-item {
    display: flex;
    align-items: center;
    gap: var(--spacing-md);
    padding: var(--spacing-sm) 0;
    border-bottom: 1px solid rgba(0,0,0,0.05);
}
#skill-building-list .skill-item:last-child {
    border-bottom: none;
}
#skill-building-list .skill-info {
    flex-grow: 1;
}
#skill-building-list .skill-info h5 {
    font-size: 1rem;
    font-weight: 500;
    margin: 0;
}
.accuracy-bar-container {
    width: 100%;
    height: 6px;
    background-color: rgba(0,0,0,0.08);
    border-radius: 3px;
    overflow: hidden;
    margin-top: var(--spacing-xs);
}
.accuracy-bar {
    height: 100%;
    width: 0%; /* Set by JS */
    border-radius: 3px;
    transition: width 1s ease-out;
}
#journey-stats-container {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: var(--spacing-md);
    text-align: center;
}
.stat-block {
    background-color: var(--surface);
    padding: var(--spacing-md);
    border-radius: var(--border-radius-md);
}
.stat-block .stat-value {
    font-size: 1.8rem;
    font-weight: 600;
    display: block;
    line-height: 1.1;
}
.stat-block .stat-label {
    font-size: 0.8rem;
    color: var(--text-secondary);
}
#history-chart-container {
  max-width: 100%;
  margin: 0 auto;
  position: relative;
  height: 250px;
}

/* --- General Animations & Effects --- */
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}
@keyframes slideIn {
  from { transform: translateY(10px); opacity: 0; }
  to { transform: translateY(0); opacity: 1; }
}
.fade-in {
  animation: fadeIn 0.5s cubic-bezier(0.16, 1, 0.3, 1);
}
.slide-in {
  animation: slideIn 0.5s cubic-bezier(0.16, 1, 0.3, 1);
}

/* --- Responsive Adjustments for Game Screens --- */
@media (max-height: 667px) {
  #question-text { font-size: 20px; }
  .character-img { width: 42px; height: 42px; font-size: 24px; }
  #header { padding: var(--spacing-xs) 0; }
  #question-container { padding: var(--spacing-lg); }
}
@media (min-height: 800px) {
  #question-text { font-size: 24px; }
  .btn { padding: var(--spacing-md) var(--spacing-lg); font-size: 18px; }
  #question-container { padding: var(--spacing-xxl); }
  .character-img { width: 56px; height: 56px; font-size: 32px; }
}

/* --- Dark Mode Specific Game Styles --- */
@media (prefers-color-scheme: dark) {
  #auth-container input[type="email"],
  #auth-container input[type="password"] {
    background-color: rgba(28, 28, 30, 0.5);
    border-color: rgba(255, 255, 255, 0.1);
    color: var(--text-primary);
  }
  #progress-bar {
    background-color: rgba(255, 255, 255, 0.1);
  }
  #paywall li {
    border-bottom-color: rgba(255, 255, 255, 0.1);
  }
  #google-signin-btn, #microsoft-signin-btn {
    background-color: var(--surface);
    color: var(--text-primary);
    border-color: rgba(255, 255, 255, 0.1);
  }
  #loading-tip:before {
    border-color: rgba(255, 255, 255, 0.1);
    border-top-color: var(--primary);
  }
  #exit-btn {
    background-color: var(--surface);
    color: var(--primary);
    border: 1px solid rgba(0, 0, 0, 0.1);
  }
  #exit-btn:hover {
    background-color: var(--surface-secondary);
  }
  #share-question:hover {
    background-color: rgba(255, 255, 255, 0.05);
  }
  #landing-screen, #game-screen, #paywall, #end-screen, #loading-screen {
    background: linear-gradient(135deg, rgba(40, 40, 40, 0.25), rgba(40, 40, 40, 0.15));
    border-color: rgba(255, 255, 255, 0.1);
    box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.37);
  }
  #question-container {
    background-color: rgba(44, 44, 46, 0.5);
    border-color: rgba(255, 255, 255, 0.1);
  }
  #level-summary-container, #topic-performance-container, #achievements-container, #review-section {
    background-color: rgba(44, 44, 46, 0.4);
    border-color: rgba(255, 255, 255, 0.1);
  }
  .settings-item {
    border-bottom-color: rgba(255, 255, 255, 0.1);
  }
  #close-settings {
    border-color: rgba(255, 255, 255, 0.1);
  }
  #accuracy-gauge {
    background: conic-gradient(var(--gauge-color, var(--success)) calc(var(--value, 0) * 1%), #2c2c2e 0);
  }
  .medal-bronze { color: #D29358; }
  .medal-silver { color: #D1D1D1; }
  .medal-gold { color: #F7E57A; }
  .pep-talk-content {
      background-color: var(--surface-secondary);
  }
  #pep-talk-character-img {
      border-color: var(--surface-secondary);
  }
  #tutor-priority-card, .stat-block {
      border-color: rgba(255,255,255,0.1);
  }
  #skill-building-list .skill-item {
      border-bottom-color: rgba(255,255,255,0.1);
  }
}

/* --- Settings Panel --- */
#settings-panel {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  animation: fadeIn 0.3s ease;
}
.settings-content {
  background-color: var(--surface);
  padding: var(--spacing-lg);
  border-radius: var(--border-radius-lg);
  width: 90%;
  max-width: 400px;
  box-shadow: var(--shadow-lg);
}
.settings-content h3 {
  margin-bottom: var(--spacing-lg);
  text-align: center;
  color: var(--text-primary);
}
.settings-item {
  display: flex;
  justify-content: space-between;
  padding: var(--spacing-md) 0;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}
#manage-subscription {
  margin-top: var(--spacing-lg);
  background: linear-gradient(135deg, var(--primary), var(--primary-dark));
}
#close-settings {
  margin-top: var(--spacing-sm);
  background-color: var(--surface);
  color: var(--text-primary);
  border: 1px solid rgba(0, 0, 0, 0.1);
}

/* --- Miscellaneous UI Elements --- */
.screenshot-feedback {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  background-color: #4CAF50;
  color: white;
  padding: 10px 20px;
  border-radius: 5px;
  animation: fadeInOut 3s ease-in-out;
  z-index: 1000;
}
@keyframes fadeInOut {
  0% { opacity: 0; } 10% { opacity: 1; } 90% { opacity: 1; } 100% { opacity: 0; }
}
.feedback-image {
  width: 24px;
  height: 24px;
  vertical-align: middle;
  margin-left: 5px;
}
.feedback-image, #funny-character img {
  border: none !important;
  outline: none !important;
  box-shadow: none !important;
}

/* --- Fullscreen on small devices --- */
@media (max-width: 600px) {
    .container {
        padding: 0; /* No padding on container for small screens */
    }
    #landing-screen, #game-screen, #paywall, #end-screen, #loading-screen {
        width: 100%;
        height: 100%;
        border-radius: 0;
        border: none;
    }
}

/* --- Juicy Impactful Animations --- */
.screen-flash-correct {
  animation: flash-correct 0.5s ease-out;
}
.screen-flash-incorrect {
  animation: flash-incorrect 0.5s ease-out;
}
@keyframes flash-correct {
  0% { box-shadow: inset 0 0 0 0px rgba(48, 209, 88, 0); }
  50% { box-shadow: inset 0 0 0 10px rgba(48, 209, 88, 0.4); }
  100% { box-shadow: inset 0 0 0 0px rgba(48, 209, 88, 0); }
}
@keyframes flash-incorrect {
  0% { box-shadow: inset 0 0 0 0px rgba(255, 69, 58, 0); }
  50% { box-shadow: inset 0 0 0 10px rgba(255, 69, 58, 0.4); }
  100% { box-shadow: inset 0 0 0 0px rgba(255, 69, 58, 0); }
}
.score-jump {
  animation: jump-and-sparkle 0.6s ease-out;
  display: inline-block;
}
@keyframes jump-and-sparkle {
  0% { transform: scale(1); }
  25% { transform: scale(1.6) rotate(-10deg); color: var(--success); }
  50% { transform: scale(1.6) rotate(10deg); }
  100% { transform: scale(1); }
}
.button-pop {
  animation: pop 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}
@keyframes pop {
  0% { transform: scale(1); } 50% { transform: scale(1.1); } 100% { transform: scale(1); }
}
.gain-life {
    animation: gain-life-anim 0.8s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}
@keyframes gain-life-anim {
    0% { transform: scale(1); }
    50% { transform: scale(1.3); text-shadow: 0 0 15px var(--success); }
    100% { transform: scale(1); }
}
.lose-life {
    animation: lose-life-anim 0.6s ease-in-out;
}
@keyframes lose-life-anim {
    0%, 100% { transform: translateX(0); }
    20% { transform: translateX(-5px); }
    40% { transform: translateX(5px); }
    60% { transform: translateX(-5px); }
    80% { transform: translateX(5px); }
}
#lives-indicator.flash-red {
    color: var(--error);
}
.plus-one-life {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 18px;
    font-weight: bold;
    color: var(--success);
    opacity: 1;
    animation: float-up-fade-out 1.5s ease-out forwards;
    pointer-events: none;
}
@keyframes float-up-fade-out {
    0% { transform: translate(-50%, 0); opacity: 1; }
    100% { transform: translate(-50%, -50px); opacity: 0; }
}

/* --- Confetti --- */
#confetti-container {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
    z-index: 9999;
}
.confetti-piece {
    position: absolute;
    width: 8px;
    height: 16px;
    background: #f00;
    top: 0;
    opacity: 0;
}
@keyframes fall {
    to {
        transform: translateY(100vh) rotate(360deg);
        opacity: 1;
    }
}
/* NEW: Level Transition Overlay */
#level-transition-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 10000;
    opacity: 0;
    pointer-events: none;
    transition: opacity 0.3s ease;
}
#level-transition-overlay.visible {
    opacity: 1;
    pointer-events: all;
}
#level-transition-text {
    font-size: 4rem;
    font-weight: bold;
    color: white;
    text-shadow: 0 0 20px var(--primary);
    transform: scale(0.5);
    opacity: 0;
}
#level-transition-overlay.visible #level-transition-text {
    animation: zoom-in-out 1.5s ease-in-out forwards;
}
@keyframes zoom-in-out {
    0% { transform: scale(0.5); opacity: 0; }
    50% { transform: scale(1.2); opacity: 1; }
    100% { transform: scale(1); opacity: 1; }
}
```
---
### **FILE: `app.html`**
---
```html
﻿<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <title>11 Plus Exam Practice | 11Plus Papers & Grammar School Prep</title>
    <meta name="description" content="Prepare for the 11 Plus Exam with Math Challenge Pro! Practice with 11Plus papers, improve math skills, and ace grammar school entrance tests. Free access with optional premium upgrade." />
    <meta name="keywords" content="11 plus exam, 11plus papers, grammar school, 11plus tutor, 11plus tuition, 11plus test, math game, math practice, online math game, interactive math learning, math challenge, math quiz, improve math skills, boost math scores, math test prep, educational game, learning app, math exercises, spiral learning, adaptive math practice" />
    <meta name="author" content="Spiral Learning Team" />
    <meta name="robots" content="index, follow" />
    <link rel="canonical" href="https://spirallearning.pages.dev/app" />
    <meta property="og:title" content="11 Plus Exam Practice | 11Plus Papers & Grammar School Prep" />
    <meta property="og:description" content="Prepare for the 11 Plus Exam with Math Challenge Pro! Practice with 11Plus papers, improve math skills, and ace grammar school entrance tests." />
    <meta property="og:image" content="https://spirallearning.pages.dev/images/learning-game-preview.jpg" />
    <meta property="og:type" content="website" />
    <meta property="og:url" content="https://spirallearning.pages.dev/" />
    <meta property="og:site_name" content="Spiral Learning" />
    <meta name="twitter:card" content="summary_large_image" />
    <meta name="twitter:title" content="11 Plus Exam Practice | 11Plus Papers & Grammar School Prep" />
    <meta name="twitter:description" content="Prepare for the 11 Plus Exam with Math Challenge Pro! Practice with 11Plus papers, improve math skills, and ace grammar school entrance tests." />
    <meta name="twitter:image" content="https://spirallearning.pages.dev/curriculum.png" />
    <meta name="twitter:site" content="@spirallearning" />
    <meta name="twitter:creator" content="@spirallearning" />
    <link rel="icon" href="/favicon.ico" sizes="any" />
    <link rel="icon" href="/icon.svg" type="image/svg+xml" />
    <!-- UPDATED: Change apple-touch-icon to 11plus-animated.gif -->
    <link rel="apple-touch-icon" href="/11plus-animated.gif" />
    <link rel="manifest" href="/manifest.json">
<meta name="theme-color" content="#4CAF50"/>
<!-- Add Apple-specific meta tags for iOS PWA experience -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="apple-mobile-web-app-title" content="11plus exam">
<link rel="apple-touch-icon" href="/images/icons/11plus-animated.gif">
    <meta name="msvalidate.01" content="765D58884257897FC04D1E7B7007F9EE" />
    <link rel="preload" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" as="style" />
    <link rel="preload" href="gamestyle.css" as="style" />
    <link rel="preload" href="https://cdn.jsdelivr.net/npm/chart.js" as="script" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" />
    <link rel="stylesheet" href="gamestyle.css" />
    <script type="application/ld+json">
    {
      "@context": "https://schema.org",
      "@type": ["WebApplication", "EducationalOrganization", "Game"],
      "name": "Math Challenge Pro",
      "url": "https://spirallearning.pages.dev",
      "logo": "https://spirallearning.pages.dev/11plus.png",
      "description": "Boost your math skills with Math Challenge Pro! A fun, interactive game featuring instant feedback, progress tracking, and performance analysis. Ideal for 11 Plus exam prep, grammar school entrance tests, and all skill levels.",
      "keywords": "11 plus exam, 11plus papers, grammar school, 11plus tutor, 11plus tuition, 11plus test, math game, math practice, online math game, interactive math learning, math challenge, math quiz, improve math skills, boost math scores, math test prep, educational game, learning app, math exercises, spiral learning, adaptive math practice",
      "operatingSystem": "WEB",
      "applicationCategory": "EducationalApplication, Game",
      "learningResourceType": ["Game", "Quiz", "Educational Resource", "Practice"],
      "educationalLevel": ["Primary School", "Middle School", "High School", "General"], // Example levels, adjust as needed
      "offers": {
        "@type": "Offer",
        "price": "0",
        "priceCurrency": "USD",
        "description": "Free basic access with optional premium upgrade."
      },
      "aggregateRating": {
        "@type": "AggregateRating",
        "ratingValue": "4.8", // Ensure this reflects actual user ratings if possible
        "ratingCount": "50000", // Ensure this reflects actual user count if possible
        "bestRating": "5",
        "worstRating": "1"
      },
      "creator": {
        "@type": "Organization",
        "name": "Spiral Learning",
        "url": "https://spirallearning.pages.dev" // Assuming the main page is the org URL
      },
      "provider": {
        "@type": "Organization",
        "name": "Spiral Learning"
      },
      "publisher": {
        "@type": "Organization",
        "name": "Spiral Learning"
      },
      "isAccessibleForFree": true,
      "potentialAction": {
         "@type": "PlayGameAction",
         "target": "https://spirallearning.pages.dev/"
      }
    }
    </script>
    <script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-YOUR_GOOGLE_ANALYTICS_ID"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        // Replace G-YOUR_GOOGLE_ANALYTICS_ID with your actual ID
        gtag('config', 'G-YOUR_GOOGLE_ANALYTICS_ID', {
            'anonymize_ip': true,
            'cookie_flags': 'SameSite=None;Secure'
        });
    </script>
    <script>
        (function(c,l,a,r,i,t,y){
            c[a]=c[a]||function(){(c[a].q=c[a].q||[]).push(arguments)};
            t=l.createElement(r);t.async=1;t.src="https://www.clarity.ms/tag/"+i+"?ref=bwt";
            y=l.getElementsByTagName(r)[0];y.parentNode.insertBefore(t,y);
        })(window, document, "clarity", "script", "r3bdl8w4wj"); // Ensure 'r3bdl8w4wj' is your correct Clarity ID
    </script>




<script src="https://cdn.onesignal.com/sdks/web/v16/OneSignalSDK.page.js" defer></script>
<script>
  window.OneSignalDeferred = window.OneSignalDeferred || [];
  OneSignalDeferred.push(async function(OneSignal) {
    await OneSignal.init({
      appId: "693bbedc-885e-432b-989c-ff6c47e7113e",
    });
  });
</script>


</head>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-QD5RP4BSJR"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'G-QD5RP4BSJR');
</script>
<body>
    <!-- NEW: Confetti container for celebrations -->
    <div id="confetti-container"></div>

    <!-- NEW: Level transition overlay -->
    <div id="level-transition-overlay">
        <div id="level-transition-text"></div>
    </div>

    <div class="container">
        <!-- Landing Screen -->
        <div id="landing-screen">
            <h1>SpiralLearning | Play And Ace Your Exams</h1>
            <div class="usp-banner">
                <p>Join 50,000+ students preparing for entrance exams!</p>
            </div>

            <!-- START: MODIFIED Login/Registration Section -->
            <button id="install-btn" class="btn" style="display: none;">Install App</button>

            <!-- New Sign-in and Registration Forms -->
            <div id="auth-container">
                <!-- Sign In Form (Visible by default) -->
                <div id="signin-form">
                    <input type="email" id="signin-email" placeholder="Email" required aria-label="Email Input" />
                    <input type="password" id="signin-password" placeholder="Password" required aria-label="Password Input" />
                    <button id="signin-btn" class="btn">Sign In</button>
                    <p class="form-switcher">Need an account? <a href="#" id="show-register">Register here</a></p>
                </div>

                <!-- Registration Form (Hidden by default) -->
                <div id="register-form" style="display: none;">
                    <input type="email" id="register-email" placeholder="Email" required aria-label="Email Input" />
                    <input type="password" id="register-password" placeholder="Password" required aria-label="Password Input" />
                    <button id="register-btn" class="btn">Create Account</button>
                    <p class="form-switcher">Already have an account? <a href="#" id="show-signin">Sign in</a></p>
                </div>
            </div>
            
            <p style="text-align: center; color: var(--text-secondary); margin: 1rem 0;">- or -</p>
            
            <button id="google-signin-btn" class="btn">Continue with Google</button>
            <button id="microsoft-signin-btn" class="btn">Continue with Microsoft</button>
            <!-- END: MODIFIED Login/Registration Section -->
            
            <div id="support-email" class="animate__animated animate__fadeIn animate__delay-3s">Need help? help.spirallearning@gmail.com</div>
            <nav class="footer-nav animate__animated animate__fadeIn animate__delay-3s" aria-label="Footer navigation">
                <a href="landing.html">Features</a>
                <a href="product-description.html">How It Works</a>
                <a href="tips.html">Practice Tips</a>
                <a href="content-marketing.html">11Plus Test Prep</a>
                <a href="testimonials.html">Success Stories</a>
                <a href="benchmarking.html">Why Choose Us</a>
                <a href="blog.html">Blog</a>
                <a href="https://www.instagram.com/spirallearningpro" target="_blank" rel="noopener noreferrer">Instagram</a>
                <a href="https://www.youtube.com/@spirallearning" target="_blank" rel="noopener noreferrer">YouTube</a>
            </nav>
        </div>

        <!-- Loading Screen -->
        <div id="loading-screen" style="display: none;">
            <p id="loading-tip">Did you know? Consistent math practice builds long-term memory!</p>
        </div>

        <!-- Game Screen -->
        <div id="game-screen" style="display: none;">
            <!-- REDESIGNED HEADER -->
            <div id="header">
                <div class="stats-bar">
                    <div class="stat-group-left">
                        <div id="level-indicator">📈<span id="current-level">1</span></div>
                        <div id="lives-indicator">💖<span id="lives-count">3</span></div>
                        <div id="score-indicator">🎯<span id="current-score">0</span></div>
                    </div>
                    <div id="streak-counter"></div>
                    <div class="game-actions">
                        <a id="upgrade-link" href="https://buy.stripe.com/dR67whcB42Ul1So000" target="_blank" rel="noopener noreferrer" title="Upgrade to Pro">Upgrade<span id="premium-indicator" style="display:none;">💎</span></a>
                        <button id="settings-btn" class="btn-icon" aria-label="Settings">⚙️</button>
                    </div>
                </div>
                <div class="progress-container">
                    <div id="progress-bar"><div id="progress"></div></div>
                </div>
                <div id="level-title"></div>
                <div id="badge-container"></div>
            </div>

            <!-- MERGED CHARACTER & QUESTION AREA -->
            <div id="character-question-area">
                <div id="funny-character">
                    <div class="character-img" role="img" aria-label="Character guiding math practice">
                        <!-- NEW: Container for aura/special effects -->
                        <div id="character-aura"></div>
                        <img src="11plus.png" alt="Character" id="character-image">
                    </div>
                    <div class="character-msg">Let's tackle this math problem!</div>
                </div>

                <div id="question-container">
                    <div id="topic-display"></div> <!-- MOVED HERE -->
                    <div id="difficulty-display"></div>
                    <p id="question-text">Creating Personalized Learning Path</p>
                    <button id="share-question" class="btn-icon" aria-label="Share this math question">🔗</button>
                </div>
            </div>

            <!-- ANSWER BUTTONS -->
            <div id="answer-buttons">
                <button id="yes-btn" class="btn">✅ Yes</button>
                <button id="no-btn" class="btn">❌ No</button>
            </div>
             <!-- NEW: Container for viral share buttons -->
            <div id="viral-share-container"></div>
        </div>

        <!-- Paywall Screen for Premium Content -->
        <div id="paywall" style="display: none;">
            <h2>Unlock Your Full Math Potential!</h2>
            <ul>
                <li>Unlimited 11Plus math questions and levels</li>
                <li>Personalized learning paths for grammar school prep</li>
                <li>Detailed performance analytics</li>
                <li>Ad-free math practice experience</li>
                <li>Exclusive tips for 11plus tutors and parents</li>
            </ul>
            <button id="subscribe-btn" class="btn" onclick="window.open('https://buy.stripe.com/dR67whcB42Ul1So000', '_blank')">Subscribe Now</button>
            <p>Supercharge your child's 11 Plus exam readiness with Math Challenge Pro Premium!</p>
        </div>

        <!-- End Screen: THE REWARD ROUND -->
        <div id="end-screen" style="display: none;">
            <!-- Dynamic Header -->
            <h2 id="end-screen-title" class="end-screen-element"></h2>
            <p id="end-screen-dynamic-title" class="end-screen-element"></p>

            <!-- Performance Summary -->
            <div id="level-summary-container" class="end-screen-element">
                <h3><span role="img" aria-label="briefcase">💼</span> Math Performance Summary</h3>
                <div id="score-container">
                    <span id="final-score-value">0</span>
                    <ul id="score-buildup-list"></ul>
                </div>
                <div id="gauge-and-difficulty-container">
                    <div id="accuracy-gauge-container">
                         <div id="accuracy-gauge" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
                            <div id="accuracy-gauge-value">0%</div>
                        </div>
                        <p>Session Accuracy</p>
                    </div>
                    <div id="difficulty-meter-container">
                        <div id="difficulty-meter"></div>
                        <p>Avg. Difficulty</p>
                    </div>
                </div>
            </div>

            <!-- Topic Performance Chart -->
            <div id="topic-performance-container" class="end-screen-element">
                <h3><span role="img" aria-label="chart increasing">📈</span> Performance by Topic</h3>
                <div id="topic-performance-chart">
                    <canvas id="performanceChart" aria-label="Math performance chart by topic"></canvas>
                </div>
            </div>

            <!-- Achievements Display: THE TROPHY WALL -->
            <div id="achievements-container" class="end-screen-element">
                <h3><span role="img" aria-label="trophy">🏆</span> Achievements Unlocked</h3>
                <div id="newly-unlocked-achievement"></div>
                <div id="trophy-wall"></div>
            </div>

            <!-- Action Buttons with Hierarchy -->
            <div class="btn-container end-screen-element">
                <button id="next-level-btn" class="btn btn-primary-action">🚀 Next Math Challenge</button>
                <button id="try-again-btn" class="btn btn-primary-action" style="display: none;">🔄 Try Again</button>
                <button id="review-btn" class="btn btn-secondary-action">🔍 Improve Weak Areas</button>
                <button id="share-btn" class="btn btn-social-action">📣 Challenge a Friend</button>
                <button id="screenshot-btn" class="btn btn-social-action">🎉 Brag About Progress</button>
                <button id="history-btn" class="btn btn-utility-action">📊 My Growth</button>
                <button id="exit-btn" class="btn btn-utility-action">🏠 Exit Game</button>
            </div>
            
            <!-- Hidden Sections for Review & History -->
            <div id="review-section" style="display: none;"></div>
            <!-- MODIFIED: History Section is now the Tutor Plan -->
            <div id="history-section" style="display: none;">
                <!-- Content is now dynamically generated by script.js -->
            </div>

            <!-- NEW: PEP TALK CONTAINER -->
            <div id="pep-talk-container" style="display: none;">
                <div class="pep-talk-content">
                    <img src="11plus_happy.png" alt="Character giving feedback" id="pep-talk-character-img">
                    <h3 id="pep-talk-opener"></h3>
                    <p id="pep-talk-body"></p>
                    <p id="pep-talk-cta"></p>
                    <div id="pep-talk-actions">
                        <!-- Buttons will be dynamically inserted here by script.js -->
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Audio Elements for Sound Effects and Music -->
    <audio id="level-music" preload="auto" loop></audio>
    <audio id="correct-sound" preload="auto" src="https://actions.google.com/sounds/v1/cartoon/magic_chime.ogg"></audio>
    <audio id="incorrect-sound" preload="auto" src="https://actions.google.com/sounds/v1/cartoon/falling_whistle.ogg"></audio>
    <audio id="levelup-sound" preload="auto" src="https://actions.google.com/sounds/v1/cartoon/cartoon_boing.ogg"></audio>
    <audio id="streak-sound" preload="auto" src="https://actions.google.com/sounds/v1/alarms/digital_watch_alarm_long.ogg"></audio>
    <audio id="swoosh-sound" preload="auto" src="https://actions.google.com/sounds/v1/transportation/air_swoosh_fast.ogg"></audio>
    <audio id="achievement-sound" preload="auto" src="https://actions.google.com/sounds/v1/achievements/achievement_fanfare.ogg"></audio>
    <audio id="score-tick-sound" preload="auto" src="https://actions.google.com/sounds/v1/camera/camera_timer.ogg"></audio>

    <!-- Scripts -->
    <script src="https://www.gstatic.com/firebasejs/9.17.2/firebase-app-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/9.17.2/firebase-firestore-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/9.17.2/firebase-auth-compat.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
    <script src="script.js"></script>
</body>
</html>
```
---
### **FILE: `script.js`**
---
```javascript
﻿﻿// --- PWA Installation Logic ---
let deferredPrompt;
const installBtn = document.getElementById('install-btn');

window.addEventListener('beforeinstallprompt', (e) => {
  // Prevent the mini-info bar from appearing on mobile
  e.preventDefault();
  // Stash the event so it can be triggered later.
  deferredPrompt = e;
  // Update UI to notify the user they can install the PWA
  if (installBtn) {
    installBtn.style.display = 'block';
  }
  console.log(`'beforeinstallprompt' event was fired.`);

  // IMPORTANT NOTE for user:
  // While the user requested the app to be "downloaded immediately",
  // browser security policies require that the PWA installation prompt
  // (deferredPrompt.prompt()) must be triggered by a user gesture
  // (e.g., a button click). Directly calling .prompt() on page load
  // or within this event listener without a user gesture will typically fail.
  // The current implementation, showing an install button for user action,
  // is the recommended and reliable approach.
});

if (installBtn) {
  installBtn.addEventListener('click', async () => {
    // Hide the app provided install promotion
    installBtn.style.display = 'none';
    // Show the install prompt
    if (deferredPrompt) { // Ensure deferredPrompt is available
        deferredPrompt.prompt();
        // Wait for the user to respond to the prompt
        const { outcome } = await deferredPrompt.userChoice;
        console.log(`User response to the install prompt: ${outcome}`);
        // We've used the prompt, and can't use it again, throw it away
        deferredPrompt = null;
    } else {
        console.warn("deferredPrompt was not available when install button was clicked.");
    }
  });
}

window.addEventListener('appinstalled', (evt) => {
  // Log install to analytics or clear the deferredPrompt
  console.log('INSTALL: Success');
  deferredPrompt = null;
});
// --- End of PWA Installation Logic ---

// --- Register the Service Worker in Your Main JavaScript File at the very top of your script.js ---
if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/service-worker.js')
      .then(registration => {
        console.log('ServiceWorker registration successful with scope: ', registration.scope);
      })
      .catch(err => {
        console.log('ServiceWorker registration failed: ', err);
      });
  });
}

// --- OneSignal Initialization for Immediate Notifications ---
// IMPORTANT: You must include the OneSignal SDK script in your index.html <head> or <body>
// For example:
// <script src="https://cdn.onesignal.com/sdks/web/v16/OneSignalSDK.page.js" defer></script>
// Replace "YOUR_ONESIGNAL_APP_ID" with your actual OneSignal App ID.
if (window.OneSignal) {
  OneSignal.init({
    appId: "693bbedc-885e-432b-989c-ff6c47e7113e", // <--- REPLACE THIS WITH YOUR ACTUAL ONESIGNAL APP ID
    allowLocalhostAsSecure: true, // Remove in production if not using localhost
    autoRegister: true, // Set to true to automatically prompt for notifications on page load
  }).then(() => {
    console.log("OneSignal initialized. User will be prompted for notifications immediately if not already subscribed.");
    // If you need more explicit control over when the prompt shows (e.g., after a specific user action),
    // you might set autoRegister to false and then call OneSignal.showNativePrompt() later.
    // However, for "prompt immediately on page load", autoRegister: true is usually sufficient.
  }).catch(error => {
    console.error("OneSignal initialization failed:", error);
  });
} else {
  console.warn("OneSignal SDK not detected. Ensure 'OneSignalSDK.page.js' is included in your HTML before script.js.");
}
// --- End of OneSignal Initialization ---

// --- Rest of your game code follows ---
// Initialize Firebase with real configuration
const firebaseConfig = {
  apiKey: "AIzaSyCkhniuPVR6LQXlpvIxVZ33Xbu2XA42_f4",
  authDomain: "wisecatquestions.firebaseapp.com",
  projectId: "wisecatquestions",
  storageBucket: "wisecatquestions.appspot.com",
  messagingSenderId: "84856181898",
  appId: "1:84856181898:web:59822c17fdd9ac4ad70973",
  measurementId: "G-9ND5FTC8CM"
};
const app = firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
const auth = firebase.auth();

// ----- Background Image Management -----
const backgroundImages = [
  'https://spirallearning.pages.dev/backgrounds/im1.jpg', 'https://spirallearning.pages.dev/backgrounds/im2.jpg', 'https://spirallearning.pages.dev/backgrounds/im3.jpg',
  'https://spirallearning.pages.dev/backgrounds/im4.jpg',
  'https://spirallearning.pages.dev/backgrounds/im5.jpg',
  'https://spirallearning.pages.dev/backgrounds/im6.jpg',
  'https://spirallearning.pages.dev/backgrounds/im7.jpg',
  'https://spirallearning.pages.dev/backgrounds/im8.jpg',
  'https://spirallearning.pages.dev/backgrounds/im9.jpg'
];
let lastBgIndex = -1; // To ensure the first random image isn't repeated immediately

/**
 * Sets a random background image on the body.
 */
function setRandomBackground() {
  let randomIndex;
  // Ensure the new random index is different from the last one
  do {
    randomIndex = Math.floor(Math.random() * backgroundImages.length);
  } while (backgroundImages.length > 1 && randomIndex === lastBgIndex);
  
  lastBgIndex = randomIndex;
  document.body.style.backgroundImage = `url('${backgroundImages[randomIndex]}')`;
}

/**
 * Sets the background image based on the current level, cycling through the array.
 * @param {number} currentLevel - The level number to determine the background.
 */
function setLevelBackground(currentLevel) {
  // The modulo operator (%) ensures we loop back to the start of the array
  // if the level number exceeds the number of available images.
  const newIndex = (currentLevel - 1) % backgroundImages.length;
  lastBgIndex = newIndex;
  document.body.style.backgroundImage = `url('${backgroundImages[newIndex]}')`;
}

/**
 * Removes the background image, reverting to the default CSS background color.
 */
function resetBackgroundImage() {
  document.body.style.backgroundImage = 'none';
}

// ----- Game State Variables -----
let allQuestions = []; // BUGFIX: Holds all questions from DB
let currentLevelQuestions = []; // BUGFIX: Holds the 10 questions for the current level
let currentQuestion = {}; // The currently displayed question object
let score = 0;
let level = 1;
let achievements = [];
let sessionTopicPerformance = {};
let isPremiumUser = false;
let wrongAnswers = [];
let userAnswers = [];
let weakTopics = [];
let streak = 0; // NEW: Streak counter
let maxStreak = 0; // Track max streak for scoring
let lives = 3; // NEW: Lives counter
let newlyUnlockedAchievements = [];
let isInDrillMode = false; // NEW: State for practice drill
let consecutiveWrongAnswers = 0; // NEW: For dynamic difficulty
// ----- DOM Elements -----
const landingScreen = document.getElementById('landing-screen');
const loadingScreen = document.getElementById('loading-screen');
const gameScreen = document.getElementById('game-screen');
const paywallScreen = document.getElementById('paywall');
const endScreen = document.getElementById('end-screen');
const yesBtn = document.getElementById('yes-btn');
const noBtn = document.getElementById('no-btn');
const nextLevelBtn = document.getElementById('next-level-btn');
const exitBtn = document.getElementById('exit-btn');
const subscribeBtn = document.getElementById('subscribe-btn');
const shareBtn = document.getElementById('share-btn');
const reviewBtn = document.getElementById('review-btn');
const reviewSection = document.getElementById('review-section');
const levelTitleDiv = document.getElementById('level-title');
const historyBtn = document.getElementById('history-btn');
const historySection = document.getElementById('history-section');
const settingsBtn = document.getElementById('settings-btn');
const questionContainer = document.getElementById('question-container'); // NEW
const streakCounter = document.getElementById('streak-counter'); // NEW
const characterImage = document.getElementById('character-image'); // NEW
const characterImgContainer = document.querySelector('.character-img'); // NEW
const livesIndicator = document.getElementById('lives-indicator'); // NEW
const livesCount = document.getElementById('lives-count'); // NEW
const viralShareContainer = document.getElementById('viral-share-container'); // NEW
const characterAura = document.getElementById('character-aura'); // NEW
// ----- Audio Elements -----
const correctSound = document.getElementById('correct-sound');
const incorrectSound = document.getElementById('incorrect-sound');
const levelupSound = document.getElementById('levelup-sound');
const streakSound = document.getElementById('streak-sound'); // NEW
const levelMusic = document.getElementById('level-music'); // NEW: Reference to new audio element
const swooshSound = document.getElementById('swoosh-sound'); // NEW
const achievementSound = document.getElementById('achievement-sound');
const scoreTickSound = document.getElementById('score-tick-sound');
// NEW: Array of music tracks for levels
const levelMusicTracks = [
  'music/level1_theme.mp3',
  'music/level2_theme.mp3',
  'music/level3_theme.mp3',
  'music/level4_theme.mp3',
  'music/level5_theme.mp3',
];
// ----- Event Listeners -----

// --- START: New Email/Password Authentication Code ---

// Get all the new elements from our HTML
const signinForm = document.getElementById('signin-form');
const registerForm = document.getElementById('register-form');
const showRegisterLink = document.getElementById('show-register');
const showSigninLink = document.getElementById('show-signin');

const signinBtn = document.getElementById('signin-btn');
const registerBtn = document.getElementById('register-btn');

// Event listeners to switch between the Sign In and Register forms
showRegisterLink.addEventListener('click', (e) => {
  e.preventDefault(); // Prevents the link from jumping the page
  signinForm.style.display = 'none';
  registerForm.style.display = 'block';
});

showSigninLink.addEventListener('click', (e) => {
  e.preventDefault();
  registerForm.style.display = 'none';
  signinForm.style.display = 'block';
});

// --- Function to handle NEW USER REGISTRATION ---
registerBtn.addEventListener('click', async (e) => {
  e.preventDefault();
  const email = document.getElementById('register-email').value;
  const password = document.getElementById('register-password').value;

  try {
    // This is the magic Firebase function to create a new user!
    const userCredential = await auth.createUserWithEmailAndPassword(email, password);
    const user = userCredential.user;
    
    console.log("Registration successful! User:", user);
    
    // After they register, we treat it like a login and start the game
    await handleSuccessfulLogin(user);

  } catch (error) {
    // If something goes wrong (e.g., weak password, email already used)
    alert("Registration failed: " + error.message);
    console.error("Registration error:", error);
  }
});

// --- Function to handle EXISTING USER SIGN IN ---
signinBtn.addEventListener('click', async (e) => {
    e.preventDefault();
    const email = document.getElementById('signin-email').value;
    const password = document.getElementById('signin-password').value;

    try {
        // This is the magic Firebase function to sign in a user!
        const userCredential = await auth.signInWithEmailAndPassword(email, password);
        const user = userCredential.user;

        console.log("Sign-in successful! User:", user);

        // After they sign in, we start the game
        await handleSuccessfulLogin(user);

    } catch (error) {
        // If something goes wrong (e.g., wrong password)
        alert("Sign-in failed: " + error.message);
        console.error("Sign-in error:", error);
    }
});

// --- Helper function to start the game after any successful login ---
async function handleSuccessfulLogin(user) {
    await registerUserInFirestore(user); // We re-use this function from Google Sign-in!
    document.getElementById('landing-screen').style.display = 'none';
    showLoadingScreen(async () => {
        setRandomBackground();
        await checkPremiumStatus(user.uid);
        await loadQuestions();
        document.getElementById('game-screen').style.display = 'flex';
        resetGame();
        displayQuestion();
        updateLevelTitle();
        playLevelMusic();
    });
}

// --- END: New Email/Password Authentication Code ---

yesBtn.addEventListener('click', (event) => {
  event.target.classList.add('button-pop');
  event.target.addEventListener('animationend', () => event.target.classList.remove('button-pop'), { once: true });
  checkAnswer(true);
});
noBtn.addEventListener('click', (event) => {
  event.target.classList.add('button-pop');
  event.target.addEventListener('animationend', () => event.target.classList.remove('button-pop'), { once: true });
  checkAnswer(false);
});
nextLevelBtn.addEventListener('click', async (event) => {
  addBounceEffect(event.target);
  await startNextLevel();
});
exitBtn.addEventListener('click', (event) => {
  addBounceEffect(event.target);
  exitGame();
});
subscribeBtn.addEventListener('click', (event) => {
  addBounceEffect(event.target);
  requestPaymentLink();
});
shareBtn.addEventListener('click', (event) => {
  addBounceEffect(event.target);
  shareChallenge();
});
reviewBtn.addEventListener('click', toggleReviewSection);
historyBtn.addEventListener('click', toggleHistorySection);
settingsBtn.addEventListener('click', showSettingsPanel);
document.getElementById('screenshot-btn').addEventListener('click', shareResultsAsScreenshot);
document.getElementById('share-question').addEventListener('click', shareQuestion);
document.getElementById('google-signin-btn').addEventListener('click', googleSignIn);
document.getElementById('try-again-btn').addEventListener('click', (event) => { // NEW
    addBounceEffect(event.target);
    exitGame();
});

// --- START: New Microsoft Login Code ---
const microsoftBtn = document.getElementById('microsoft-signin-btn');
microsoftBtn.addEventListener('click', signInWithMicrosoft);

function signInWithMicrosoft() {
  // 1. YOUR SPECIAL APP ID
  // !!! IMPORTANT: Replace "PASTE_YOUR_CLIENT_ID_HERE" with the ID from the Azure Portal.
  const clientId = "783e6a70-4631-4c12-9a98-3d638b140c75";

  // 2. THE RETURN ADDRESS
  const redirectUri = "https://spirallearning.pages.dev/app";

  // 3. WHAT PERMISSION WE ARE ASKING FOR
  const scope = "User.Read openid profile";

  // 4. BUILDING THE SPECIAL URL
  const authUrl = `https://login.microsoftonline.com/common/oauth2/v2.0/authorize?` +
    `client_id=${clientId}` +
    `&response_type=token` + // We will handle the token on the client side
    `&redirect_uri=${encodeURIComponent(redirectUri)}` +
    `&scope=${encodeURIComponent(scope)}` +
    `&response_mode=fragment` +
    `&state=12345` + // A simple placeholder
    `&nonce=${new Date().getTime()}`; // A unique number for security

  // 5. SEND THE USER TO MICROSOFT!
  window.location.href = authUrl;
}
// --- END: New Microsoft Login Code ---


// ----- Google Sign-In Integration -----
function googleSignIn() {
  const provider = new firebase.auth.GoogleAuthProvider();
  auth.signInWithPopup(provider)
    .then(async (result) => {
      const user = result.user;
      console.log("Google Sign-In successful. User:", user);
      // MODIFIED: Use the new helper function
      await handleSuccessfulLogin(user);
    })
    .catch((error) => {
      console.error("Error during Google Sign-In:", error);
      alert("Google Sign-In failed. Please try again.");
    });
}
// ----- Register/Update User in Firestore -----
async function registerUserInFirestore(user) {
  try {
    const userRef = db.collection('users').doc(user.uid);
    const userDoc = await userRef.get();
    const userData = {
      // Use display name if available, otherwise use email
      displayName: user.displayName || user.email,
      email: user.email,
      lastLogin: firebase.firestore.FieldValue.serverTimestamp(),
      lastPlayed: firebase.firestore.FieldValue.serverTimestamp()
    };
    if (!userDoc.exists) {
      await userRef.set({
        ...userData,
        createdAt: firebase.firestore.FieldValue.serverTimestamp(),
        isPremium: false,
        lastLevelCompleted: 0,
        subscriptionDate: null
      });
      console.log("New user registered with default values");
    } else {
      await userRef.update(userData);
      console.log("Existing user updated with login timestamps");
    }
  } catch (error) {
    console.error("Error registering/updating user in Firestore:", error);
  }
}
// ----- Update User Progress in Firestore -----
async function updateUserProgress() {
  const user = auth.currentUser;
  if (!user) return;
  try {
    await db.collection('users').doc(user.uid).update({
      lastLevelCompleted: level,
      lastPlayed: firebase.firestore.FieldValue.serverTimestamp()
    });
    console.log("User progress updated successfully");
  } catch (error) {
    console.error("Error updating user progress:", error);
  }
}
// ----- Premium User Check Function -----
async function checkPremiumStatus(userId) {
  if (!userId) {
    isPremiumUser = false;
    return;
  }
  try {
    const userDoc = await db.collection('users').doc(userId).get();
    if (userDoc.exists) {
      const userData = userDoc.data();
      isPremiumUser = userData.isPremium === true;
      console.log(`User premium status: ${isPremiumUser}`);
    } else {
      isPremiumUser = false;
    }
  } catch (error) {
    console.error("Error checking premium status:", error);
    isPremiumUser = false;
  }
}
// ----- Core Game Functions -----
function addBounceEffect(element) {
  element.classList.add('bounce');
  setTimeout(() => element.classList.remove('bounce'), 500);
}

function showLoadingScreen(callback) {
  loadingScreen.style.display = 'flex'; // BUGFIX: Use flex
  const loadingTip = document.getElementById('loading-tip');
  const tips = [
    "Did you know? Consistent practice builds long-term memory!",
    "Why was the math book sad? It had too many problems!",
    "Fun Fact: The more you learn, the more you earn (brain points)!",
    "Keep going, your brain is getting stronger with every question!",
    "Fun Fact: Every expert was once a beginner!",
    "Why did the student bring a ladder to class? To reach the high grades!"
  ];
  loadingTip.textContent = tips[Math.floor(Math.random() * tips.length)];
  setTimeout(() => {
    loadingScreen.style.display = 'none';
    callback();
  }, 2000);
}
function resetGame() {
  score = 0;
  level = 1;
  achievements = [];
  sessionTopicPerformance = {};
  wrongAnswers = [];
  userAnswers = [];
  weakTopics = [];
  streak = 0;
  maxStreak = 0;
  lives = 3; // NEW: Reset lives
  consecutiveWrongAnswers = 0; // NEW: Reset for dynamic difficulty
  updateStreakCounter();
  updateLivesDisplay(); // NEW: Update UI
}
// NEW: Replaced narrative with thematic level titles
function updateLevelTitle() {
    const levelThemes = [
        "The Journey Begins", "Number Nexus", "Logic Labyrinth", "Verbal Voyage", "Fraction Fields",
        "Decimal Depths", "Geometry Gauntlet", "Problem Peak", "Syntax Summit", "The Final Challenge"
    ];
    let title;
    if (isInDrillMode) {
        title = "🎯 Practice Drill!";
    } else {
        title = levelThemes[(level - 1) % levelThemes.length] || `Challenge Arena ${level}`;
    }
    levelTitleDiv.textContent = title;
}

// NEW: Function to handle smooth question transitions
function transitionToNextQuestion() {
    swooshSound.play();
    questionContainer.classList.add('slide-out');
    // After the slide-out animation completes, update the content and slide in
    setTimeout(() => {
        displayQuestion(); // Update content while it's invisible
        questionContainer.classList.remove('slide-out');
        questionContainer.classList.add('slide-in');
    }, 400); // This duration should match the transition time in CSS
}

// BUGFIX: Rewritten to be more robust and prevent repeats
function displayQuestion() {
  questionContainer.classList.remove('slide-in'); // Reset for next transition
  viralShareContainer.innerHTML = ''; // Clear viral buttons

  if (currentLevelQuestions.length === 0) {
    if (isInDrillMode) {
        endDrillMode();
    } else {
        triggerLevelComplete();
    }
    return;
  }

  const premiumIndicator = document.getElementById('premium-indicator');
  premiumIndicator.style.display = isPremiumUser ? 'inline' : 'none';
  
  updateLevelTitle();

  let questionPool = currentLevelQuestions;
  if (weakTopics.length > 0 && !isInDrillMode) { // Don't use weak topic logic in drill mode
    const weakTopicQuestions = questionPool.filter(q => weakTopics.includes(q.topic));
    if (weakTopicQuestions.length > 0) {
      questionPool = weakTopicQuestions;
    }
  }

  const randomIndex = Math.floor(Math.random() * questionPool.length);
  currentQuestion = questionPool[randomIndex];

  const indexToRemove = currentLevelQuestions.findIndex(q => q.question === currentQuestion.question);
  if (indexToRemove !== -1) {
    currentLevelQuestions.splice(indexToRemove, 1);
  }

  const questionText = document.getElementById('question-text');
  const topicDisplay = document.getElementById('topic-display');
  
  topicDisplay.textContent = currentQuestion.topic;
  questionText.textContent = currentQuestion.question;
  
  document.getElementById('current-level').textContent = level;
  document.getElementById('current-score').textContent = score;

  // BUG FIX: Corrected difficulty display
  console.log('Current Question Data:', currentQuestion); // For debugging
  const difficultyDisplay = document.getElementById('difficulty-display');
  difficultyDisplay.innerHTML = '';
  // The difficulty value from the database is 1-5, which directly corresponds to the number of stars.
  const stars = currentQuestion.difficulty || 1;

  for (let i = 0; i < 5; i++) {
      const star = document.createElement('span');
      // If the loop index is less than the star rating, it's a filled star.
      star.textContent = i < stars ? '★' : '☆';
      difficultyDisplay.appendChild(star);
  }

  updateProgress();
}

// NEW: More expressive character messages
const correctCharacterMessages = [
    "You got it! Amazing work! ✨", "Fantastic! Nailed it!", "Brilliant! Keep it up!",
    "Perfect! I knew you could do it!", "Correct! So proud of your effort!", "Yes! Another one down!",
    "Awesome! You're on fire today!", "Spot on! That was a tricky one!", "Woohoo! You're on fire today!",
];
const incorrectCharacterMessages = [
    "Not quite! But every try is a step forward. ✨", "Close! The next one is yours.", "It's okay! We learn the most from our mistakes.",
    "Good effort! Let's analyze what happened and try again.", "Don't worry! You'll get the next one! 💪",
];

function getRandomMessage(messages) {
  return messages[Math.floor(Math.random() * messages.length)];
}

// NEW: Function to update the lives display and add animations
function updateLivesDisplay(isGaining = false, isLosing = false) {
    if (!livesIndicator || !livesCount) return;

    livesCount.textContent = lives;

    livesIndicator.classList.remove('gain-life', 'lose-life');

    if (isGaining) {
        void livesIndicator.offsetWidth;
        livesIndicator.classList.add('gain-life');
        const plusOne = document.createElement('div');
        plusOne.textContent = '+1 ❤️';
        plusOne.className = 'plus-one-life';
        livesIndicator.appendChild(plusOne);
        setTimeout(() => plusOne.remove(), 1500);
    }

    if (isLosing) {
        void livesIndicator.offsetWidth;
        livesIndicator.classList.add('lose-life');
        livesIndicator.classList.add('flash-red');
        setTimeout(() => livesIndicator.classList.remove('flash-red'), 600);
    }
}

// REFACTORED `checkAnswer` for juiciness and immediate feedback
function checkAnswer(userAnswer) {
    const isCorrect = userAnswer === currentQuestion.answer;

    // Only track answers in main game mode, not drills
    if (!isInDrillMode) {
        userAnswers.push({
            question: currentQuestion.question,
            correctAnswer: currentQuestion.answer,
            userAnswer,
            explanation: currentQuestion.explanation,
            topic: currentQuestion.topic
        });
        updateTopicPerformance(currentQuestion, isCorrect);
    }

    if (isCorrect) {
        handleCorrectAnswer();
    } else {
        handleIncorrectAnswer();
    }

    updateStreakCounter();
    
    if (isCorrect) {
        setTimeout(() => {
            characterImage.src = '11plus.png';
            updateCharacterFeedback("Let's try the next one!");
            prepareNextQuestion();
        }, 1500);
    }
}

function handleCorrectAnswer() {
    consecutiveWrongAnswers = 0; // Reset on correct answer
    score += (currentQuestion.difficulty || 1);
    streak++;
    if(streak > maxStreak) maxStreak = streak;

    if (navigator.vibrate) navigator.vibrate(50);

    document.querySelector('.container').classList.add('screen-flash-correct');
    setTimeout(() => document.querySelector('.container').classList.remove('screen-flash-correct'), 500);
    correctSound.play();
    triggerConfetti(true); // Bigger confetti burst

    const scoreIndicator = document.getElementById('score-indicator');
    const scoreSpan = document.getElementById('current-score');
    scoreIndicator.classList.add('score-jump');
    scoreIndicator.addEventListener('animationend', () => scoreIndicator.classList.remove('score-jump'), { once: true });

    let startScore = parseInt(scoreSpan.textContent);
    let endScore = score;
    let duration = 500;
    let startTime = null;

    function animateValue(timestamp) {
        if (!startTime) startTime = timestamp;
        const progress = Math.min((timestamp - startTime) / duration, 1);
        scoreSpan.textContent = Math.floor(progress * (endScore - startScore) + startScore);
        if (progress < 1) requestAnimationFrame(animateValue);
    }
    requestAnimationFrame(animateValue);

    characterImage.src = '11plus_happy.png';
    characterImgContainer.classList.add('bounce-big');
    characterImgContainer.addEventListener('animationend', () => characterImgContainer.classList.remove('bounce-big'), { once: true });
    let characterMessage = streak > 2 ? `🔥 That's ${streak} in a row!` : getRandomMessage(correctCharacterMessages);
    updateCharacterFeedback(characterMessage, 'correct');

    // NEW: Genius Moment Share
    if (currentQuestion.difficulty >= 4 || streak === 5) {
        showGeniusMomentShare();
    }
}

function handleIncorrectAnswer() {
    consecutiveWrongAnswers++; // Increment on incorrect answer
    streak = 0;
    if (!isInDrillMode) {
        lives--;
        updateLivesDisplay(false, true);
    }

    if (navigator.vibrate) navigator.vibrate([100, 50, 100]);

    document.querySelector('.container').classList.add('screen-flash-incorrect', 'cracked');
    setTimeout(() => document.querySelector('.container').classList.remove('screen-flash-incorrect', 'cracked'), 500);
    incorrectSound.play();
    wrongAnswers.push(currentQuestion);

    yesBtn.disabled = true;
    noBtn.disabled = true;

    characterImage.src = '11plus_sad.png';
    characterImgContainer.classList.add('shake');
    characterImgContainer.addEventListener('animationend', () => characterImgContainer.classList.remove('shake'), { once: true });
    
    // NEW: Lightbulb moment
    setTimeout(() => {
        characterImgContainer.classList.add('lightbulb');
        updateCharacterFeedback(`Here's a tip: ${currentQuestion.explanation || 'Keep practicing this topic!'}`, 'incorrect');
    }, 800);
    
    const correctBtn = currentQuestion.answer ? yesBtn : noBtn;
    correctBtn.classList.add('correct-answer-highlight');

    const continueBtn = document.createElement('button');
    continueBtn.textContent = 'Got it!';
    continueBtn.className = 'btn';
    continueBtn.id = 'continue-btn';
    document.getElementById('answer-buttons').appendChild(continueBtn);

    continueBtn.addEventListener('click', () => {
        yesBtn.disabled = false;
        noBtn.disabled = false;
        correctBtn.classList.remove('correct-answer-highlight');
        characterImgContainer.classList.remove('lightbulb');
        viralShareContainer.innerHTML = ''; // Clear viral buttons
        continueBtn.remove();
        characterImage.src = '11plus.png';
        updateCharacterFeedback("You can do this!");

        if (lives <= 0 && !isInDrillMode) {
            triggerLevelComplete(true); // Game Over
        } else {
            prepareNextQuestion();
        }
    }, { once: true });
}

/**
 * NEW: Decides the next question, implementing dynamic difficulty.
 * This function is the new central point for advancing the game.
 */
function prepareNextQuestion() {
    // Check if the user is struggling (2 consecutive wrong answers)
    if (consecutiveWrongAnswers >= 2 && !isInDrillMode) {
        // Acknowledge the struggle and offer help through the character
        updateCharacterFeedback("That last one was tough! Let's try a different type of question to warm up.", 'incorrect');
        characterImage.src = '11plus.png'; // Change back to neutral character image

        // Find an easier, unseen question from the master list
        const easyQuestions = allQuestions.filter(q => q.difficulty <= 2 && !userAnswers.some(a => a.question === q.question));
        
        if (easyQuestions.length > 0) {
            // Get a random easy question
            const easyQuestion = easyQuestions[Math.floor(Math.random() * easyQuestions.length)];
            // Add the easy question to the front of the current level's question queue
            currentLevelQuestions.unshift(easyQuestion); 
            console.log("Injecting an easier question to help the user.");
        }

        // Reset the struggle counter so we don't get stuck in a loop
        consecutiveWrongAnswers = 0;

        // Give the user a moment to read the feedback before showing the new question
        setTimeout(() => {
            transitionToNextQuestion();
        }, 2000); // 2-second delay for the user to read the message

    } else {
        // If not struggling, proceed with the normal game flow
        if (currentLevelQuestions.length > 0) {
            transitionToNextQuestion();
        } else {
            if (isInDrillMode) {
                endDrillMode();
            } else {
                triggerLevelComplete();
            }
        }
    }
}

// --- NEW: Streak Counter & Character State Logic ---
function updateStreakCounter() {
    if (streak >= 3) {
        characterImage.classList.add('sunglasses');
        yesBtn.classList.add('powered-up');
        noBtn.classList.add('powered-up');
    } else {
        characterImage.classList.remove('sunglasses');
        yesBtn.classList.remove('powered-up');
        noBtn.classList.remove('powered-up');
    }

    if (streak >= 5) {
        characterAura.classList.add('on-fire');
    } else {
        characterAura.classList.remove('on-fire');
    }

    if (streak > 1) {
        streakCounter.textContent = `🔥 x${streak}`;
        streakCounter.classList.add('visible');
        document.body.classList.add('streak-active');
        if (streak === 3 || streak === 5 || streak === 10) {
            streakSound.play();
        }
    } else {
        streakCounter.classList.remove('visible');
        document.body.classList.remove('streak-active');
    }
}
// --- NEW: Confetti Effect ---
function triggerConfetti(isBig = false) {
    const confettiContainer = document.getElementById('confetti-container');
    const confettiCount = isBig ? 100 : 30;
    const colors = ['#0071e3', '#30d158', '#ff9f0a', '#ff453a', '#9866ff'];
    for (let i = 0; i < confettiCount; i++) {
        const confetti = document.createElement('div');
        confetti.classList.add('confetti-piece');
        confetti.style.left = (Math.random() * 100) + 'vw';
        confetti.style.background = colors[Math.floor(Math.random() * colors.length)];
        confetti.style.animation = `fall ${Math.random() * 2 + 3}s linear ${Math.random() * 2}s forwards`;
        confettiContainer.appendChild(confetti);
        confetti.addEventListener('animationend', () => {
            confetti.remove();
        });
    }
}
// BUGFIX: Now populates a master list and a separate list for the current level
async function loadQuestions() {
  try {
    // Only fetch from DB if the master list is empty
    if (allQuestions.length === 0) {
        const querySnapshot = await db.collection('questions').get();
        allQuestions = querySnapshot.docs.map((doc) => doc.data());
    }
    shuffleArray(allQuestions);
    // Take 10 questions for the level
    currentLevelQuestions = allQuestions.slice(0, 10);
  } catch (error) {
    alert("Oops! Questions couldn't load. Tell a grown-up!");
    console.error("Firebase error:", error);
  }
}
function shuffleArray(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}
function updateTopicPerformance(question, isCorrect) {
  const topic = question.topic;
  if (!topic) return; // Defensive check
  if (!sessionTopicPerformance[topic]) {
    sessionTopicPerformance[topic] = { correct: 0, total: 0 };
  }
  sessionTopicPerformance[topic].total++;
  if (isCorrect) sessionTopicPerformance[topic].correct++;
  const accuracy = (sessionTopicPerformance[topic].correct / sessionTopicPerformance[topic].total) * 100;
  if (accuracy < 50 && !weakTopics.includes(topic)) {
    weakTopics.push(topic);
  }
}
function getJokeMessage(topic) {
  let lowerTopic = topic.toLowerCase();
  if (lowerTopic.includes("math")) return "You're as sharp as a calculator!";
  if (lowerTopic.includes("english")) return "Shakespeare would be proud!";
  return "Great job!";
}
function updateCharacterFeedback(message, feedbackClass = '') {
  const characterMsg = document.querySelector("#funny-character .character-msg");
  characterMsg.textContent = message;
  characterMsg.classList.remove('correct', 'incorrect');
  if (feedbackClass) {
    characterMsg.classList.add(feedbackClass);
  }
}
// NEW: Dramatic Level Complete Sequence
function triggerLevelComplete(isGameOver = false) {
    checkAchievements(); // Final check before showing screen
    levelupSound.play();
    const overlay = document.getElementById('level-transition-overlay');
    const text = document.getElementById('level-transition-text');
    text.textContent = isGameOver ? 'GAME OVER' : 'LEVEL COMPLETE!';
    overlay.style.display = 'flex'; // Make it visible
    overlay.classList.add('visible');

    setTimeout(() => {
        overlay.classList.remove('visible');
        // Hide it after animation
        setTimeout(() => {
            overlay.style.display = 'none';
        }, 300);
        showEndScreen(isGameOver);
    }, 2500);
}

function shareQuestion() {
  const question = currentQuestion.question;
  const shareData = { title: 'Challenge Question', text: `Can you solve this? ${question}`, url: window.location.href };
  if (navigator.share) {
    navigator.share(shareData).catch(console.error);
  } else {
    navigator.clipboard.writeText(question).then(() => alert("Question copied to clipboard! Send it to a friend!"));
  }
}
// UPDATED: Progress bar animation
function updateProgress() {
  const progress = document.getElementById('progress');
  const totalQuestions = isInDrillMode ? 3 : 10;
  const questionsAnswered = totalQuestions - currentLevelQuestions.length;
  const width = (questionsAnswered / totalQuestions) * 100;
  progress.style.width = `${width}%`;
  progress.classList.add('progress-update');
  progress.addEventListener('animationend', () => progress.classList.remove('progress-update'), { once: true });
}
const achievementsList = [
    { name: "Bronze Scholar", emoji: "🥉", requirement: 70, description: "Reach 70% Accuracy", medalClass: "medal-bronze" },
    { name: "Silver Scholar", emoji: "🥈", requirement: 85, description: "Reach 85% Accuracy", medalClass: "medal-silver" },
    { name: "Gold Genius", emoji: "🥇", requirement: 95, description: "Reach 95% Accuracy", medalClass: "medal-gold" }
];
function checkAchievements() {
    const totalQuestions = userAnswers.length;
    if (totalQuestions === 0) return;
    const totalCorrect = userAnswers.filter(a => a.userAnswer === a.correctAnswer).length;
    const accuracy = (totalCorrect / totalQuestions) * 100;
    
    newlyUnlockedAchievements = []; // Reset for the current level check

    achievementsList.forEach(ach => {
        if (accuracy >= ach.requirement && !achievements.includes(ach.name)) {
            achievements.push(ach.name);
            newlyUnlockedAchievements.push(ach.name);
        }
    });
}

// =================================================================================
// REWARD ROUND - `showEndScreen` MAJOR REFACTOR (THE REVEAL)
// =================================================================================
function showEndScreen(isGameOver = false) {
    gameScreen.style.display = 'none';
    endScreen.style.display = 'flex';

    // Get all elements to animate
    const endScreenTitle = document.getElementById('end-screen-title');
    const dynamicTitle = document.getElementById('end-screen-dynamic-title');
    const summaryContainer = document.getElementById('level-summary-container');
    const topicContainer = document.getElementById('topic-performance-container');
    const achievementsContainer = document.getElementById('achievements-container');
    const btnContainer = document.querySelector('.btn-container');
    
    // Hide all elements initially
    [endScreenTitle, dynamicTitle, summaryContainer, topicContainer, achievementsContainer, btnContainer].forEach(el => {
        el.style.opacity = 0;
        el.style.transform = 'translateY(20px)';
    });
    endScreenTitle.classList.remove('visible');

    const totalQuestions = userAnswers.length;
    const totalCorrect = userAnswers.filter(a => a.userAnswer === a.correctAnswer).length;
    const accuracy = totalQuestions > 0 ? Math.round((totalCorrect / totalQuestions) * 100) : 0;

    // --- Start the Reveal Sequence ---

    // 1. Animate Title
    setTimeout(() => {
        if (isGameOver) {
            endScreenTitle.textContent = "Game Over";
            dynamicTitle.textContent = "Great effort! Let's try that again.";
            document.getElementById('next-level-btn').style.display = 'none';
            document.getElementById('try-again-btn').style.display = 'inline-block';
        } else {
            endScreenTitle.textContent = `Level ${level} Complete!`;
            if (accuracy >= 95) dynamicTitle.textContent = "Flawless Victory! You're a true mastermind!";
            else if (accuracy >= 85) dynamicTitle.textContent = "Brilliant Performance! You're on fire!";
            else dynamicTitle.textContent = "Great work! On to the next challenge.";
            document.getElementById('next-level-btn').style.display = 'inline-block';
            document.getElementById('try-again-btn').style.display = 'none';
        }
        endScreenTitle.style.opacity = 1;
        endScreenTitle.classList.add('visible');
        dynamicTitle.style.opacity = 1;
        dynamicTitle.style.transform = 'translateY(0)';
    }, 100);

    // 2. Animate Score Container and Count Up
    setTimeout(() => {
        summaryContainer.style.opacity = 1;
        summaryContainer.style.transform = 'translateY(0)';

        const finalScoreEl = document.getElementById('final-score-value');
        const scoreBuildupEl = document.getElementById('score-buildup-list');
        const accuracyScore = totalCorrect * 2;
        const difficultyBonus = Math.round(userAnswers.reduce((sum, answer) => {
            if (answer.userAnswer === answer.correctAnswer) {
                const q = allQuestions.find(q => q.question === answer.question);
                return sum + (q ? (q.difficulty - 2.5) : 0);
            }
            return sum;
        }, 0));
        const streakBonus = maxStreak > 2 ? maxStreak : 0;
        const finalScore = accuracyScore + difficultyBonus + streakBonus;
        score = finalScore;

        scoreBuildupEl.innerHTML = `
            <li>✅ Accuracy Score: ${accuracyScore}</li>
            <li>🧠 Difficulty Bonus: ${difficultyBonus}</li>
            <li>🔥 Streak Bonus: ${streakBonus}</li>
        `;
        animateCountUp(finalScoreEl, finalScore);

        // Update Gauge & Meter
        const accuracyGauge = document.getElementById('accuracy-gauge');
        const accuracyValue = document.getElementById('accuracy-gauge-value');
        accuracyGauge.style.setProperty('--value', accuracy);
        let gaugeColor = 'var(--error)';
        if (accuracy >= 85) gaugeColor = 'var(--success)';
        else if (accuracy >= 70) gaugeColor = 'var(--warning)';
        accuracyGauge.style.setProperty('--gauge-color', gaugeColor);
        accuracyValue.textContent = `${accuracy}%`;

        const difficultyMeter = document.getElementById('difficulty-meter');
        const avgDifficulty = totalQuestions > 0 ? userAnswers.reduce((sum, answer) => {
            const q = allQuestions.find(q => q.question === answer.question);
            return sum + (q ? q.difficulty || 1 : 1);
        }, 0) / totalQuestions : 0;
        difficultyMeter.innerHTML = '';
        for (let i = 0; i < 5; i++) {
            difficultyMeter.innerHTML += `<span>${i < Math.round(avgDifficulty) ? '★' : '☆'}</span>`;
        }
    }, 800);

    // 3. Animate Achievements "Treasure Chest"
    setTimeout(() => {
        achievementsContainer.style.opacity = 1;
        achievementsContainer.style.transform = 'translateY(0)';
        displayAchievements();
    }, 1500);

    // 4. Animate Topic Performance Chart
    setTimeout(() => {
        topicContainer.style.opacity = 1;
        topicContainer.style.transform = 'translateY(0)';
        displayTopicPerformance();
    }, 1800);

    // 5. Reveal Buttons and Trigger Pep Talk
    setTimeout(() => {
        if (!isGameOver) {
            showPepTalk();
        } else {
            btnContainer.style.opacity = 1;
            btnContainer.style.transform = 'translateY(0)';
        }
    }, 2200);

    updateUserProgress();
    saveUserDataToFirestore();
}

function animateCountUp(el, to, onComplete = () => {}) {
    let from = 0;
    const duration = 1500;
    const step = timestamp => {
        if (!start) start = timestamp;
        const progress = timestamp - start;
        const current = Math.floor(to * (progress / duration));
        el.textContent = current > to ? to : current; // Cap at final value
        if (progress < duration) {
            if (parseInt(el.textContent) % 3 === 0 && !scoreTickSound.paused) scoreTickSound.play();
            window.requestAnimationFrame(step);
        } else {
            el.textContent = to;
            onComplete();
        }
    };
    let start = null;
    window.requestAnimationFrame(step);
}

async function saveUserDataToFirestore() {
  const user = auth.currentUser;
  if (user) {
    const userId = user.uid;
    const sessionData = {
      levelCompleted: level,
      sessionScore: score,
      allUserAnswers: userAnswers,
      wrongAnswersThisSession: wrongAnswers,
      weakTopicsThisSession: weakTopics,
      timestamp: firebase.firestore.FieldValue.serverTimestamp()
    };
    try {
      await db.collection('users').doc(userId).collection('gameSessions').add(sessionData);
      console.log("Session data saved successfully!");
    } catch (error) {
      console.error("Error saving session data: ", error);
    }
  } else {
    console.log("No user is signed in.");
  }
}
// BUGFIX: Added defensive code for empty data and division by zero
function displayTopicPerformance() {
  const topicChart = document.getElementById('topic-performance-chart');
  topicChart.innerHTML = '<canvas id="performanceChart"></canvas>'; // Clear previous chart

  const sortedTopics = Object.keys(sessionTopicPerformance)
    .map((topic) => ({ 
        topic, 
        accuracy: sessionTopicPerformance[topic].total > 0 ? 
                  (sessionTopicPerformance[topic].correct / sessionTopicPerformance[topic].total) * 100 : 0 
    }))
    .sort((a, b) => a.accuracy - b.accuracy);

  if (sortedTopics.length === 0) {
    topicChart.innerHTML = '<p style="text-align: center; padding: 20px;">No topic performance was recorded for this level.</p>';
    return;
  }
  
  const backgroundColors = sortedTopics.map(t => {
      if (t.accuracy < 60) return 'rgba(255, 69, 58, 0.7)';
      if (t.accuracy < 85) return 'rgba(255, 159, 10, 0.7)';
      return 'rgba(48, 209, 88, 0.7)';
  });

  const borderColors = sortedTopics.map(t => {
      if (t.accuracy < 60) return 'rgba(255, 69, 58, 1)';
      if (t.accuracy < 85) return 'rgba(255, 159, 10, 1)';
      return 'rgba(48, 209, 88, 1)';
  });
  
  // Highlight the weakest topic
  if (borderColors.length > 0) {
      borderColors[0] = '#FFFFFF';
  }

  const ctx = document.getElementById('performanceChart').getContext('2d');
  new Chart(ctx, {
    type: 'bar',
    data: {
      labels: sortedTopics.map(t => t.topic),
      datasets: [{
        label: 'Accuracy (%)',
        data: sortedTopics.map(t => t.accuracy),
        backgroundColor: backgroundColors,
        borderColor: borderColors,
        borderWidth: sortedTopics.map((_, i) => i === 0 ? 3 : 1),
        barThickness: 15,
      }]
    },
    options: {
      indexAxis: 'y', responsive: true, maintainAspectRatio: false,
      scales: {
        x: { beginAtZero: true, max: 100, grid: { display: false }, ticks: { color: 'var(--text-secondary)' } },
        y: { grid: { display: false }, ticks: { color: 'var(--text-primary)' } }
      },
      plugins: { legend: { display: false } },
    }
  });
}
function displayAchievements() {
    const newUnlockDiv = document.getElementById('newly-unlocked-achievement');
    const trophyWallDiv = document.getElementById('trophy-wall');
    newUnlockDiv.innerHTML = '';
    trophyWallDiv.innerHTML = '';

    // Main event: Show newly unlocked achievement
    if (newlyUnlockedAchievements.length > 0) {
        const ach = achievementsList.find(a => a.name === newlyUnlockedAchievements[0]);
        if(ach) {
            achievementSound.play();
            newUnlockDiv.innerHTML = `
                <div class="achievement-medal newly-unlocked">
                    <div class="achievement-medal-icon ${ach.medalClass}">${ach.emoji}</div>
                    <div class="achievement-medal-text">
                        <h4>${ach.name}</h4>
                        <p>${ach.description}</p>
                    </div>
                </div>`;
        }
    }

    // Trophy Wall: Show all achievements with their states
    achievementsList.forEach(ach => {
        let stateClass = 'not-yet-unlocked';
        if (newlyUnlockedAchievements.includes(ach.name)) {
            return; // Don't show it again if it was the main event
        }
        if (achievements.includes(ach.name)) {
            stateClass = 'previously-unlocked';
        }

        trophyWallDiv.innerHTML += `
            <div class="achievement-medal ${stateClass}">
                <div class="achievement-medal-icon ${ach.medalClass}">${ach.emoji}</div>
                <div class="achievement-medal-text">
                    <h4>${ach.name}</h4>
                    <p>${ach.description}</p>
                </div>
            </div>`;
    });
}
function toggleReviewSection() {
  if (reviewSection.style.display === 'none') {
    displayReviewSection();
    reviewSection.style.display = 'block';
    reviewBtn.textContent = "Hide Review";
  } else {
    reviewSection.style.display = 'none';
    reviewBtn.textContent = "🔍 Improve Weak Areas";
  }
}
function displayReviewSection() {
  reviewSection.innerHTML = '<h2>Review Your Mistakes</h2>';
  const seenQuestions = new Set();
  wrongAnswers.forEach((item, index) => {
    if (!seenQuestions.has(item.question)) {
      seenQuestions.add(item.question);
      reviewSection.innerHTML += `
        <div class="review-item">
          <h3>Question ${index + 1}:</h3>
          <p><strong>Q:</strong> ${item.question}</p>
          <p><strong>Correct Answer:</strong> ${item.answer ? "Yes" : "No"}</p>
          <p><strong>Explanation:</strong> ${item.explanation}</p>
        </div><hr>`;
    }
  });
  if (seenQuestions.size === 0) reviewSection.innerHTML += '<p>No mistakes made. Excellent work!</p>';
}
function showPaywall() {
  gameScreen.style.display = 'none';
  endScreen.style.display = 'none';
  paywallScreen.style.display = 'flex'; // BUGFIX: Use flex
}
async function startNextLevel() {
  if (level === 3 && !isPremiumUser) {
    showPaywall();
    return;
  }
  level++;
  lives++; // NEW: Add a life for passing the level
  setLevelBackground(level); // Set new background for the next level
  
  // BUGFIX: Reset session-specific stats for the new level
  score = 0;
  sessionTopicPerformance = {};
  wrongAnswers = [];
  userAnswers = [];
  streak = 0; // Reset streak for next level
  maxStreak = 0;
  newlyUnlockedAchievements = []; // Reset for new level
  updateStreakCounter();

  endScreen.style.display = 'none';
  endScreen.classList.remove('pep-talk-active'); // NEW: Reset animation class
  gameScreen.style.display = 'flex'; // BUGFIX: Use flex to maintain glassmorphism
  updateLivesDisplay(true, false); // NEW: Update UI with gaining animation
  await loadQuestions();
  displayQuestion();
  updateLevelTitle();
  playLevelMusic(); // NEW: Play new music for the next level
}
// NEW: Function to play level-specific music
function playLevelMusic() {
    if (!levelMusic.paused) {
        levelMusic.pause();
        levelMusic.currentTime = 0;
    }
    const trackIndex = (level - 1) % levelMusicTracks.length;
    levelMusic.src = levelMusicTracks[trackIndex];
    levelMusic.load(); 
    levelMusic.play().catch(e => console.warn("Music playback failed:", e));
}
function exitGame() {
  endScreen.style.display = 'none';
  endScreen.classList.remove('pep-talk-active'); // NEW: Reset animation class
  paywallScreen.style.display = 'none';
  resetBackgroundImage(); // Remove background image
  landingScreen.style.display = 'flex'; // BUGFIX: Use flex
  document.getElementById('next-level-btn').style.display = 'inline-block';
  document.getElementById('try-again-btn').style.display = 'none';
  resetGame();
  levelMusic.pause(); // NEW: Stop music on exit
  levelMusic.currentTime = 0; // NEW: Reset music to beginning
}
function requestPaymentLink() {
  const user = auth.currentUser;
  if (user) {
    alert("Please check your email for the payment link.");
    setTimeout(() => {
      db.collection('users').doc(user.uid).update({
        isPremium: true,
        subscriptionDate: firebase.firestore.FieldValue.serverTimestamp()
      }).then(() => {
        isPremiumUser = true;
        paywallScreen.style.display = 'none';
        gameScreen.style.display = 'flex'; // BUGFIX: Use flex
        alert("Thank you for subscribing! You now have access to all levels.");
      }).catch(error => console.error("Error updating premium status:", error));
    }, 2000);
  } else {
    alert("Please sign in to subscribe.");
  }
}
function shareChallenge() {
  const shareData = {
    title: 'Math and English Challenge Pro',
    text: `I scored ${score} on Level ${level} in Math Challenge Pro! Can you beat my score?`,
    url: window.location.href
  };
  if (navigator.share) {
    navigator.share(shareData).catch(console.error);
  } else {
    navigator.clipboard.writeText(`${shareData.text} ${shareData.url}`).then(() => alert("Challenge copied. Share it with your friends!"));
  }
}
// ----- NEW: Viral Sharing Functions -----
function showGeniusMomentShare() {
    viralShareContainer.innerHTML = `
        <button id="genius-share-btn" class="btn btn-viral">
            Share Your Genius Moment! 🧠✨
        </button>
    `;
    document.getElementById('genius-share-btn').addEventListener('click', () => {
        const shareText = `I'm an official 11+ Genius! 🏆 I just nailed this tough question: "${currentQuestion.question}" Think you can keep up? #11PlusGenius`;
        const shareData = {
            title: 'I\'m an 11+ Genius!',
            text: shareText,
            url: window.location.href
        };
        if (navigator.share) {
            navigator.share(shareData).catch(console.error);
        } else {
            navigator.clipboard.writeText(shareText).then(() => alert("Genius moment copied! Go share it!"));
        }
    });
}
async function toggleHistorySection() {
  if (historySection.style.display === 'none') {
    await displayHistoricalPerformance();
    historySection.style.display = 'flex';
    historyBtn.textContent = "📊 Hide My Growth";
  } else {
    historySection.style.display = 'none';
    historyBtn.textContent = "📊 My Growth";
  }
}
// =================================================================================
// TUTOR'S PRIORITY PLAN - `displayHistoricalPerformance` MAJOR REFACTOR
// =================================================================================
async function displayHistoricalPerformance() {
    const user = auth.currentUser;
    if (!user) {
        historySection.innerHTML = '<p>Please sign in to view your growth plan.</p>';
        return;
    }

    try {
        const sessionsSnapshot = await db.collection('users').doc(user.uid).collection('gameSessions').orderBy('timestamp', 'asc').get();
        
        if (sessionsSnapshot.empty) {
            historySection.innerHTML = `<div id="tutor-priority-card">
                <h4>Your Personalized Growth Plan is Waiting!</h4>
                <p class="tutor-message" style="margin-top: 1rem;">After you play a few rounds, this screen will transform into your personal tutor. It will analyze your unique skills to show you the #1 topic to practice for the fastest improvement.</p>
                <button class="btn btn-primary-action" onclick="toggleHistorySection()">Play Your First Round!</button>
            </div>`;
            return;
        }

        // 1. Aggregate all historical data
        const topicMastery = {};
        const dailyPerformance = {};
        let totalQuestionsAnswered = 0;
        let totalCorrectAnswers = 0;

        sessionsSnapshot.forEach(doc => {
            const session = doc.data();
            const date = session.timestamp.toDate().setHours(0,0,0,0);
            if (!dailyPerformance[date]) {
                dailyPerformance[date] = { questions: 0 };
            }
            
            if (session.allUserAnswers && Array.isArray(session.allUserAnswers)) {
                dailyPerformance[date].questions += session.allUserAnswers.length;
                totalQuestionsAnswered += session.allUserAnswers.length;

                session.allUserAnswers.forEach(answer => {
                    if (answer.correctAnswer === answer.userAnswer) {
                        totalCorrectAnswers++;
                    }
                    if (!topicMastery[answer.topic]) {
                        topicMastery[answer.topic] = { correct: 0, total: 0 };
                    }
                    topicMastery[answer.topic].total++;
                    if (answer.correctAnswer === answer.userAnswer) {
                        topicMastery[answer.topic].correct++;
                    }
                });
            }
        });

        // 2. Calculate topic accuracies and find priorities
        const topicsArray = Object.keys(topicMastery).map(topic => {
            const data = topicMastery[topic];
            return {
                name: topic,
                accuracy: data.total > 0 ? (data.correct / data.total) * 100 : 0,
                volume: data.total
            };
        });

        // Fallback for first session: recommend lowest accuracy regardless of volume
        let priorityTopics = topicsArray.sort((a, b) => a.accuracy - b.accuracy);
        
        // More robust logic: filter for topics with enough data, but keep fallback
        const struggleZone = topicsArray.filter(t => t.volume >= 5).sort((a, b) => a.accuracy - b.accuracy);
        if (struggleZone.length > 0) {
            priorityTopics = struggleZone;
        }

        const topPriority = priorityTopics[0];
        const buildSkills = priorityTopics.slice(1, 4);

        // 3. Prepare data for cumulative stats and chart
        const overallAccuracy = totalQuestionsAnswered > 0 ? Math.round((totalCorrectAnswers / totalQuestionsAnswered) * 100) : 0;
        const totalSessions = sessionsSnapshot.size;
        const estimatedTime = totalSessions * 4; // Estimate 4 minutes per session

        const chartData = Object.keys(dailyPerformance).map(date => ({
            x: new Date(parseInt(date)),
            y: dailyPerformance[date].questions
        }));

        // 4. Render the entire component
        historySection.innerHTML = `
            <div>
                <h3 class="history-section-title">The Priority Plan</h3>
                <div id="tutor-priority-card">
                    <h4>Tutor's Top Priority</h4>
                    <p class="topic-name">${topPriority ? topPriority.name : 'Play More!'}</p>
                    ${topPriority ? `
                    <p class="topic-accuracy">${Math.round(topPriority.accuracy)}% Accuracy</p>
                    <p class="tutor-message">Mastering this is your next big breakthrough. A little focus here will make a huge difference!</p>
                    <button class="btn btn-practice-drill" onclick="startDrillMode('${topPriority.name}')">Practice Now 🎯</button>
                    ` : `
                    <p class="tutor-message">Play a few more games to unlock your personalized priority!</p>
                    `}
                </div>
            </div>

            ${buildSkills.length > 0 ? `
            <div>
                <h3 class="history-section-title">Building Your Skills</h3>
                <div id="skill-building-list">
                    ${buildSkills.map(skill => `
                    <div class="skill-item">
                        <div class="skill-info">
                            <h5>${skill.name}</h5>
                            <div class="accuracy-bar-container">
                                <div class="accuracy-bar" style="width: ${skill.accuracy}%; background-color: ${getAccuracyColor(skill.accuracy)};"></div>
                            </div>
                        </div>
                        <button class="btn btn-secondary" style="width: auto; padding: 8px 12px;" onclick="startDrillMode('${skill.name}')">Practice</button>
                    </div>
                    `).join('')}
                </div>
            </div>
            ` : ''}

            <div>
                <h3 class="history-section-title">Your Journey So Far</h3>
                <div id="journey-stats-container">
                    <div class="stat-block">
                        <span class="stat-value">${totalQuestionsAnswered}</span>
                        <span class="stat-label">Total Questions</span>
                    </div>
                    <div class="stat-block">
                        <span class="stat-value">${overallAccuracy}%</span>
                        <span class="stat-label">Overall Accuracy</span>
                    </div>
                    <div class="stat-block">
                        <span class="stat-value">${totalSessions}</span>
                        <span class="stat-label">Sessions Played</span>
                    </div>
                    <div class="stat-block">
                        <span class="stat-value">~${estimatedTime}</span>
                        <span class="stat-label">Minutes Practiced</span>
                    </div>
                </div>
            </div>

            <div>
                <h3 class="history-section-title">Progress Over Time</h3>
                <div id="history-chart-container">
                    <canvas id="historyChart"></canvas>
                </div>
            </div>
        `;

        // 5. Initialize the line chart
        new Chart(document.getElementById('historyChart').getContext('2d'), {
            type: 'line',
            data: {
                datasets: [{
                    label: 'Questions Answered',
                    data: chartData,
                    borderColor: 'var(--primary)',
                    backgroundColor: 'rgba(0, 113, 227, 0.1)',
                    fill: true,
                    tension: 0.3
                }]
            },
            options: {
                responsive: true, maintainAspectRatio: false,
                scales: {
                    x: { type: 'time', time: { unit: 'day' }, grid: { display: false } },
                    y: { beginAtZero: true, grid: { display: false }, ticks: { precision: 0 } }
                },
                plugins: { legend: { display: false } }
            }
        });

    } catch (error) {
        console.error("Error loading historical data:", error);
        historySection.innerHTML = '<p>Error loading your growth plan. Please try again.</p>';
    }
}

function getAccuracyColor(accuracy) {
    if (accuracy >= 80) return 'var(--success)';
    if (accuracy >= 50) return 'var(--warning)';
    return 'var(--error)';
}
function showSettingsPanel() {
  const settingsPanel = document.createElement('div');
  settingsPanel.id = 'settings-panel';
  settingsPanel.innerHTML = `
    <div class="settings-content">
      <h3>Settings</h3>
      <div class="settings-item">
        <span>Subscription Status:</span>
        <span>${isPremiumUser ? '⭐ Premium' : 'Free Account'}</span>
      </div>
      <button id="manage-subscription" class="btn">${isPremiumUser ? 'Manage' : 'Upgrade'}</button>
      <button id="close-settings" class="btn secondary">Close</button>
    </div>`;
  document.body.appendChild(settingsPanel);
  document.getElementById('manage-subscription').addEventListener('click', () => window.open('https://billing.stripe.com/p/login/5kA012aES8yqcRa6oo', '_blank'));
  document.getElementById('close-settings').addEventListener('click', () => settingsPanel.remove());
  settingsPanel.addEventListener('click', (e) => e.target === settingsPanel && settingsPanel.remove());
}
async function shareResultsAsScreenshot() {
  try {
    const endScreenElement = document.getElementById('end-screen');
    const buttonsToHide = endScreenElement.querySelectorAll('.btn-container');
    
    buttonsToHide.forEach(el => el.style.visibility = 'hidden');

    endScreenElement.scrollTop = 0;

    const canvas = await html2canvas(endScreenElement, {
      scale: 2,
      useCORS: true,
    });

    buttonsToHide.forEach(el => el.style.visibility = 'visible');

    canvas.toBlob(async (blob) => {
      if (!blob) {
        console.error("Failed to create blob from canvas.");
        alert("Sorry, we couldn't create the screenshot image.");
        return;
      }
      try {
        const file = new File([blob], 'results.png', { type: 'image/png' });
        if (navigator.share && navigator.canShare({ files: [file] })) {
          await navigator.share({
            title: 'My Learning Results',
            text: `I scored ${score} on Level ${level} in Math Challenge Pro!`,
            files: [file]
          });
        } else {
          const link = document.createElement('a');
          link.download = 'math-challenge-results.png';
          link.href = canvas.toDataURL('image/png');
          link.click();
        }
      } catch (error) {
        if (error.name !== 'AbortError') {
          console.error('Error during sharing:', error);
          alert('Could not share results.');
        }
      }
    }, 'image/png');
  } catch (error) {
    console.error('Error capturing screenshot:', error);
    alert('Could not capture the screenshot.');
    endScreenElement.querySelectorAll('.btn-container').forEach(el => el.style.visibility = 'visible');
  }
}

// ----- NEW: PEP TALK AND DRILL MODE FUNCTIONS -----

/**
 * Generates a personalized, multi-part feedback message based on session performance.
 * @param {object} topicPerformance - The sessionTopicPerformance object.
 * @returns {object} An object containing the message parts and identified topics.
 */
function generatePersonalizedFeedback(topicPerformance) {
    // BUG FIX: Check for perfect score *before* filtering topics.
    const totalQuestions = userAnswers.length;
    const totalCorrect = userAnswers.filter(a => a.userAnswer === a.correctAnswer).length;
    const isPerfect = totalCorrect === totalQuestions;

    if (isPerfect) {
        return {
            opener: "Are you even real?!",
            body: `A perfect score! You mastered every single topic. That was a flawless victory!`,
            callToAction: "There's nothing to practice, you're a genius! Let's go to the next level!",
            weakTopic: null
        };
    }
    
    // Original logic starts here, but now it won't incorrectly handle the perfect score case.
    // BUG FIX: The filter is removed to consider ALL topics, even those with only one question.
    const topics = Object.keys(topicPerformance).map(topic => ({
        name: topic,
        accuracy: (topicPerformance[topic].correct / topicPerformance[topic].total) * 100,
        total: topicPerformance[topic].total
    }));

    if (topics.length === 0) { // Should not happen if not a perfect score, but a good safeguard.
        return {
            opener: "Incredible work on that level!",
            body: "You're building a great foundation. Keep up the amazing effort!",
            callToAction: "Ready for the next adventure?",
            weakTopic: null
        };
    }

    // Sort to find the best and worst topics
    topics.sort((a, b) => a.accuracy - b.accuracy);
    const weakTopic = topics[0];
    const strongTopic = topics[topics.length - 1];

    // --- Phrase Pools for Dynamic Messages ---
    const openers = ["Wow, what a performance!", "That was brilliant!", "Incredible effort on that level!"];
    const strengthConnectors = ["I was so impressed with how you handled", "You absolutely crushed", "You were a total superstar on"];
    const transitions = ["Now, I see a really cool opportunity for us.", "I think I've spotted the next challenge we can conquer together.", "Okay, let's strategize for a moment."];
    const weaknessFraming = ["Those questions can be real puzzles, can't they?", "That topic is designed to be tricky.", "It's one of the toughest areas, but we can master it."];
    const ctaPrompts = ["How about we do a quick 3-question drill on it right now?", "Let's turn that into your new superpower with a short practice round.", "Want to tackle a few of those head-on before the next level?"];

    // --- Construct the Message ---
    let bodyMessage;
    // If the strong and weak topics are the same, it means there was only one topic category in the level.
    if (strongTopic.name === weakTopic.name) {
        bodyMessage = `I noticed the <strong class="weak-topic">${weakTopic.name}</strong> questions were giving us a bit of a fight. ${weaknessFraming[Math.floor(Math.random() * weaknessFraming.length)]}`;
    } else {
        bodyMessage = `<strong class="strong-topic">${strengthConnectors[Math.floor(Math.random() * strengthConnectors.length)]} the ${strongTopic.name} questions!</strong><br><br>${transitions[Math.floor(Math.random() * transitions.length)]} I noticed the <strong class="weak-topic">${weakTopic.name}</strong> questions were giving us a bit of a fight. ${weaknessFraming[Math.floor(Math.random() * weaknessFraming.length)]}`;
    }
    
    let message = {
        opener: openers[Math.floor(Math.random() * openers.length)],
        body: bodyMessage,
        callToAction: ctaPrompts[Math.floor(Math.random() * ctaPrompts.length)],
        weakTopic: weakTopic.name
    };
    
    return message;
}


/**
 * Displays the cinematic pep talk from the character.
 */
function showPepTalk() {
    const pepTalkContainer = document.getElementById('pep-talk-container');
    const feedback = generatePersonalizedFeedback(sessionTopicPerformance);

    document.getElementById('pep-talk-opener').textContent = feedback.opener;
    document.getElementById('pep-talk-body').innerHTML = feedback.body;
    document.getElementById('pep-talk-cta').textContent = feedback.callToAction;

    const actionsContainer = document.getElementById('pep-talk-actions');
    actionsContainer.innerHTML = ''; // Clear previous buttons

    if (feedback.weakTopic) {
        const practiceBtn = document.createElement('button');
        practiceBtn.className = 'btn btn-practice-drill';
        practiceBtn.textContent = `🎯 Practice ${feedback.weakTopic}`;
        practiceBtn.onclick = () => startDrillMode(feedback.weakTopic);
        actionsContainer.appendChild(practiceBtn);
    }

    const continueBtn = document.createElement('button');
    continueBtn.className = 'btn btn-secondary';
    continueBtn.textContent = feedback.weakTopic ? '🚀 No thanks, next level' : '🚀 Let\'s Go!';
    continueBtn.onclick = () => {
        pepTalkContainer.style.display = 'none';
        endScreen.classList.remove('pep-talk-active');
        const btnContainer = document.querySelector('.btn-container');
        btnContainer.style.opacity = 1;
        btnContainer.style.transform = 'translateY(0)';
    };
    actionsContainer.appendChild(continueBtn);

    endScreen.classList.add('pep-talk-active');
    pepTalkContainer.style.display = 'flex';
}

/**
 * Starts a short practice drill for a specific topic.
 * @param {string} topic - The topic to drill.
 */
function startDrillMode(topic) {
    isInDrillMode = true;
    // Hide history section if it's open
    if (historySection.style.display !== 'none') {
        historySection.style.display = 'none';
        historyBtn.textContent = "📊 My Growth";
    }
    document.getElementById('pep-talk-container').style.display = 'none';
    endScreen.style.display = 'none';
    endScreen.classList.remove('pep-talk-active');

    // Filter for 3 questions of the specified topic
    const drillQuestions = allQuestions.filter(q => q.topic === topic);
    shuffleArray(drillQuestions);
    currentLevelQuestions = drillQuestions.slice(0, 3);
    
    // Reset streak for the drill
    streak = 0;
    updateStreakCounter();

    gameScreen.style.display = 'flex';
    displayQuestion();
}

/**
 * Concludes the drill mode and returns to the end screen.
 */
function endDrillMode() {
    isInDrillMode = false;
    gameScreen.style.display = 'none';
    endScreen.style.display = 'flex';

    // Show a final confirmation message in the pep talk container
    const pepTalkContainer = document.getElementById('pep-talk-container');
    document.getElementById('pep-talk-opener').textContent = "Great Practice!";
    document.getElementById('pep-talk-body').innerHTML = "That's how we turn weaknesses into strengths. You're ready for anything now!";
    document.getElementById('pep-talk-cta').textContent = "";
    
    const actionsContainer = document.getElementById('pep-talk-actions');
    actionsContainer.innerHTML = ''; // Clear old buttons
    const continueBtn = document.createElement('button');
    continueBtn.className = 'btn btn-primary-action';
    continueBtn.textContent = '🚀 Bring on the Next Level!';
    continueBtn.onclick = () => {
        pepTalkContainer.style.display = 'none';
        endScreen.classList.remove('pep-talk-active');
        const btnContainer = document.querySelector('.btn-container');
        btnContainer.style.opacity = 1;
        btnContainer.style.transform = 'translateY(0)';
    };
    actionsContainer.appendChild(continueBtn);

    pepTalkContainer.style.display = 'flex';
    endScreen.classList.add('pep-talk-active');
}
```