<x-app-layout>
    @push('styles')
    <style>


        .gradient-secondary {
            background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
        }

        .form-card {
            transition: all 0.3s ease;
            border: 1px solid #e7e2d9;
        }

        .form-card:hover {
            box-shadow: 0 20px 25px -5px rgba(120, 80, 50, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }

        .animate-fade-in {
            animation: fadeIn 0.5s ease-in-out;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .map-container {
            height: 300px;
            border-radius: 0.75rem;
            overflow: hidden;
            border: 2px solid #e7e2d9;
        }

        .section-card {
            background: white;
            border: 1px solid #e7e2d9;
            border-radius: 1rem;
            padding: 1.25rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
        }

        .section-title {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-weight: 600;
            color: #44403c;
            margin-bottom: 1rem;
        }

        .section-title i {
            color: var(--brand-text);
        }

        /* Custom select styling */
        select, input, textarea {
            background-color: #faf7f2;
            border-color: #e7e2d9;
            color: #44403c;
            border-radius: 0.75rem;
            padding: 0.625rem 1rem;
            font-size: 0.875rem;
            transition: all 0.2s;
        }

        select:focus, input:focus, textarea:focus {
            border-color: var(--brand-text);
            box-shadow: 0 0 0 3px rgba(180, 83, 9, 0.1);
            outline: none;
            background-color: white;
        }

        select:disabled, input:read-only {
            background-color: #f1ede8;
            border-color: #d6c8bc;
            color: #78716c;
        }

        /* Button styles */


        .btn-secondary {
            background: #f1ede8;
            color: #57534e;
            padding: 0.625rem 1.5rem;
            border-radius: 0.75rem;
            font-weight: 600;
            font-size: 0.875rem;
            border: 1px solid #d6c8bc;
            transition: all 0.2s;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }

        .btn-secondary:hover {
            background: #e7e2d9;
            color: #44403c;
        }

        .btn-back {
            background: white;
            color: #57534e;
            padding: 0.5rem 1.25rem;
            border-radius: 0.75rem;
            font-weight: 500;
            font-size: 0.875rem;
            border: 1px solid #e7e2d9;
            transition: all 0.2s;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }

        .btn-back:hover {
            background: #f1ede8;
            color: #44403c;
        }

        /* Alert styles */
        .alert-info {
            background: linear-gradient(to right, var(--color-primary), var(--color-secondary));
            color: #78350f;
            border-radius: 0.75rem;
            padding: 1rem;
        }

        .alert-info i {
            color: #fcd34d;
        }

        /* Required field indicator */
        .required {
            color: #dc2626;
        }
    </style>
    @endpush

    <x-slot name="header">
        <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
            <div class="flex items-center gap-3">
                <div class="w-9 h-9 sm:w-10 sm:h-10 gradient-primary rounded-xl flex items-center justify-center shadow-lg flex-shrink-0">
                    <i class="fas fa-map-marker-alt text-white text-sm"></i>
                </div>
                <div>
                    <h1 class="text-lg sm:text-xl font-bold text-stone-800">Tambah Alamat Baru</h1>
                    <p class="text-xs text-stone-500">Lengkapi detail alamat pengiriman Anda</p>
                </div>
            </div>
        </div>
    </x-slot>

    <div class="py-4 sm:py-6 bg-stone-50 min-h-screen">
        <div class="space-y-6">

            <div class="form-card bg-white rounded-xl sm:rounded-2xl shadow-sm border border-stone-200 overflow-hidden">
                <div class="p-4 sm:p-5 md:p-6">

                    @if($redirectTo === 'cart.checkout.get')
                    <div class="alert-info mb-6 flex items-center gap-3">
                        <i class="fas fa-info-circle text-xl"></i>
                        <span class="text-sm font-medium">Tambahkan alamat untuk pengiriman pesanan Anda</span>
                    </div>
                    @endif

                    <form method="POST" action="{{ route('address.store') }}" class="space-y-6">
                        @csrf

                        {{-- Simpan redirect_to agar controller tahu harus kembali ke mana --}}
                        <input type="hidden" name="redirect_to" value="{{ $redirectTo }}">

                        <div class="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-6">
                            {{-- Left Column: Form Inputs --}}
                            <div class="space-y-4 sm:space-y-5">

                                {{-- Data Penerima --}}
                                <div class="section-card">
                                    <h3 class="section-title">
                                        <i class="fas fa-user"></i>
                                        Data Penerima
                                    </h3>
                                    <div class="space-y-4">
                                        <div>
                                            <label class="block text-xs font-medium text-stone-700 mb-1.5">
                                                Nama Penerima <span class="required">*</span>
                                            </label>
                                            <input type="text" name="recipient_name"
                                                placeholder="Masukkan nama penerima"
                                                class="w-full"
                                                value="{{ old('recipient_name') }}" required>
                                            @error('recipient_name')
                                            <p class="mt-1 text-xs text-rose-600">{{ $message }}</p>
                                            @enderror
                                        </div>

                                        <div>
                                            <label class="block text-xs font-medium text-stone-700 mb-1.5">
                                                Nomor Telepon <span class="required">*</span>
                                            </label>
                                            <input type="tel" name="phone"
                                                placeholder="Contoh: 08123456789"
                                                class="w-full"
                                                value="{{ old('phone') }}" required>
                                            @error('phone')
                                            <p class="mt-1 text-xs text-rose-600">{{ $message }}</p>
                                            @enderror
                                        </div>
                                    </div>
                                </div>

                                {{-- Wilayah Administratif --}}
                                <div class="section-card">
                                    <h3 class="section-title">
                                        <i class="fas fa-map-marked-alt"></i>
                                        Wilayah Administratif
                                    </h3>
                                    <div class="space-y-4">
                                        <div>
                                            <label class="block text-xs font-medium text-stone-700 mb-1.5">
                                                Provinsi <span class="required">*</span>
                                            </label>
                                            <select id="province" name="province_code" class="w-full" required>
                                                <option value="">Pilih Provinsi</option>
                                            </select>
                                            @error('province_code')
                                            <p class="mt-1 text-xs text-rose-600">{{ $message }}</p>
                                            @enderror
                                        </div>

                                        <div>
                                            <label class="block text-xs font-medium text-stone-700 mb-1.5">
                                                Kota/Kabupaten <span class="required">*</span>
                                            </label>
                                            <select id="city" name="city_code" disabled class="w-full" required>
                                                <option value="">Pilih Kota</option>
                                            </select>
                                            @error('city_code')
                                            <p class="mt-1 text-xs text-rose-600">{{ $message }}</p>
                                            @enderror
                                        </div>

                                        <div>
                                            <label class="block text-xs font-medium text-stone-700 mb-1.5">
                                                Kecamatan <span class="required">*</span>
                                            </label>
                                            <select id="district" name="district_code" disabled class="w-full" required>
                                                <option value="">Pilih Kecamatan</option>
                                            </select>
                                            @error('district_code')
                                            <p class="mt-1 text-xs text-rose-600">{{ $message }}</p>
                                            @enderror
                                        </div>

                                        <div>
                                            <label class="block text-xs font-medium text-stone-700 mb-1.5">
                                                Desa/Kelurahan <span class="required">*</span>
                                            </label>
                                            <select id="village" name="village_code" disabled class="w-full" required>
                                                <option value="">Pilih Desa</option>
                                            </select>
                                            @error('village_code')
                                            <p class="mt-1 text-xs text-rose-600">{{ $message }}</p>
                                            @enderror
                                        </div>
                                    </div>
                                </div>

                                {{-- Detail Alamat --}}
                                <div class="section-card">
                                    <h3 class="section-title">
                                        <i class="fas fa-home"></i>
                                        Detail Alamat
                                    </h3>
                                    <div class="space-y-4">
                                        <div>
                                            <label class="block text-xs font-medium text-stone-700 mb-1.5">
                                                Nama Jalan <span class="required">*</span>
                                            </label>
                                            <input type="text" name="street"
                                                placeholder="Contoh: Jl. Sudirman No. 123"
                                                class="w-full"
                                                value="{{ old('street') }}" required>
                                            @error('street')
                                            <p class="mt-1 text-xs text-rose-600">{{ $message }}</p>
                                            @enderror
                                        </div>

                                        <div>
                                            <label class="block text-xs font-medium text-stone-700 mb-1.5">
                                                Detail Alamat <span class="required">*</span>
                                            </label>
                                            <textarea name="address_detail" rows="3"
                                                placeholder="Contoh: RT 01/RW 02, Blok A, Patokan: Dekat Masjid"
                                                class="w-full resize-none"
                                                required>{{ old('address_detail') }}</textarea>
                                            @error('address_detail')
                                            <p class="mt-1 text-xs text-rose-600">{{ $message }}</p>
                                            @enderror
                                        </div>
                                    </div>
                                </div>
                            </div>

                            {{-- Right Column: Map & Coordinates --}}
                            <div class="space-y-4 sm:space-y-5">

                                {{-- Map --}}
                                <div class="section-card">
                                    <h3 class="section-title">
                                        <i class="fas fa-map"></i>
                                        Pilih Lokasi di Peta
                                    </h3>
                                    <div class="map-container">
                                        <div id="map" class="w-full h-full"></div>
                                    </div>
                                    <p class="text-xs text-stone-500 mt-3 flex items-center gap-1.5">
                                        <i class="fas fa-info-circle text-amber-600"></i>
                                        Klik pada peta untuk menentukan lokasi (opsional, namun disarankan untuk akurasi pengiriman)
                                    </p>
                                </div>

                                {{-- Koordinat --}}
                                <div class="section-card">
                                    <h3 class="section-title">
                                        <i class="fas fa-map-pin"></i>
                                        Koordinat Lokasi
                                    </h3>
                                    <div class="grid grid-cols-2 gap-3">
                                        <div>
                                            <label class="block text-xs font-medium text-stone-700 mb-1.5">
                                                Latitude
                                            </label>
                                            <input id="lat" name="latitude" type="text" readonly
                                                class="w-full bg-stone-100"
                                                value="{{ old('latitude') }}"
                                                placeholder="Pilih di peta">
                                        </div>
                                        <div>
                                            <label class="block text-xs font-medium text-stone-700 mb-1.5">
                                                Longitude
                                            </label>
                                            <input id="lng" name="longitude" type="text" readonly
                                                class="w-full bg-stone-100"
                                                value="{{ old('longitude') }}"
                                                placeholder="Pilih di peta">
                                        </div>
                                    </div>
                                </div>

                                {{-- Tips --}}
                                <div class="section-card bg-amber-50 border-amber-200">
                                    <div class="flex items-start gap-3">
                                        <i class="fas fa-lightbulb text-amber-600 text-lg mt-0.5"></i>
                                        <div>
                                            <h4 class="text-sm font-semibold text-stone-800 mb-1">Tips Pengisian Alamat</h4>
                                            <ul class="text-xs text-stone-600 space-y-1 list-disc list-inside">
                                                <li>Pastikan alamat lengkap untuk memudahkan kurir</li>
                                                <li>Sertakan patokan yang mudah dikenali</li>
                                                <li>Gunakan peta untuk akurasi lokasi</li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        {{-- Buttons --}}
                        <div class="flex flex-col-reverse sm:flex-row justify-end gap-3 pt-6 border-t border-stone-200">
                            {{-- Tombol batal kembali ke halaman asal --}}
                            <a href="{{ route($redirectTo) }}"
                                class="btn-secondary w-full sm:w-auto justify-center">
                                <i class="fas fa-times"></i>
                                Batal
                            </a>
                            <button type="submit"
                                class="btn-primary w-full sm:w-auto justify-center">
                                <i class="fas fa-save"></i>
                                Simpan Alamat
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    {{-- Leaflet CSS & JS --}}
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <script src="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.css" />

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const province = document.getElementById('province');
            const city = document.getElementById('city');
            const district = document.getElementById('district');
            const village = document.getElementById('village');
            const streetInput = document.querySelector('input[name="street"]');
            const latInput = document.getElementById('lat');
            const lngInput = document.getElementById('lng');

            const map = L.map('map').setView([-2.5489, 118.0149], 5);
            let marker = null;

            L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png', {
                attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>, &copy; CartoDB',
                subdomains: 'abcd',
                maxZoom: 19
            }).addTo(map);

            map.scrollWheelZoom.disable();
            map.on('click', function() {
                map.scrollWheelZoom.enable();
            });
            map.on('mouseout', function() {
                map.scrollWheelZoom.disable();
            });

            const geocoder = L.Control.geocoder({
                    defaultMarkGeocode: false,
                    placeholder: 'Cari alamat...',
                    errorMessage: 'Alamat tidak ditemukan'
                })
                .on('markgeocode', function(e) {
                    const result = e.geocode;
                    map.setView(result.center, 16);

                    if (marker) map.removeLayer(marker);
                    marker = L.marker(result.center).addTo(map)
                        .bindPopup(result.name)
                        .openPopup();

                    latInput.value = result.center.lat.toFixed(6);
                    lngInput.value = result.center.lng.toFixed(6);
                    updateStreetFromGeocode(result.name);
                })
                .addTo(map);

            fetch('/indonesia/provinces')
                .then(res => res.json())
                .then(data => {
                    data.forEach(p => {
                        const option = document.createElement('option');
                        option.value = p.code;
                        option.textContent = p.name;
                        province.appendChild(option);
                    });
                })
                .catch(error => console.error('Error loading provinces:', error));

            province.addEventListener('change', () => {
                city.disabled = true;
                district.disabled = true;
                village.disabled = true;

                if (!province.value) {
                    city.innerHTML = '<option value="">Pilih Kota</option>';
                    district.innerHTML = '<option value="">Pilih Kecamatan</option>';
                    village.innerHTML = '<option value="">Pilih Desa</option>';
                    return;
                }

                fetch(`/indonesia/cities/${province.value}`)
                    .then(res => res.json())
                    .then(data => {
                        city.innerHTML = '<option value="">Pilih Kota</option>';
                        data.forEach(c => {
                            const option = document.createElement('option');
                            option.value = c.code;
                            option.textContent = c.name;
                            city.appendChild(option);
                        });
                        city.disabled = false;

                        district.innerHTML = '<option value="">Pilih Kecamatan</option>';
                        district.disabled = true;
                        village.innerHTML = '<option value="">Pilih Desa</option>';
                        village.disabled = true;
                    })
                    .catch(error => console.error('Error loading cities:', error));
            });

            city.addEventListener('change', () => {
                district.disabled = true;
                village.disabled = true;

                if (!city.value) {
                    district.innerHTML = '<option value="">Pilih Kecamatan</option>';
                    village.innerHTML = '<option value="">Pilih Desa</option>';
                    return;
                }

                fetch(`/indonesia/districts/${city.value}`)
                    .then(res => res.json())
                    .then(data => {
                        district.innerHTML = '<option value="">Pilih Kecamatan</option>';
                        data.forEach(d => {
                            const option = document.createElement('option');
                            option.value = d.code;
                            option.textContent = d.name;
                            district.appendChild(option);
                        });
                        district.disabled = false;

                        village.innerHTML = '<option value="">Pilih Desa</option>';
                        village.disabled = true;
                    })
                    .catch(error => console.error('Error loading districts:', error));
            });

            district.addEventListener('change', () => {
                village.disabled = true;

                if (!district.value) {
                    village.innerHTML = '<option value="">Pilih Desa</option>';
                    return;
                }

                fetch(`/indonesia/villages/${district.value}`)
                    .then(res => res.json())
                    .then(data => {
                        village.innerHTML = '<option value="">Pilih Desa</option>';
                        data.forEach(v => {
                            const option = document.createElement('option');
                            option.value = v.code;
                            option.textContent = v.name;
                            village.appendChild(option);
                        });
                        village.disabled = false;
                    })
                    .catch(error => console.error('Error loading villages:', error));
            });

            map.on('click', async (e) => {
                latInput.value = e.latlng.lat.toFixed(6);
                lngInput.value = e.latlng.lng.toFixed(6);

                if (marker) map.removeLayer(marker);
                marker = L.marker(e.latlng).addTo(map);

                try {
                    const response = await fetch(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${e.latlng.lat}&lon=${e.latlng.lng}&zoom=18&addressdetails=1`);
                    const data = await response.json();

                    if (data.address) {
                        const street = data.address.road || data.address.pedestrian ||
                            data.address.footway || data.address.cycleway || '';
                        if (street) streetInput.value = street;
                    }
                } catch (error) {
                    console.log('Reverse geocoding failed:', error);
                }
            });

            function updateStreetFromGeocode(addressString) {
                const parts = addressString.split(',');
                if (parts.length > 0) {
                    const possibleStreet = parts[0].trim();
                    if (possibleStreet && !possibleStreet.match(/^\d/)) {
                        streetInput.value = possibleStreet;
                    }
                }
            }
        });
    </script>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const alerts = document.querySelectorAll('.animate-fade-in');
            alerts.forEach(alert => {
                setTimeout(() => {
                    alert.style.transition = 'opacity 0.5s ease';
                    alert.style.opacity = '0';
                    setTimeout(() => alert.remove(), 500);
                }, 5000);
            });
        });

        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
            anchor.addEventListener('click', function (e) {
                e.preventDefault();
                const target = document.querySelector(this.getAttribute('href'));
                if (target) {
                    target.scrollIntoView({ behavior: 'smooth' });
                }
            });
        });
    </script>

    <style>
        @media (max-width: 480px) {
            .section-card {
                padding: 1rem;
            }

            .map-container {
                height: 250px;
            }
        }

        button, a, select, input, textarea {
            touch-action: manipulation;
        }

        input, select, textarea {
            font-size: 16px !important;
        }

        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }

        ::-webkit-scrollbar-track {
            background: #f1ede8;
        }

        ::-webkit-scrollbar-thumb {
            background: var(--color-primary, #fdba74);
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: var(--color-secondary, #f97316);
        }
    </style>
</x-app-layout>