(function () {
    const form           = document.getElementById('bookingForm');
    if (!form) return;

    const pickupDT       = document.getElementById('pickupDT');
    const returnDT       = document.getElementById('returnDT');
    const pickupHidden   = document.getElementById('pickupDate');
    const returnHidden   = document.getElementById('returnDate');
    const typeHidden     = document.getElementById('typeInput');
    const errorBox       = document.getElementById('bookingError');
    const summary        = document.getElementById('tripSummary');
    const tsDuration     = document.getElementById('tsDuration');
    const tsFrom         = document.getElementById('tsFrom');
    const tsUntil        = document.getElementById('tsUntil');
    const tsPrice        = document.getElementById('tsPrice');
    const sameLoc        = document.getElementById('sameLoc');
    const dropLocField   = document.getElementById('dropLocField');
    const dropLocation   = document.getElementById('dropLocation');
    const pickupLocation = document.getElementById('pickupLocation');
    const promoToggle    = document.getElementById('promoToggle');
    const promoRow       = document.getElementById('promoRow');
    const promoInput     = document.getElementById('promoInput');
    const promoStatus    = document.getElementById('promoStatus');
    const applyPromo     = document.getElementById('applyPromo');
    const spotBtn        = document.getElementById('spotBookBtn');

    // Cheapest daily rate published by the server as a data-attr on <body>, fallback 800
    const minRate = parseFloat(document.body.dataset.minRate || '800');

    // ---------- helpers ----------
    const pad = n => String(n).padStart(2, '0');

    function toLocalInputValue(d) {
        return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
    }

    function fmtPretty(d) {
        return d.toLocaleString(undefined, {
            weekday: 'short', day: 'numeric', month: 'short',
            hour: 'numeric', minute: '2-digit'
        });
    }

    function fmtDuration(ms) {
        const totalMin = Math.round(ms / 60000);
        const days = Math.floor(totalMin / 1440);
        const hours = Math.floor((totalMin % 1440) / 60);
        if (days >= 1 && hours === 0) return `${days} day${days > 1 ? 's' : ''}`;
        if (days >= 1) return `${days}d ${hours}h`;
        return `${hours}h ${totalMin % 60}m`;
    }

    function fmtINR(n) {
        return '₹' + Math.round(n).toLocaleString('en-IN');
    }

    function setError(msg) {
        if (!msg) { errorBox.hidden = true; errorBox.textContent = ''; return; }
        errorBox.hidden = false;
        errorBox.textContent = msg;
    }

    // ---------- init defaults ----------
    const now = new Date();
    const minStr = toLocalInputValue(now);
    pickupDT.min = minStr;
    returnDT.min = minStr;

    // Default pickup = next round hour, drop-off = same +1 day
    const defaultPickup = new Date(now);
    defaultPickup.setMinutes(0, 0, 0);
    defaultPickup.setHours(defaultPickup.getHours() + 1);
    pickupDT.value = toLocalInputValue(defaultPickup);

    const defaultReturn = new Date(defaultPickup);
    defaultReturn.setDate(defaultReturn.getDate() + 1);
    returnDT.value = toLocalInputValue(defaultReturn);

    syncHiddenAndSummary();

    // ---------- sync hidden + summary ----------
    function syncHiddenAndSummary() {
        const p = pickupDT.value ? new Date(pickupDT.value) : null;
        const r = returnDT.value ? new Date(returnDT.value) : null;

        if (p) pickupHidden.value = pickupDT.value.slice(0, 10); // yyyy-MM-dd
        if (r) returnHidden.value = returnDT.value.slice(0, 10);

        if (!p || !r) { summary.hidden = true; return; }

        if (r <= p) {
            setError('Drop-off must be after pick-up.');
            summary.hidden = true;
            return;
        }
        setError('');

        const ms = r - p;
        const days = Math.max(1, Math.ceil(ms / (1000 * 60 * 60 * 24)));
        tsDuration.textContent = fmtDuration(ms);
        tsFrom.textContent     = fmtPretty(p);
        tsUntil.textContent    = fmtPretty(r);
        tsPrice.textContent    = fmtINR(minRate * days);
        summary.hidden         = false;
    }

    pickupDT.addEventListener('change', () => {
        // If return is now invalid, push it to pickup + 1 day
        if (returnDT.value && new Date(returnDT.value) <= new Date(pickupDT.value)) {
            const newR = new Date(pickupDT.value);
            newR.setDate(newR.getDate() + 1);
            returnDT.value = toLocalInputValue(newR);
        }
        returnDT.min = pickupDT.value;
        syncHiddenAndSummary();
    });
    returnDT.addEventListener('change', syncHiddenAndSummary);

    // ---------- duration quick-pick chips ----------
    document.querySelectorAll('.duration-chips .chip').forEach(btn => {
        btn.addEventListener('click', () => {
            const hours = parseInt(btn.dataset.hours, 10);
            const base = pickupDT.value ? new Date(pickupDT.value) : new Date();
            const r = new Date(base);
            r.setHours(r.getHours() + hours);
            returnDT.value = toLocalInputValue(r);
            syncHiddenAndSummary();
            flash(btn);
        });
    });

    // ---------- category chips ----------
    const catChips = document.querySelectorAll('#categoryChips .chip');
    catChips.forEach(chip => {
        chip.addEventListener('click', () => {
            catChips.forEach(c => c.classList.remove('chip-active'));
            chip.classList.add('chip-active');
            typeHidden.value = chip.dataset.type || '';
        });
    });

    // ---------- vehicle-kind tabs (Cars / Bikes) ----------
    document.querySelectorAll('.tabs .tab').forEach(tab => {
        tab.addEventListener('click', () => {
            document.querySelectorAll('.tabs .tab').forEach(t => t.classList.remove('active'));
            tab.classList.add('active');
            // If "Bikes" tab → preselect BIKE category, else clear
            const kind = tab.dataset.kind;
            if (kind === 'BIKE') {
                catChips.forEach(c => c.classList.toggle('chip-active', c.dataset.type === 'BIKE'));
                typeHidden.value = 'BIKE';
            } else {
                catChips.forEach(c => c.classList.toggle('chip-active', c.dataset.type === ''));
                typeHidden.value = '';
            }
        });
    });

    // ---------- spot booking ----------
    spotBtn.addEventListener('click', () => {
        const p = new Date();
        p.setMinutes(p.getMinutes() + 30);
        const r = new Date(p);
        r.setDate(r.getDate() + 1);
        pickupDT.value = toLocalInputValue(p);
        returnDT.value = toLocalInputValue(r);
        returnDT.min = pickupDT.value;
        syncHiddenAndSummary();
        flash(spotBtn);
    });

    // ---------- same-location ----------
    function applySameLoc() {
        if (sameLoc.checked) {
            dropLocField.style.opacity = '.5';
            dropLocation.disabled = true;
            dropLocation.value = pickupLocation.value;
        } else {
            dropLocField.style.opacity = '';
            dropLocation.disabled = false;
        }
    }
    sameLoc.addEventListener('change', applySameLoc);
    pickupLocation.addEventListener('change', () => {
        if (sameLoc.checked) dropLocation.value = pickupLocation.value;
    });
    applySameLoc();

    // ---------- promo ----------
    promoToggle.addEventListener('click', () => {
        const willOpen = promoRow.hasAttribute('hidden');
        if (willOpen) promoRow.removeAttribute('hidden');
        else promoRow.setAttribute('hidden', '');
        promoToggle.querySelector('span').textContent = willOpen ? '−' : '+';
    });
    applyPromo.addEventListener('click', () => {
        const code = (promoInput.value || '').trim().toUpperCase();
        if (!code) { promoStatus.textContent = ''; return; }
        // Demo codes — server can also honor these later
        const known = { WHEELS10: 10, WHEELS20: 20, FIRSTRIDE: 15 };
        if (known[code]) {
            promoStatus.textContent = `${known[code]}% off applied`;
            promoStatus.className = 'promo-status ok';
        } else {
            promoStatus.textContent = 'Code not recognized';
            promoStatus.className = 'promo-status err';
        }
    });

    // ---------- submit guard ----------
    form.addEventListener('submit', e => {
        const p = pickupDT.value ? new Date(pickupDT.value) : null;
        const r = returnDT.value ? new Date(returnDT.value) : null;
        if (!p || !r) { e.preventDefault(); setError('Please pick both dates.'); return; }
        if (r <= p)   { e.preventDefault(); setError('Drop-off must be after pick-up.'); return; }
        // pickupHidden/returnHidden are already kept fresh
    });

    function flash(el) {
        el.classList.add('chip-pulse');
        setTimeout(() => el.classList.remove('chip-pulse'), 300);
    }
})();
