document.addEventListener('click', function (event) {
    const toggle = event.target.closest('[data-toggle-sidebar], [data-mobile-menu]');
    if (toggle) {
        document.body.classList.toggle('sidebar-open');
    }

    if (event.target.closest('.sidebar-nav a')) {
        document.body.classList.remove('sidebar-open');
    }

    const remove = event.target.closest('[data-remove-row]');
    if (remove) {
        const row = remove.closest('.line-item-row, .stop-row');
        if (row) row.remove();
    }

    const addStop = event.target.closest('[data-add-stop]');
    if (addStop) {
        const container = document.querySelector('#load-stops');
        if (container) {
            const row = document.createElement('div');
            row.className = 'stop-row';
            row.className = 'stop-row stop-row-expanded';
            row.innerHTML = `
                <select name="stop_type[]" aria-label="Stop type"><option value="pickup">Pickup</option><option value="delivery">Delivery</option></select>
                <input name="stop_location[]" placeholder="Location">
                <input type="datetime-local" name="stop_datetime[]" aria-label="Scheduled time">
                <input name="stop_contact[]" placeholder="Contact">
                <input type="number" step="0.1" name="stop_temperature[]" placeholder="Temp">
                <select name="stop_temperature_unit[]" aria-label="Temperature unit"><option value="">Unit</option><option value="F">°F</option><option value="C">°C</option></select>
                <input name="stop_seal_number[]" placeholder="Seal number">
                <input name="stop_notes[]" placeholder="Stop notes">
                <input type="hidden" name="stop_latitude[]">
                <input type="hidden" name="stop_longitude[]">
                <button class="btn btn-danger btn-sm" type="button" data-remove-row>Remove</button>
            `;
            container.appendChild(row);
        }
    }

    const addInvoiceItem = event.target.closest('[data-add-invoice-item]');
    if (addInvoiceItem) {
        const container = document.querySelector('#invoice-items');
        if (container) {
            const row = document.createElement('div');
            row.className = 'line-item-row';
            row.innerHTML = `
                <input name="item_description[]" placeholder="Description">
                <input type="number" step="0.01" name="item_amount[]" placeholder="Amount">
                <button class="btn btn-danger btn-sm" type="button" data-remove-row>Remove</button>
            `;
            container.appendChild(row);
        }
    }

    const stopUpload = event.target.closest('[data-fill-stop-upload]');
    if (stopUpload) {
        const relatedType = document.querySelector('#upload-related-type');
        const relatedId = document.querySelector('#upload-related-id');
        const docType = document.querySelector('#upload-document-type');
        const note = document.querySelector('#selected-stop-note');
        const form = document.querySelector('#driver-upload-form');
        if (relatedType && relatedId) {
            relatedType.value = 'stop';
            relatedId.value = stopUpload.getAttribute('data-fill-stop-upload');
        }
        if (docType) docType.value = 'Stop Photo';
        if (note) note.textContent = 'Attached to stop: ' + (stopUpload.getAttribute('data-stop-label') || 'Selected stop');
        if (form) form.scrollIntoView({behavior: 'smooth', block: 'start'});
    }
});

document.addEventListener('change', function (event) {
    const loadSelect = event.target.closest('#invoice-load-select');
    if (!loadSelect) return;

    const selected = loadSelect.options[loadSelect.selectedIndex];
    const brokerId = selected ? selected.getAttribute('data-broker') : '';
    const rate = selected ? selected.getAttribute('data-rate') : '';
    const brokerSelect = document.querySelector('#invoice-broker-select');
    if (brokerSelect && brokerId) brokerSelect.value = brokerId;

    const firstAmount = document.querySelector('#invoice-items input[name="item_amount[]"]');
    if (firstAmount && rate) firstAmount.value = rate;
});

