<div>
    <div class="container mx-auto">

        <x-dashboard.breadcrumb :items="[
            'Dashboard' => route('home'),
            'Etablissement' => route('merchant.show'),
            'Modifier  l\'établissement' => null,
        ]">
            <x-slot name="action">
                <x-dashboard.merchants.dropdown />
            </x-slot>
        </x-dashboard.breadcrumb>

        @if (isMerchantActive())
            <x-basics.alert type="warning" class="mt-6"
                message="Votre établissement est actif. Vous ne pouvez pas modifier les informations de votre établissement." />
        @endif

        <div class="flex flex-col lg:flex-row gap-6 mt-6">
            <div class="w-full lg:w-8/12 space-y-6">
                <form wire:submit.prevent="saveGeneral">
                    <x-basics.card title="Informations générales" subtitle="Informations de base de l'établissement">
                        
                        <x-slot name="action">
                            <x-basics.flash :model="'successGeneral'" :timeout="3000" />
                        </x-slot>

                        <div class="space-y-4">
                            <x-basics.input label="Nom de l'établissement" required wire:model.defer="merchant_name" name="merchant_name" mb="mb-4" :disabled="$disabled" />
                            <x-basics.input label="Slogan" wire:model.defer="merchant_slogan" name="merchant_slogan" mb="mb-4" :disabled="$disabled" />
                            @php
                                $merchantTypes = $merchantTypes;
                            @endphp
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <x-basics.select label="Type d'établissement" required wire:model.defer="merchant_type" name="merchant_type" :options="$merchantTypes" mb="mb-0" :disabled="$disabled" />
                                <x-basics.input label="CNOP" wire:model.defer="merchant_cnop" name="merchant_cnop" mb="mb-0" hint="CNOP de l'établissement" :disabled="$disabled" />
                            </div>
                        </div>

                        @if(!$disabled)
                        <x-slot name="footer">
                            <x-basics.button type="submit" class="w-full" :disabled="$loadingGeneral" leftIcon="floppy-disk">
                                @if ($loadingGeneral)
                                    Enregistrement...
                                @else
                                    Enregistrer les modifications
                                @endif
                            </x-basics.button>
                        </x-slot>
                        @endif
                    </x-basics.card>
                </form>

                <form wire:submit.prevent="saveAddress">
                    <x-basics.card title="Adresse et localisation" subtitle="Informations de localisation de l'établissement">
                        <x-slot name="action">
                            <x-basics.flash :model="'successAddress'" :timeout="3000"/>
                        </x-slot>

                        <div class="space-y-4">
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                @php
                                    $provinces = $provinces;
                                    $cities = $cities;
                                @endphp
                                <x-basics.select label="Province" required placeholder="Sélectionner une province" :options="$provinces" optionValue="id" optionLabel="name" wire:model.live="merchant_province_id" name="merchant_province_id" mb="mb-0" :disabled="$disabled" />
                                <x-basics.select label="Ville" required placeholder="Sélectionner une ville" :options="$cities" optionValue="id" optionLabel="name" wire:model.defer="merchant_city_id" name="merchant_city_id" mb="mb-0" :disabled="empty($cities) || $disabled" />
                            </div>

                            <x-basics.input label="Adresse" wire:model.defer="merchant_address" name="merchant_address" mb="mb-0" placeholder="Adresse complète de l'établissement" :disabled="$disabled" />
                            <div class="flex gap-4 items-end">
                                <div class="flex-1">
                                    <x-basics.input label="Latitude" wire:model.defer="merchant_latitude" name="merchant_latitude" mb="mb-0" readonly hint="Cliquez sur la carte pour définir la position" :disabled="$disabled" />
                                </div>
                                <div class="flex-1">
                                    <x-basics.input label="Longitude" wire:model.defer="merchant_longitude" name="merchant_longitude" mb="mb-0" readonly hint="Cliquez sur la carte pour définir la position" :disabled="$disabled" />
                                </div>
                                @if(!$disabled)
                                    @unless(app()->environment('production'))
                                    <div class="flex-1">
                                        <x-basics.button type="button" :disabled="$locationLoading" leftIcon="location" class="w-full" onclick="useCurrentLocation()">
                                            @if($locationLoading)
                                                Récupération...
                                            @else
                                                Ma position
                                            @endif
                                        </x-basics.button>
                                    </div>
                                    @endunless
                                @endif
                            </div>

                            <div class="space-y-2">
                                <label class="block text-sm font-medium text-gray-700">Carte de localisation</label>
                                @if(app()->environment('production'))
                                    <div class="rounded-md bg-amber-50 text-amber-800 text-sm p-3 mb-2">
                                        La géolocalisation automatique n'est pas disponible en production. Cliquez sur la carte pour définir l'emplacement exact de votre établissement.
                                    </div>
                                @endif
                                <div class="border border-gray-300 rounded-lg overflow-hidden relative" wire:ignore>
                                    <div id="merchant-map" class="h-96 w-full bg-gray-100 flex items-center justify-center">
                                        <div class="text-gray-500">
                                            <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600 mx-auto mb-2"></div>
                                            <p class="text-sm">Chargement de la carte...</p>
                                        </div>
                                    </div>
                                </div>
                                <p class="text-sm text-gray-500">Cliquez sur la carte pour définir l'emplacement exact de votre établissement</p>
                            </div>
                        </div>

                        @if(!$disabled)
                        <x-slot name="footer">
                            <x-basics.button type="submit" class="w-full" :disabled="$loadingAddress" leftIcon="floppy-disk">
                                @if($loadingAddress)
                                    Enregistrement...
                                @else
                                    Enregistrer les modifications
                                @endif
                            </x-basics.button>
                        </x-slot>
                        @endif
                    </x-basics.card>
                </form>

                <form wire:submit.prevent="saveContact">
                    <x-basics.card title="Informations de contact">
                        <x-slot name="action">
                            <x-basics.flash :model="'successContact'" :timeout="3000"/>
                        </x-slot>

                        <div class="space-y-4">
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <x-basics.input label="Téléphone" required wire:model.defer="merchant_phone" name="merchant_phone" mb="mb-0" placeholder="+243 123 456 789" hint="Numéro de téléphone principal" :disabled="$disabled" />
                                <x-basics.input label="Email" required type="email" wire:model.defer="merchant_email" name="merchant_email" mb="mb-0" placeholder="contact@mapharmacie.com" hint="Adresse email de contact" :disabled="$disabled" />
                            </div>
                        </div>

                        @if(!$disabled)
                        <x-slot name="footer">
                            <x-basics.button type="submit" class="w-full" :disabled="$loadingContact" leftIcon="floppy-disk">
                                @if($loadingContact)
                                    Enregistrement...
                                @else
                                    Enregistrer les modifications
                                @endif
                            </x-basics.button>
                        </x-slot>
                        @endif
                    </x-basics.card>
                </form>
            </div>

            <div class="w-full lg:w-4/12 space-y-6">
                <x-dashboard.merchants.sidebar />
            </div>
        </div>

    </div>

    @push('scripts')
    <!-- Use local Leaflet files for offline compatibility -->
    <link rel="stylesheet" href="{{ asset('plugins/leaflet/leaflet.css') }}" />
    <script src="{{ asset('plugins/leaflet/leaflet.js') }}"></script>
    <script>
        // Use window object to avoid variable conflicts
        window.merchantMap = window.merchantMap || {};
        window.merchantMap.map = null;
        window.merchantMap.marker = null;
        
        const defaultLat = {{ $merchant_latitude ?? -2.8797 }};
        const defaultLng = {{ $merchant_longitude ?? 23.6560 }};
        
        function initMerchantMap() {
            // Check if Leaflet is loaded
            if (typeof L === 'undefined') {
                console.error('Leaflet library not loaded. Attempting to load from CDN...');
                loadLeafletFromCDN();
                return;
            }
            
            // Remove existing map if any
            if (window.merchantMap.map) {
                window.merchantMap.map.remove();
                window.merchantMap.map = null;
                window.merchantMap.marker = null;
            }
            
            const mapElement = document.getElementById('merchant-map');
            if (!mapElement) return;
            
            try {
                // Clear loading state
                mapElement.innerHTML = '';
                mapElement.className = 'h-96 w-full';
                
                // Create a completely custom icon that doesn't rely on default paths
                const customIcon = L.divIcon({
                    html: `
                        <div style="
                            width: 32px; 
                            height: 32px; 
                            background-color: #4f46e5; 
                            border-radius: 50%; 
                            border: 2px solid white; 
                            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); 
                            display: flex; 
                            align-items: center; 
                            justify-content: center;
                            font-size: 16px;
                        ">
                            <i class="ph ph-map-pin text-white"></i>
                        </div>
                    `,
                    className: 'custom-marker-icon',
                    iconSize: [32, 32],
                    iconAnchor: [16, 16],
                    popupAnchor: [0, -16]
                });
                
                console.log('Custom marker icon created');
                
                window.merchantMap.map = L.map('merchant-map').setView([defaultLat, defaultLng], 4);
                L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { 
                    attribution: '© OpenStreetMap contributors' 
                }).addTo(window.merchantMap.map);
                
                window.merchantMap.marker = L.marker([defaultLat, defaultLng], { 
                    icon: customIcon,
                    draggable: {{ !$disabled ? 'true' : 'false' }} 
                }).addTo(window.merchantMap.map);
                
                console.log('Marker created with custom icon');
                
                window.merchantMap.marker.on('dragend', function(event) { 
                    const p = event.target.getLatLng(); 
                    updateLivewireCoordinates(p.lat, p.lng); 
                });
                
                window.merchantMap.map.on('click', function(event) { 
                    if ({{ !$disabled ? 'true' : 'false' }}) { 
                        const lat = event.latlng.lat; 
                        const lng = event.latlng.lng; 
                        window.merchantMap.marker.setLatLng([lat, lng]); 
                        updateLivewireCoordinates(lat, lng); 
                    } 
                });
                
                // Force map to invalidate size after initialization
                setTimeout(() => {
                    if (window.merchantMap.map) {
                        window.merchantMap.map.invalidateSize();
                    }
                }, 100);
            } catch (error) {
                console.error('Error initializing map:', error);
                mapElement.innerHTML = '<div class="flex items-center justify-center h-full bg-gray-100 text-gray-500"><p>Erreur lors du chargement de la carte.</p></div>';
            }
        }
        
        function loadLeafletFromCDN() {
            console.log('Loading Leaflet from CDN as fallback...');
            
            // Load CSS
            const cssLink = document.createElement('link');
            cssLink.rel = 'stylesheet';
            cssLink.href = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css';
            document.head.appendChild(cssLink);
            
            // Load JS
            const script = document.createElement('script');
            script.src = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js';
            script.onload = function() {
                console.log('Leaflet loaded from CDN successfully');
                // Retry map initialization (Phosphor icon will be used)
                setTimeout(() => initMerchantMap(), 100);
            };
            script.onerror = function() {
                console.error('Failed to load Leaflet from CDN');
                const mapElement = document.getElementById('merchant-map');
                if (mapElement) {
                    mapElement.innerHTML = '<div class="flex items-center justify-center h-full bg-gray-100 text-gray-500"><p>Erreur: Impossible de charger la carte. Vérifiez votre connexion internet.</p></div>';
                }
            };
            document.head.appendChild(script);
        }
        
        function updateLivewireCoordinates(lat, lng) {
            const parent = document.getElementById('merchant-map')?.closest('[wire\\:id]');
            if (parent) { 
                const id = parent.getAttribute('wire:id'); 
                const c = Livewire.find(id); 
                if (c) { 
                    c.set('merchant_latitude', lat.toFixed(6)); 
                    c.set('merchant_longitude', lng.toFixed(6)); 
                    return; 
                } 
            }
            const latInput = document.querySelector('input[name="merchant_latitude"]'); 
            const lngInput = document.querySelector('input[name="merchant_longitude"]'); 
            if (latInput && lngInput) { 
                latInput.value = lat.toFixed(6); 
                lngInput.value = lng.toFixed(6); 
                latInput.dispatchEvent(new Event('input', { bubbles: true })); 
                lngInput.dispatchEvent(new Event('input', { bubbles: true })); 
            }
        }
        
        function useCurrentLocation() { 
            if (!navigator.geolocation) { 
                alert('La géolocalisation n\'est pas supportée par votre navigateur.'); 
                return; 
            } 
            navigator.geolocation.getCurrentPosition(function(pos) { 
                const lat = pos.coords.latitude; 
                const lng = pos.coords.longitude; 
                if (window.merchantMap.marker && window.merchantMap.map) {
                    window.merchantMap.marker.setLatLng([lat, lng]); 
                    window.merchantMap.map.setView([lat, lng], 13); 
                    updateLivewireCoordinates(lat, lng); 
                }
            }, function() { 
                alert('Impossible d\'obtenir votre position actuelle.'); 
            }); 
        }
        
        // Initialize on DOMContentLoaded
        document.addEventListener('DOMContentLoaded', function() { 
            console.log('DOMContentLoaded - initializing map');
            initMerchantMap(); 
        });
        
        // Re-initialize on Livewire navigation
        document.addEventListener('livewire:navigate', function() { 
            console.log('Livewire navigate detected, reinitializing map...');
            setTimeout(() => {
                console.log('Attempting to reinitialize map after navigation');
                initMerchantMap();
            }, 200); 
        });
        
        document.addEventListener('livewire:navigated', function() { 
            console.log('Livewire navigated detected, reinitializing map...');
            setTimeout(() => {
                console.log('Attempting to reinitialize map after navigation');
                initMerchantMap();
            }, 200); 
        });
        
        // Listen for when Livewire is loaded
        document.addEventListener('livewire:initialized', function() { 
            console.log('Livewire initialized');
        });
        
        // Listen for Livewire load
        document.addEventListener('livewire:load', function() { 
            console.log('Livewire load - initializing map');
            setTimeout(() => initMerchantMap(), 100);
        });
    </script>

    @endpush
    <style>
        .leaflet-container {
            z-index: 0;
        }
        
        /* Custom Phosphor marker styling */
        .custom-phosphor-marker {
            background: transparent !important;
            border: none !important;
        }
        
        .custom-phosphor-marker div {
            display: flex !important;
            align-items: center !important;
            justify-content: center !important;
        }
        
        /* Ensure Phosphor icons are loaded */
        .ph {
            font-family: 'Phosphor', sans-serif;
        }
    </style>
</div>
