document.addEventListener('DOMContentLoaded', function() {
    const subtotal = parseFloat(document.getElementById('subtotal').value);
    
    // State and shipping method selectors
    const stateSelect = document.getElementById('state');
    const cityInput = document.getElementById('city');
    const zipCodeInput = document.getElementById('zipCode');
    const shippingMethodSelect = document.getElementById('shipping_method');
    
    // Event listeners
    stateSelect.addEventListener('change', updateShippingRates);
    cityInput.addEventListener('change', updateShippingRates);
    zipCodeInput.addEventListener('change', updateShippingRates);
    shippingMethodSelect.addEventListener('change', calculateTotals);
    
    function updateShippingRates() {
        const state = stateSelect.value;
        const city = cityInput.value;
        const zipCode = zipCodeInput.value;
        
        if (state && city && zipCode) {
            fetch('/checkout/get-shipping-rates', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                },
                body: JSON.stringify({
                    state: state,
                    city: city,
                    zip_code: zipCode,
                    weight: document.getElementById('total-weight').value
                })
            })
            .then(response => response.json())
            .then(data => {
                updateShippingMethods(data.shipping_methods);
                calculateTotals();
            });
        }
    }
    
    function updateShippingMethods(methods) {
        const select = document.getElementById('shipping_method');
        select.innerHTML = '';
        
        methods.forEach(method => {
            const option = new Option(
                `${method.carrier} - ${method.name} ($${method.rate}) - ${method.estimated_days} days`,
                method.id
            );
            select.add(option);
        });
    }
    
    function calculateTotals() {
        const selectedMethod = document.getElementById('shipping_method').value;
        const shippingCost = parseFloat(document.querySelector(`option[value="${selectedMethod}"]`)?.dataset.rate || 0);
        const state = stateSelect.value;
        
        // Calculate tax
        const taxRate = getTaxRate(state);
        const taxAmount = subtotal * taxRate;
        
        // Update display
        document.getElementById('shipping-cost').textContent = `$${shippingCost.toFixed(2)}`;
        document.getElementById('tax-amount').textContent = `$${taxAmount.toFixed(2)}`;
        
        const total = subtotal + shippingCost + taxAmount;
        document.getElementById('total-amount').textContent = `$${total.toFixed(2)}`;
    }
    
    function getTaxRate(state) {
        const taxRates = {
            'AL': 0.04, 'AK': 0.00, 'AZ': 0.056, 'AR': 0.065,
            'CA': 0.0725, 'CO': 0.029, 'CT': 0.0635, 'DE': 0.00,
            'FL': 0.06, 'GA': 0.04, 'HI': 0.04, 'ID': 0.06,
            // Add all US states
        };
        return taxRates[state] || 0;
    }
});