document.addEventListener('DOMContentLoaded', function() {
    // Quick View functionality
    const quickViewButtons = document.querySelectorAll('.quick-view');
    quickViewButtons.forEach(button => {
        button.addEventListener('click', function() {
            const productId = this.dataset.productId;
            fetch(`/products/${productId}/quick-view`)
                .then(response => response.text())
                .then(html => {
                    const modal = new bootstrap.Modal(document.getElementById('quickViewModal'));
                    document.querySelector('#quickViewModal .modal-content').innerHTML = html;
                    modal.show();
                });
        });
    });

    // Wishlist functionality
    const wishlistButtons = document.querySelectorAll('.add-to-wishlist');
    wishlistButtons.forEach(button => {
        button.addEventListener('click', function() {
            const productId = this.dataset.productId;
            fetch(`/wishlist/toggle/${productId}`, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                }
            })
            .then(response => response.json())
            .then(data => {
                const icon = this.querySelector('i');
                if (data.added) {
                    icon.classList.remove('far');
                    icon.classList.add('fas', 'text-danger');
                } else {
                    icon.classList.remove('fas', 'text-danger');
                    icon.classList.add('far');
                }
                showToast(data.message);
            });
        });
    });

    initializeShippingCalculator();
});



function initializeShippingCalculator() {
    const shippingMethodSelect = document.getElementById('shipping_method');
    const deliveryRadios = document.querySelectorAll('input[name="delivery_method"]');
    const shippingAddressSection = document.getElementById('shippingAddressSection');
    
    if (deliveryRadios && shippingAddressSection) {
        deliveryRadios.forEach(radio => {
            radio.addEventListener('change', function() {
                if (this.value === 'delivery') {
                    shippingAddressSection.style.display = 'block';
                    // Calculate initial shipping if all fields are filled
                    if (areShippingFieldsFilled()) {
                        calculateShippingRates();
                    }
                } else {
                    shippingAddressSection.style.display = 'none';
                    clearShippingRates();
                }
            });
        });
    }
    
    // Calculate shipping when method changes
    if (shippingMethodSelect) {
        shippingMethodSelect.addEventListener('change', calculateShippingRates);
    }
    
    // Calculate shipping when address fields change
    const addressFields = ['zipCode', 'state'];
    addressFields.forEach(field => {
        const element = document.getElementById(field);
        if (element) {
            element.addEventListener('change', calculateShippingRates);
        }
    });
}

function areShippingFieldsFilled() {
    const requiredFields = ['zipCode', 'state', 'shipping_method'];
    return requiredFields.every(field => {
        const element = document.getElementById(field);
        return element && element.value.trim() !== '';
    });
}


function calculateShippingRates() {
    if (!areShippingFieldsFilled()) {
        return;
    }

    const formData = {
        address: document.getElementById('address').value,
        city: document.getElementById('city').value,
        state: document.getElementById('state').value,
        zip_code: document.getElementById('zipCode').value,
        country: 'US',
        weight: getCartWeight()
    };
    
    const shippingRatesDiv = document.getElementById('shipping-rates');
    shippingRatesDiv.innerHTML = '<div class="alert alert-info">Calculating shipping rates...</div>';
    
    fetch('/shipping/calculate', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
        },
        body: JSON.stringify(formData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            displayShippingRates(data.rates);
        } else {
            shippingRatesDiv.innerHTML = `<div class="alert alert-warning">${data.error}</div>`;
        }
    })
    .catch(error => {
        console.error('Shipping calculation error:', error);
        shippingRatesDiv.innerHTML = '<div class="alert alert-danger">Unable to calculate shipping rates</div>';
    });
}

// function calculateShippingRates() {
//     if (!areShippingFieldsFilled()) {
//         return;
//     }

//     const zipCode = document.getElementById('zipCode').value;
//     const state = document.getElementById('state').value;
//     const method = document.getElementById('shipping_method').value;
//     const shippingRatesDiv = document.getElementById('shipping-rates');
    
//     // Show loading state
//     shippingRatesDiv.innerHTML = '<div class="alert alert-info">Calculating shipping rates...</div>';
    
//     // Get cart weight (you might need to adjust this based on your cart structure)
//     const cartWeight = getCartWeight();
    
//     fetch('/shipping/calculate', {
//         method: 'POST',
//         headers: {
//             'Content-Type': 'application/json',
//             'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
//         },
//         body: JSON.stringify({
//             zip_code: zipCode,
//             state: state,
//             method: method,
//             weight: cartWeight
//         })
//     })
//     .then(response => response.json())
//     .then(data => {
//         if (data.success) {
//             displayShippingRates(data.rates);
//             updateOrderSummary(data.rates.rate);
//         } else {
//             shippingRatesDiv.innerHTML = `<div class="alert alert-warning">${data.error || 'Unable to calculate shipping rates'}</div>`;
//         }
//     })
//     .catch(error => {
//         console.error('Error calculating shipping:', error);
//         shippingRatesDiv.innerHTML = '<div class="alert alert-danger">Error calculating shipping rates</div>';
//     });
// }

