(() => {
  'use strict';

  /* =========================
     0) Zentrale Ergebnisstruktur (für spätere Auswertung)
     ========================= */


window.PRICEFUCHS_RESULTS = window.PRICEFUCHS_RESULTS || {
  quizzes: {}
};

function saveQuizResult(taskKey, payload) {
  window.PRICEFUCHS_RESULTS.quizzes[taskKey] = {
    ...payload,
    timestamp: new Date().toISOString()
  };
}


  /* =========================
     1) Navigation: Start -> Info
     ========================= */
  document.addEventListener('DOMContentLoaded', () => {
    const btnStart = document.getElementById('btnStart');
    const screenStart = document.getElementById('screen-start');
    const screenInfo = document.getElementById('screen-info');
    const stage = document.querySelector('main.stage');

    if (!btnStart || !screenStart || !screenInfo) return;

    btnStart.addEventListener('click', () => {
      screenStart.classList.add('d-none');
      screenInfo.classList.remove('d-none');

      // Stage: wir sind im Shop-Screen
      if (stage) stage.classList.add('shop');

      // Optional: Stage-Background aktualisieren (Crossfade)
      if (typeof window.updateStageBackground === 'function') {
        window.updateStageBackground();
      }

      // Safety: falls irgendwo schon ein Backdrop rumhängt (z.B. durch Testläufe)
      document.querySelectorAll('.modal-backdrop').forEach(b => b.remove());
      document.body.classList.remove('modal-open');
      document.body.style.removeProperty('padding-right');

      // Intro-Modal erst nach dem Einblenden öffnen
      requestAnimationFrame(() => {
        if (typeof window.showScreenInfoIntroModal === 'function') {
          window.showScreenInfoIntroModal();
        } else {
          const introModalEl = document.getElementById('task1IntroModal');
          if (introModalEl && window.bootstrap?.Modal) {
            new bootstrap.Modal(introModalEl, { backdrop: 'static', keyboard: false }).show();
          }
        }
      });
    });
  });

  /* =========================
     2) Task 1: Dynamic Pricing + Found Counter + Next Button + Quiz
     ========================= */
  const screenInfo = document.getElementById('screen-info');
  if (!screenInfo) return;

  // WICHTIG: data-task1-root sollte auf einem gemeinsamen Container liegen,
  // der Shop + Widgets + Taskbar enthält.
  const root = screenInfo.querySelector('[data-task1-root]') || screenInfo;

  const stage = document.querySelector('main.stage');

  // --- Konfiguration ---
  const products = [
    { name: 'AeroStep Classic', basePrice: 49.90 },
    { name: 'MetroRunner Pro', basePrice: 69.95 },
    { name: 'Nimbus Street',   basePrice: 120.00 },
  ];

  const weatherStates = [
    { key: 'sunny', label: '☀️ Sonnig',           priceMultiplier: 1.00 },
    { key: 'rain',  label: '🌧️ Stark regnerisch', priceMultiplier: 1.15 },
  ];

  const timeSlots = [
    { key: 'morning', label: '08:15', multiplier: 1.00 },
    { key: 'noon',    label: '12:30', multiplier: 1.08 },
    { key: 'evening', label: '18:45', multiplier: 1.18 },
    { key: 'late',    label: '22:10', multiplier: 1.25 },
  ];

  const dayMultipliers = {
    1: 1.00, // Mo
    2: 0.99, // Di
    3: 1.01, // Mi
    4: 1.00, // Do
    5: 1.02, // Fr
    6: 1.20, // Sa
    0: 1.25, // So
  };

  const timeClassMap = {
    morning: 'morgens',
    noon: 'mittags',
    evening: 'abends',
    late: 'nachts',
  };

  const currencyFormatter = new Intl.NumberFormat('de-DE', {
    style: 'currency',
    currency: 'EUR'
  });

  const DEFAULT_WEATHER_INDEX = 0;
  const DEFAULT_TIME_INDEX = 0;
  const DEFAULT_DAY_OFFSET = 0;

  // --- State ---
  let weatherIndex = DEFAULT_WEATHER_INDEX;
  let timeIndex = DEFAULT_TIME_INDEX;
  const baseDate = new Date();
  let dayOffset = DEFAULT_DAY_OFFSET;

  let activeFactor = 'none'; // 'weather'|'time'|'date'|'none'
  const found = { weather: false, date: false, time: false };

  // --- Elements ---
  const weatherLabelEls = [...root.querySelectorAll('[data-task1-weather-label]')];
  const dateLabelEls    = [...root.querySelectorAll('[data-task1-date-label]')];
  const timeLabelEls    = [...root.querySelectorAll('[data-task1-time-label]')];
  const statusEl = root.querySelector('[data-task1-status]'); // optional

  const foundCountEl = root.querySelector('[data-task1-found-count]');
  const nextBtnEl = root.querySelector('[data-task1-next]');

  // Modals (bestehende)
  const introModalEl = document.getElementById('task1IntroModal');
  const emailModalEl = document.getElementById('task1EmailModal');
  const werbungModalEl = document.getElementById('task1Werbung');

  const introModal = introModalEl ? new bootstrap.Modal(introModalEl, { backdrop: 'static', keyboard: false }) : null;
  const emailModal = emailModalEl ? new bootstrap.Modal(emailModalEl) : null;
  const werbungModal = werbungModalEl ? new bootstrap.Modal(werbungModalEl) : null;

  // Quiz Modal (neu)
  const quizModalEl = document.getElementById('task1QuizModal');
  const quizModal = quizModalEl ? new bootstrap.Modal(quizModalEl, { backdrop: 'static', keyboard: false }) : null;

//   const quizForm = document.getElementById('task1QuizForm');
//   const quizSubmitBtn = document.getElementById('task1QuizSubmit');
//   const quizCloseBtn = document.getElementById('task1QuizClose');
//   const quizTryEl = document.getElementById('task1QuizTry');
//   const quizFeedbackEl = document.getElementById('task1QuizFeedback');

  // A11y: Fokus nach Intro-Modal schließen sinnvoll setzen
  if (introModalEl) {
    introModalEl.addEventListener('hidden.bs.modal', () => {
      const firstWidget = document.querySelector('#screen-info [data-task1-action]');
      if (firstWidget) firstWidget.focus();
    });
  }

  /* =========================
     Helpers
     ========================= */
  function getWeather() { return weatherStates[weatherIndex]; }
  function getTimeSlot() { return timeSlots[timeIndex]; }

  function getCurrentDate() {
    const d = new Date(baseDate);
    d.setDate(baseDate.getDate() + dayOffset);
    return d;
  }

  function getDayMultiplier(d) {
    return dayMultipliers[d.getDay()] ?? 1.00;
  }

  function resetWeather() { weatherIndex = DEFAULT_WEATHER_INDEX; }
  function resetTime()    { timeIndex = DEFAULT_TIME_INDEX; }
  function resetDate()    { dayOffset = DEFAULT_DAY_OFFSET; }

  function enforceSingleFactor(nextActive) {
    if (nextActive !== 'weather') resetWeather();
    if (nextActive !== 'time')    resetTime();
    if (nextActive !== 'date')    resetDate();
    activeFactor = nextActive;
  }

  function syncWeatherClass() {
    if (!stage) return;
    stage.classList.toggle('regen', getWeather().key === 'rain');
  }

  function syncTimeClass() {
    if (!stage) return;
    ['morgens', 'mittags', 'abends', 'nachts'].forEach(c => stage.classList.remove(c));
    const cls = timeClassMap[getTimeSlot().key];
    if (cls) stage.classList.add(cls);
  }

  function renderWeather() {
    const txt = getWeather().label;
    weatherLabelEls.forEach(el => { if (el) el.textContent = txt; });
  }

  function renderTime() {
    const txt = getTimeSlot().label;
    timeLabelEls.forEach(el => { if (el) el.textContent = txt; });
  }

  function renderDate() {
    const d = getCurrentDate();
    const txt = d.toLocaleDateString('de-DE', {
      weekday: 'short', day: '2-digit', month: '2-digit', year: 'numeric'
    });
    dateLabelEls.forEach(el => { if (el) el.textContent = txt; });
  }

  function updateFoundUI() {
    const count = (found.weather ? 1 : 0) + (found.date ? 1 : 0) + (found.time ? 1 : 0);
    if (foundCountEl) foundCountEl.textContent = String(count);
    if (nextBtnEl) nextBtnEl.classList.toggle('d-none', count < 3);
  }

  function recalcPrices() {
    const wMul = getWeather().priceMultiplier;
    const tMul = getTimeSlot().multiplier;
    const d = getCurrentDate();
    const dMul = getDayMultiplier(d);

    const finalMul = wMul * tMul * dMul;

    products.forEach((p, i) => {
      const price = p.basePrice * finalMul;
      const el = root.querySelector(`[data-task1-price="${i}"]`);
      if (el) el.textContent = currencyFormatter.format(price);
    });

    if (statusEl) {
      const dayKey = d.getDay();
      const dayName = ['So','Mo','Di','Mi','Do','Fr','Sa'][dayKey];
      statusEl.textContent = `Aktiv: ${activeFactor} • Wetter: ${getWeather().key} • Zeit: ${getTimeSlot().key} • Tag: ${dayName}`;
    }
  }

  function refreshAll() {
    renderWeather();
    renderTime();
    renderDate();
    syncWeatherClass();
    syncTimeClass();
    recalcPrices();
    updateFoundUI();

    if (typeof window.updateStageBackground === 'function') {
      window.updateStageBackground();
    }
  }

  /* =========================
     Actions (Single-Factor)
     ========================= */
  function onWeatherClick() {
    found.weather = true;
    enforceSingleFactor('weather');
    weatherIndex = (weatherIndex + 1) % weatherStates.length;
    refreshAll();
  }

  function onTimeClick() {
    found.time = true;
    enforceSingleFactor('time');
    timeIndex = (timeIndex + 1) % timeSlots.length;
    refreshAll();
  }

  function onDateClick() {
    found.date = true;
    enforceSingleFactor('date');
    dayOffset = (dayOffset + 1) % 7;
    refreshAll();
  }

 /* =========================
   Quiz: Button-Answers (2 Versuche)
   ========================= */
const TASK_KEY = 'task1';
const CORRECT_VALUE = 'd'; // Dynamic Pricing

let quizAttemptsUsed = 0;
const quizAnswers = [];
let quizLocked = false;

// Elemente (angepasst: quizForm ist jetzt ein DIV)
const quizForm = document.getElementById('task1QuizForm');
const quizSubmitBtn = document.getElementById('task1QuizSubmit');
const quizNextBtn = document.getElementById('task1QuizNext');
const quizCloseBtn = document.getElementById('task1QuizClose');
const quizTryEl = document.getElementById('task1QuizTry');
const quizFeedbackEl = document.getElementById('task1QuizFeedback');

function quizOptions() {
  return quizForm ? [...quizForm.querySelectorAll('.quiz-option[data-quiz-value]')] : [];
}

function quizClearOptionStyles() {
  quizOptions().forEach(btn => {
    btn.classList.remove('active', 'btn-success', 'btn-danger', 'btn-outline-secondary');
    // zurück auf neutral
    btn.classList.add('btn-outline-secondary');
    btn.setAttribute('aria-pressed', 'false');
    btn.disabled = false;
  });
}

function quizSetActive(value) {
  quizOptions().forEach(btn => {
    const isThis = btn.getAttribute('data-quiz-value') === value;
    btn.classList.toggle('active', isThis);
    btn.setAttribute('aria-pressed', isThis ? 'true' : 'false');
  });
}

function quizGetSelected() {
  const activeBtn = quizForm?.querySelector('.quiz-option.active');
  return activeBtn ? activeBtn.getAttribute('data-quiz-value') : null;
}

function quizShowFeedback(html) {
  if (quizFeedbackEl) quizFeedbackEl.innerHTML = html;
}

function quizResetUI() {
  quizAttemptsUsed = 0;
  quizAnswers.length = 0;
  quizLocked = false;

  if (quizTryEl) quizTryEl.textContent = '1';
  quizShowFeedback('');
  quizClearOptionStyles();

  if (quizCloseBtn) quizCloseBtn.classList.add('d-none');
 if (quizSubmitBtn) {
  quizSubmitBtn.disabled = false;
  quizSubmitBtn.classList.remove('d-none');     // <- wichtig
  quizSubmitBtn.textContent = 'Antwort prüfen';
}

if (quizNextBtn) quizNextBtn.classList.add('d-none');
}

function quizLock() {
  quizLocked = true;

  // Submit weg
  if (quizSubmitBtn) {
    quizSubmitBtn.disabled = true;
    quizSubmitBtn.classList.add('d-none');
  }

  // Next rein
  if (quizNextBtn) quizNextBtn.classList.remove('d-none');

  // Antworten sperren
  quizOptions().forEach(btn => (btn.disabled = true));
}


function quizMarkResult(selectedValue, isCorrect) {
  const selectedBtn = quizForm?.querySelector(`.quiz-option[data-quiz-value="${selectedValue}"]`);
  if (!selectedBtn) return;

  // Neutral-Klasse weg
  selectedBtn.classList.remove('btn-outline-secondary');

  // Falsch => rot, Richtig => grün
  selectedBtn.classList.add(isCorrect ? 'btn-success' : 'btn-danger');
}

function quizMarkCorrectAnswer() {
  const correctBtn = quizForm?.querySelector(`.quiz-option[data-quiz-value="${CORRECT_VALUE}"]`);
  if (!correctBtn) return;

  correctBtn.classList.remove('btn-outline-secondary', 'btn-danger');
  correctBtn.classList.add('btn-success');
}

function quizSubmit() {
  if (quizLocked) return;

  const selected = quizGetSelected();
  if (!selected) {
    quizShowFeedback(`<div class="alert alert-warning mb-0">Bitte wähle eine Antwort aus.</div>`);
    return;
  }

  quizAttemptsUsed += 1;
  quizAnswers.push(selected);

  const isCorrect = (selected === CORRECT_VALUE);

  // Markiere Auswahl
  quizMarkResult(selected, isCorrect);

  if (isCorrect) {
    saveQuizResult(TASK_KEY, {
      correct: true,
      correctAttempt: quizAttemptsUsed,
      attemptsUsed: quizAttemptsUsed,
      answers: [...quizAnswers]
    });

    quizShowFeedback(`<div class="alert alert-success mb-0"><strong>Richtig!</strong> Die Preise bilden sich entsprechend der aktuellen Nachfrage und diese hängt ab z. B. vom Wochentag, dem Wetter oder der Tageszeit.
</div>`);
    quizLock();
    return;
  }

  // Falsch
  if (quizAttemptsUsed < 2) {
    if (quizTryEl) quizTryEl.textContent = '2';
    quizShowFeedback(`<div class="alert alert-danger mb-0"><strong>Leider falsch.</strong> Du hast noch einen zweiten Versuch.</div>`);
    return;
  }

  // 2. Versuch auch falsch: richtige Antwort zeigen
  saveQuizResult(TASK_KEY, {
    correct: false,
    correctAttempt: 0,
    attemptsUsed: 2,
    answers: [...quizAnswers]
  });

  quizMarkCorrectAnswer();
  quizShowFeedback(
    `<div class="alert alert-danger mb-2"><strong>Leider wieder falsch.</strong></div>
     <div class="alert alert-info mb-0">Die richtige Antwort ist: <strong>Dynamic Pricing</strong>. Die Preise bilden sich entsprechend der aktuellen Nachfrage und diese hängt ab z. B. vom Wochentag, dem Wetter oder der Tageszeit.</div>`
  );
  quizLock();
}

function openQuizModal() {
  if (!quizModal) return;
  quizResetUI();
  quizModal.show();

  // Fokus auf erste Option
  requestAnimationFrame(() => {
    const first = quizForm?.querySelector('.quiz-option');
    if (first) first.focus();
  });
}

/* Klick auf Antwort-Buttons: Active setzen (wechselbar bis zur Prüfung) */
if (quizForm) {
  quizForm.addEventListener('click', (e) => {
    const btn = e.target.closest('.quiz-option[data-quiz-value]');
    if (!btn || quizLocked) return;
    quizSetActive(btn.getAttribute('data-quiz-value'));
  });
}

if (quizSubmitBtn) {
  quizSubmitBtn.addEventListener('click', quizSubmit);
  
}
if (quizNextBtn) {
quizNextBtn.addEventListener('click', () => {

  if (quizModal) quizModal.hide();

  const screenInfoEl = document.getElementById('screen-info');
  const screenStreichpreise = document.getElementById('screen-streichpreise');
  const task2ModalEl = document.getElementById('task2IntroModal');

  if (screenInfoEl) screenInfoEl.classList.add('d-none');
  if (screenStreichpreise) screenStreichpreise.classList.remove('d-none');

  /* Backdrop-Safety (wichtig bei schnellem Modalwechsel) */
  document.querySelectorAll('.modal-backdrop').forEach(b => b.remove());
  document.body.classList.remove('modal-open');
  document.body.style.removeProperty('padding-right');

  /* Background neu berechnen */
  if (typeof window.updateStageBackground === 'function') {
    window.updateStageBackground();
  }

  /* Intro-Modal Task 2 öffnen (mit sauberem Timing) */
  if (task2ModalEl && window.bootstrap?.Modal) {
    requestAnimationFrame(() => {
      new bootstrap.Modal(task2ModalEl, {
        backdrop: 'static',
        keyboard: false
      }).show();
    });
  }
});

}

  /* =========================
     Next: öffnet Quiz statt Screenwechsel
     ========================= */
  function goNext() {
    const count = (found.weather ? 1 : 0) + (found.date ? 1 : 0) + (found.time ? 1 : 0);
    if (count < 3) return;

    openQuizModal();
  }

  /* =========================
     Events (delegiert)
     ========================= */
  root.addEventListener('click', (e) => {
    // Next button in taskbar
    const nextBtn = e.target.closest('[data-task1-next]');
    if (nextBtn) return goNext();

    const btn = e.target.closest('[data-task1-action]');
    if (!btn) return;

    const action = btn.getAttribute('data-task1-action');

    if (action === 'weather') return onWeatherClick();
    if (action === 'time')    return onTimeClick();
    if (action === 'date')    return onDateClick();

    if (action === 'email') {
      enforceSingleFactor('none');
      refreshAll();
      if (emailModal) emailModal.show();
      return;
    }

    if (action === 'werbung') {
      enforceSingleFactor('none');
      refreshAll();
      if (werbungModal) werbungModal.show();
      return;
    }
  });

  // Init
  enforceSingleFactor('none');
  refreshAll();

  // Intro-Modal wird durch Navigation geöffnet
  window.showScreenInfoIntroModal = () => {
    if (introModal) introModal.show();
  };
})();
/* =========================
   Task 2 Quiz: Referenzpreise (Ankerpreise)
   Öffnet beim Klick auf einen Sneaker in #screen-streichpreise
   2 Versuche, zentrale Speicherung
   ========================= */
