@props([
    'id' => 'google-map-' . uniqid(),
    'height' => '300px',
    'markers' => [],
    'offices' => [],
    'center' => null,
    'zoom' => 15,
    'showRadius' => true,
    'fitBounds' => true,
])

@php
    // Auto-calculate center if not provided
    if (!$center && count($markers) > 0) {
        $center = [
            'lat' => $markers[0]['lat'] ?? -6.2,
            'lng' => $markers[0]['lng'] ?? 106.8,
        ];
    } elseif (!$center && count($offices) > 0) {
        $center = [
            'lat' => $offices[0]['lat'] ?? -6.2,
            'lng' => $offices[0]['lng'] ?? 106.8,
        ];
    } elseif (!$center) {
        $center = ['lat' => -6.2, 'lng' => 106.8];
    }
@endphp

<div {{ $attributes->merge(['class' => 'google-map-container']) }}>
    <div id="{{ $id }}" style="height: {{ $height }}; width: 100%;" class="rounded-lg border border-gray-200 dark:border-gray-700 z-0"></div>
</div>

@once
    @push('scripts')
        <script src="https://maps.googleapis.com/maps/api/js?key={{ config('services.google_maps.api_key', env('GOOGLE_MAPS_API_KEY', '')) }}&libraries=geometry"></script>
    @endpush
@endonce

@push('scripts')
<script>
    (function() {
        function initGoogleMap_{{ str_replace('-', '_', $id) }}() {
            const mapContainer = document.getElementById('{{ $id }}');
            if (!mapContainer) return;

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

            const center = @json($center);
            const offices = @json($offices);
            const markers = @json($markers);
            const showRadius = {{ $showRadius ? 'true' : 'false' }};
            const fitBounds = {{ $fitBounds ? 'true' : 'false' }};
            const defaultZoom = {{ $zoom }};

            // Initialize map
            const map = new google.maps.Map(mapContainer, {
                center: { lat: center.lat, lng: center.lng },
                zoom: defaultZoom,
                mapTypeId: 'roadmap',
                styles: [
                    {
                        featureType: 'poi',
                        elementType: 'labels',
                        stylers: [{ visibility: 'off' }]
                    }
                ]
            });

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

            // Add office markers with radius
            offices.forEach(office => {
                if (!office.lat || !office.lng) return;

                const officePosition = { lat: office.lat, lng: office.lng };
                bounds.extend(officePosition);

                // Add radius circle
                if (showRadius && office.radius) {
                    const circle = 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'
                });

                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;">${office.name || 'Kantor'}</h3>
                            ${office.address ? `<p style="color:#6b7280;font-size:11px;margin:0;">${office.address}</p>` : ''}
                        </div>
                    `
                });

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

                allMarkers.push(officeMarker);
            });

            // Add check-in and check-out markers
            markers.forEach(marker => {
                if (!marker.lat || !marker.lng) return;

                const markerPosition = { lat: marker.lat, lng: marker.lng };
                bounds.extend(markerPosition);

                let typeLabel = 'Check In';
                let typeColor = '#10b981';
                let iconColor = '#10b981';

                if (marker.type === 'check_out') {
                    typeLabel = 'Check Out';
                    typeColor = '#ef4444';
                    iconColor = '#ef4444';
                } else if (marker.type === 'check_in') {
                    typeLabel = 'Check In';
                    typeColor = '#10b981';
                    iconColor = '#10b981';
                }

                const mapMarker = new google.maps.Marker({
                    position: markerPosition,
                    map: map,
                    icon: {
                        path: google.maps.SymbolPath.CIRCLE,
                        scale: 12,
                        fillColor: iconColor,
                        fillOpacity: 1,
                        strokeColor: '#ffffff',
                        strokeWeight: 2
                    },
                    title: typeLabel
                });

                const infoWindow = 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;">${marker.name || typeLabel}</h3>
                            <p style="font-weight:600;color:${typeColor};font-size:12px;margin:0 0 4px 0;">${typeLabel}${marker.time ? ': ' + marker.time : ''}</p>
                            ${marker.address ? `<p style="color:#6b7280;font-size:11px;margin:0;">${marker.address}</p>` : ''}
                            ${marker.distance !== undefined ? `<p style="color:#9ca3af;font-size:11px;margin:4px 0 0 0;">Jarak: ${marker.distance}m</p>` : ''}
                        </div>
                    `
                });

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

                allMarkers.push(mapMarker);
            });

            // Fit bounds to show all markers
            if (fitBounds && allMarkers.length > 0) {
                map.fitBounds(bounds);
                // Set appropriate zoom level after bounds change
                google.maps.event.addListenerOnce(map, 'bounds_changed', function() {
                    // For very close markers (within ~20m), use zoom 20 to show them clearly
                    // Max zoom is 21, but 20 provides good detail while showing context
                    if (map.getZoom() > 20) {
                        map.setZoom(20);
                    }
                    // If markers are too close and zoom is very high, ensure minimum context
                    if (map.getZoom() < 15) {
                        map.setZoom(15);
                    }
                });
            }

            // Store map instance
            mapContainer._googleMap = map;
        }

        // Initialize on DOMContentLoaded
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', initGoogleMap_{{ str_replace('-', '_', $id) }});
        } else {
            // Wait for Google Maps API to load
            if (typeof google !== 'undefined' && google.maps) {
                initGoogleMap_{{ str_replace('-', '_', $id) }}();
            } else {
                window.addEventListener('load', initGoogleMap_{{ str_replace('-', '_', $id) }});
            }
        }

        // Re-initialize on Livewire navigation
        document.addEventListener('livewire:navigated', () => {
            setTimeout(initGoogleMap_{{ str_replace('-', '_', $id) }}, 100);
        });
    })();
</script>
@endpush
