@php
    $record = $getRecord();
    $user = auth()->user();
    $company = $user->company;
    
    // Check permissions
    $isSuperAdmin = $user->hasRole('super_admin');
    $isOwnAttendance = $record->user_id == $user->id;
    $backdateEnabled = $company->backdate_enabled ?? false;
    $editableEnabled = $company->allow_editable_location ?? false;
    
    // Can edit if: (super admin OR own attendance) AND backdate enabled AND editable enabled
    // Note: Tidak ada batasan periode cutoff untuk edit koordinat map
    $canEdit = ($isSuperAdmin || $isOwnAttendance) && $backdateEnabled && $editableEnabled;

    $markers = [];
    $offices = [];

    // Helper function to sanitize strings for JSON
    $sanitizeForJson = function($value) {
        if ($value === null) return null;
        if (is_numeric($value)) return $value;
        // Remove any control characters and normalize line breaks
        $value = preg_replace('/[\x00-\x1F\x7F]/u', '', (string)$value);
        return $value;
    };

    // Add check-in marker (draggable if can edit)
    if ($record->check_in_latitude && $record->check_in_longitude) {
        $markers[] = [
            'lat' => (float) $record->check_in_latitude,
            'lng' => (float) $record->check_in_longitude,
            'type' => 'check_in',
            'name' => $sanitizeForJson($record->user?->name ?? 'User'),
            'time' => $record->check_in_time ? \Carbon\Carbon::parse($record->check_in_time)->format('H:i') : null,
            'address' => $sanitizeForJson($record->check_in_address),
            'distance' => $record->check_in_distance,
            'draggable' => $canEdit,
        ];
    }

    // Add check-out marker (draggable if can edit)
    if ($record->check_out_latitude && $record->check_out_longitude) {
        $markers[] = [
            'lat' => (float) $record->check_out_latitude,
            'lng' => (float) $record->check_out_longitude,
            'type' => 'check_out',
            'name' => $sanitizeForJson($record->user?->name ?? 'User'),
            'time' => $record->check_out_time ? \Carbon\Carbon::parse($record->check_out_time)->format('H:i') : null,
            'address' => $sanitizeForJson($record->check_out_address),
            'distance' => $record->check_out_distance,
            'draggable' => $canEdit,
        ];
    }

    // Add office marker if available
    if ($record->office && $record->office->latitude && $record->office->longitude) {
        $offices[] = [
            'lat' => (float) $record->office->latitude,
            'lng' => (float) $record->office->longitude,
            'name' => $sanitizeForJson($record->office->name),
            'address' => $sanitizeForJson($record->office->address),
            'radius' => $record->office->radius ?? 100,
        ];
    }

    $hasLocation = count($markers) > 0;
    $mapId = 'attendance-map-' . $record->id;
    $mapIdJs = str_replace('-', '_', $mapId);
    $initMapFunctionName = 'initMap_' . $mapIdJs;
    $initSearchFunctionName = 'initSearch_' . $mapIdJs;
    $saveCoordinatesFunctionName = 'saveCoordinates_' . $mapIdJs;
@endphp