(() => {
  const screenTask2 = document.getElementById('screen-streichpreise');
  if (!screenTask2) return;

  const quizModalEl = document.getElementById('task2QuizModal');
  if (!quizModalEl || !window.bootstrap?.Modal) return;

  const quizModal = new bootstrap.Modal(quizModalEl, { backdrop: 'static', keyboard: false });

  const quizContextEl = document.getElementById('task2QuizContext');
  const quizForm = document.getElementById('task2QuizForm');
  const quizSubmitBtn = document.getElementById('task2QuizSubmit');
  const quizCloseBtn = document.getElementById('task2QuizClose');
  const quizTryEl = document.getElementById('task2QuizTry');
  const quizFeedbackEl = document.getElementById('task2QuizFeedback');

  const TASK_KEY = 'task2';
  const CORRECT_VALUE = 'c';

  const EXPLANATION =
    'Referenzpreise (Ankerpreise) können das Verbraucherverhalten beeinflussen. ' +
    'Wird neben einem reduzierten Preis ein höherer Ankerpreis angezeigt, erscheint das Produkt wertiger ' +
    'und kann Verbraucherinnen und Verbraucher eher zum Kauf anregen.';

  let quizLocked = false;
  let quizAttemptsUsed = 0;
  const quizAnswers = [];
  let lastClickedProductIndex = null;

  function options() {
    return quizForm ? [...quizForm.querySelectorAll('.quiz2-option[data-quiz2-value]')] : [];
  }

  function setActive(value) {
    options().forEach(btn => {
      const isThis = btn.getAttribute('data-quiz2-value') === value;
      btn.classList.toggle('active', isThis);
      btn.setAttribute('aria-pressed', isThis ? 'true' : 'false');
    });
  }

  function getSelected() {
    const activeBtn = quizForm?.querySelector('.quiz2-option.active');
    return activeBtn ? activeBtn.getAttribute('data-quiz2-value') : null;
  }

  function showFeedback(html) {
    if (quizFeedbackEl) quizFeedbackEl.innerHTML = html;
  }

  function clearStyles() {
    options().forEach(btn => {
      btn.classList.remove('active', 'btn-success', 'btn-danger', 'btn-outline-secondary');
      btn.classList.add('btn-outline-secondary');
      btn.setAttribute('aria-pressed', 'false');
      btn.disabled = false;
    });
  }

  function markResult(selected, isCorrect) {
    const btn = quizForm?.querySelector(`.quiz2-option[data-quiz2-value="${selected}"]`);
    if (!btn) return;
    btn.classList.remove('btn-outline-secondary');
    btn.classList.add(isCorrect ? 'btn-success' : 'btn-danger');
  }

  function markCorrectAnswer() {
    const btn = quizForm?.querySelector(`.quiz2-option[data-quiz2-value="${CORRECT_VALUE}"]`);
    if (!btn) return;
    btn.classList.remove('btn-outline-secondary', 'btn-danger');
    btn.classList.add('btn-success');
  }

  function lockQuiz() {
    quizLocked = true;

    // Submit ausblenden
    if (quizSubmitBtn) {
      quizSubmitBtn.disabled = true;
      quizSubmitBtn.classList.add('d-none');
    }

    // Close einblenden
    if (quizCloseBtn) quizCloseBtn.classList.remove('d-none');

    // Optionen sperren
    options().forEach(btn => (btn.disabled = true));
  }

  function resetQuiz(contextText) {
    quizLocked = false;
    quizAttemptsUsed = 0;
    quizAnswers.length = 0;

    if (quizTryEl) quizTryEl.textContent = '1';
    if (quizContextEl) quizContextEl.textContent = contextText || '';

    showFeedback('');
    clearStyles();

    if (quizCloseBtn) quizCloseBtn.classList.add('d-none');
    if (quizSubmitBtn) {
      quizSubmitBtn.disabled = false;
      quizSubmitBtn.classList.remove('d-none');
      quizSubmitBtn.textContent = 'Antwort prüfen';
    }
  }

  function submit() {
    if (quizLocked) return;

    const selected = getSelected();
    if (!selected) {
      showFeedback(`<div class="alert alert-warning mb-0">Bitte wähle eine Antwort aus.</div>`);
      return;
    }

    quizAttemptsUsed += 1;
    quizAnswers.push(selected);

    const isCorrect = selected === CORRECT_VALUE;
    markResult(selected, isCorrect);

    if (isCorrect) {
      saveQuizResult(TASK_KEY, {
        correct: true,
        correctAttempt: quizAttemptsUsed,
        attemptsUsed: quizAttemptsUsed,
        answers: [...quizAnswers],
        meta: { productIndex: lastClickedProductIndex }
      });

      showFeedback(
        `<div class="alert alert-success mb-2"><strong>Richtig!</strong></div>
         <div class="alert alert-info mb-0">${EXPLANATION}</div>`
      );
      lockQuiz();
      return;
    }

    // falsch
    if (quizAttemptsUsed < 2) {
      if (quizTryEl) quizTryEl.textContent = '2';
      showFeedback(`<div class="alert alert-danger mb-0"><strong>Leider falsch.</strong> Du hast noch einen zweiten Versuch.</div>`);
      return;
    }

    // 2× falsch
    saveQuizResult(TASK_KEY, {
      correct: false,
      correctAttempt: 0,
      attemptsUsed: 2,
      answers: [...quizAnswers],
      meta: { productIndex: lastClickedProductIndex }
    });

    markCorrectAnswer();
    showFeedback(
      `<div class="alert alert-danger mb-2"><strong>Leider wieder falsch.</strong></div>
       <div class="alert alert-info mb-0">${EXPLANATION}</div>`
    );
    lockQuiz();
  }

  // Klick auf Antwort-Buttons
  if (quizForm) {
    quizForm.addEventListener('click', (e) => {
      const btn = e.target.closest('.quiz2-option[data-quiz2-value]');
      if (!btn || quizLocked) return;
      setActive(btn.getAttribute('data-quiz2-value'));
    });
  }

  if (quizSubmitBtn) quizSubmitBtn.addEventListener('click', submit);

  // Öffnen beim Klick auf Produkt
  screenTask2.addEventListener('click', (e) => {
    const card = e.target.closest('[data-task2-product]');
    if (!card) return;

    const idx = Number(card.getAttribute('data-task2-product'));
    lastClickedProductIndex = Number.isFinite(idx) ? idx : null;

    const isReduced = (idx === 1 || idx === 2);
    const contextText = isReduced
      ? 'Du hast dich für einen reduzierten Sneaker entschieden.'
      : 'Du hast dich für den Sneaker zum regulären Preis entschieden.';

    resetQuiz(contextText);
    quizModal.show();
  });
})();


