/** Shopify CDN: Minification failed

Line 33:2 Unexpected "constructor("
Line 34:8 Expected ":"
Line 35:8 Expected ":"
Line 36:8 Expected ":"
Line 38:8 Expected ":"
Line 39:8 Expected ":"
Line 41:7 Unexpected "("
Line 42:13 Expected ":"
Line 43:12 Expected ":"
Line 46:8 Expected ":"
... and 88 more hidden warnings

**/
/**
 * Conditional Variant Dropdowns for Shopify Dawn Theme
 * Cardinal Valley Industrial Supply
 *
 * Logic:
 * - "New" condition      → shows variants whose option1 === "New"
 * - "Remanufactured"     → shows variants whose option1 === "Remanufactured"
 * - Part numbers ending in "-R" are Reman (e.g. 150BMPE88R54-R)
 * - Part numbers without "-R" are New (e.g. 150BMPE88R54)
 * - Some models may only exist in one condition — handled gracefully
 *
 * Shopify Variant Setup:
 *   Option 1 Name: "Condition"    Values: "New", "Remanufactured"
 *   Option 2 Name: "Model Number" Values: e.g. "150BMPE88R54", "150BMPE88R54-R"
 */

class ConditionalVariants {
  constructor(productJson, container) {
    this.product = productJson;
    this.container = container;
    this.variants = productJson.variants;

    this.conditionSelect = container.querySelector('[data-option-index="0"]');
    this.modelSelect = container.querySelector('[data-option-index="1"]');

    if (!this.conditionSelect || !this.modelSelect) {
      console.warn('ConditionalVariants: Could not find dropdowns in', container);
      return;
    }

    this.init();
  }

  init() {
    // Populate model dropdown for the default/pre-selected condition
    this.updateModelOptions(false);

    // Re-filter models whenever condition changes
    this.conditionSelect.addEventListener('change', () => {
      this.updateModelOptions(true);
    });

    // Update variant state when model is chosen
    this.modelSelect.addEventListener('change', () => {
      this.updateSelectedVariant();
    });

    // Set the initial variant state on load
    this.updateSelectedVariant();
  }

  /**
   * Return all variants matching the given condition value ("New" or "Remanufactured")
   * Filters by option1 which Shopify sets from the "Condition" option.
   */
  getVariantsForCondition(condition) {
    return this.variants.filter(v => v.option1 === condition);
  }

  /**
   * Rebuild the Model Number <select> based on the currently selected Condition.
   * @param {boolean} resetSelection - if true, auto-select first available model
   */
  updateModelOptions(resetSelection) {
    const selectedCondition = this.conditionSelect.value;
    const matchingVariants = this.getVariantsForCondition(selectedCondition);
    const previousModel = this.modelSelect.value;

    // Briefly mark as updating for CSS transition
    this.modelSelect.closest('.select').classList.add('select--updating');

    // Clear existing options
    this.modelSelect.innerHTML = '';

    if (matchingVariants.length === 0) {
      const opt = document.createElement('option');
      opt.value = '';
      opt.textContent = '— No models available —';
      opt.disabled = true;
      opt.selected = true;
      this.modelSelect.appendChild(opt);
      this.modelSelect.closest('.select').classList.remove('select--updating');
      this.disableAddToCart('Unavailable');
      return;
    }

    // Add a placeholder prompt
    const placeholder = document.createElement('option');
    placeholder.value = '';
    placeholder.textContent = '— Select Model Number —';
    placeholder.disabled = true;
    placeholder.selected = true;
    this.modelSelect.appendChild(placeholder);

    let firstAvailableValue = null;
    let restoredPrevious = false;

    matchingVariants.forEach(variant => {
      const opt = document.createElement('option');
      opt.value = variant.option2;
      opt.textContent = variant.option2;

      if (!variant.available) {
        opt.disabled = true;
        opt.textContent += ' — Sold Out';
      } else {
        if (!firstAvailableValue) firstAvailableValue = variant.option2;
      }

      // Restore previous selection if it's still valid for this condition
      if (!resetSelection && variant.option2 === previousModel) {
        opt.selected = true;
        placeholder.selected = false;
        restoredPrevious = true;
      }

      this.modelSelect.appendChild(opt);
    });

    // On condition change, auto-select first available model
    if (resetSelection || !restoredPrevious) {
      if (firstAvailableValue) {
        this.modelSelect.value = firstAvailableValue;
        placeholder.selected = false;
      }
    }

    this.modelSelect.closest('.select').classList.remove('select--updating');

    // Trigger variant update now that model is set
    this.updateSelectedVariant();
  }

