@props([
    'id' => 'leaflet-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' => 'leaflet-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('styles')
        <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
        <style>
            .leaflet-map-container .custom-marker {
                background: transparent;
                border: none;
            }
            .leaflet-map-container .leaflet-popup-content-wrapper {
                border-radius: 12px;
                box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
            }
            .leaflet-map-container .leaflet-popup-content {
                margin: 0;
                padding: 0;
            }
            .dark .leaflet-map-container .leaflet-popup-content-wrapper {
                background: #1f2937;
                color: #f3f4f6;
            }
            .dark .leaflet-map-container .leaflet-popup-tip {
                background: #1f2937;
            }
        </style>
    @endpush

    @push('scripts')
        <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    @endpush
@endonce

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

            // Clear existing map
            if (mapContainer._leaflet_id) {
                mapContainer._leaflet_id = 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 = L.map('{{ $id }}').setView([center.lat, center.lng], defaultZoom);

            // Add tile layer (OpenStreetMap)
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                maxZoom: 19,
                attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
            }).addTo(map);

            // Custom icons
            const officeIcon = L.divIcon({
                className: 'custom-marker',
                html: '<div style="width:32px;height:32px;background:#3b82f6;border-radius:50%;display:flex;align-items:center;justify-content:center;box-shadow:0 2px 8px rgba(0,0,0,0.3);border:2px solid white;"><svg style="width:20px;height:20px;color:white;" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M4 4a2 2 0 012-2h8a2 2 0 012 2v12a1 1 0 110 2h-3a1 1 0 01-1-1v-2a1 1 0 00-1-1H9a1 1 0 00-1 1v2a1 1 0 01-1 1H4a1 1 0 110-2V4zm3 1h2v2H7V5zm2 4H7v2h2V9zm2-4h2v2h-2V5zm2 4h-2v2h2V9z" clip-rule="evenodd"></path></svg></div>',
                iconSize: [32, 32],
                iconAnchor: [16, 32],
                popupAnchor: [0, -32]
            });

            const checkInIcon = L.divIcon({
                className: 'custom-marker',
                html: '<div style="width:28px;height:28px;background:#22c55e;border-radius:50%;display:flex;align-items:center;justify-content:center;box-shadow:0 2px 8px rgba(0,0,0,0.3);border:2px solid white;"><svg style="width:18px;height:18px;color:white;" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"></path></svg></div>',
                iconSize: [28, 28],
                iconAnchor: [14, 28],
                popupAnchor: [0, -28]
            });

            const checkOutIcon = L.divIcon({
                className: 'custom-marker',
                html: '<div style="width:28px;height:28px;background:#ef4444;border-radius:50%;display:flex;align-items:center;justify-content:center;box-shadow:0 2px 8px rgba(0,0,0,0.3);border:2px solid white;"><svg style="width:18px;height:18px;color:white;" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"></path></svg></div>',
                iconSize: [28, 28],
                iconAnchor: [14, 28],
                popupAnchor: [0, -28]
            });

            const locationIcon = L.divIcon({
                className: 'custom-marker',
                html: '<div style="width:24px;height:24px;background:#8b5cf6;border-radius:50%;display:flex;align-items:center;justify-content:center;box-shadow:0 2px 8px rgba(0,0,0,0.3);border:2px solid white;"><svg style="width:14px;height:14px;color:white;" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M5.05 4.05a7 7 0 119.9 9.9L10 18.9l-4.95-4.95a7 7 0 010-9.9zM10 11a2 2 0 100-4 2 2 0 000 4z" clip-rule="evenodd"></path></svg></div>',
                iconSize: [24, 24],
                iconAnchor: [12, 24],
                popupAnchor: [0, -24]
            });

            const allPoints = [];

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

                allPoints.push([office.lat, office.lng]);

                // Add radius circle
                if (showRadius && office.radius) {
                    L.circle([office.lat, office.lng], {
                        color: '#3b82f6',
                        fillColor: '#3b82f6',
                        fillOpacity: 0.1,
                        radius: office.radius,
                        weight: 2
                    }).addTo(map);
                }

                // Add office marker
                L.marker([office.lat, office.lng], { icon: officeIcon })
                    .bindPopup(`
                        <div style="padding:12px;min-width:180px;">
                            <h3 style="font-weight:700;color:#3b82f6;margin:0 0 4px 0;font-size:14px;">${office.name || 'Kantor'}</h3>
                            <p style="color:#6b7280;font-size:12px;margin:0;">${office.address || '-'}</p>
                            ${office.radius ? `<p style="color:#9ca3af;font-size:11px;margin:4px 0 0 0;">Radius: ${office.radius}m</p>` : ''}
                        </div>
                    `)
                    .addTo(map);
            });

            // Add attendance markers
            markers.forEach(marker => {
                if (!marker.lat || !marker.lng) return;

                allPoints.push([marker.lat, marker.lng]);

                let icon = locationIcon;
                let typeLabel = 'Lokasi';
                let typeColor = '#8b5cf6';

                if (marker.type === 'check_in') {
                    icon = checkInIcon;
                    typeLabel = 'Check In';
                    typeColor = '#22c55e';
                } else if (marker.type === 'check_out') {
                    icon = checkOutIcon;
                    typeLabel = 'Check Out';
                    typeColor = '#ef4444';
                }

                L.marker([marker.lat, marker.lng], { icon: icon })
                    .bindPopup(`
                        <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>
                    `)
                    .addTo(map);
            });

            // Fit bounds to show all markers
            if (fitBounds && allPoints.length > 1) {
                map.fitBounds(allPoints, { padding: [30, 30] });
            } else if (allPoints.length === 1) {
                map.setView(allPoints[0], defaultZoom);
            }

            // Fix map size after load
            setTimeout(() => {
                map.invalidateSize();
            }, 100);
        }

        // Initialize on DOMContentLoaded
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', initLeafletMap_{{ str_replace('-', '_', $id) }});
        } else {
            initLeafletMap_{{ str_replace('-', '_', $id) }}();
        }

        // Re-initialize on Livewire navigation
        document.addEventListener('livewire:navigated', initLeafletMap_{{ str_replace('-', '_', $id) }});

        // Re-initialize when modal opens (for Alpine.js modals)
        window.initLeafletMap_{{ str_replace('-', '_', $id) }} = initLeafletMap_{{ str_replace('-', '_', $id) }};
    })();
</script>
@endpush
