<x-admin-layout>

    <div class="p-0 font-sans bg-slate-50 min-h-screen">
        @if($errors->any())
            <div x-data="{ show: true }" x-init="setTimeout(() => show = false, 6000)" x-show="show"
                class="mx-4 mb-6 bg-red-50 p-3 rounded-lg shadow-sm relative md:mx-0 shadow-md" role="alert">
                <div class="flex">

                    <div>
                        <p class="font-bold text-sm">Veuillez corriger les erreurs ci-dessous.</p>
                        <ul class="mt-1 text-xs list-disc list-inside space-y-0.5">
                            @foreach($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                </div>
            </div>
        @endif

        <div class="bg-white border-none shadow-none md:rounded-none p-4 md:p-6 relative min-h-screen">
            <div class="mb-6 flex items-center justify-between">
                <h5 class="text-[14px] font-bold text-gray-700 uppercase tracking-wide">
                    Mise à jour
                </h5>
                <a href="{{ route('admin.members.index') }}"
                    class="px-4 py-2 text-gray-600 hover:text-gray-900 transition-all text-sm font-bold flex items-center">
                    <svg class="h-4 w-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M10 19l-7-7m0 0l7-7m-7 7h18" />
                    </svg>
                    Retour
                </a>
            </div>

            <form id="member-edit-form" method="POST" action="{{ route('admin.members.update', $member) }}"
                class="space-y-6">
                @csrf
                @method('PUT')

                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">

                    <div>
                        <label for="first_name" class="block text-sm font-semibold text-gray-700 mb-2">Prénom <span
                                class="text-red-600 font-bold">*</span></label>
                        <input type="text" name="first_name" id="first_name"
                            value="{{ old('first_name', $member->first_name) }}" required
                            class="block w-full px-3 py-2 border border-gray-300 rounded-sm focus:ring-1 focus:ring-blue-600 focus:border-blue-600 transition-all h-[38px] capitalize">
                    </div>

                    <div>
                        <label for="last_name" class="block text-sm font-semibold text-gray-700 mb-2">Nom <span
                                class="text-red-600 font-bold">*</span></label>
                        <input type="text" name="last_name" id="last_name"
                            value="{{ old('last_name', $member->last_name) }}" required
                            class="block w-full px-3 py-2 border border-gray-300 rounded-sm focus:ring-1 focus:ring-blue-600 focus:border-blue-600 transition-all h-[38px] capitalize">
                    </div>

                    <div>
                        <label for="gender" class="block text-sm font-semibold text-gray-700 mb-2">Genre <span
                                class="text-red-600 font-bold">*</span></label>
                        <select name="gender" id="gender" required
                            class="block w-full px-3 py-2 border border-gray-300 rounded-sm focus:ring-1 focus:ring-blue-600 focus:border-blue-600 transition-all h-[38px] bg-white">
                            <option value="homme" {{ old('gender', $member->gender) === 'homme' ? 'selected' : '' }}>Homme
                            </option>
                            <option value="femme" {{ old('gender', $member->gender) === 'femme' ? 'selected' : '' }}>Femme
                            </option>
                        </select>
                    </div>

                    <div>
                        <label for="birth_date" class="block text-sm font-semibold text-gray-700 mb-2">Date de
                            Naissance <span class="text-red-600 font-bold">*</span></label>
                        <input type="date" name="birth_date" id="birth_date"
                            value="{{ old('birth_date', $member->birth_date ? $member->birth_date->format('Y-m-d') : '') }}"
                            required
                            class="block w-full px-3 py-2 border border-gray-300 rounded-sm focus:ring-1 focus:ring-blue-600 focus:border-blue-600 transition-all h-[38px]">
                    </div>

                    <div>
                        <label for="birth_place" class="block text-sm font-semibold text-gray-700 mb-2">Lieu de
                            Naissance <span class="text-red-600 font-bold">*</span></label>
                        <input type="text" name="birth_place" id="birth_place"
                            value="{{ old('birth_place', $member->birth_place) }}" required
                            class="block w-full px-3 py-2 border border-gray-300 rounded-sm focus:ring-1 focus:ring-blue-600 focus:border-blue-600 transition-all h-[38px] capitalize">
                    </div>

                    <div>
                        <label for="nationality" class="block text-sm font-semibold text-gray-700 mb-2">Nationalité
                            <span class="text-red-600 font-bold">*</span></label>
                        <select name="nationality" id="nationality" required
                            class="block w-full px-3 py-2 border border-gray-300 rounded-sm focus:ring-1 focus:ring-blue-600 focus:border-blue-600 transition-all h-[38px] bg-white">
                            <option value="Sénégal" {{ old('nationality', $member->nationality) == 'Sénégal' ? 'selected' : '' }}>Sénégal</option>
                            <option value="Espagne" {{ old('nationality', $member->nationality) == 'Espagne' ? 'selected' : '' }}>Espagne</option>
                        </select>
                    </div>

                    <div>
                        <label for="cni" class="block text-sm font-semibold text-gray-700 mb-2">CNI <span
                                class="text-red-600 font-bold">*</span></label>
                        <input type="text" name="cni" id="cni" value="{{ old('cni', $member->cni) }}" required
                            class="block w-full px-3 py-2 border border-gray-300 rounded-sm focus:ring-1 focus:ring-blue-600 focus:border-blue-600 transition-all h-[38px]">
                    </div>

                    <div>
                        <label for="passport_number" class="block text-sm font-semibold text-gray-700 mb-2">Numéro de
                            Passeport</label>
                        <input type="text" name="passport_number" id="passport_number"
                            value="{{ old('passport_number', $member->passport_number) }}"
                            class="block w-full px-3 py-2 border border-gray-300 rounded-sm focus:ring-1 focus:ring-blue-600 focus:border-blue-600 transition-all h-[38px]">
                    </div>

                    <div>
                        <label for="email" class="block text-sm font-semibold text-gray-700 mb-2">Email <span
                                class="text-red-600 font-bold">*</span></label>
                        <input type="email" name="email" id="email" value="{{ old('email', $member->email) }}" required
                            class="block w-full px-3 py-2 border border-gray-300 rounded-sm focus:ring-1 focus:ring-blue-600 focus:border-blue-600 transition-all h-[38px]">
                    </div>

                    <div>
                        <label for="phone_input" class="block text-sm font-semibold text-gray-700 mb-2">Téléphone <span
                                class="text-red-600 font-bold">*</span></label>
                        <div class="w-full">
                            <input type="tel" id="phone_input"
                                class="block w-full px-3 py-2 border border-gray-300 rounded-sm focus:ring-1 focus:ring-blue-600 focus:border-blue-600 transition-all h-[38px]">
                            <input type="hidden" name="phone" id="phone_hidden"
                                value="{{ old('phone', $member->phone) }}">
                        </div>
                    </div>

                    <div>
                        <label for="residence" class="block text-sm font-semibold text-gray-700 mb-2">Résidence <span
                                class="text-red-600 font-bold">*</span></label>
                        <select name="residence" id="residence" required
                            class="block w-full px-3 py-2 border border-gray-300 rounded-sm focus:ring-1 focus:ring-blue-600 focus:border-blue-600 transition-all h-[38px] bg-white">
                            <option value="Sénégal" {{ old('residence', $member->residence) == 'Sénégal' ? 'selected' : '' }}>
                                Sénégal</option>
                            <option value="Espagne" {{ old('residence', $member->residence) == 'Espagne' ? 'selected' : '' }}>
                                Espagne</option>
                        </select>
                    </div>

                    <div class="md:col-span-2">
                        <label for="address" class="block text-sm font-semibold text-gray-700 mb-2">Adresse <span
                                class="text-red-600 font-bold">*</span></label>
                        <textarea name="address" id="address" rows="3" required
                            class="block w-full px-3 py-2 border border-gray-300 rounded-sm focus:ring-1 focus:ring-blue-600 focus:border-blue-600 transition-all h-[38px] capitalize">{{ old('address', $member->address) }}</textarea>
                    </div>

                    <div>
                        <label for="status" class="block text-sm font-semibold text-gray-700 mb-2">Statut <span
                                class="text-red-600 font-bold">*</span></label>
                        <select name="status" id="status" required
                            class="block w-full px-3 py-2 border border-gray-300 rounded-sm focus:ring-1 focus:ring-blue-600 focus:border-blue-600 transition-all h-[38px] bg-white">
                            <option value="active" {{ old('status', $member->status) === 'active' ? 'selected' : '' }}>
                                Actif</option>
                            <option value="pending" {{ old('status', $member->status) === 'pending' ? 'selected' : '' }}>
                                En attente</option>
                            <option value="inactive" {{ old('status', $member->status) === 'inactive' ? 'selected' : '' }}>
                                Inactif</option>
                        </select>
                    </div>
                </div>

                <div class="flex flex-col sm:flex-row items-stretch sm:items-center justify-end gap-3 pt-2">
                    <a href="{{ route('admin.members.index') }}"
                        class="px-5 py-2 bg-white border border-gray-200 text-gray-700 rounded-sm hover:bg-gray-50 transition-all text-sm font-semibold shadow-sm hover:shadow-md text-center h-[38px] inline-flex items-center">
                        Annuler
                    </a>
                    <button type="submit"
                        class="px-5 py-2 text-white rounded-sm hover:opacity-90 transition-all duration-200 text-sm font-semibold shadow-sm hover:shadow-md h-[38px]"
                        style="background-color: #5867dd !important;">
                        Valider
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- intl-tel-input -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/intl-tel-input@24.5.0/build/css/intlTelInput.css">
    <script src="https://cdn.jsdelivr.net/npm/intl-tel-input@24.5.0/build/js/intlTelInput.min.js"></script>

    <style>
        .iti {
            width: 100%;
        }

        .iti__country-list {
            z-index: 50;
        }

        .iti__flag-container {
            border-radius: 2px 0 0 2px;
        }
    </style>

    <script>
        const phoneInputField = document.querySelector("#phone_input");
        const phoneHiddenInput = document.querySelector("#phone_hidden");

        const iti = window.intlTelInput(phoneInputField, {
            initialCountry: "sn",
            preferredCountries: ["sn", "es"],
            utilsScript: "https://cdn.jsdelivr.net/npm/intl-tel-input@24.5.0/build/js/utils.js",
            autoPlaceholder: "aggressive",
            nationalMode: true,
            separateDialCode: true,
            i18n: {
                sb: "Îles Salomon",
                ad: "Andorre",
                ae: "Émirats arabes unis",
                af: "Afghanistan",
                ag: "Antigua-et-Barbuda",
                ai: "Anguilla",
                al: "Albanie",
                am: "Arménie",
                ao: "Angola",
                aq: "Antarctique",
                ar: "Argentine",
                as: "Samoa américaines",
                at: "Autriche",
                au: "Australie",
                aw: "Aruba",
                ax: "Îles Åland",
                az: "Azerbaïdjan",
                ba: "Bosnie-Herzégovine",
                bb: "Barbade",
                bd: "Bangladesh",
                be: "Belgique",
                bf: "Burkina Faso",
                bg: "Bulgarie",
                bah: "Bahreïn",
                bi: "Burundi",
                bj: "Bénin",
                bl: "Saint-Barthélemy",
                bm: "Bermudes",
                bn: "Brunei",
                bo: "Bolivie",
                bq: "Pays-Bas caribéens",
                br: "Brésil",
                bs: "Bahamas",
                bt: "Bhoutan",
                bv: "Île Bouvet",
                bw: "Botswana",
                by: "Biélorussie",
                bz: "Belize",
                ca: "Canada",
                cc: "Îles Cocos",
                cd: "République démocratique du Congo",
                cf: "République centrafricaine",
                cg: "Congo-Brazzaville",
                ch: "Suisse",
                ci: "Côte d’Ivoire",
                ck: "Îles Cook",
                cl: "Chili",
                cm: "Cameroun",
                cn: "Chine",
                co: "Colombie",
                cr: "Costa Rica",
                cu: "Cuba",
                cv: "Cap-Vert",
                cw: "Curaçao",
                cx: "Île Christmas",
                cy: "Chypre",
                cz: "Tchéquie",
                de: "Allemagne",
                dj: "Djibouti",
                dk: "Danemark",
                dm: "Dominique",
                do: "République dominicaine",
                dz: "Algérie",
                ec: "Équateur",
                ee: "Estonie",
                eg: "Égypte",
                eh: "Sahara occidental",
                er: "Érythrée",
                es: "Espagne",
                et: "Éthiopie",
                fi: "Finlande",
                fj: "Fidji",
                fk: "Îles Malouines",
                fm: "Micronésie",
                fo: "Îles Féroé",
                fr: "France",
                ga: "Gabon",
                gb: "Royaume-Uni",
                gd: "Grenade",
                ge: "Géorgie",
                gf: "Guyane française",
                gg: "Guernesey",
                gh: "Ghana",
                gi: "Gibraltar",
                gl: "Groenland",
                gm: "Gambie",
                gn: "Guinée",
                gp: "Guadeloupe",
                gq: "Guinée équatoriale",
                gr: "Grèce",
                gs: "Géorgie du Sud-et-les Îles Sandwich du Sud",
                gt: "Guatemala",
                gu: "Guam",
                gw: "Guinée-Bissau",
                gy: "Guyana",
                hk: "Hong Kong",
                hm: "Îles Heard-et-MacDonald",
                hn: "Honduras",
                hr: "Croatie",
                ht: "Haïti",
                hu: "Hongrie",
                id: "Indonésie",
                ie: "Irlande",
                il: "Israël",
                im: "Île de Man",
                in: "Inde",
                io: "Territoire britannique de l’océan Indien",
                iq: "Irak",
                ir: "Iran",
                is: "Islande",
                it: "Italie",
                je: "Jersey",
                jm: "Jamaïque",
                jo: "Jordanie",
                jp: "Japon",
                ke: "Kenya",
                kg: "Kirghizistan",
                kh: "Cambodge",
                ki: "Kiribati",
                km: "Comores",
                kn: "Saint-Christophe-et-Niévès",
                kp: "Corée du Nord",
                kr: "Corée du Sud",
                kw: "Koweït",
                ky: "Îles Caïmans",
                kz: "Kazakhstan",
                la: "Laos",
                lb: "Liban",
                lc: "Sainte-Lucie",
                li: "Liechtenstein",
                lk: "Sri Lanka",
                lr: "Liberia",
                ls: "Lesotho",
                lt: "Lituanie",
                lu: "Luxembourg",
                lv: "Lettonie",
                ly: "Libye",
                ma: "Maroc",
                mc: "Monaco",
                md: "Moldavie",
                me: "Monténégro",
                mf: "Saint-Martin",
                mg: "Madagascar",
                mh: "Îles Marshall",
                mk: "Macédoine du Nord",
                ml: "Mali",
                mm: "Birmanie",
                mn: "Mongolie",
                mo: "Macao",
                mp: "Îles Mariannes du Nord",
                mq: "Martinique",
                mr: "Mauritanie",
                ms: "Montserrat",
                mt: "Malte",
                mu: "Maurice",
                mv: "Maldives",
                mw: "Malawi",
                mx: "Mexique",
                my: "Malaisie",
                mz: "Mozambique",
                na: "Namibie",
                nc: "Nouvelle-Calédonie",
                ne: "Niger",
                nf: "Île Norfolk",
                ng: "Nigeria",
                ni: "Nicaragua",
                nl: "Pays-Bas",
                no: "Norvège",
                np: "Népal",
                nr: "Nauru",
                nu: "Niue",
                nz: "Nouvelle-Zélande",
                om: "Oman",
                pa: "Panama",
                pe: "Pérou",
                pf: "Polynésie française",
                pg: "Papouasie-Nouvelle-Guinée",
                ph: "Philippines",
                pk: "Pakistan",
                pl: "Pologne",
                pm: "Saint-Pierre-et-Miquelon",
                pn: "Îles Pitcairn",
                pr: "Porto Rico",
                ps: "Territoires palestiniens",
                pt: "Portugal",
                pw: "Palaos",
                py: "Paraguay",
                qa: "Qatar",
                re: "La Réunion",
                ro: "Roumanie",
                rs: "Serbie",
                ru: "Russie",
                rw: "Rwanda",
                sa: "Arabie saoudite",
                sb: "Îles Salomon",
                sc: "Seychelles",
                sd: "Soudan",
                se: "Suède",
                sg: "Singapour",
                sh: "Sainte-Hélène",
                si: "Slovénie",
                sj: "Svalbard et Jan Mayen",
                sk: "Slovaquie",
                sl: "Sierra Leone",
                sm: "Saint-Marin",
                sn: "Sénégal",
                so: "Somalie",
                sr: "Suriname",
                ss: "Soudan du Sud",
                st: "Sao Tomé-et-Principe",
                sv: "Salvador",
                sx: "Saint-Martin",
                sy: "Syrie",
                sz: "Eswatini",
                tc: "Îles Turques-et-Caïques",
                td: "Tchad",
                tf: "Terres australes françaises",
                tg: "Togo",
                th: "Thaïlande",
                tj: "Tadjikistan",
                tk: "Tokelau",
                tl: "Timor oriental",
                tm: "Turkménistan",
                tn: "Tunisie",
                to: "Tonga",
                tr: "Turquie",
                tt: "Trinité-et-Tobago",
                tv: "Tuvalu",
                tw: "Taïwan",
                tz: "Tanzanie",
                ua: "Ukraine",
                ug: "Ouganda",
                um: "Îles mineures éloignées des États-Unis",
                us: "États-Unis",
                uy: "Uruguay",
                uz: "Ouzbékistan",
                va: "État de la Cité du Vatican",
                vc: "Saint-Vincent-et-les-Grenadines",
                ve: "Venezuela",
                vg: "Îles Vierges britanniques",
                vi: "Îles Vierges des États-Unis",
                vn: "Viêt Nam",
                vu: "Vanuatu",
                wf: "Wallis-et-Futuna",
                ws: "Samoa",
                ye: "Yémen",
                yt: "Mayotte",
                za: "Afrique du Sud",
                zm: "Zambie",
                zw: "Zimbabwe"
            }
        });

        const updatePhoneValue = () => {
            const fullNumber = iti.getNumber();
            phoneHiddenInput.value = fullNumber;
        };

        const form = document.getElementById('member-edit-form');
        form.addEventListener('submit', (e) => {
            updatePhoneValue();
            console.log("Phone submitted:", phoneHiddenInput.value);
        });

        phoneInputField.addEventListener('input', updatePhoneValue);
        phoneInputField.addEventListener('countrychange', updatePhoneValue);

        // Populate if exists
        if (phoneHiddenInput.value) {
            iti.setNumber(phoneHiddenInput.value);
            // Ensure synchronization right away
            updatePhoneValue();
        }
    </script>
</x-admin-layout>