@if($hasLocation)
    <div class="space-y-3">
        @if($canEdit)
            <div class="flex items-center justify-between p-3 bg-primary-50 dark:bg-primary-900/20 rounded-lg border border-primary-200 dark:border-primary-800">
                <div class="flex items-center gap-2">
                    <x-heroicon-o-information-circle class="w-5 h-5 text-primary-600 dark:text-primary-400" />
                    <p class="text-sm text-primary-700 dark:text-primary-300">
                        <span class="font-medium">Mode Edit:</span> Drag marker atau cari lokasi untuk mengubah koordinat
                    </p>
                </div>
            </div>
            
            {{-- Search Box --}}
            <div class="relative">
                <div class="flex items-center gap-2">
                    <div class="relative flex-1">
                        <x-heroicon-o-magnifying-glass class="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
                        <input 
                            type="text" 
                            id="search-input-{{ $mapId }}"
                            placeholder="Cari lokasi (contoh: Jl. Sudirman, Jakarta)" 
                            class="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 placeholder-gray-400 focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                        />
                    </div>
                    <select 
                        id="marker-type-{{ $mapId }}"
                        class="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-primary-500 focus:border-transparent"
                    >
                        <option value="check_in">Check In</option>
                        <option value="check_out">Check Out</option>
                    </select>
                </div>
            </div>
        @endif

        <div id="{{ $mapId }}" style="height: 350px; width: 100%;" class="rounded-lg border border-gray-200 dark:border-gray-700"></div>

        {{-- Coordinate Display --}}
        <div class="grid grid-cols-2 gap-3">
            @if($record->check_in_latitude && $record->check_in_longitude)
                <div class="p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                    <div class="text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">Check In</div>
                    <div class="text-sm font-mono text-gray-900 dark:text-gray-100" id="checkin-coords">
                        {{ number_format((float)$record->check_in_latitude, 6) }}, {{ number_format((float)$record->check_in_longitude, 6) }}
                    </div>
                </div>
            @endif
            @if($record->check_out_latitude && $record->check_out_longitude)
                <div class="p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                    <div class="text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">Check Out</div>
                    <div class="text-sm font-mono text-gray-900 dark:text-gray-100" id="checkout-coords">
                        {{ number_format((float)$record->check_out_latitude, 6) }}, {{ number_format((float)$record->check_out_longitude, 6) }}
                    </div>
                </div>
            @endif
        </div>

        {{-- Save Button (only if can edit) --}}
        @if($canEdit)
            <div class="flex justify-end">
                <button 
                    type="button"
                    data-save-function="{{ $saveCoordinatesFunctionName }}"
                    class="px-4 py-2 bg-primary-600 hover:bg-primary-700 text-white rounded-lg text-sm font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                    id="save-btn-{{ $mapId }}"
                    disabled
                >
                    <span class="flex items-center gap-2">
                        <x-heroicon-o-check class="w-4 h-4" />
                        Simpan Perubahan
                    </span>
                </button>
            </div>
        @endif

        {{-- Legend --}}
        <div class="flex items-center gap-4 text-xs text-gray-500 dark:text-gray-400">
            @if(count($offices) > 0)
                <div class="flex items-center gap-1.5">
                    <span class="w-3 h-3 rounded-full bg-blue-500"></span>
                    <span>Kantor</span>
                </div>
            @endif
            <div class="flex items-center gap-1.5">
                <span class="w-3 h-3 rounded-full bg-green-500"></span>
                <span>Check In</span>
            </div>
            <div class="flex items-center gap-1.5">
                <span class="w-3 h-3 rounded-full bg-red-500"></span>
                <span>Check Out</span>
            </div>
        </div>
    </div>
@else
    <div class="flex flex-col items-center justify-center py-8 text-gray-400 dark:text-gray-500">
        <x-heroicon-o-map class="w-12 h-12 mb-2" />
        <p class="text-sm">Tidak ada data lokasi</p>
    </div>
@endif

@once
    @push('scripts')
        @php
            $apiKey = config('services.google_maps.api_key', env('GOOGLE_MAPS_API_KEY', ''));
        @endphp
        @if($apiKey)
        @php
            $callbackName = 'initGoogleMapsCallback_' . $mapIdJs;
        @endphp
            <script>
                (function() {
                    if (!window.googleMapsCallbacks) {
                        window.googleMapsCallbacks = [];
                    }
                    
                    window[@json($callbackName)] = function() {
                        window.googleMapsLoaded = true;
                        if (window.googleMapsCallbacks && Array.isArray(window.googleMapsCallbacks)) {
                            window.googleMapsCallbacks.forEach(function(cb) {
                                try {
                                    if (typeof cb === 'function') {
                                        cb();
                                    }
                                } catch(e) {
                                    console.error('Error in Google Maps callback:', e);
                                }
                            });
                            window.googleMapsCallbacks = [];
                        }
                    };
                    
                    var script = document.createElement('script');
                    script.src = @json('https://maps.googleapis.com/maps/api/js?key=' . $apiKey . '&libraries=places,geometry&callback=' . $callbackName);
                    script.async = true;
                    script.defer = true;
                    document.head.appendChild(script);
                })();
            </script>
        @else
            <script>
                console.error('Google Maps API key tidak ditemukan. Pastikan GOOGLE_MAPS_API_KEY sudah dikonfigurasi di .env');
            </script>
        @endif
    @endpush
@endonce

