<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Can You Pass This Dementia Test?</title>
  
  
  <script src="https://j24iGSTy4hDgBLfJR.ay.delivery/manager/j24iGSTy4hDgBLfJR" type="text/javascript" referrerpolicy="no-referrer-when-downgrade"></script> 
  
  
  
  
  <!-- Meta Pixel Code -->
<script>
!function(f,b,e,v,n,t,s)
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s)}(window, document,'script',
'https://connect.facebook.net/en_US/fbevents.js');
fbq('init', '1463144898836249');
fbq('track', 'PageView');
</script>
<noscript><img height="1" width="1" style="display:none"
src="https://www.facebook.com/tr?id=1463144898836249&ev=PageView&noscript=1"
/></noscript>
<!-- End Meta Pixel Code -->
  
  
  <script async src="https://securepubads.g.doubleclick.net/tag/js/gpt.js"></script>
  <style>
    * { box-sizing: border-box; }

    :root {
      --green: #39a542;
      --green-dark: #2f8f37;
      --green-soft: #eef5ee;
      --bg: #f3f6f1;
      --card: #ffffff;
      --text: #1f2b20;
      --muted: #5d6b5d;
      --border: #dfe7dd;
      --danger: #b42318;
      --disabled: #cfd7cf;
      --shadow: 0 10px 30px rgba(36, 61, 36, 0.06);
    }

    body {
      margin: 0;
      font-family: Inter, Arial, Helvetica, sans-serif;
      background: var(--bg);
      color: var(--text);
    }

    .header {
      height: 50px;
      border-bottom: 1px solid #d9e2d8;
      background: rgba(255,255,255,0.35);
    }

    .header-inner {
      max-width: 1380px;
      margin: 0 auto;
      height: 100%;
      padding: 0 28px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 20px;
    }

    .brand {
      font-size: 28px;
      font-weight: 800;
      letter-spacing: -0.02em;
      color: var(--green);
    }

    .fine-print{
    margin-top:10px;}
    
    .top-note,
    .fine-print,
    .footer {
      font-size: 15px;
      color: var(--muted);
      text-align: center;
    }

    .top-note {
      line-height: 1.3;
    }

    .container {
      width: 100%;
      max-width: 1380px;
      margin: 0 auto;
      padding: 0 24px 32px;
    }

    .hero {
      padding: 64px 0 42px;
      text-align: center;
    }

    .title {
      max-width: 900px;
      margin: 0 auto 18px;
      font-size: 82px;
      line-height: 0.98;
      font-weight: 800;
      letter-spacing: -0.04em;
      color: var(--green);
    }

    .subtitle {
      max-width: 760px;
      margin: 0 auto 34px;
      font-size: 26px;
      line-height: 1.45;
      color: #546454;
    }

    .cta-stack {
      max-width: 360px;
      margin: 0 auto 34px;
    }

    .action-btn {
      width: 100%;
      padding: 22px 28px; /* taller */
      min-height: 72px; /* ensure height */
      font-size: 22px;
      font-weight: 800;
      border: none;
      border-radius: 22px;
      background: linear-gradient(90deg, var(--green) 0%, #66ba67 100%);
      color: #fff;
      cursor: pointer;
      box-shadow: 0 14px 32px rgba(57, 165, 66, 0.2);
      transition: transform 0.15s ease, box-shadow 0.15s ease, filter 0.15s ease;
    }

    .action-btn:hover {
      transform: translateY(-1px);
      filter: brightness(1.02);
      box-shadow: 0 18px 36px rgba(57, 165, 66, 0.24);
    }

    .action-btn[disabled] {
      background: var(--disabled);
      box-shadow: none;
      cursor: not-allowed;
      transform: none;
      filter: none;
    }

    .message,
    .gate-note {
      margin-top: 12px;
      font-size: 15px;
      color: var(--danger);
      text-align: center;
      min-height: 22px;
      line-height: 1.4;
    }

    .hero-meta {
      display: inline-flex;
      align-items: center;
      gap: 34px;
      flex-wrap: wrap;
      justify-content: center;
      color: #4f604f;
      font-size: 20px;
      font-weight: 500;
    }

    .hero-meta-item {
      display: inline-flex;
      align-items: center;
      gap: 10px;
    }

    .hero-meta-icon {
      width: 34px;
      height: 34px;
      border-radius: 999px;
      background: #e6efe3;
      color: var(--green);
      display: inline-flex;
      align-items: center;
      justify-content: center;
      font-size: 18px;
      font-weight: 700;
    }

    .features-grid {
      display: grid;
      grid-template-columns: repeat(3, minmax(0, 1fr));
      gap: 18px;
      margin-bottom: 30px;
    }

    .feature-card,
    .card {
      background: var(--card);
      border: 1px solid var(--border);
      border-radius: 20px;
      box-shadow: var(--shadow);
    }

    .feature-card {
      padding: 28px 24px;
      text-align: center;
      min-height: 220px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }

    .feature-icon {
      width: 56px;
      height: 56px;
      border-radius: 999px;
      background: #edf4ec;
      color: var(--green);
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 28px;
      margin-bottom: 22px;
    }

    .feature-title {
      font-size: 22px;
      font-weight: 800;
      margin-bottom: 10px;
    }

    .feature-text {
      font-size: 16px;
      line-height: 1.55;
      color: var(--muted);
      max-width: 290px;
    }

    .card {
      overflow: hidden;
    }

    .quiz-box {
      padding: 22px;
    }

    .quiz-meta {
      display: flex;
      justify-content: space-between;
      font-size: 14px;
      font-weight: 700;
      margin-bottom: 12px;
      color: var(--muted);
    }

    .progress-wrap {
      height: 12px;
      border-radius: 999px;
      background: #e8eee6;
      overflow: hidden;
      margin-bottom: 22px;
    }

    .progress {
      height: 100%;
      width: 0;
      background: var(--green);
      transition: width 0.25s ease;
    }

    .question {
      font-size: 32px;
      font-weight: 800;
      text-align: center;
      margin-bottom: 22px;
      line-height: 1.25;
    }

    .answers {
      display: grid;
      gap: 14px;
    }

    .answer {
      width: 100%;
      min-height: 70px;
      padding: 18px 20px;
      font-size: 18px;
      border-radius: 18px;
      background: #fff;
      border: 2px solid var(--border);
      cursor: pointer;
      display: flex;
      align-items: center;
      gap: 12px;
      transition: all 0.18s ease;
      -webkit-appearance: none;
      appearance: none;
      touch-action: manipulation;
      text-align: left;
      color: var(--text);
    }

    .answer:hover {
      border-color: #b9d4b8;
      background: var(--green-soft);
    }

    .answer:active {
      transform: scale(0.995);
    }

    .answer:focus-visible {
      outline: 3px solid rgba(57, 165, 66, 0.18);
      outline-offset: 2px;
      border-color: var(--green);
    }

    .letter {
      width: 38px;
      height: 38px;
      border-radius: 999px;
      background: var(--green);
      color: #fff;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      font-size: 16px;
      font-weight: 700;
      flex: 0 0 auto;
    }

    .gate-card,
    .result-card {
      text-align: center;
      padding: 34px 28px;
    }

    .gate-title,
    .result-title {
      font-size: 34px;
      font-weight: 800;
      margin-bottom: 12px;
      line-height: 1.15;
    }

    .gate-text,
    .result-text {
      font-size: 19px;
      line-height: 1.6;
      color: var(--muted);
    }

    .result-score {
      font-size: 64px;
      font-weight: 800;
      margin-bottom: 12px;
      color: var(--green);
    }

    .result-bar-wrap {
      height: 14px;
      background: #e8eee6;
      border-radius: 999px;
      overflow: hidden;
      margin: 22px 0;
    }

    .result-bar {
      height: 100%;
      width: 0;
      background: var(--green);
      transition: width 0.35s ease;
    }

    .about-box {
      padding: 22px 24px;
      border-top: 1px solid var(--border);
      background: #fafcf9;
    }

    .about-title {
      font-size: 18px;
      font-weight: 700;
      margin-bottom: 8px;
    }

    .about-text {
      font-size: 15px;
      line-height: 1.7;
      color: var(--muted);
    }

    .footer {
      padding: 26px 20px 34px;
      line-height: 1.45;
    }

    .hidden { display: none; }

    @media (max-width: 980px) {
      .title {
        font-size: 62px;
      }

      .subtitle {
        font-size: 22px;
      }

      .features-grid {
        grid-template-columns: 1fr;
      }
    }

    @media (max-width: 640px) {
      .header {
        height: 50px;
      }

      .header-inner {
        padding: 14px 16px 12px;
        align-items: flex-start;
        flex-direction: column;
      }

      .brand {
        font-size: 22px;
      }

      .top-cta-wrap {
        width: 100%;
      }

      .container {
        max-width: 100%;
        margin: 0;
        padding: 0 0 26px;
      }

      .hero {
        padding: 30px 16px 22px;
      }

      .title {
        font-size: 44px;
        margin-bottom: 14px;
      }

      .subtitle {
        font-size: 20px;
        margin-bottom: 24px;
      }

      .cta-stack {
        max-width: none;
        margin-bottom: 24px;
      }

      .hero-meta {
        gap: 16px 22px;
        font-size: 18px;
      }

      .hero-meta-icon {
        width: 30px;
        height: 30px;
        font-size: 16px;
      }

      .features-grid {
        gap: 14px;
        padding: 0 16px;
      }

      .card {
        border-radius: 0;
        box-shadow: none;
        border-left: none;
        border-right: none;
      }

      .quiz-box {
        padding: 16px;
      }

      .question {
        font-size: 24px;
      }

      .gate-title,
      .result-title {
        font-size: 26px;
      }

      .gate-text,
      .result-text,
      .intro-text {
        font-size: 17px;
      }

      .answer {
        min-height: 74px;
        padding: 16px;
        font-size: 17px;
      }
    }
  </style>
</head>
<body>
  <header class="header">
    <div class="header-inner">
      <div class="brand">Rainbowhub</div>
    </div>
  </header>

  <main class="container">
    <section class="hero">
      <h1 class="title">Dementia Test</h1>
      <p class="subtitle">Discover more about yourself with a scientifically prepared, quick dementia test.</p>
      <div class="cta-stack">
        <button id="startBtn" class="action-btn" type="button">▷ Start Test</button>
        <div class="fine-print">(You need to view a short ad to take the test.)</div>
        <div id="startMessage" class="message"></div>
      </div>
      <div class="hero-meta">
        <div class="hero-meta-item"><span class="hero-meta-icon">◷</span><span>1 Minute</span></div>
        <div class="hero-meta-item"><span class="hero-meta-icon">🧠</span><span>7 Questions</span></div>
      </div>
    </section>

    <section class="features-grid">
      <div class="feature-card">
        <div class="feature-icon">✓</div>
        <div class="feature-title">Fast and Easy</div>
        <div class="feature-text">Complete the test quickly with a clean, simple layout that is easy to follow.</div>
      </div>
      <div class="feature-card">
        <div class="feature-icon">🧠</div>
        <div class="feature-title">Scientific Questions</div>
        <div class="feature-text">Short memory, logic, and reasoning prompts designed to feel structured and clear.</div>
      </div>
      <div class="feature-card">
        <div class="feature-icon">✓</div>
        <div class="feature-title">Instant Results</div>
        <div class="feature-text">Finish the test and unlock your result straight away after the final ad step.</div>
      </div>
    </section>

    <section class="card">
      <div class="quiz-box">
        <section id="start" class="hidden"></section>

        <section id="quiz" class="hidden">
          <div class="quiz-meta">
            <span id="q-count"></span>
            <span>Trending</span>
          </div>
          <div class="progress-wrap"><div class="progress" id="progress"></div></div>
          <div class="question" id="question"></div>
          <div class="answers" id="answers"></div>
        </section>

        <section id="resultsGate" class="hidden">
          <div class="gate-card">
            <div class="gate-title">Test Completed! 🎉</div>
            <div class="gate-text">You successfully completed the test. You must watch a short ad to see your results.</div>
            <button id="resultsBtn" class="action-btn" type="button">Unlock My Results 🔓</button>
            <div id="resultsMessage" class="gate-note"></div>
          </div>
        </section>

        <section id="result" class="hidden">
          <div class="result-card">
            <div class="result-score" id="final"></div>
            <div class="result-title" id="resultTitle"></div>
            <div class="result-text" id="resultText"></div>
            <div class="result-bar-wrap"><div class="result-bar" id="resultBar"></div></div>
            <button class="action-btn" id="playAgainBtn" type="button">Play Again</button>
          </div>
        </section>
      </div>

      <div class="about-box">
        <div class="about-title">About this test</div>
        <div class="about-text">This short quiz is designed for entertainment purposes and includes simple memory, logic, and everyday reasoning questions. It is not a medical assessment. Scores can vary based on focus, fatigue, and how quickly you respond.</div>
      </div>
    </section>
  </main>

  <footer class="footer">
    <div>© 2026 Quiz Lab</div>
    <div style="margin-top:6px;">For entertainment only · Not medical advice</div>
  </footer>

  <script>
    window.googletag = window.googletag || { cmd: [] };

    const START_AD_SLOT = '/22677279144/rewarded';
    const RESULTS_AD_SLOT = '/22677279144/rewarded2';

const quizData = [
  {
    question: 'You are told: "Take the blue folder, then lock the door, then turn off the kitchen light." You pick up the blue folder and lock the door. What should you do next?',
    answers: ['Open the window', 'Turn off the kitchen light', 'Put down the folder', 'Go upstairs'],
    correct: 1
  },
  {
    question: 'Which number comes next in the pattern: 3, 6, 12, 24, ?',
    answers: ['30', '36', '42', '48'],
    correct: 3
  },
  {
    question: 'A man has 3 daughters. Each daughter has 1 brother. How many children does he have in total?',
    answers: ['3', '4', '6', '7'],
    correct: 1
  },
  {
    question: 'You read the following sequence once: PEN, BOOK, CHAIR. Which item was in the middle?',
    answers: ['Pen', 'Book', 'Chair', 'Table'],
    correct: 1
  },
  {
    question: 'Which word does NOT fit the pattern?',
    answers: ['January', 'March', 'Tuesday', 'November'],
    correct: 2
  },
  {
    question: 'If all Bloops are Lazzes, and all Lazzes are Mips, then all Bloops are:',
    answers: ['Definitely Mips', 'Definitely not Mips', 'Only sometimes Mips', 'None of the above'],
    correct: 0
  },
  {
    question: 'Which number comes next: 1, 4, 9, 16, ?',
    answers: ['20', '21', '25', '27'],
    correct: 2
  }
];

    const letters = ['A', 'B', 'C', 'D'];

    const startEl = document.getElementById('start');
    const quizEl = document.getElementById('quiz');
    const resultsGateEl = document.getElementById('resultsGate');
    const resultEl = document.getElementById('result');

    const startBtn = document.getElementById('startBtn');
        const resultsBtn = document.getElementById('resultsBtn');
    const playAgainBtn = document.getElementById('playAgainBtn');

    const startMessageEl = document.getElementById('startMessage');
    const resultsMessageEl = document.getElementById('resultsMessage');

    const qCountEl = document.getElementById('q-count');
    const progressEl = document.getElementById('progress');
    const questionEl = document.getElementById('question');
    const answersEl = document.getElementById('answers');
    const finalEl = document.getElementById('final');
    const resultTitleEl = document.getElementById('resultTitle');
    const resultTextEl = document.getElementById('resultText');
    const resultBarEl = document.getElementById('resultBar');

    let currentQuestion = 0;
    let score = 0;

    let gptInitialized = false;
    let listenersBound = false;
    let currentSlot = null;
    let currentPhase = null;
    let rewardGranted = false;
    let servicesEnabled = false;
    let adRequestTimer = null;

    function updateUrlState(stage = 'start') {
      const params = new URLSearchParams(window.location.search);

      if (stage === 'start') {
        params.delete('stage');
        params.delete('q');
        params.delete('score');
      } else {
        params.set('stage', stage);
        params.set('q', String(currentQuestion));
        params.set('score', String(score));
      }

      const query = params.toString();
      const nextUrl = query ? `${window.location.pathname}?${query}` : window.location.pathname;
      window.history.replaceState({}, '', nextUrl);
    }

    function clearUrlState() {
      updateUrlState('start');
    }

    function getResultData(value) {
      if (value === 7) {
        return {
          title: 'Excellent Result 🎉',
          text: 'You got every question right. Strong memory and reasoning on this short test.',
          bar: 100
        };
      }
      if (value >= 6) {
        return {
          title: 'Very Strong Result 👏',
          text: 'You did very well overall, with only one question catching you out.',
          bar: 85
        };
      }
      if (value >= 4) {
        return {
          title: 'Solid Result 🙂',
          text: 'A good score on this short memory and logic quiz.',
          bar: 65
        };
      }
      if (value >= 2) {
        return {
          title: 'A Few Tricky Ones 😅',
          text: 'Some questions were tougher than they looked. Scores can vary with focus and tiredness.',
          bar: 45
        };
      }
      return {
        title: 'Thanks For Taking The Test',
        text: 'This was only a short entertainment quiz, and scores can vary for many everyday reasons.',
        bar: 25
      };
    }

    function showStart() {
      quizEl.classList.add('hidden');
      resultsGateEl.classList.add('hidden');
      resultEl.classList.add('hidden');
      updateUrlState('start');
    }

    function showQuiz() {
      quizEl.classList.remove('hidden');
      resultsGateEl.classList.add('hidden');
      resultEl.classList.add('hidden');
      updateUrlState('quiz');
    }

    function showResultsGate() {
      quizEl.classList.add('hidden');
      resultsGateEl.classList.remove('hidden');
      resultEl.classList.add('hidden');
      updateUrlState('gate');
    }

    function showResults() {
      quizEl.classList.add('hidden');
      resultsGateEl.classList.add('hidden');
      resultEl.classList.remove('hidden');

      finalEl.textContent = `${score}/7`;
      const result = getResultData(score);
      resultTitleEl.textContent = result.title;
      resultTextEl.textContent = result.text;
      resultBarEl.style.width = `${result.bar}%`;
      updateUrlState('results');
    }

    function restoreStartButtons() {
      [startBtn].forEach((btn) => {
        btn.disabled = false;
        if (btn.dataset.originalText) btn.textContent = btn.dataset.originalText;
      });
    }

    function restoreResultsButton() {
      resultsBtn.disabled = false;
      if (resultsBtn.dataset.originalText) {
        resultsBtn.textContent = resultsBtn.dataset.originalText;
      }
    }

    function showStartMessage(message = '') {
      startMessageEl.textContent = message;
    }

    function showResultsMessage(message = '') {
      resultsMessageEl.textContent = message;
    }

    function clearCurrentSlot() {
      clearTimeout(adRequestTimer);
      adRequestTimer = null;
      if (currentSlot) {
        try {
          googletag.destroySlots([currentSlot]);
        } catch {
          // ignore cleanup errors
        }
      }
      currentSlot = null;
      currentPhase = null;
      rewardGranted = false;
    }

    function setButtonLoading(button, label) {
      if (!button.dataset.originalText) {
        button.dataset.originalText = button.textContent;
      }
      button.disabled = true;
      button.textContent = label;
    }

    function setStartButtonsLoading(label) {
      setButtonLoading(startBtn, label);
    }

    function renderQuestion() {
      if (currentQuestion >= quizData.length) {
        showResultsGate();
        return;
      }

      showQuiz();
      const item = quizData[currentQuestion];
      qCountEl.textContent = `Question ${currentQuestion + 1}/7`;
      progressEl.style.width = `${(currentQuestion / quizData.length) * 100}%`;
      questionEl.textContent = item.question;
      answersEl.innerHTML = '';

      item.answers.forEach((answer, index) => {
        const button = document.createElement('button');
        button.type = 'button';
        button.className = 'answer';
        button.innerHTML = `<span class="letter">${letters[index]}</span><span>${answer}</span>`;
        button.addEventListener('click', () => {
          if (index === item.correct) score += 1;
          currentQuestion += 1;
          updateUrlState(currentQuestion >= quizData.length ? 'gate' : 'quiz');
          renderQuestion();
        });
        answersEl.appendChild(button);
      });

      updateUrlState('quiz');
    }

    function startQuiz() {
      currentQuestion = 0;
      score = 0;
      resultBarEl.style.width = '0%';
      showStartMessage('');
      showResultsMessage('');
      updateUrlState('quiz');
      renderQuestion();
      window.scrollTo({ top: quizEl.offsetTop - 12, behavior: 'smooth' });
    }

    function resetQuiz() {
      restoreStartButtons();
      restoreResultsButton();
      showStartMessage('');
      showResultsMessage('');
      clearCurrentSlot();
      currentQuestion = 0;
      score = 0;
      resultBarEl.style.width = '0%';
      clearUrlState();
      showStart();
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }

    function restoreFromUrl() {
      const params = new URLSearchParams(window.location.search);
      const stage = params.get('stage');
      const qParam = parseInt(params.get('q'), 10);
      const scoreParam = parseInt(params.get('score'), 10);

      currentQuestion = Number.isNaN(qParam) ? 0 : Math.max(0, Math.min(quizData.length, qParam));
      score = Number.isNaN(scoreParam) ? 0 : Math.max(0, Math.min(quizData.length, scoreParam));

      if (stage === 'results') {
        if (currentQuestion < quizData.length) currentQuestion = quizData.length;
        showResults();
        return;
      }

      if (stage === 'gate') {
        if (currentQuestion < quizData.length) currentQuestion = quizData.length;
        showResultsGate();
        return;
      }

      if (stage === 'quiz') {
        if (currentQuestion >= quizData.length) {
          showResultsGate();
        } else {
          renderQuestion();
        }
        return;
      }

      currentQuestion = 0;
      score = 0;
      showStart();
    }

    function handleAdGrant() {
      const phase = currentPhase;
      if (phase === 'start') {
      

        restoreStartButtons();
        showStartMessage('');
        clearCurrentSlot();
        startQuiz();
      } else if (phase === 'results') {
        restoreResultsButton();
        showResultsMessage('');
        clearCurrentSlot();
        showResults();
      }
    }

    function handleAdNoFillOrFailure() {
      handleAdGrant();
    }

    function handleAdClosedEarly() {
      const phase = currentPhase;
      if (phase === 'start') {
        restoreStartButtons();
        showStartMessage('You need to watch the ad to take the test. Please tap Start Test again.');
      } else if (phase === 'results') {
        restoreResultsButton();
        showResultsMessage('You need to watch the ad to see your results. Please tap again.');
      }
      clearCurrentSlot();
    }

    function ensureGptSetup() {
      if (gptInitialized) return;
      gptInitialized = true;

      googletag.cmd.push(() => {
        if (!servicesEnabled) {
          googletag.enableServices();
          servicesEnabled = true;
        }

        if (listenersBound) return;
        listenersBound = true;

        const pubads = googletag.pubads();

        pubads.addEventListener('rewardedSlotReady', (event) => {
          if (!currentSlot || event.slot !== currentSlot) return;
          clearTimeout(adRequestTimer);
          adRequestTimer = null;
          try {
            const shown = event.makeRewardedVisible();
            if (shown === false) handleAdNoFillOrFailure();
          } catch {
            handleAdNoFillOrFailure();
          }
        });

        pubads.addEventListener('rewardedSlotGranted', (event) => {
          if (!currentSlot || event.slot !== currentSlot) return;
          rewardGranted = true;
     fbq('trackCustom', 'QuizStart');
    console.log("Reward");
        });

        pubads.addEventListener('rewardedSlotClosed', (event) => {
          if (!currentSlot || event.slot !== currentSlot) return;
          if (rewardGranted) handleAdGrant();
          else handleAdClosedEarly();
        });

        pubads.addEventListener('slotRenderEnded', (event) => {
          if (!currentSlot || event.slot !== currentSlot) return;
          if (event.isEmpty) handleAdNoFillOrFailure();
        });
      });
    }

    function requestRewardedAd(phase) {
      ensureGptSetup();
      currentPhase = phase;
      rewardGranted = false;

      if (phase === 'start') {
        showStartMessage('');
        setStartButtonsLoading('Loading Ad…');
      } else {
        showResultsMessage('');
        setButtonLoading(resultsBtn, 'Loading Ad…');
      }

      googletag.cmd.push(() => {
        clearCurrentSlot();
        currentPhase = phase;
        rewardGranted = false;

        const slotPath = phase === 'start' ? START_AD_SLOT : RESULTS_AD_SLOT;
        const slot = googletag.defineOutOfPageSlot(slotPath, googletag.enums.OutOfPageFormat.REWARDED);

        if (!slot) {
          handleAdNoFillOrFailure();
          return;
        }

        currentSlot = slot;
        slot.addService(googletag.pubads());

        adRequestTimer = setTimeout(() => {
          if (currentSlot === slot && !rewardGranted) handleAdNoFillOrFailure();
        }, 5000);

        try {
          googletag.display(slot);
        } catch {
          handleAdNoFillOrFailure();
        }
      });
    }

    function runSelfTests() {
      const params = new URLSearchParams();
      params.set('score', '5');
      console.assert(params.get('score') === '5', 'Score should persist in URL');
      params.set('stage', 'quiz');
      params.set('q', '3');
      console.assert(params.get('stage') === 'quiz', 'Stage should persist in URL');
      console.assert(params.get('q') === '3', 'Question index should persist in URL');
      console.assert(Array.isArray(quizData) && quizData.length === 7, 'Quiz should contain 7 questions');
      console.assert(getResultData(7).bar === 100, 'Perfect score should map to 100%');
      console.assert(getResultData(0).bar === 25, 'Low score should map to 25%');
      console.assert(typeof requestRewardedAd === 'function', 'requestRewardedAd should exist');
      console.assert(typeof showResultsGate === 'function', 'Results gate should exist');
      console.assert(typeof handleAdClosedEarly === 'function', 'Early close handler should exist');
      console.assert(typeof handleAdNoFillOrFailure === 'function', 'No-fill/failure handler should exist');
    }

    startBtn.addEventListener('click', () => requestRewardedAd('start'));
        resultsBtn.addEventListener('click', () => requestRewardedAd('results'));
    playAgainBtn.addEventListener('click', resetQuiz);

    runSelfTests();
    restoreFromUrl();
  </script>
</body>
</html>