document.addEventListener('submit', function (event) {
    const form = event.target.closest('[data-location-form]');
    if (!form || form.dataset.locationReady === '1') return;

    const needsLat = form.querySelector('[data-latitude]');
    const needsLng = form.querySelector('[data-longitude]');
    if (!needsLat || !needsLng) return;

    if (!navigator.geolocation) {
        return;
    }

    event.preventDefault();
    const submitter = event.submitter;
    if (submitter) {
        submitter.disabled = true;
        submitter.dataset.originalText = submitter.textContent;
        submitter.textContent = 'Capturing location...';
    }

    navigator.geolocation.getCurrentPosition(function (position) {
        form.querySelectorAll('[data-latitude]').forEach(function (input) { input.value = position.coords.latitude.toFixed(7); });
        form.querySelectorAll('[data-longitude]').forEach(function (input) { input.value = position.coords.longitude.toFixed(7); });
        form.querySelectorAll('[data-accuracy]').forEach(function (input) { input.value = position.coords.accuracy ? position.coords.accuracy.toFixed(2) : ''; });
        form.dataset.locationReady = '1';
        form.submit();
    }, function () {
        form.dataset.locationReady = '1';
        form.submit();
    }, {
        enableHighAccuracy: true,
        timeout: 8000,
        maximumAge: 60000
    });
});

