/* Sunny Coin 2 — Khmer single-spin build.
 *
 * Replaces the original bundle.js. Everything analytics-shaped is gone: no GTM,
 * no dataLayer, no aft() fingerprint beacon, no DataDome. One spin lands on the
 * top segment (USD 99), the prize badge appears, then the claim modal opens.
 * The claim button is the only outbound link and it reads window.LANDING_LINK,
 * which the admin backend rewrites in link.js.
 */
(function () {
  'use strict';

  var SPIN_MS = 4000;   // matches the newSpinOnce keyframe in kh.css
  var BADGE_MS = 4000;  // prize badge appears when the wheel stops
  var MODAL_MS = 5200;  // modal follows shortly after

  function targetLink() {
    var l = (window.LANDING_LINK || '').trim();
    return l && l !== '#' ? l : null;
  }

  /* Carry the incoming query string through to the destination so stream/subid
     tracking still works for whoever is buying the traffic. */
  function withQuery(url) {
    var q = window.location.search;
    if (!q || q.length < 2) return url;
    return url + (url.indexOf('?') === -1 ? '?' : '&') + q.slice(1);
  }

  function openModal() {
    document.querySelector('.main__modal').classList.add('main__modal_show');
    document.querySelector('.modal__wrapper').classList.add('modal__wrapper_show');
    document.body.style.overflowY = 'hidden';
  }

  var spun = false;
  function spin() {
    if (spun) return;
    spun = true;

    var layout = document.querySelector('.wheel__layout');
    layout.classList.remove('stage-1');
    layout.classList.add('spin-once');

    setTimeout(function () {
      layout.classList.remove('spin-once');
      layout.classList.add('stage-won');
      document.querySelector('.wheel__achievements-bet').classList.remove('hide');
    }, BADGE_MS);

    setTimeout(openModal, MODAL_MS);
  }

  document.addEventListener('DOMContentLoaded', function () {
    Array.prototype.forEach.call(document.querySelectorAll('.run-circle'), function (el) {
      el.addEventListener('click', spin);
    });

    var btn = document.getElementById('claimBtn');
    var link = targetLink();
    if (link) btn.setAttribute('href', withQuery(link));
    btn.addEventListener('click', function (e) {
      var l = targetLink();
      if (!l) {
        e.preventDefault();
        alert('រង្វាន់មិនទាន់ភ្ជាប់តំណ — សូមកំណត់តំណនៅក្នុងផ្ទាំងគ្រប់គ្រង (admin).');
      }
    });

    /* Parallax on the decor layers, kept from the original build. */
    var box = document.getElementById('parallaxContainer');
    if (!box) return;
    box.addEventListener('mousemove', function (ev) {
      var r = box.getBoundingClientRect();
      var dx = ev.clientX - r.left;
      var items = box.querySelectorAll('.paralax-item');
      for (var i = 0; i < items.length; i++) {
        var shift = (i + 1) * (dx - r.width / 2) / 200;
        items[i].style.transform = window.matchMedia('(orientation: landscape)').matches
          ? 'translate(' + shift + 'px)' : null;
      }
    });
  });
})();
