/** Shopify CDN: Minification failed

Line 11:0 Unexpected "("

**/
/* =============================================================
   My Klick Shop — Animations & Interactions
   Emil design-eng philosophy: unseen details that compound
   ============================================================= */

(function () {
  'use strict';

  /* ── SCROLL FADE-UP ──────────────────────────────────────── */
  function initScrollAnimations(root) {
    root = root || document;
    var targets = root.querySelectorAll('.mks-fade-up, .mks-fade-in');
    if (!targets.length) return;

    var io = new IntersectionObserver(function (entries) {
      entries.forEach(function (entry) {
        if (entry.isIntersecting) {
          entry.target.classList.add('is-visible');
          io.unobserve(entry.target);
        }
      });
    }, {
      threshold: 0.06,
      rootMargin: '0px 0px -32px 0px'
    });

    targets.forEach(function (el) { io.observe(el); });
  }

  /* ── STAGGER: marca hijos de .mks-stagger con mks-fade-up ── */
  function initStagger(root) {
    root = root || document;
    root.querySelectorAll('.mks-stagger').forEach(function (group) {
      Array.from(group.children).forEach(function (child) {
        child.classList.add('mks-fade-up');
      });
    });
  }

  /* ── STICKY ATC MOBILE ───────────────────────────────────── */
  function initStickyAtc() {
    document.querySelectorAll('[data-sticky-atc]').forEach(function (bar) {
      var targetId = bar.dataset.stickyAtc;
      var trigger  = document.getElementById(targetId);
      if (!trigger) return;

      var io = new IntersectionObserver(function (entries) {
        entries.forEach(function (entry) {
          bar.classList.toggle('mks-sticky-atc--visible', !entry.isIntersecting);
        });
      }, { threshold: 0 });

      io.observe(trigger);
    });
  }

  /* ── BUTTON RIPPLE (Emil: feedback visual al presionar) ───── */
  function initButtonRipple(root) {
    root = root || document;
    root.querySelectorAll('.mks-btn--cod, .mks-btn--primary').forEach(function (btn) {
      btn.addEventListener('pointerdown', function (e) {
        var rect   = this.getBoundingClientRect();
        var x      = e.clientX - rect.left;
        var y      = e.clientY - rect.top;
        var ripple = document.createElement('span');
        var size   = Math.max(rect.width, rect.height) * 2.2;

        Object.assign(ripple.style, {
          position:     'absolute',
          width:        size + 'px',
          height:       size + 'px',
          left:         (x - size / 2) + 'px',
          top:          (y - size / 2) + 'px',
          background:   'rgba(255,255,255,0.14)',
          borderRadius: '50%',
          transform:    'scale(0)',
          pointerEvents:'none',
          transition:   'transform 480ms cubic-bezier(0.23,1,0.32,1), opacity 280ms ease',
        });

        this.appendChild(ripple);
        requestAnimationFrame(function () {
          ripple.style.transform = 'scale(1)';
          ripple.style.opacity   = '0';
        });
        setTimeout(function () { if (ripple.parentNode) ripple.remove(); }, 600);
      });
    });
  }

  /* ── TOOLTIP: instant en hover subsiguiente (Emil) ───────── */
  function initInstantTooltips() {
    var open = false;
    document.querySelectorAll('[data-mks-tooltip]').forEach(function (el) {
      el.addEventListener('mouseenter', function () {
        if (open) this.setAttribute('data-instant', '');
        open = true;
      });
      el.addEventListener('mouseleave', function () {
        this.removeAttribute('data-instant');
        open = false;
      });
    });
  }

  /* ── ANNOUNCEMENT BAR: rotación de mensajes ──────────────── */
  function initAnnouncementBars(root) {
    root = root || document;
    root.querySelectorAll('.mks-announcement[data-rotate="true"]').forEach(function (bar) {
      var items    = bar.querySelectorAll('.mks-announcement__item');
      if (items.length <= 1) return;
      var current  = 0;
      var interval = parseInt(bar.dataset.interval || '4000', 10);

      setInterval(function () {
        items[current].classList.remove('is-active');
        items[current].classList.add('is-exiting');
        var prev = current;
        setTimeout(function () { items[prev].classList.remove('is-exiting'); }, 400);
        current = (current + 1) % items.length;
        items[current].classList.add('is-active');
      }, interval);
    });
  }

  /* ── PRODUCT GALLERY: thumbnail switcher ─────────────────── */
  function initProductGallery(root) {
    root = root || document;
    root.querySelectorAll('.mks-gallery').forEach(function (gallery) {
      var main   = gallery.querySelector('.mks-gallery__main-img');
      var thumbs = gallery.querySelectorAll('.mks-gallery__thumb');
      if (!main || !thumbs.length) return;

      thumbs.forEach(function (thumb) {
        thumb.addEventListener('click', function () {
          var src    = this.dataset.full || this.querySelector('img').src;
          var srcset = this.dataset.srcset || '';

          main.style.opacity = '0';
          main.style.transform = 'scale(0.98)';
          setTimeout(function () {
            main.src = src;
            if (srcset) main.srcset = srcset;
            main.style.opacity   = '1';
            main.style.transform = 'scale(1)';
          }, 160);

          thumbs.forEach(function (t) { t.classList.remove('is-active'); });
          this.classList.add('is-active');
        });
      });
    });
  }

  /* ── VARIANT SELECTOR: actualiza datos del botón COD ─────── */
  function initVariantSelects(root) {
    root = root || document;
    root.querySelectorAll('[data-variant-select]').forEach(function (select) {
      var form = select.closest('[data-product-form]');
      if (!form) return;

      select.addEventListener('change', function () {
        var variantId    = this.value;
        var variantTitle = this.options[this.selectedIndex].text;
        var variantPrice = this.options[this.selectedIndex].dataset.price || '';

        form.querySelectorAll('.mks-cod-trigger').forEach(function (btn) {
          btn.dataset.variantId    = variantId;
          btn.dataset.variantTitle = variantTitle;
          if (variantPrice) btn.dataset.variantPrice = variantPrice;
        });

        /* También actualiza sticky ATC */
        var stickyBtn = document.querySelector('[data-sticky-for="' + form.id + '"] .mks-cod-trigger');
        if (stickyBtn) {
          stickyBtn.dataset.variantId    = variantId;
          stickyBtn.dataset.variantTitle = variantTitle;
        }
      });
    });
  }

  /* ── PRICE DISPLAY: formatea precios Shopify ─────────────── */
  function formatMoney(cents, format) {
    var value = (cents / 100).toFixed(2);
    return (format || 'S/. {{amount}}').replace('{{amount}}', value);
  }
  window.MKS = window.MKS || {};
  window.MKS.formatMoney = formatMoney;

  /* ── COD BUTTON: tracking de clic ────────────────────────── */
  function initCodTracking() {
    document.addEventListener('click', function (e) {
      var btn = e.target.closest('.mks-cod-trigger');
      if (!btn) return;

      /* Dispara evento personalizado — Realistiq u otras apps pueden escucharlo */
      var detail = {
        productId:    btn.dataset.productId,
        variantId:    btn.dataset.variantId,
        productTitle: btn.dataset.productTitle,
        variantPrice: btn.dataset.variantPrice,
      };
      document.dispatchEvent(new CustomEvent('mks:cod-click', { detail: detail, bubbles: true }));

      /* Feedback visual inmediato — loading state breve */
      var label = btn.querySelector('.mks-btn__label');
      if (label && !btn.dataset.loading) {
        var original = label.textContent;
        btn.dataset.loading = '1';
        label.style.opacity = '0.6';
        setTimeout(function () {
          label.style.opacity = '';
          delete btn.dataset.loading;
        }, 1200);
      }
    });
  }

  /* ── INIT ────────────────────────────────────────────────── */
  function init(root) {
    initStagger(root);
    initScrollAnimations(root);
    initButtonRipple(root);
    initAnnouncementBars(root);
    initProductGallery(root);
    initVariantSelects(root);
  }

  function initGlobal() {
    init(document);
    initStickyAtc();
    initInstantTooltips();
    initCodTracking();
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initGlobal);
  } else {
    initGlobal();
  }

  /* Shopify Theme Editor: re-init en cada cambio de sección */
  document.addEventListener('shopify:section:load', function (e) {
    init(e.target);
    initStickyAtc();
  });

  /* API pública */
  window.MKS.init                = init;
  window.MKS.initScrollAnimations = initScrollAnimations;
  window.MKS.initProductGallery  = initProductGallery;
  window.MKS.initStickyAtc       = initStickyAtc;
})();
