/* Wheel landing — single spin, fixed USD 30 prize, no registration form.
 *
 * Replaces the original webpack bundle. Differences from the source landing:
 *   - one spin instead of three, and it parks on the USD 30 segment
 *   - the prize dialog has no inputs; its one button goes straight to the offer link
 *   - no GTM / DataDome / fingerprinting, and no landingConfig blob
 *   - the offer link comes from api/link.php (admin-editable) with a config.js fallback
 */
(function () {
  'use strict';

  var LINK_ENDPOINT = 'api/link.php';
  var SPIN_MS = 5400; // must match the spinToPrize animation-duration in khmer.css

  var wheel = document.querySelector('.main__wheel');
  var spinBtn = document.querySelector('.run-circle');
  var titleFirst = document.querySelector('.title__first');
  var titleSecond = document.querySelector('.title__second');
  var titleThird = document.querySelector('.title__third');
  var prizeList = document.querySelector('.lights__content');
  var bonus = document.getElementById('bonus');
  var audio = document.getElementById('audio');
  var preloader = document.querySelector('.preloader');

  /* ---------- offer link ---------------------------------------------------- */

  var currentLink = window.LANDING_LINK || '#';

  // Forward the landing's own query string so affiliate subids survive the hop.
  function withQuery(link) {
    var qs = window.location.search;
    if (!qs || qs.length < 2 || link === '#') return link;
    return link + (link.indexOf('?') === -1 ? '?' : '&') + qs.slice(1);
  }

  function applyLink() {
    var href = withQuery(currentLink);
    var links = document.querySelectorAll('.claim-link');
    for (var i = 0; i < links.length; i++) links[i].href = href;
  }

  applyLink();

  // api/link.php wins when PHP is available; a static deploy keeps config.js's value.
  if (window.fetch) {
    fetch(LINK_ENDPOINT, { cache: 'no-store' })
      .then(function (r) { return r.ok ? r.json() : null; })
      .then(function (data) {
        if (data && data.link) { currentLink = data.link; applyLink(); }
      })
      .catch(function () { /* static hosting — the fallback already applies */ });
  }

  /* ---------- layout ------------------------------------------------------- */

  // Below 900px the design relies on a pixel min-height rather than 100vh, so mobile
  // browser chrome does not push the wheel off screen.
  function sizeViewport() {
    var header = document.querySelector('header');
    var main = document.querySelector('.main');
    if (!header || !main) return;
    if (document.body.clientWidth < 900) {
      var gap = parseFloat(window.getComputedStyle(header).marginBottom) || 0;
      document.body.style.minHeight = window.innerHeight + 'px';
      main.style.minHeight = (window.innerHeight - (header.clientHeight + gap)) + 'px';
    } else {
      document.body.style.minHeight = '100vh';
      main.style.minHeight = '100vh';
    }
  }

  window.addEventListener('resize', sizeViewport);
  sizeViewport();

  window.addEventListener('load', function () {
    if (!preloader) return;
    preloader.classList.add('hide');
    setTimeout(function () { if (preloader.parentNode) preloader.parentNode.removeChild(preloader); }, 600);
  });

  // Autoplay is blocked until the user interacts, so the ambience starts on first click.
  document.body.addEventListener('click', function () {
    if (audio && audio.play) { var p = audio.play(); if (p && p.catch) p.catch(function () {}); }
  }, { once: true });

  /* ---------- prize dialog ------------------------------------------------- */

  function onKeydown(e) {
    if (e.key === 'Escape' || e.keyCode === 27) closeBonus();
  }

  function openBonus() {
    if (!bonus) return;
    bonus.hidden = false;
    // one frame with the element laid out but not yet .is-open, so the transition runs
    requestAnimationFrame(function () {
      bonus.classList.add('is-open');
      var cta = bonus.querySelector('.bonus__cta');
      if (cta) cta.focus();
    });
    document.addEventListener('keydown', onKeydown);
  }

  function closeBonus() {
    if (!bonus || bonus.hidden) return;
    bonus.classList.remove('is-open');
    document.removeEventListener('keydown', onKeydown);
    setTimeout(function () { bonus.hidden = true; }, 350);
  }

  if (bonus) {
    var closers = bonus.querySelectorAll('[data-bonus-close]');
    for (var c = 0; c < closers.length; c++) closers[c].addEventListener('click', closeBonus);
  }

  /* ---------- the spin ----------------------------------------------------- */

  function revealPrizeCards() {
    if (!prizeList) return;
    ['first', 'second', 'third'].forEach(function (key, i) {
      var card = prizeList.querySelector('[key="' + key + '"]');
      if (card) setTimeout(function () { card.classList.add('show'); }, 1200 + i * 1150);
    });
  }

  var PRIZE = 'USD 30';

  function finishSpin() {
    wheel.classList.add('is-done');
    // the hub stops inviting another spin and states the result instead
    if (spinBtn) { spinBtn.textContent = PRIZE; spinBtn.removeAttribute('href'); }
    if (titleFirst) titleFirst.classList.add('hide');
    if (titleSecond) titleSecond.classList.add('show');
    if (titleThird) titleThird.classList.add('show');
    openBonus();
  }

  var spun = false;

  function spin(e) {
    if (e) e.preventDefault();
    if (spun) return;
    spun = true;
    // dropping stage-1 stops the idle shake so the spin animation starts clean
    wheel.classList.remove('stage-1');
    wheel.classList.add('is-spinning');
    revealPrizeCards();
    setTimeout(finishSpin, SPIN_MS);
  }

  if (spinBtn) spinBtn.addEventListener('click', spin);
  if (wheel) wheel.addEventListener('click', spin);
})();