function getCartWeight() {
    // You should implement this based on your cart structure
    // For now, returning a default weight
    return 1.0;
}

function clearShippingRates() {
    const shippingRatesDiv = document.getElementById('shipping-rates');
    if (shippingRatesDiv) {
        shippingRatesDiv.innerHTML = '';
    }
    updateOrderSummary(0);
}

function displayShippingRates(rates) {
    const shippingRatesDiv = document.getElementById('shipping-rates');
    
    const ratesHtml = rates.map(rate => `
        <div class="shipping-rate-option mb-3">
            <input type="radio" name="shipping_rate" id="rate_${rate.id}" 
                   value="${rate.id}" data-cost="${rate.rate}"
                   class="form-check-input me-2">
            <label for="rate_${rate.id}" class="form-check-label">
                <div class="rate-details">
                    <strong>${rate.name}</strong>
                    <div class="text-muted">Estimated delivery: ${rate.days} days</div>
                    <div class="rate-price">$${parseFloat(rate.rate).toFixed(2)}</div>
                </div>
            </label>
        </div>
    `).join('');

    shippingRatesDiv.innerHTML = `
        <div class="shipping-rates-container">
            <h6 class="mb-3">Available Shipping Options</h6>
            ${ratesHtml}
        </div>
    `;

    // Add event listeners for rate selection
    document.querySelectorAll('input[name="shipping_rate"]').forEach(radio => {
        radio.addEventListener('change', function() {
            updateOrderSummary(this.dataset.cost);
        });
    });
}


// function displayShippingRates(rate) {
//     const shippingRatesDiv = document.getElementById('shipping-rates');
    
//     shippingRatesDiv.innerHTML = `
//         <div class="card mt-3">
//             <div class="card-body">
//                 <h5 class="card-title">${rate.name}</h5>
//                 <p class="card-text">Estimated delivery: ${rate.estimated_days} days</p>
//                 <p class="card-text fw-bold">Shipping cost: $${parseFloat(rate.rate).toFixed(2)}</p>
//                 <input type="hidden" name="shipping_rate_id" value="${rate.id}">
//                 <input type="hidden" name="shipping_cost" value="${rate.rate}">
//             </div>
//         </div>
//     `;
// }

function updateOrderSummary(shippingCost) {
    const subtotal = parseFloat(document.getElementById('subtotal').dataset.value);
    const tax = parseFloat(document.getElementById('tax').dataset.value);
    const shipping = parseFloat(shippingCost || 0);
    
    document.getElementById('shipping-cost').textContent = `$${shipping.toFixed(2)}`;
    
    const total = subtotal + tax + shipping;
    document.getElementById('order-total').textContent = `$${total.toFixed(2)}`;
    
    // Update hidden input for form submission
    const shippingInput = document.getElementById('shipping_cost');
    if (shippingInput) {
        shippingInput.value = shipping.toFixed(2);
    }
}

// Add this to your existing shipping rate selection handler
document.querySelectorAll('input[name="shipping_rate"]').forEach(radio => {
    radio.addEventListener('change', function() {
        const selectedRate = this.dataset.cost;
        updateOrderSummary(selectedRate);
        
        // Add selected class to parent container
        document.querySelectorAll('.shipping-rate-option').forEach(option => {
            option.classList.remove('selected');
        });
        this.closest('.shipping-rate-option').classList.add('selected');
    });
});

// Initialize cart functionality
function initializeCart() {
    document.querySelectorAll('.product-buttons form').forEach(form => {
        form.addEventListener('submit', handleAddToCart);
    });
}

// Handle add to cart submission
function handleAddToCart(e) {
    e.preventDefault();
    
    const submitBtn = this.querySelector('button[type="submit"]');
    if (submitBtn.classList.contains('disabled')) return;
    
    submitBtn.disabled = true;
    
    fetch(this.action, {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
            'Accept': 'application/json'
        },
        body: new FormData(this)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            updateCartCounters(data.cartCount);
            showToast(data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('Failed to add item to cart', 'error');
    })
    .finally(() => {
        submitBtn.disabled = false;
    });
}

// Update all cart counters
function updateCartCounters(count) {
    document.querySelectorAll('.cart-counter, .badge-pill').forEach(counter => {
        counter.textContent = count;
        counter.classList.add('updated');
        setTimeout(() => counter.classList.remove('updated'), 1000);
    });
}

// Initialize on page load
//document.addEventListener('DOMContentLoaded', initializeCart);
document.addEventListener('DOMContentLoaded', function() {
    initializeCart();
    initializeShippingCalculator();
});