document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('orderForm');
    const phone = document.getElementById('phone');
    const location = document.getElementById('location');
    const quantity = document.getElementById('quantity');
    const date = document.getElementById('date');
    const time = document.getElementById('time');
    const total = document.getElementById('total');
    const price = parseFloat(form.querySelector('input[name="price"]').value);
    const startPeriod = form.querySelector('input[name="start_period"]').value; // 'MM-DD'
    const endPeriod = form.querySelector('input[name="end_period"]').value;
    const unitType = form.querySelector('input[name="unit_type"]').value;

    // Phone masking: Only allow 8 digits after +993
    phone.addEventListener('input', function(e) {
        let val = this.value.replace(/\D/g, '').slice(0, 8); // Digits only, max 8
        this.value = '+993' + (val || '');
        if (val.length !== 8) {
            this.parentElement.classList.add('error');
        } else {
            this.parentElement.classList.remove('error');
        }
    });

    // Location price extraction: value="price|label"
    function getDeliveryPrice() {
        const selected = location.options[location.selectedIndex].value.split('|')[0];
        return parseFloat(selected) || 0;
    }

    // Calculate total
    function calculateTotal() {
        const qty = parseFloat(quantity.value) || 0;
        const delivery = getDeliveryPrice();
        const subtotal = price * qty;
        const grandTotal = subtotal + delivery;
        total.textContent = grandTotal.toFixed(2) + ' манат';
    }

    location.addEventListener('change', calculateTotal);
    quantity.addEventListener('input', calculateTotal);

    // Date validation: Future, within annual period (e.g., Jun25-Jul15)
    date.addEventListener('change', function() {
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        const selectedDate = new Date(this.value);
        const [startM, startD] = startPeriod.split('-').map(Number);
        const [endM, endD] = endPeriod.split('-').map(Number);
        const currentYear = today.getFullYear();
        const selectedYear = selectedDate.getFullYear();
        const selectedMonth = selectedDate.getMonth() + 1;
        const selectedDay = selectedDate.getDate();

        let valid = selectedDate > today && // Future only (not today/past)
                    selectedYear >= currentYear && // Not past years
                    ((selectedYear > currentYear) || // Future year: any date in period
                     (selectedYear === currentYear && selectedMonth === startM && selectedDay >= startD) ||
                     (selectedMonth > startM && selectedMonth < endM) ||
                     (selectedMonth === endM && selectedDay <= endD)); // Same year: within period

        if (!valid) {
            this.parentElement.classList.add('error');
        } else {
            this.parentElement.classList.remove('error');
            updateTimeOptions(); // Enable time validation
        }
    });

    // Time validation based on date/season
    function updateTimeOptions() {
        const selectedDate = new Date(date.value);
        const month = selectedDate.getMonth() + 1;
        const day = selectedDate.getDate();
        const isSummer = (month > 7 || (month === 7 && day >= 15)) && (month < 9 || (month === 9 && day <= 15)); // Jul15-Sep15
        const isWeekday = selectedDate.getDay() >= 1 && selectedDate.getDay() <= 5; // Mon-Fri

        let minTime, maxTime;
        if (isSummer) {
            minTime = '08:30';
            maxTime = '19:30';
        } else if (isWeekday) {
            minTime = '11:00';
            maxTime = '14:30';
        } else {
            // Weekend off-season: invalid
            showTimeError('Saýlanan günde eltip bermek ýok / В выбранный день доставка не работает');
            return;
        }

        time.setAttribute('min', minTime);
        time.setAttribute('max', maxTime);
        time.parentElement.querySelector('.tooltip').textContent = `Saýlanan günde eltip bermek diňe ${minTime}-den ${maxTime}-e çenli elýeterlidir / В выбранный день доставка работает только с ${minTime} до ${maxTime}`;
    }

    time.addEventListener('change', function() {
        const min = this.getAttribute('min');
        const max = this.getAttribute('max');
        if (this.value < min || this.value > max) {
            this.parentElement.classList.add('error');
        } else {
            this.parentElement.classList.remove('error');
        }
    });

    function showTimeError(msg) {
        time.parentElement.classList.add('error');
        time.parentElement.querySelector('.tooltip').textContent = msg;
    }

    // Form submit: Basic validation (add more if needed)
    form.addEventListener('submit', function(e) {
        if (!form.checkValidity() || phone.parentElement.classList.contains('error') ||
            date.parentElement.classList.contains('error') || time.parentElement.classList.contains('error')) {
            e.preventDefault();
            alert('Zehmet olmasa, barlyk meýdanlary dogry dolduryň / Пожалуйста, заполните все поля корректно');
        } else {
            // Format phone for submit
            phone.name = 'phone'; // Already +993XXXXXXXX
        }
    });

    // Initial calc
    calculateTotal();
});