(function () {
    if ('serviceWorker' in navigator) {
        window.addEventListener('load', function () {
            navigator.serviceWorker.register((document.body.dataset.baseUrl || '') + '/service-worker.js').catch(function () {});
        });
    }

    const tracker = document.querySelector('[data-live-tracking]');
    if (tracker) {
        const loadId = tracker.dataset.loadId;
        const pingUrl = tracker.dataset.pingUrl;
        const stopUrl = tracker.dataset.stopUrl;
        const csrf = tracker.dataset.csrf;
        const intervalMs = Math.max(15000, Number(tracker.dataset.interval || 30) * 1000);
        const startButton = tracker.querySelector('[data-start-tracking]');
        const stopButton = tracker.querySelector('[data-stop-tracking]');
        const state = tracker.querySelector('[data-tracking-state]');
        const message = tracker.querySelector('[data-tracking-message]');
        const storageKey = 'fleetlume_tracking_' + loadId;
        let watchId = null;
        let sessionId = Number(localStorage.getItem(storageKey) || 0);
        let lastSentAt = 0;
        let batteryLevel = null;

        if (navigator.getBattery) {
            navigator.getBattery().then(function (battery) {
                batteryLevel = Math.round(battery.level * 100);
                battery.addEventListener('levelchange', function () { batteryLevel = Math.round(battery.level * 100); });
            }).catch(function () {});
        }

        function setTracking(active, text) {
            startButton.disabled = active;
            stopButton.disabled = !active;
            state.textContent = active ? 'Sharing live location' : 'Not sharing';
            state.classList.toggle('is-live', active);
            message.textContent = text || (active ? 'Location updates are being sent while this page is open.' : 'Location sharing is stopped.');
        }

        function postPosition(position, force) {
            const now = Date.now();
            if (!force && now - lastSentAt < intervalMs) return;
            lastSentAt = now;
            const data = new URLSearchParams();
            data.set('_csrf_token', csrf);
            data.set('load_id', loadId);
            data.set('session_id', String(sessionId || ''));
            data.set('latitude', String(position.coords.latitude));
            data.set('longitude', String(position.coords.longitude));
            data.set('accuracy', String(position.coords.accuracy || ''));
            data.set('speed', String(position.coords.speed == null ? '' : Math.max(0, position.coords.speed * 2.23694)));
            data.set('heading', String(position.coords.heading == null ? '' : position.coords.heading));
            data.set('battery_level', batteryLevel == null ? '' : String(batteryLevel));
            fetch(pingUrl, {method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'}, body: data.toString(), credentials: 'same-origin'})
                .then(function (response) { return response.json(); })
                .then(function (result) {
                    if (!result.ok) throw new Error(result.message || 'Location update failed');
                    sessionId = Number(result.session_id || sessionId);
                    localStorage.setItem(storageKey, String(sessionId));
                    setTracking(true, 'Last GPS update: ' + new Date().toLocaleTimeString());
                })
                .catch(function (error) { message.textContent = error.message + '. The app will retry.'; });
        }

        function startTracking() {
            if (!navigator.geolocation) { message.textContent = 'Location services are not supported on this device.'; return; }
            setTracking(true, 'Requesting location permission...');
            watchId = navigator.geolocation.watchPosition(function (position) {
                postPosition(position, lastSentAt === 0);
            }, function (error) {
                setTracking(false, error.code === 1 ? 'Location permission was denied. Enable it in browser settings.' : 'Unable to read GPS location.');
            }, {enableHighAccuracy: true, maximumAge: 5000, timeout: 20000});
        }

        function stopTracking() {
            if (watchId !== null) navigator.geolocation.clearWatch(watchId);
            watchId = null;
            const data = new URLSearchParams(); data.set('_csrf_token', csrf); data.set('session_id', String(sessionId || ''));
            fetch(stopUrl, {method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'}, body: data.toString(), credentials: 'same-origin'}).catch(function () {});
            localStorage.removeItem(storageKey); sessionId = 0; lastSentAt = 0; setTracking(false, 'Live tracking stopped.');
        }

        startButton.addEventListener('click', startTracking);
        stopButton.addEventListener('click', stopTracking);
        if (sessionId) startTracking();
    }

    const mapElement = document.querySelector('#tracking-map');
    if (mapElement && window.L) {
        const map = L.map(mapElement).setView([39.5, -98.35], 4);
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {maxZoom: 19, attribution: '&copy; OpenStreetMap'}).addTo(map);
        const markers = {};
        const list = document.querySelector('#tracking-list');
        const updated = document.querySelector('#tracking-updated');

        function refreshMap() {
            fetch(mapElement.dataset.endpoint, {credentials: 'same-origin'}).then(function (r) { return r.json(); }).then(function (result) {
                if (!result.ok) return;
                const bounds = [];
                list.innerHTML = '';
                result.locations.forEach(function (location) {
                    const lat = Number(location.latitude), lng = Number(location.longitude);
                    if (!Number.isFinite(lat) || !Number.isFinite(lng)) return;
                    bounds.push([lat, lng]);
                    const html = '<strong>' + escapeHtml(location.driver_name || 'Driver') + '</strong><br>' + escapeHtml(location.load_number || '') + ' · ' + escapeHtml(location.unit_number || '-') + '<br><small>' + escapeHtml(location.last_location_address || '') + '<br>Updated ' + escapeHtml(location.last_location_at || '-') + '</small>';
                    if (markers[location.load_id]) markers[location.load_id].setLatLng([lat, lng]).setPopupContent(html);
                    else markers[location.load_id] = L.marker([lat, lng]).addTo(map).bindPopup(html);
                    const card = document.createElement('button'); card.type = 'button'; card.className = 'mini-card tracking-list-card'; card.innerHTML = '<strong>' + escapeHtml(location.driver_name || 'Driver') + ' · ' + escapeHtml(location.load_number || '') + '</strong><span>' + escapeHtml(location.unit_number || '-') + ' · ' + escapeHtml(location.status || '') + '<br>' + escapeHtml(location.last_location_at || '-') + '</span>';
                    card.addEventListener('click', function () { map.setView([lat, lng], 12); markers[location.load_id].openPopup(); }); list.appendChild(card);
                });
                if (bounds.length) map.fitBounds(bounds, {padding: [30, 30], maxZoom: 11});
                if (!result.locations.length) list.innerHTML = '<p class="empty">No active driver locations yet.</p>';
                updated.textContent = 'Updated ' + new Date().toLocaleTimeString();
            }).catch(function () { updated.textContent = 'Unable to refresh'; });
        }
        document.querySelector('#refresh-tracking')?.addEventListener('click', refreshMap);
        refreshMap(); setInterval(refreshMap, 20000);
    }

    function escapeHtml(value) {
        return String(value == null ? '' : value).replace(/[&<>'"]/g, function (char) { return {'&':'&amp;','<':'&lt;','>':'&gt;',"'":'&#39;','"':'&quot;'}[char]; });
    }

    window.addEventListener('online', function () { document.body.classList.remove('is-offline'); });
    window.addEventListener('offline', function () { document.body.classList.add('is-offline'); });
})();

(function () {
    function initResponsiveTables(root) {
        (root || document).querySelectorAll('.table-wrap table:not(.invoice-table)').forEach(function (table) {
            table.classList.add('responsive-table');
            const headers = Array.from(table.querySelectorAll('thead th')).map(function (th) { return th.textContent.trim(); });
            table.querySelectorAll('tbody tr').forEach(function (row) {
                Array.from(row.children).forEach(function (cell, index) {
                    if (cell.tagName === 'TD' && !cell.hasAttribute('data-label')) cell.setAttribute('data-label', headers[index] || 'Details');
                });
            });
        });
    }

    function toggleFields(toggle, fields) {
        if (!toggle || !fields) return;
        fields.classList.toggle('is-disabled', !toggle.checked);
        fields.querySelectorAll('input,select,textarea').forEach(function (input) {
            if (input.type !== 'hidden') input.disabled = !toggle.checked;
        });
    }

    function formatMoney(value, sample) {
        const symbol = (sample || '$').replace(/[\d\s,.-]/g, '') || '$';
        return symbol + Number(value || 0).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});
    }

    const loadForm = document.querySelector('[data-load-form]');
    if (loadForm) {
        const carrierSelect = loadForm.querySelector('[data-carrier-select]');
        const customerRate = loadForm.querySelector('[data-customer-rate]');
        const carrierRate = loadForm.querySelector('[data-carrier-rate]');
        const feeType = loadForm.querySelector('[data-fee-type]');
        const feeValue = loadForm.querySelector('[data-fee-value]');
        const equipmentSelects = loadForm.querySelectorAll('[data-equipment-select], [data-trailer-select]');
        const trailerSelect = loadForm.querySelector('[data-trailer-select]');
        const reeferToggle = loadForm.querySelector('[data-load-reefer-toggle]');
        const reeferFields = loadForm.querySelector('[data-load-reefer-fields]');
        const previewCustomer = loadForm.querySelector('[data-preview-customer]');
        const previewCarrier = loadForm.querySelector('[data-preview-carrier]');
        const previewFee = loadForm.querySelector('[data-preview-fee]');
        const previewNet = loadForm.querySelector('[data-preview-net]');

        function filterEquipment() {
            const carrierId = carrierSelect ? carrierSelect.value : '';
            equipmentSelects.forEach(function (select) {
                Array.from(select.options).forEach(function (option, index) {
                    if (index === 0) return;
                    const matches = !carrierId || option.dataset.carrierId === carrierId || option.selected;
                    option.hidden = !matches;
                    option.disabled = !matches;
                });
            });
        }

        function updateFinancialPreview() {
            const customer = Number(customerRate?.value || 0);
            const gross = Number(carrierRate?.value || 0);
            const feeInput = Number(feeValue?.value || 0);
            const fee = feeType?.value === 'fixed' ? feeInput : gross * feeInput / 100;
            const net = Math.max(0, gross - fee);
            const sample = previewCustomer?.textContent || '$';
            if (previewCustomer) previewCustomer.textContent = formatMoney(customer, sample);
            if (previewCarrier) previewCarrier.textContent = formatMoney(gross, sample);
            if (previewFee) previewFee.textContent = formatMoney(fee, sample);
            if (previewNet) previewNet.textContent = formatMoney(net, sample);
        }

        carrierSelect?.addEventListener('change', function () {
            const option = carrierSelect.options[carrierSelect.selectedIndex];
            const defaultType = option?.dataset.feeType;
            const defaultValue = option?.dataset.feeValue;
            if (defaultType && feeType) feeType.value = defaultType === 'fixed_per_load' ? 'fixed' : 'percentage';
            if (defaultValue !== undefined && feeValue) feeValue.value = defaultValue;
            filterEquipment();
            updateFinancialPreview();
        });
        [customerRate, carrierRate, feeType, feeValue].forEach(function (field) {
            field?.addEventListener('input', updateFinancialPreview);
            field?.addEventListener('change', updateFinancialPreview);
        });
        trailerSelect?.addEventListener('change', function () {
            const option = trailerSelect.options[trailerSelect.selectedIndex];
            if (option?.dataset.reefer === '1' && reeferToggle) {
                reeferToggle.checked = true;
                toggleFields(reeferToggle, reeferFields);
                const setpoint = loadForm.querySelector('[name="temperature_setpoint"]');
                const unit = loadForm.querySelector('[name="temperature_unit"]');
                if (setpoint && !setpoint.value && option.dataset.setpoint) setpoint.value = option.dataset.setpoint;
                if (unit && option.dataset.tempUnit) unit.value = option.dataset.tempUnit;
            }
        });
        reeferToggle?.addEventListener('change', function () { toggleFields(reeferToggle, reeferFields); });
        filterEquipment();
        toggleFields(reeferToggle, reeferFields);
        updateFinancialPreview();
    }

    const trailerForm = document.querySelector('[data-trailer-form]');
    if (trailerForm) {
        const type = trailerForm.querySelector('[data-trailer-type]');
        const toggle = trailerForm.querySelector('[data-reefer-toggle]');
        const fields = trailerForm.querySelector('[data-reefer-fields]');
        function syncReefer() {
            if (type && /reefer/i.test(type.value) && toggle) toggle.checked = true;
            toggleFields(toggle, fields);
        }
        type?.addEventListener('change', syncReefer);
        toggle?.addEventListener('change', function () { toggleFields(toggle, fields); });
        syncReefer();
    }

    document.addEventListener('click', function (event) {
        if (document.body.classList.contains('sidebar-open') && !event.target.closest('#sidebar') && !event.target.closest('[data-mobile-menu], [data-toggle-sidebar]')) {
            document.body.classList.remove('sidebar-open');
        }
    });
    document.addEventListener('keydown', function (event) {
        if (event.key === 'Escape') document.body.classList.remove('sidebar-open');
    });

    initResponsiveTables(document);
})();


(function () {
    document.querySelectorAll('[data-sidebar-close]').forEach(function (button) {
        button.addEventListener('click', function () { document.body.classList.remove('sidebar-open'); });
    });
    document.querySelectorAll('.sidebar-v2 .nav-item').forEach(function (link) {
        link.addEventListener('click', function () {
            if (window.matchMedia('(max-width: 860px)').matches) document.body.classList.remove('sidebar-open');
        });
    });
    document.querySelectorAll('.nav-section').forEach(function (section, index) {
        var key = 'fleetlume_nav_section_' + index;
        if (!section.querySelector('.nav-item.active')) {
            var saved = localStorage.getItem(key);
            if (saved === 'open') section.open = true;
            if (saved === 'closed') section.open = false;
        }
        section.addEventListener('toggle', function () { localStorage.setItem(key, section.open ? 'open' : 'closed'); });
    });

    document.querySelectorAll('[data-panel-toggle]').forEach(function (button) {
        button.addEventListener('click', function () {
            var panel = document.getElementById(button.dataset.panelToggle);
            if (!panel) return;
            panel.hidden = false;
            panel.scrollIntoView({behavior:'smooth', block:'start'});
        });
    });
    document.querySelectorAll('[data-panel-close]').forEach(function (button) {
        button.addEventListener('click', function () {
            var panel = button.closest('[data-collapsible-panel]');
            if (panel) panel.hidden = true;
        });
    });

    var form = document.querySelector('[data-fuel-allocation-form]');
    if (form) {
        var load = form.querySelector('[data-fuel-load]');
        var miles = form.querySelector('[data-fuel-miles]');
        var mpg = form.querySelector('[data-fuel-mpg]');
        var price = form.querySelector('[data-fuel-price]');
        var reserve = form.querySelector('[data-fuel-reserve]');
        var gallons = form.querySelector('[data-fuel-gallons]');
        var recommended = form.querySelector('[data-fuel-recommended]');
        var driver = form.querySelector('[data-fuel-driver]');
        var truck = form.querySelector('[data-fuel-truck]');
        var carrier = form.querySelector('[data-fuel-carrier]');
        function calculate() {
            var planned = Math.max(0, Number(miles.value || 0));
            var target = Math.max(.1, Number(mpg.value || 6.5));
            var expected = Math.max(0, Number(price.value || 0));
            var buffer = Math.max(0, Number(reserve.value || 0));
            var gal = planned / target;
            var amount = gal * expected * (1 + buffer / 100);
            gallons.value = gal.toFixed(2);
            recommended.value = '$' + amount.toLocaleString(undefined,{minimumFractionDigits:2,maximumFractionDigits:2});
        }
        [miles,mpg,price,reserve].forEach(function (input) { input.addEventListener('input', calculate); });
        load.addEventListener('change', function () {
            var option = load.options[load.selectedIndex];
            if (!option) return;
            if (option.dataset.miles) miles.value = option.dataset.miles;
            if (option.dataset.driver) driver.value = option.dataset.driver;
            if (option.dataset.truck) truck.value = option.dataset.truck;
            if (option.dataset.carrier) carrier.value = option.dataset.carrier;
            calculate();
        });
        calculate();
    }

    document.querySelectorAll('.fuel-purchase-form form').forEach(function (purchaseForm) {
        var gallons = purchaseForm.querySelector('[data-purchase-gallons]');
        var price = purchaseForm.querySelector('[data-purchase-price]');
        var amount = purchaseForm.querySelector('[data-purchase-amount]');
        function calculatePurchase() {
            var total = Number(gallons.value || 0) * Number(price.value || 0);
            if (total > 0) amount.value = total.toFixed(2);
        }
        gallons.addEventListener('input', calculatePurchase);
        price.addEventListener('input', calculatePurchase);
    });
})();

// Driver logbook location capture.
document.querySelectorAll('[data-hos-capture-location]').forEach((button) => {
    button.addEventListener('click', () => {
        const form = button.closest('[data-hos-location-form]');
        if (!form || !navigator.geolocation) {
            window.alert('Location is not available in this browser.');
            return;
        }
        const originalText = button.textContent;
        button.disabled = true;
        button.textContent = 'Locating…';
        navigator.geolocation.getCurrentPosition((position) => {
            const latitude = form.querySelector('[data-hos-latitude]');
            const longitude = form.querySelector('[data-hos-longitude]');
            const address = form.querySelector('[data-hos-location-address]');
            if (latitude) latitude.value = position.coords.latitude.toFixed(7);
            if (longitude) longitude.value = position.coords.longitude.toFixed(7);
            if (address && !address.value) address.value = `GPS ${position.coords.latitude.toFixed(5)}, ${position.coords.longitude.toFixed(5)}`;
            button.textContent = 'GPS Added';
            setTimeout(() => { button.disabled = false; button.textContent = originalText; }, 1800);
        }, (error) => {
            button.disabled = false;
            button.textContent = originalText;
            window.alert(error.message || 'Location permission was not granted.');
        }, { enableHighAccuracy: true, timeout: 12000, maximumAge: 30000 });
    });
});


(function () {
    document.querySelectorAll('[data-ai-prompt]').forEach(function (button) {
        button.addEventListener('click', function () {
            const textarea = button.closest('form')?.querySelector('textarea[name="question"]');
            if (!textarea) return;
            textarea.value = button.dataset.aiPrompt || '';
            textarea.focus();
        });
    });
    document.querySelectorAll('[data-copy-target]').forEach(function (button) {
        button.addEventListener('click', function () {
            const target = document.querySelector(button.dataset.copyTarget || '');
            if (!target || !navigator.clipboard) return;
            navigator.clipboard.writeText(target.innerText || target.textContent || '').then(function () {
                const old = button.textContent;
                button.textContent = 'Copied';
                setTimeout(function () { button.textContent = old; }, 1500);
            });
        });
    });
    document.querySelectorAll('.ai-submit').forEach(function (button) {
        button.closest('form')?.addEventListener('submit', function () {
            button.disabled = true;
            button.dataset.originalText = button.textContent;
            button.textContent = 'Working…';
        });
    });
})();
