/** Shopify CDN: Minification failed

Line 15:0 Unexpected "("

**/
/*
  FILE:  assets/stickr-configurator.js
  PASTE: Themes > Edit code > assets > Add new asset (.js)

  Load order — add to layout/theme.liquid just before </body>:
    {{ 'stickerPricing.js'         | asset_url | script_tag }}
    {{ 'stickr-configurator.js'    | asset_url | script_tag }}
*/

(function () {
  'use strict';

  var wrap = document.getElementById('slcConfigurator');
  if (!wrap) return;

  function $  (id)  { return document.getElementById(id); }
  function $$ (sel) { return wrap.querySelectorAll(sel); }

  /* Size */
  var widthInput        = $('slcWidth');
  var heightInput       = $('slcHeight');
  var customSizeRow     = $('slcCustomSizeRow');
  var customSizeToggle  = $('slcCustomSizeToggle');

  /* Qty */
  var customQtyInput    = $('slcCustomQtyInput');
  var customQtyRow      = $('slcCustomQtyRow');
  var customQtyToggle   = $('slcCustomQtyToggle');

  /* Upload */
  var fileInput         = $('slcFile');
  var uploadZone        = $('slcUploadZone');
  var uploadLabel       = $('slcUploadLabel');

  /* Production tiles */
  var proofNoBtn        = $('slcProofNoBtn');
  var proofNoCheck      = $('slcProofNoCheck');
  var proofYesCheck     = $('slcProofYesCheck');

  /* Footer */
  var sfShape           = $('sfShape');
  var sfSize            = $('sfSize');
  var sfFinish          = $('sfFinish');
  var sfBorder          = $('sfBorder');
  var sfQty             = $('sfQty');
  var sfPrice           = $('sfPrice');
  var sfEach            = $('sfEach');
  var sfActionBtn       = $('sfActionBtn');
  var sfUploadBtn       = $('sfUploadBtn');

  /* State */
  var state = {
    shape:     'Square',
    sizeMode:  'preset',
    presetW:   null,
    presetH:   null,
    customW:   null,
    customH:   null,
    qty:       10,
    finish:    'Matte',
    border:    'Standard Cut',
    proof:     'Instant Production (No Proof)',
    price:     null,
  };

  /* Computed helpers */
  function getWidth()  { return state.sizeMode === 'custom' ? state.customW : state.presetW; }
  function getHeight() { return state.sizeMode === 'custom' ? state.customH : state.presetH; }
  function getQty()    { return state.qty; }

  function isReadyToPrice() {
    var w = getWidth(), h = getHeight(), q = getQty();
    return w >= 0.5 && w <= 14 && h >= 0.5 && h <= 14 && q >= 10 && q <= 10000;
  }

  /* Price computation — always runs, no mode conditions */
  function computePrice() {
    if (!isReadyToPrice()) { state.price = null; return; }
    try {
      state.price = calculatePrice(getWidth(), getHeight(), getQty());
    } catch (e) {
      state.price = null;
    }
  }

  /* Tile / chip click delegation */
  wrap.addEventListener('click', function (e) {
    var btn = e.target.closest('[data-group]');
    if (!btn) return;
    var group = btn.dataset.group;
    var value = btn.dataset.value;

    wrap.querySelectorAll('[data-group="' + group + '"]').forEach(function (b) {
      b.classList.remove('slc-tile--active', 'slc-chip--active', 'slc-qty-chip--active');
    });

    if (group === 'shape')  { state.shape  = value; btn.classList.add('slc-tile--active'); }
    if (group === 'finish') { state.finish = value; btn.classList.add('slc-tile--active'); }
    if (group === 'border') { state.border = value; btn.classList.add('slc-tile--active'); }

    if (group === 'proof') {
      state.proof = value;
      btn.classList.add('slc-tile--active');
      updateProofChecks();
    }

    if (group === 'size') {
      state.sizeMode = 'preset';
      state.presetW  = parseFloat(btn.dataset.w);
      state.presetH  = parseFloat(btn.dataset.h);
      btn.classList.add('slc-chip--active');
      collapseCustomSize();
    }

    if (group === 'qty') {
      state.qty = parseInt(value, 10);
      btn.classList.add('slc-qty-chip--active');
      if (customQtyInput) customQtyInput.value = '';
      collapseCustomQty();
    }

    refresh();
  });

  /* Custom size toggle */
  customSizeToggle.addEventListener('click', function () {
    var isOpen = !customSizeRow.classList.contains('slc-hidden');
    if (isOpen) {
      collapseCustomSize();
      state.sizeMode = 'preset';
    } else {
      customSizeRow.classList.remove('slc-hidden');
      customSizeToggle.classList.add('slc-expand-btn--open');
      $$('[data-group="size"]').forEach(function (b) { b.classList.remove('slc-chip--active'); });
      state.sizeMode = 'custom';
      widthInput.focus();
    }
    refresh();
  });

  function collapseCustomSize() {
    customSizeRow.classList.add('slc-hidden');
    customSizeToggle.classList.remove('slc-expand-btn--open');
  }

  widthInput.addEventListener('input', function () {
    state.customW  = parseFloat(widthInput.value) || null;
    state.sizeMode = 'custom';
    refresh();
  });
  heightInput.addEventListener('input', function () {
    state.customH  = parseFloat(heightInput.value) || null;
    state.sizeMode = 'custom';
    refresh();
  });

  /* Custom qty toggle — same behavior as custom size */
  customQtyToggle.addEventListener('click', function () {
    var isOpen = !customQtyRow.classList.contains('slc-hidden');
    if (isOpen) {
      collapseCustomQty();
    } else {
      customQtyRow.classList.remove('slc-hidden');
      customQtyToggle.classList.add('slc-expand-btn--open');
      $$('[data-group="qty"]').forEach(function (b) { b.classList.remove('slc-qty-chip--active'); });
      customQtyInput.focus();
    }
    refresh();
  });

  function collapseCustomQty() {
    customQtyRow.classList.add('slc-hidden');
    customQtyToggle.classList.remove('slc-expand-btn--open');
  }

  /* Custom qty input — updates live, no mode switching needed */
  customQtyInput.addEventListener('input', function () {
    var val = parseInt(customQtyInput.value, 10);
    if (customQtyInput.value && !isNaN(val) && val >= 10) {
      state.qty = val;
      $$('[data-group="qty"]').forEach(function (b) { b.classList.remove('slc-qty-chip--active'); });
    } else if (!customQtyInput.value) {
      /* Field cleared — restore first preset */
      var firstChip = wrap.querySelector('[data-group="qty"]');
      if (firstChip) {
        state.qty = parseInt(firstChip.dataset.value, 10);
        firstChip.classList.add('slc-qty-chip--active');
      }
    }
    refresh();
  });

  /* Proof tile checkmarks */
  function updateProofChecks() {
    var isNo = (state.proof === 'Instant Production (No Proof)');
    proofNoCheck.classList.toggle('slc-hidden',  !isNo);
    proofYesCheck.classList.toggle('slc-hidden', isNo);
  }

  /* File upload UX */
  fileInput.addEventListener('change', function () {
    var f = fileInput.files && fileInput.files[0];
    uploadLabel.textContent = f ? f.name : 'Drag and drop your file here';
    uploadLabel.classList.toggle('slc-file-ok', !!f);
  });
  uploadZone.addEventListener('dragover', function (e) {
    e.preventDefault();
    uploadZone.classList.add('slc-over');
  });
  uploadZone.addEventListener('dragleave', function () { uploadZone.classList.remove('slc-over'); });
  uploadZone.addEventListener('drop', function (e) {
    e.preventDefault();
    uploadZone.classList.remove('slc-over');
    var f = e.dataTransfer.files[0];
    if (f) {
      try { var dt = new DataTransfer(); dt.items.add(f); fileInput.files = dt.files; } catch (_) {}
      uploadLabel.textContent = f.name;
      uploadLabel.classList.add('slc-file-ok');
    }
  });

  /* Upload button scrolls to upload zone */
  sfUploadBtn.addEventListener('click', function () {
    uploadZone.scrollIntoView({ behavior: 'smooth', block: 'center' });
    uploadZone.style.borderColor = 'var(--sc-blue)';
    setTimeout(function () { uploadZone.style.borderColor = ''; }, 1600);
  });

  /* Refresh cycle */
  function refresh() {
    computePrice();
    updateFooter();
    updateActionButton();
  }

  function updateFooter() {
    var w = getWidth(), h = getHeight(), q = getQty();

    sfShape.textContent  = state.shape || '--';
    sfFinish.textContent = state.finish || '--';
    sfBorder.textContent = state.border || '--';
    sfSize.textContent   = (w && h) ? w + '" x ' + h + '"' : '--';
    sfQty.textContent    = (q && q >= 10) ? q : '--';

    if (state.price !== null) {
      sfPrice.textContent = '$' + state.price.toFixed(2);
      sfEach.textContent  = '$' + pricePerSticker(w, h, q) + ' each';
    } else {
      sfPrice.textContent = '--';
      sfEach.textContent  = '';
    }
  }

  /* Add to Cart is always active once ready — no invoice branching */
  function updateActionButton() {
    sfActionBtn.disabled = !isReadyToPrice();
  }

  /* Add to Cart */
  sfActionBtn.addEventListener('click', function () {
    if (sfActionBtn.disabled) return;
    handleAddToCart();
  });

  function handleAddToCart() {
    var variantId = parseInt(wrap.dataset.variantId, 10);
    if (!variantId) { alert('No variant ID found. Check data-variant-id attribute.'); return; }
    setLoading(true);
    fetch('/cart/add.js', {
      method:  'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        items: [{
          id:       variantId,
          quantity: getQty(),
          properties: {
            'Shape':         state.shape,
            'Size':          getWidth() + '" x ' + getHeight() + '"',
            'Finish':        state.finish,
            'Cut':           state.border,
            'Production':    state.proof,
            '_quoted_price': '$' + (state.price || 0).toFixed(2),
          }
        }]
      })
    }).then(function (res) {
      if (!res.ok) throw new Error('Cart error');
      window.location.href = '/cart';
    }).catch(function (err) {
      console.error(err);
      alert('Could not add to cart. Please try again.');
      setLoading(false);
    });
  }

  function setLoading(on) {
    sfActionBtn.disabled = on;
    sfActionBtn.style.opacity = on ? '.5' : '';
  }

  /* Init */
  (function init() {
    var firstSize = wrap.querySelector('[data-group="size"]');
    if (firstSize) {
      firstSize.classList.add('slc-chip--active');
      state.presetW = parseFloat(firstSize.dataset.w);
      state.presetH = parseFloat(firstSize.dataset.h);
    }

    var firstQty = wrap.querySelector('[data-group="qty"]');
    if (firstQty) {
      firstQty.classList.add('slc-qty-chip--active');
      state.qty = parseInt(firstQty.dataset.value, 10);
    }

    updateProofChecks();
    if (proofNoBtn) proofNoBtn.classList.add('slc-tile--active');

    refresh();
  })();

})();