/* =========================
   Stage Background Crossfade (wiederhergestellt)
   Voraussetzungen:
   - HTML enthält in <main class="stage">:
     <div class="stage-bg" aria-hidden="true">
       <div class="bg-layer bg-a"></div>
       <div class="bg-layer bg-b"></div>
     </div>
   - CSS: stage-bg/layer + opacity nur bei .shop (siehe unten)
   ========================= */
(() => {
  const stage = document.querySelector('main.stage');
  if (!stage) return;

  const layerA = stage.querySelector('.bg-a');
  const layerB = stage.querySelector('.bg-b');
  if (!layerA || !layerB) {
    // Wenn du das HTML noch nicht ergänzt hast, passiert hier nichts.
    return;
  }

  let active = layerA;
  let inactive = layerB;

  // Deine bisherige Bildlogik 1:1
  const BG = {
    shop:    'files/bg0.png',
    regen:   'files/bg4.png',
    morgens: 'files/bg0.png',
    mittags: 'files/bg1.png',
    abends:  'files/bg2.png',
    nachts:  'files/bg3.png',
  };

  const cache = new Set();

  function preload(url) {
    if (!url || cache.has(url)) return Promise.resolve();
    return new Promise((resolve) => {
      const img = new Image();
      img.onload = () => { cache.add(url); resolve(); };
      img.onerror = () => resolve(); // nicht blockieren
      img.src = url;
    });
  }

  function pickBgUrl() {
    // Hintergrund nur im Shop-Modus
    if (!stage.classList.contains('shop')) return null;

    // Regen überschreibt alles
    if (stage.classList.contains('regen')) return BG.regen;

    // Tageszeit
    if (stage.classList.contains('nachts'))  return BG.nachts;
    if (stage.classList.contains('abends'))  return BG.abends;
    if (stage.classList.contains('mittags')) return BG.mittags;
    if (stage.classList.contains('morgens')) return BG.morgens;

    // Default im Shop
    return BG.shop;
  }

  async function setStageBackground() {
    const url = pickBgUrl();

    // Wenn kein Shop: Layer ausblenden/leer
    if (!url) {
      active.classList.remove('is-active');
      inactive.classList.remove('is-active');
      active.style.backgroundImage = '';
      inactive.style.backgroundImage = '';
      return;
    }

    await preload(url);

    inactive.style.backgroundImage = `url("${url}")`;
    inactive.classList.add('is-active');
    active.classList.remove('is-active');

    [active, inactive] = [inactive, active];
  }

  // Initial setzen (falls du direkt im Shop startest oder bei erstem Wechsel)
  (async () => {
    const url = pickBgUrl();
    if (!url) return;
    await preload(url);
    active.style.backgroundImage = `url("${url}")`;
    active.classList.add('is-active');
  })();

  // global verfügbar, damit dein bestehender Code weiter funktioniert
  window.updateStageBackground = setStageBackground;

  // Preload, damit beim ersten Wechsel kein „leerer“ Moment entsteht
  preload(BG.shop);
  preload(BG.regen);
  preload(BG.morgens);
  preload(BG.mittags);
  preload(BG.abends);
  preload(BG.nachts);
})();
