$(document).ready(function () {
    // --- DOM Elements ---
    const mkSelect = document.getElementById('dashFilterMk');
    const agroSelect = document.getElementById('dashFilterAgronomis');
    const faSelect = document.getElementById('dashFilterFA');
    const dateRangeInput = $('#date-range');
    const loadingOverlay = document.getElementById('loading-overlay');
    const mapContainer = document.getElementById('visitMap');

    // --- State Management ---
    let currentFilters = {
        marketing_manager_id: ['semua'],
        agronomist_id: ['semua'],
        field_assistant_id: ['semua'],
        start_date: moment().startOf('week').format('YYYY-MM-DD'),
        end_date: moment().endOf('week').format('YYYY-MM-DD'),
    };
    let map = null;
    let activeMarkers = [];

    // --- Daterangepicker Initialization ---
    if (dateRangeInput.length) {
        dateRangeInput.daterangepicker({
            opens: 'left',
            startDate: moment(currentFilters.start_date),
            endDate: moment(currentFilters.end_date),
            locale: {
                format: 'DD/MM/YYYY'
            }
        });
    }

    // --- TomSelect Initialization ---
    function setupExclusiveSemua(tsInstance) {
        tsInstance.on('item_add', function(value, item) {
            if (value === 'semua') {
                if (tsInstance.getValue().length > 1) tsInstance.setValue(['semua'], true);
            } else {
                if (tsInstance.getValue().includes('semua')) {
                    tsInstance.removeItem('semua', true);
                }
            }
        });
        tsInstance.on('item_remove', function(value, item) {
            if (tsInstance.getValue().length === 0) tsInstance.setValue(['semua'], true);
        });
    }

    let tsMk = null, tsAgro = null, tsFa = null;

    if (mkSelect) {
        tsMk = new TomSelect(mkSelect, { placeholder: "Pilih Marketing Manager..." });
        setupExclusiveSemua(tsMk);
    }
    if (agroSelect) {
        tsAgro = new TomSelect(agroSelect, { placeholder: "Pilih Agronomis..." });
        setupExclusiveSemua(tsAgro);
    }
    if (faSelect) {
        tsFa = new TomSelect(faSelect, { placeholder: "Pilih Field Assistant..." });
        setupExclusiveSemua(tsFa);
    }


    function initializeMap() {
        mapboxgl.accessToken = window.Laravel.routes.mapboxToken;
        map = new mapboxgl.Map({
            container: mapContainer,
            style: 'mapbox://styles/mapbox/streets-v12',
            center: [110.3695, -7.7956],
            zoom: 7
        });
        map.addControl(new mapboxgl.NavigationControl());
    }

    function updateMap(mapData) {
        // Remove old markers
        activeMarkers.forEach(marker => marker.remove());
        activeMarkers = [];

        if (!mapData || mapData.length === 0) {
            $('#map-badge-count').text('0 titik');
            // Optionally reset map view
            map.flyTo({ center: [110.3695, -7.7956], zoom: 7 });
            return;
        }

        $('#map-badge-count').text(`${mapData.length} titik`);
        const bounds = new mapboxgl.LngLatBounds();

        mapData.forEach(point => {
            const el = document.createElement('div');
            el.className = 'custom-marker';

            const label = document.createElement('div');
            label.className = 'marker-label';
            label.textContent = point.user_name;
            el.appendChild(label);

            const pin = document.createElement('div');
            pin.className = 'marker-pin';
            pin.style.backgroundColor = point.hex_color || '#808080';
            if (point.type === 'visit') {
                pin.classList.add('is-visit');
            }
            el.appendChild(pin);

            let popupContent = `
                <strong>${point.user_name}</strong><br>
                Waktu: ${point.time}<br>
                Tipe: ${point.type.charAt(0).toUpperCase() + point.type.slice(1)}
            `;
            if (point.type === 'visit') {
                popupContent += `<br>Customer: ${point.customer_name || 'N/A'}`;
            }

            const popup = new mapboxgl.Popup({ offset: 25 }).setHTML(popupContent);

            const marker = new mapboxgl.Marker(el)
                .setLngLat([point.lng, point.lat])
                .setPopup(popup)
                .addTo(map);

            activeMarkers.push(marker);
            bounds.extend([point.lng, point.lat]);
        });

        map.fitBounds(bounds, { padding: 50, maxZoom: 15 });
    }

    function populateSelect(tomSelectInstance, items, defaultOptionText = 'Semua') {
        if (!tomSelectInstance) return;
        tomSelectInstance.clear(true);
        tomSelectInstance.clearOptions();
        tomSelectInstance.removeOption('semua');
        tomSelectInstance.addOption({ value: 'semua', text: defaultOptionText });
        items.forEach(item => {
            tomSelectInstance.addOption({
                value: item.id,
                text: item.name
            });
        });
        tomSelectInstance.setValue(['semua'], true);
        tomSelectInstance.enable();
    }

    function buildQueryString(key, values) {
        if (!values || values.length === 0 || (values.length === 1 && values[0] === 'semua')) {
            return '';
        }
        return values.map(val => `${key}[]=${encodeURIComponent(val)}`).join('&');
    }

    async function loadMarketingManagers() {
        if (!tsMk) return;
        tsMk.disable();
        tsMk.clear(true);
        tsMk.clearOptions();
        tsMk.removeOption('semua');
        tsMk.addOption({value: 'semua', text: 'Memuat...'});
        tsMk.setValue(['semua'], true);
        try {
            const response = await fetch(window.Laravel.routes.listMk);
            const result = await response.json();
            if (result.success) {
                populateSelect(tsMk, result.data);
            }
        } catch (error) {
            console.error('Error loading Marketing Managers:', error);
            populateSelect(tsMk, [], 'Semua');
            tsMk.enable();
        }
    }

    async function loadAgronomists(marketingManagerIds = ['semua']) {
        if (!tsAgro) return;
        tsAgro.disable();
        tsAgro.clear(true);
        tsAgro.clearOptions();
        tsAgro.removeOption('semua');
        tsAgro.addOption({value: 'semua', text: 'Memuat...'});
        tsAgro.setValue(['semua'], true);
        try {
            const mkQuery = buildQueryString('marketing_manager_id', marketingManagerIds);
            const url = `${window.Laravel.routes.listAgronomis}${mkQuery ? '?' + mkQuery : ''}`;

            const response = await fetch(url);
            const result = await response.json();
            if (result.success) {
                populateSelect(tsAgro, result.data);
            }
        } catch (error) {
            console.error('Error loading Agronomists:', error);
            populateSelect(tsAgro, [], 'Semua');
            tsAgro.enable();
        }
    }

    async function loadFieldAssistants(marketingManagerIds = ['semua'], agronomistIds = ['semua']) {
        if (!tsFa) return;
        tsFa.disable();
        tsFa.clear(true);
        tsFa.clearOptions();
        tsFa.removeOption('semua');
        tsFa.addOption({value: 'semua', text: 'Memuat...'});
        tsFa.setValue(['semua'], true);
        try {
            const mkQuery = buildQueryString('marketing_manager_id', marketingManagerIds);
            const agroQuery = buildQueryString('agronomist_id', agronomistIds);

            let queryParams = [mkQuery, agroQuery].filter(q => q).join('&');
            const url = `${window.Laravel.routes.listFa}${queryParams ? '?' + queryParams : ''}`;

            const response = await fetch(url);
            const result = await response.json();
            if (result.success) {
                populateSelect(tsFa, result.data);
            }
        } catch (error) {
            console.error('Error loading Field Assistants:', error);
            populateSelect(tsFa, [], 'Semua');
            tsFa.enable();
        }
    }

    if (tsMk) {
        tsMk.on('change', function() {
            const selectedMkIds = tsMk.getValue();
            loadAgronomists(selectedMkIds);
            loadFieldAssistants(selectedMkIds, ['semua']);
        });
    }

    if (tsAgro) {
        tsAgro.on('change', function() {
            const selectedMkIds = tsMk ? tsMk.getValue() : ['semua'];
            const selectedAgroIds = tsAgro.getValue();
            loadFieldAssistants(selectedMkIds, selectedAgroIds);
        });
    }

    async function fetchDashboardData(filters) {
        loadingOverlay.style.display = 'flex';

        const params = new URLSearchParams();
        for (const key in filters) {
            if (Array.isArray(filters[key])) {
                filters[key].forEach(value => params.append(`${key}[]`, value));
            } else {
                params.append(key, filters[key]);
            }
        }

        const url = `${window.Laravel.routes.query}?${params.toString()}`;

        try {
            const response = await fetch(url);
            const result = await response.json();

            if (result.success) {
                updateStatCards(result.data.stats);
                updateMap(result.data.map_data); // <-- INTEGRATION POINT
            } else {
                console.error('Failed to fetch dashboard data:', result.message);
            }
        } catch (error) {
            console.error('Error during dashboard data fetch:', error);
        } finally {
            loadingOverlay.style.display = 'none';
        }
    }

    function updateStatCards(stats) {
        document.getElementById('stat-checkin').textContent = stats.check_in || '0';
        document.getElementById('stat-dealer').textContent = stats.visit_dealer || '0';
        document.getElementById('stat-retailer').textContent = stats.visit_retailer || '0';
        document.getElementById('stat-farmer').textContent = stats.visit_farmer || '0';
    }

    // --- Global Functions & Initial Load ---
    window.applyDashboardFilter = function () {
        const dateRangePicker = dateRangeInput.data('daterangepicker');
        currentFilters = {
            marketing_manager_id: tsMk ? tsMk.getValue() : ['semua'],
            agronomist_id: tsAgro ? tsAgro.getValue() : ['semua'],
            field_assistant_id: tsFa ? tsFa.getValue() : ['semua'],
            start_date: dateRangePicker.startDate.format('YYYY-MM-DD'),
            end_date: dateRangePicker.endDate.format('YYYY-MM-DD'),
        };
        fetchDashboardData(currentFilters);
    }

    window.resetDashboardFilter = function () {
        if (tsMk) tsMk.setValue(['semua']);
        if (tsAgro) tsAgro.setValue(['semua']);
        if (tsFa) tsFa.setValue(['semua']);

        const startOfWeek = moment().startOf('week');
        const endOfWeek = moment().endOf('week');
        dateRangeInput.data('daterangepicker').setStartDate(startOfWeek);
        dateRangeInput.data('daterangepicker').setEndDate(endOfWeek);

        if (tsMk) loadMarketingManagers();
        if (tsAgro) loadAgronomists();
        if (tsFa) loadFieldAssistants();

        applyDashboardFilter();
    }

    window.exportDashboard = function () {
        const params = new URLSearchParams();
        for (const key in currentFilters) {
            if (Array.isArray(currentFilters[key])) {
                currentFilters[key].forEach(value => params.append(`${key}[]`, value));
            } else {
                params.append(key, currentFilters[key]);
            }
        }
        window.location.href = `${window.Laravel.routes.export}?${params.toString()}`;
    }

    // --- Initial Load Sequence ---
    initializeMap();
    loadMarketingManagers();
    loadAgronomists();
    loadFieldAssistants();
    applyDashboardFilter();
});