@push('scripts')
<script>
(function() {
    const mapId = @json($mapId);
    const recordId = @json($record->id);
    const canEdit = {{ $canEdit ? 'true' : 'false' }};
    let map = null;
    let checkInMarker = null;
    let checkOutMarker = null;
    let hasChanges = false;
    let autocomplete = null;

    window[@json($initMapFunctionName)] = function() {
        // Wait for Google Maps API
        if (typeof google === 'undefined' || !google.maps || !google.maps.Map) {
            console.log('Waiting for Google Maps API to load...');
            if (window.googleMapsCallbacks) {
                window.googleMapsCallbacks.push(window[@json($initMapFunctionName)]);
            } else {
                setTimeout(window[@json($initMapFunctionName)], 100);
            }
            return;
        }
        
        console.log('Google Maps API loaded, initializing map...');

        const mapContainer = document.getElementById(mapId);
        if (!mapContainer) return;

        // Clear existing map
        if (mapContainer._googleMap) {
            mapContainer._googleMap = null;
        }
        mapContainer.innerHTML = '';

        const markers = @json($markers, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        const offices = @json($offices, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        const defaultZoom = 16;

        // Calculate center
        let center = { lat: -6.2, lng: 106.8 };
        if (markers.length > 0) {
            center = { lat: markers[0].lat, lng: markers[0].lng };
        } else if (offices.length > 0) {
            center = { lat: offices[0].lat, lng: offices[0].lng };
        }

        // Initialize Google Map with controls
        map = new google.maps.Map(mapContainer, {
            center: center,
            zoom: defaultZoom,
            mapTypeId: 'roadmap',
            zoomControl: true,
            mapTypeControl: true,
            scaleControl: true,
            streetViewControl: true,
            fullscreenControl: true,
            mapTypeControlOptions: {
                style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
                position: google.maps.ControlPosition.TOP_RIGHT
            },
            zoomControlOptions: {
                position: google.maps.ControlPosition.RIGHT_CENTER
            },
            styles: [
                {
                    featureType: 'poi',
                    elementType: 'labels',
                    stylers: [{ visibility: 'off' }]
                }
            ]
        });

        const bounds = new google.maps.LatLngBounds();
        const allMarkers = [];

        // Add office markers with radius
        offices.forEach(office => {
            const officePosition = { lat: office.lat, lng: office.lng };
            bounds.extend(officePosition);

            // Add radius circle
            if (office.radius) {
                new google.maps.Circle({
                    strokeColor: '#3b82f6',
                    strokeOpacity: 0.8,
                    strokeWeight: 2,
                    fillColor: '#3b82f6',
                    fillOpacity: 0.1,
                    map: map,
                    center: officePosition,
                    radius: office.radius
                });
            }

            // Add office marker
            const officeMarker = new google.maps.Marker({
                position: officePosition,
                map: map,
                icon: {
                    path: google.maps.SymbolPath.CIRCLE,
                    scale: 16,
                    fillColor: '#3b82f6',
                    fillOpacity: 1,
                    strokeColor: '#ffffff',
                    strokeWeight: 3
                },
                title: office.name || 'Kantor'
            });

            // Escape HTML and quotes for safe display
            const officeName = (office.name || 'Kantor').toString().replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
            const officeAddress = office.address ? office.address.toString().replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;') : '';
            
            const officeInfo = new google.maps.InfoWindow({
                content: '<div style="padding:12px;min-width:180px;">' +
                    '<h3 style="font-weight:700;margin:0 0 4px 0;font-size:14px;">' + officeName + '</h3>' +
                    (officeAddress ? '<p style="color:#6b7280;font-size:11px;margin:0;">' + officeAddress + '</p>' : '') +
                    '</div>'
            });

            officeMarker.addListener('click', () => {
                officeInfo.open(map, officeMarker);
            });

            allMarkers.push(officeMarker);
        });

        // Add attendance markers (draggable if can edit)
        markers.forEach(marker => {
            const markerPosition = { lat: marker.lat, lng: marker.lng };
            bounds.extend(markerPosition);

            const typeLabel = marker.type === 'check_in' ? 'Check In' : 'Check Out';
            const typeColor = marker.type === 'check_in' ? '#22c55e' : '#ef4444';

            // Create marker with custom icon
            // Draggable if canEdit is true (marker.draggable is already set based on canEdit in PHP)
            // Use canEdit directly since marker.draggable is set from $canEdit in PHP
            const isDraggable = canEdit === true;
            const mapMarker = new google.maps.Marker({
                position: markerPosition,
                map: map,
                draggable: isDraggable,
                icon: {
                    path: google.maps.SymbolPath.CIRCLE,
                    scale: 14,
                    fillColor: typeColor,
                    fillOpacity: 1,
                    strokeColor: '#ffffff',
                    strokeWeight: 3
                },
                title: typeLabel,
                cursor: isDraggable ? 'move' : 'default'
            });

            // Create info window - escape HTML and quotes
            const escapeHtml = function(str) {
                if (!str) return '';
                return str.toString()
                    .replace(/&/g, '&amp;')
                    .replace(/</g, '&lt;')
                    .replace(/>/g, '&gt;')
                    .replace(/"/g, '&quot;')
                    .replace(/'/g, '&#39;');
            };
            
            const markerName = escapeHtml(marker.name || typeLabel);
            const markerTime = marker.time ? escapeHtml(marker.time) : '';
            const markerAddress = marker.address ? escapeHtml(marker.address) : '';
            const markerDistance = marker.distance !== undefined ? String(marker.distance) : '';
            
            const infoWindowContent = '<div style="padding:12px;min-width:180px;">' +
                '<h3 style="font-weight:700;margin:0 0 4px 0;font-size:14px;">' + markerName + '</h3>' +
                '<p style="font-weight:600;color:' + typeColor + ';font-size:12px;margin:0 0 4px 0;">' + typeLabel + (markerTime ? ': ' + markerTime : '') + '</p>' +
                (markerAddress ? '<p style="color:#6b7280;font-size:11px;margin:0;">' + markerAddress + '</p>' : '') +
                (markerDistance ? '<p style="color:#9ca3af;font-size:11px;margin:4px 0 0 0;">Jarak: ' + markerDistance + 'm</p>' : '') +
                '</div>';
            
            const infoWindow = new google.maps.InfoWindow({
                content: infoWindowContent
            });

            mapMarker.addListener('click', () => {
                infoWindow.open(map, mapMarker);
            });

            // Handle drag events - enable if canEdit is true
            if (isDraggable) {
                mapMarker.addListener('dragend', function(e) {
                    const position = e.latLng;
                    updateCoordinates(marker.type, position.lat(), position.lng());
                    
                    // Update info window with new position
                    const escapeHtml = function(str) {
                        if (!str) return '';
                        return str.toString()
                            .replace(/&/g, '&amp;')
                            .replace(/</g, '&lt;')
                            .replace(/>/g, '&gt;')
                            .replace(/"/g, '&quot;')
                            .replace(/'/g, '&#39;');
                    };
                    const updatedMarkerName = escapeHtml(marker.name || typeLabel);
                    const updatedMarkerTime = marker.time ? escapeHtml(marker.time) : '';
                    const updatedContent = '<div style="padding:12px;min-width:180px;">' +
                        '<h3 style="font-weight:700;margin:0 0 4px 0;font-size:14px;">' + updatedMarkerName + '</h3>' +
                        '<p style="font-weight:600;color:' + typeColor + ';font-size:12px;margin:0 0 4px 0;">' + typeLabel + (updatedMarkerTime ? ': ' + updatedMarkerTime : '') + '</p>' +
                        '<p style="color:#6b7280;font-size:11px;margin:0;">Koordinat: ' + position.lat().toFixed(6) + ', ' + position.lng().toFixed(6) + '</p>' +
                        '</div>';
                    infoWindow.setContent(updatedContent);
                });
            }

            if (marker.type === 'check_in') {
                checkInMarker = mapMarker;
            } else if (marker.type === 'check_out') {
                checkOutMarker = mapMarker;
            }

            allMarkers.push(mapMarker);
        });

        // Fit bounds
        if (allMarkers.length > 1 || offices.length > 0) {
            map.fitBounds(bounds);
            google.maps.event.addListenerOnce(map, 'bounds_changed', function() {
                if (map.getZoom() > 20) {
                    map.setZoom(20);
                }
                if (map.getZoom() < 15) {
                    map.setZoom(15);
                }
            });
        }

        // Store map instance
        mapContainer._googleMap = map;

        // Initialize search functionality if can edit
        if (canEdit && typeof google !== 'undefined' && google.maps && google.maps.places) {
            setTimeout(() => {
                window[@json($initSearchFunctionName)]();
            }, 200);
        }
    }

    window[@json($initSearchFunctionName)] = function() {
        const searchInput = document.getElementById('search-input-' + mapId);
        const markerTypeSelect = document.getElementById('marker-type-' + mapId);

        if (!searchInput) return;

        // Use Google Places Autocomplete
        if (typeof google !== 'undefined' && google.maps && google.maps.places) {
            autocomplete = new google.maps.places.Autocomplete(searchInput, {
                types: ['geocode', 'establishment'],
                componentRestrictions: { country: 'id' } // Restrict to Indonesia
            });

            autocomplete.addListener('place_changed', function() {
                const place = autocomplete.getPlace();
                if (!place.geometry || !place.geometry.location) {
                    return;
                }

                const lat = place.geometry.location.lat();
                const lng = place.geometry.location.lng();
                const address = place.formatted_address || place.name;
                const selectedType = markerTypeSelect ? markerTypeSelect.value : 'check_in';

                moveMarkerToLocation(selectedType, lat, lng, address);
                searchInput.value = '';
            });
        } else {
            // Fallback: manual geocoding
            let geocoder = null;
            if (typeof google !== 'undefined' && google.maps) {
                geocoder = new google.maps.Geocoder();
            }

            if (!geocoder) return;

            let searchTimeout = null;
            searchInput.addEventListener('input', function(e) {
                const query = e.target.value.trim();
                clearTimeout(searchTimeout);

                if (query.length < 3) return;

                searchTimeout = setTimeout(() => {
                    geocoder.geocode({ address: query }, function(results, status) {
                        if (status === 'OK' && results.length > 0) {
                            const result = results[0];
                            const lat = result.geometry.location.lat();
                            const lng = result.geometry.location.lng();
                            const address = result.formatted_address;
                            const selectedType = markerTypeSelect ? markerTypeSelect.value : 'check_in';

                            moveMarkerToLocation(selectedType, lat, lng, address);
                            searchInput.value = '';
                        }
                    });
                }, 500);
            });
        }
    }

    function moveMarkerToLocation(type, lat, lng, address) {
        const typeColor = type === 'check_in' ? '#22c55e' : '#ef4444';
        let targetMarker = type === 'check_in' ? checkInMarker : checkOutMarker;

        if (!targetMarker) {
            // Create new marker if doesn't exist
            targetMarker = new google.maps.Marker({
                position: { lat: lat, lng: lng },
                map: map,
                draggable: canEdit,
                icon: {
                    path: google.maps.SymbolPath.CIRCLE,
                    scale: 14,
                    fillColor: typeColor,
                    fillOpacity: 1,
                    strokeColor: '#ffffff',
                    strokeWeight: 3
                },
                title: type === 'check_in' ? 'Check In' : 'Check Out',
                cursor: canEdit ? 'move' : 'default'
            });

            if (type === 'check_in') {
                checkInMarker = targetMarker;
            } else {
                checkOutMarker = targetMarker;
            }

            // Add drag handler
            targetMarker.addListener('dragend', function(e) {
                const position = e.latLng;
                updateCoordinates(type, position.lat(), position.lng());
            });
        } else {
            // Move existing marker
            targetMarker.setPosition({ lat: lat, lng: lng });
        }

        // Update coordinates
        updateCoordinates(type, lat, lng);

        // Center map on new location
        map.setCenter({ lat: lat, lng: lng });
        map.setZoom(17);

        // Create/update info window
        // Escape HTML for safe display
        const escapeHtml = function(str) {
            if (!str) return '';
            return str.toString()
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;')
                .replace(/'/g, '&#39;');
        };
        const typeLabel = type === 'check_in' ? 'Check In' : 'Check Out';
        const escapedAddress = address ? escapeHtml(address) : '';
        const infoWindowContent = '<div style="padding:12px;min-width:180px;">' +
            '<h3 style="font-weight:700;margin:0 0 4px 0;font-size:14px;">' + typeLabel + '</h3>' +
            (escapedAddress ? '<p style="color:#6b7280;font-size:11px;margin:0;">' + escapedAddress + '</p>' : '') +
            '</div>';
        const infoWindow = new google.maps.InfoWindow({
            content: infoWindowContent
        });
        infoWindow.open(map, targetMarker);
    }

    function updateCoordinates(type, lat, lng) {
        hasChanges = true;
        const saveBtn = document.getElementById('save-btn-' + mapId);
        if (saveBtn) {
            saveBtn.disabled = false;
        }

        // Update coordinate display
        if (type === 'check_in') {
            const coordsEl = document.getElementById('checkin-coords');
            if (coordsEl) {
                coordsEl.textContent = lat.toFixed(6) + ', ' + lng.toFixed(6);
            }
        } else if (type === 'check_out') {
            const coordsEl = document.getElementById('checkout-coords');
            if (coordsEl) {
                coordsEl.textContent = lat.toFixed(6) + ', ' + lng.toFixed(6);
            }
        }
    }

    window[@json($saveCoordinatesFunctionName)] = function() {
        if (!hasChanges) return;

        const data = {
            check_in_latitude: checkInMarker ? checkInMarker.getPosition().lat() : null,
            check_in_longitude: checkInMarker ? checkInMarker.getPosition().lng() : null,
            check_out_latitude: checkOutMarker ? checkOutMarker.getPosition().lat() : null,
            check_out_longitude: checkOutMarker ? checkOutMarker.getPosition().lng() : null,
        };

        // Show loading
        const saveBtn = document.getElementById('save-btn-' + mapId);
        if (saveBtn) {
            saveBtn.disabled = true;
            const loadingHtml = '<span class="flex items-center gap-2"><svg class="animate-spin h-4 w-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg> Menyimpan...</span>';
            saveBtn.innerHTML = loadingHtml;
        }

        // Call Filament action
        @php
            $isEmployee = str_contains(request()->path(), 'employee');
            if ($isEmployee) {
                $actionUrl = route('employee.my-attendances.update-coordinates', $record->id);
            } else {
                $actionUrl = route('admin.attendances.update-coordinates', $record->id);
            }
        @endphp
        const actionUrl = @json($actionUrl);

        // Get CSRF token
        const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || 
                         document.querySelector('input[name="_token"]')?.value || '';

        fetch(actionUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': csrfToken,
                'Accept': 'application/json',
            },
            body: JSON.stringify(data)
        })
        .then(response => {
            if (!response.ok) {
                return response.json().then(err => Promise.reject(err));
            }
            return response.json();
        })
        .then(result => {
            if (result.success) {
                hasChanges = false;
                if (saveBtn) {
                    saveBtn.disabled = true;
                    const successHtml = '<span class="flex items-center gap-2"><svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg> Simpan Perubahan</span>';
                    saveBtn.innerHTML = successHtml;
                }
                
                // Reload page to show Filament notification from backend
                // The notification is already sent from backend via Notification::make()
                setTimeout(() => {
                    window.location.reload();
                }, 500);
            } else {
                throw new Error(result.message || 'Gagal menyimpan koordinat');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            if (saveBtn) {
                saveBtn.disabled = false;
                const errorHtml = '<span class="flex items-center gap-2"><svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg> Simpan Perubahan</span>';
                saveBtn.innerHTML = errorHtml;
            }
            const errorMessage = error.message || (typeof error === 'string' ? error : 'Gagal menyimpan koordinat');
            
            // Show error notification using Filament's notification system
            // Try to use Livewire's notification system
            if (window.Livewire && window.Livewire.find) {
                const component = window.Livewire.find(document.querySelector('[wire\\:id]')?.getAttribute('wire:id'));
                if (component) {
                    component.$wire.dispatch('notify', {
                        type: 'danger',
                        title: 'Gagal',
                        body: 'Gagal menyimpan koordinat: ' + errorMessage
                    });
                }
            }
            
            // Fallback: reload page to show backend notification
            if (!window.Livewire || !window.Livewire.find) {
                setTimeout(() => {
                    window.location.reload();
                }, 1000);
            }
        });
    };

    // Initialize map
    function startInit() {
        if (window.googleMapsLoaded) {
            window[@json($initMapFunctionName)]();
        } else {
            if (window.googleMapsCallbacks) {
                window.googleMapsCallbacks.push(window[@json($initMapFunctionName)]);
            } else {
                // Wait for API to load
                const checkInterval = setInterval(() => {
                    if (typeof google !== 'undefined' && google.maps && google.maps.Map) {
                        clearInterval(checkInterval);
                        window[@json($initMapFunctionName)]();
                    }
                }, 100);
            }
        }
    }

    // Attach save button click handler
    function attachSaveButtonHandler() {
        const saveBtnEl = document.getElementById('save-btn-' + mapId);
        if (saveBtnEl) {
            const saveFunctionName = saveBtnEl.getAttribute('data-save-function');
            if (saveFunctionName) {
                // Remove existing listener if any
                const newBtn = saveBtnEl.cloneNode(true);
                saveBtnEl.parentNode.replaceChild(newBtn, saveBtnEl);
                // Add new listener
                newBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    if (window[saveFunctionName]) {
                        window[saveFunctionName]();
                    }
                });
            }
        }
    }

    // Initialize on DOMContentLoaded
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() {
            startInit();
            attachSaveButtonHandler();
        });
    } else {
        startInit();
        attachSaveButtonHandler();
    }

    // Re-initialize on Livewire navigation
    document.addEventListener('livewire:navigated', () => {
        setTimeout(function() {
            startInit();
            attachSaveButtonHandler();
        }, 100);
    });
})();
</script>
@endpush
