document.addEventListener('DOMContentLoaded', function() { const modal = document.getElementById('munchmakers-modal'); if (!modal) return; const isVariable = false; const availableVariations = null; const attributeNamesMap = ; const defaultVariation = ; const variationInputs = modal.querySelectorAll('#modal-variations-container select, #modal-variations-container input[type="hidden"]'); const productId = Flexible Shipping; let currentVariation = null; let currentPricingData = ; // CRITICAL FIX: Prevent event propagation on all modal content clicks const modalContent = modal.querySelector('.modal-content'); if (modalContent) { modalContent.addEventListener('click', function(e) { e.stopPropagation(); }); } // Color swatch functionality function initColorSwatches() { const colorSwatches = modal.querySelectorAll('.color-swatches'); console.log('initColorSwatches called, found containers:', colorSwatches.length); colorSwatches.forEach(swatchContainer => { const attributeName = swatchContainer.dataset.attribute; const hiddenInput = modal.querySelector(`#${attributeName}`); const swatches = swatchContainer.querySelectorAll('.color-swatch'); console.log('Initializing color swatches for:', attributeName); console.log('Found hidden input:', hiddenInput); console.log('Found swatches:', swatches.length); swatches.forEach(swatch => { swatch.addEventListener('click', function(e) { e.preventDefault(); e.stopPropagation(); console.log('Color swatch clicked:', this.dataset.value); // Remove selected class from all swatches in this container swatches.forEach(s => s.classList.remove('selected')); // Add selected class to clicked swatch this.classList.add('selected'); // Update hidden input value if (hiddenInput) { hiddenInput.value = this.dataset.value; console.log('Hidden input updated:', hiddenInput.name || hiddenInput.id, '=', hiddenInput.value); // Trigger change event hiddenInput.dispatchEvent(new Event('change', { bubbles: true })); // Also trigger variation state update console.log('About to call updateVariationState...'); updateVariationState(); } else { console.error('Hidden input not found for:', attributeName); } }); }); }); } function closeModal() { modal.style.display = 'none'; document.body.style.overflow = ''; const form = document.querySelector('form.cart.munchmakers-active'); if (form) form.classList.remove('munchmakers-active'); } function showStep(stepName) { modal.querySelectorAll('.modal-step').forEach(step => step.classList.remove('active')); const targetStep = modal.querySelector('#step-' + stepName); if (targetStep) targetStep.classList.add('active'); // Update progress bar updateProgressBar(stepName); } function updateProgressBar(currentStepName) { const stepMapping = { 'variations': 1, 'quantity': isVariable ? 2 : 1, 'artwork': isVariable ? 3 : 2 }; const currentStepNumber = stepMapping[currentStepName]; const maxSteps = isVariable ? 3 : 2; // Reset all steps modal.querySelectorAll('.progress-step').forEach(step => { step.classList.remove('active', 'completed'); }); // Mark completed and active steps for (let i = 1; i <= maxSteps; i++) { const stepElement = modal.querySelector(`[data-step="${i}"]`); if (stepElement) { if (i < currentStepNumber) { stepElement.classList.add('completed'); } else if (i === currentStepNumber) { stepElement.classList.add('active'); } } } // Hide step 3 for simple products if (!isVariable) { const step3 = modal.querySelector('[data-step="3"]'); const line2 = step3?.previousElementSibling; if (step3) step3.style.display = 'none'; if (line2 && line2.classList.contains('progress-line')) line2.style.display = 'none'; } } function findMatchingVariation() { let selectedOptions = {}; let allOptionsSelected = true; variationInputs.forEach(input => { const attributeName = input.name; if (!input.value) allOptionsSelected = false; selectedOptions[attributeName] = input.value; }); if (!allOptionsSelected) return null; return availableVariations.find(variation => Object.keys(variation.attributes).every(key => variation.attributes[key] === '' || variation.attributes[key] === selectedOptions[key]) ) || null; } function setDefaultVariation() { if (!isVariable || !defaultVariation) return; // Set the input values to match the default variation variationInputs.forEach(input => { const attributeName = input.name; const attributeValue = defaultVariation.attributes[attributeName]; if (attributeValue) { input.value = attributeValue; // If it's a color swatch, also visually select it if (input.type === 'hidden') { const swatchContainer = modal.querySelector(`[data-attribute="${attributeName}"]`); if (swatchContainer) { swatchContainer.querySelectorAll('.color-swatch').forEach(s => s.classList.remove('selected')); const targetSwatch = swatchContainer.querySelector(`[data-value="${attributeValue}"]`); if (targetSwatch) targetSwatch.classList.add('selected'); } } } }); // Update the variation state updateVariationState(); } function updateVariationState() { console.log('=== updateVariationState called ==='); currentVariation = findMatchingVariation(); console.log('Current variation found:', currentVariation); const nextBtn = modal.querySelector('#next-to-quantity'); const wholesaleTrigger = document.getElementById('wholesale-pricing-trigger'); if (currentVariation) { console.log('✅ Variation found - enabling next button'); if (nextBtn) nextBtn.disabled = false; if(wholesaleTrigger) wholesaleTrigger.style.display = 'block'; fetchVariationPricing(currentVariation.variation_id); let selectionParts = []; for(const attr_key in currentVariation.attributes) { const slug = currentVariation.attributes[attr_key]; if(slug) { const taxonomyName = attr_key.replace('attribute_', ''); if (attributeNamesMap[taxonomyName] && attributeNamesMap[taxonomyName][slug]) { selectionParts.push(attributeNamesMap[taxonomyName][slug]); } else { selectionParts.push(slug.replace(/-/g, ' ').replace(/\b\w/g, l => l.toUpperCase())); } } } let selectionText = 'Current Selection: ' + selectionParts.join(', '); const variationStepSelection = modal.querySelector('#variation-step-selection'); const quantityStepSelection = modal.querySelector('#quantity-step-selection'); const selectedOptionsInput = document.querySelector('#munchmakers_selected_options'); if (variationStepSelection) variationStepSelection.textContent = selectionText; if (quantityStepSelection) quantityStepSelection.textContent = selectionText; if (selectedOptionsInput) selectedOptionsInput.value = selectionText; } else { console.log('❌ No variation found - disabling next button'); if (nextBtn) nextBtn.disabled = true; if(wholesaleTrigger) wholesaleTrigger.style.display = 'none'; const variationStepSelection = modal.querySelector('#variation-step-selection'); const quantityStepSelection = modal.querySelector('#quantity-step-selection'); if (variationStepSelection) variationStepSelection.textContent = 'Please select all options.'; if (quantityStepSelection) quantityStepSelection.textContent = ''; if (window.updateWholesaleModalContent) window.updateWholesaleModalContent(null); } } function fetchVariationPricing(variationId) { const data = new FormData(); data.append('action', 'munchmakers_get_variation_pricing'); data.append('product_id', productId); data.append('variation_id', variationId); data.append('nonce', munchmakers_ajax.pricing_nonce); fetch(munchmakers_ajax.ajax_url, { method: 'POST', body: data }) .then(response => response.json()) .then(result => { if (result.success && result.data) { currentPricingData = result.data; initQuantitySlider(); if (window.updateWholesaleModalContent) window.updateWholesaleModalContent(result.data); } }) .catch(error => { console.error('Error fetching variation pricing:', error); }); } function initQuantitySlider() { const slider = modal.querySelector('#modal-slider'); const quantityInput = modal.querySelector('#modal-quantity'); if (typeof window.noUiSlider === 'undefined') { if(slider) slider.innerHTML = '
Error: Slider library failed to load.
'; return; } if (slider && quantityInput) { if (slider.noUiSlider) slider.noUiSlider.destroy(); const minQty = currentPricingData.moq || 1; const interval = currentPricingData.interval || 1; const maxQty = Math.max(1000, currentPricingData.max_qty || 1000); quantityInput.min = minQty; quantityInput.step = interval; quantityInput.value = minQty; // Set to minimum quantity window.noUiSlider.create(slider, { start: [minQty], connect: 'lower', tooltips: true, step: interval, range: { 'min': minQty, 'max': maxQty }, format: { to: v => Math.round(v), from: v => Number(v) } }); slider.noUiSlider.on('update', values => { const qty = parseInt(values[0], 10); quantityInput.value = qty; updateModalPricing(qty); }); quantityInput.addEventListener('change', () => { const newValue = Math.max(minQty, parseInt(quantityInput.value) || minQty); quantityInput.value = newValue; slider.noUiSlider.set(newValue); }); updateModalPricing(minQty); } } function updateModalPricing(qty) { const basePrice = currentPricingData.base_price || 0; const rules = currentPricingData.rules || {}; let unitPrice = basePrice; if (rules && Object.keys(rules).length > 0) { let matchedPrice = basePrice; for (const ruleQty in rules) { if (qty >= parseInt(ruleQty)) matchedPrice = parseFloat(rules[ruleQty]); } unitPrice = matchedPrice; } const subtotal = unitPrice * qty; const savings = (basePrice * qty) - subtotal; const unitPriceInput = modal.querySelector('#modal-unit-price'); const subtotalSpan = modal.querySelector('#modal-subtotal'); const savingsSpan = modal.querySelector('#modal-savings'); const savingsEl = modal.querySelector('.savings'); if (unitPriceInput) unitPriceInput.value = '