  /**
   * Match the selected Condition + Model Number to a Shopify variant,
   * then sync the hidden ID input, price, URL, and Add to Cart button.
   */
  updateSelectedVariant() {
    const selectedCondition = this.conditionSelect.value;
    const selectedModel = this.modelSelect.value;

    if (!selectedModel) return;

    const matchedVariant = this.variants.find(
      v => v.option1 === selectedCondition && v.option2 === selectedModel
    );

    if (!matchedVariant) return;

    // ── Update hidden variant ID input (Dawn uses this for cart) ──
    const variantInput = this.container.closest('form')
      ? this.container.closest('form').querySelector('input[name="id"]')
      : document.querySelector(`#${this.container.dataset.formId} input[name="id"]`);

    if (variantInput) {
      variantInput.value = matchedVariant.id;
      variantInput.dispatchEvent(new Event('change', { bubbles: true }));
    }

    // ── Update price ──
    this.updatePrice(matchedVariant);

    // ── Update Add to Cart button ──
    this.updateAddToCartButton(matchedVariant);

    // ── Update browser URL with variant param ──
    this.updateUrl(matchedVariant.id);

    // ── Dispatch custom event for any other Dawn listeners ──
    document.dispatchEvent(new CustomEvent('variant:changed', {
      detail: { variant: matchedVariant, productHandle: this.product.handle }
    }));
  }

  updatePrice(variant) {
    const formatMoney = (cents) =>
      '$' + (cents / 100).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');

    const priceWrapper = document.querySelector('.price');
    const regularPriceEl = document.querySelector('.price__regular .price-item--regular');
    const salePriceEl = document.querySelector('.price__sale .price-item--sale');
    const comparePriceEl = document.querySelector('.price__sale .price-item--regular');

    if (!regularPriceEl) return;

    const isOnSale = variant.compare_at_price && variant.compare_at_price > variant.price;

    if (isOnSale) {
      priceWrapper?.classList.add('price--on-sale');
      if (salePriceEl) salePriceEl.textContent = formatMoney(variant.price);
      if (comparePriceEl) comparePriceEl.textContent = formatMoney(variant.compare_at_price);
    } else {
      priceWrapper?.classList.remove('price--on-sale');
      regularPriceEl.textContent = formatMoney(variant.price);
    }
  }

  updateAddToCartButton(variant) {
    const btn = document.querySelector('[name="add"]');
    if (!btn) return;

    if (variant.available) {
      btn.disabled = false;
      btn.querySelector('span')
        ? (btn.querySelector('span').textContent = 'Add to cart')
        : (btn.textContent = 'Add to cart');
    } else {
      btn.disabled = true;
      btn.querySelector('span')
        ? (btn.querySelector('span').textContent = 'Sold out')
        : (btn.textContent = 'Sold out');
    }
  }

  disableAddToCart(label) {
    const btn = document.querySelector('[name="add"]');
    if (!btn) return;
    btn.disabled = true;
    btn.querySelector('span')
      ? (btn.querySelector('span').textContent = label)
      : (btn.textContent = label);
  }

  updateUrl(variantId) {
    try {
      const url = new URL(window.location.href);
      url.searchParams.set('variant', variantId);
      window.history.replaceState({}, '', url.toString());
    } catch (e) {
      // URL update is non-critical, fail silently
    }
  }
}

// ── Initialize on DOM ready ─────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll('[data-conditional-variants]').forEach(container => {
    const handle = container.dataset.productHandle;
    const jsonEl = document.getElementById('ProductJson-' + handle);

    if (!jsonEl) {
      console.warn('ConditionalVariants: No product JSON found for handle:', handle);
      return;
    }

    try {
      const productJson = JSON.parse(jsonEl.textContent);
      new ConditionalVariants(productJson, container);
    } catch (err) {
      console.error('ConditionalVariants: Failed to initialize for', handle, err);
    }
  });
});
