'use client';
import { useState, useEffect } from 'react';
import { fetchWrapper } from '@/helpers';
import { toast } from 'react-toastify';
import { Plus, Trash2, Star, MapPin, Building2, User } from 'lucide-react';
import Swal from 'sweetalert2';

import { useT } from "@/context/I18nContext"; 

// ── Formularul de adresă în HTML string pentru Swal ──────────────────────────
function buildAddressFormHtml(initial = {}, romaniaData = null) {
    const isPJ = initial.billingType === 1;

    // Construim selecturile pentru județ și oraș
    const countiesOptions = romaniaData
        ? Object.keys(romaniaData).sort().map(c =>
            `<option value="${c}" ${initial._selectedCounty === c ? 'selected' : ''}>${c}</option>`
          ).join('')
        : '';

    const initialCounty = initial._selectedCounty || '';
    const initialCity = initial._selectedCity || '';
    const citiesOptions = romaniaData && initialCounty
        ? romaniaData[initialCounty]
            .map(c => c.name)
            .filter((v, i, a) => a.indexOf(v) === i)
            .sort()
            .map(c => `<option value="${c}" ${initialCity === c ? 'selected' : ''}>${c}</option>`)
            .join('')
        : '';

    return `
       <style>
        .addr-form-popup { border-radius: 16px !important; padding: 0 !important; box-shadow: 0 20px 60px rgba(0,0,0,0.15) !important; }
        .addr-form-container { text-align: left; max-height: 80vh; overflow-y: auto; padding: 40px; }
        .addr-form-container::-webkit-scrollbar { width: 8px; }
        .addr-form-container::-webkit-scrollbar-track { background: #f5f5f5; border-radius: 4px; }
        .addr-form-container::-webkit-scrollbar-thumb { background: #d0d0d0; border-radius: 4px; }
        .addr-form-title { font-size: 26px; font-weight: 700; color: #000; margin: 0 0 6px 0; }
        .addr-form-subtitle { font-size: 14px; color: #888; margin: 0 0 28px 0; }
        .addr-type-toggle { display: flex; gap: 10px; margin-bottom: 28px; }
        .addr-type-btn {
            flex: 1; padding: 12px; border-radius: 10px; border: 2px solid #e5e5e5;
            background: #fafafa; font-size: 13px; font-weight: 600; cursor: pointer;
            transition: all 0.2s; display: flex; align-items: center; justify-content: center; gap: 8px; color: #555;
        }
        .addr-type-btn.active { border-color: #000; background: #000; color: #fff; }
        .addr-fields-pf, .addr-fields-pj { display: none; }
        .addr-fields-pf.visible, .addr-fields-pj.visible { display: block; }
        .addr-grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
        .addr-form-group { margin-bottom: 16px; }
        .addr-form-label { display: block; font-size: 13px; font-weight: 600; color: #000; margin-bottom: 6px; }
        .addr-form-input, .addr-form-select {
            width: 100%; padding: 12px 14px; border: 2px solid #e5e5e5; border-radius: 10px;
            font-size: 14px; color: #000; background: #fafafa; font-family: inherit;
            transition: all 0.2s; box-sizing: border-box;
        }
        .addr-form-input:focus, .addr-form-select:focus { outline: none; border-color: #000; background: #fff; }
        .addr-section-title {
            font-size: 11px; font-weight: 700; text-transform: uppercase;
            letter-spacing: 0.08em; color: #999; margin: 20px 0 14px 0;
        }
        .addr-confirm-btn {
            background: #000 !important; color: #fff !important; border: none !important;
            border-radius: 10px !important; padding: 14px 32px !important;
            font-size: 15px !important; font-weight: 600 !important;
        }
        .addr-cancel-btn {
            background: transparent !important; color: #666 !important;
            border: 2px solid #d0d0d0 !important; border-radius: 10px !important;
            padding: 14px 32px !important; font-size: 15px !important; font-weight: 600 !important;
        }
        @media (max-width: 600px) {
            .addr-form-container { padding: 24px; }
            .addr-grid-2 { grid-template-columns: 1fr; }
        }
        .addr-location-row { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
        .addr-form-select {
            width: 100%; padding: 12px 14px; border: 2px solid #e5e5e5; border-radius: 10px;
            font-size: 14px; color: #000; background: #fafafa; font-family: inherit;
            transition: all 0.2s; box-sizing: border-box; cursor: pointer;
            appearance: none;
            background-image: url("data:image/svg+xml,%3Csvg width='12' height='8' viewBox='0 0 12 8' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M1 1.5L6 6.5L11 1.5' stroke='%23666666' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: right 14px center;
            padding-right: 40px;
        }
        .addr-form-select:focus { outline: none; border-color: #000; background-color: #fff; }
        .addr-form-select:disabled { opacity: 0.4; cursor: not-allowed; }
        .addr-city-search {
            width: 100%; padding: 10px 14px; border: 2px solid #e5e5e5; border-radius: 8px;
            font-size: 13px; margin-bottom: 8px; box-sizing: border-box; font-family: inherit;
        }
        .addr-city-search:focus { outline: none; border-color: #000; }
        .addr-city-list {
            width: 100%; border: 2px solid #e5e5e5; border-radius: 10px;
            font-size: 14px; color: #000; background: #fafafa; font-family: inherit;
            box-sizing: border-box; cursor: pointer; max-height: 160px;
            padding: 4px 0;
        }
        .addr-city-list option { padding: 8px 14px; }
    </style>

    <div class="addr-form-container">
        <h2 class="addr-form-title">${initial.id ? 'Editează adresa' : 'Adresă nouă'}</h2>
        <p class="addr-form-subtitle">Completează datele de facturare și livrare</p>

        <div class="addr-type-toggle">
            <button type="button" class="addr-type-btn ${!isPJ ? 'active' : ''}" id="btn-pf">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
                Persoană fizică
            </button>
            <button type="button" class="addr-type-btn ${isPJ ? 'active' : ''}" id="btn-pj">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16"/></svg>
                Persoană juridică
            </button>
        </div>

        <div class="addr-form-group">
            <label class="addr-form-label">Etichetă (ex: Acasă, Birou)</label>
            <input id="f-label" class="addr-form-input" placeholder="Acasă" value="${initial.label || ''}" />
        </div>

        <!-- ── PF ── -->
        <div class="addr-fields-pf ${!isPJ ? 'visible' : ''}" id="fields-pf">
            <div class="addr-section-title">Date personale</div>
            <div class="addr-grid-2">
                <div class="addr-form-group">
                    <label class="addr-form-label">Prenume *</label>
                    <input id="f-pf-prenume" class="addr-form-input" placeholder="Ion" value="${initial.pf_prenume || ''}" />
                </div>
                <div class="addr-form-group">
                    <label class="addr-form-label">Nume de familie *</label>
                    <input id="f-pf-nume" class="addr-form-input" placeholder="Popescu" value="${initial.pf_nume_familie || ''}" />
                </div>
                <div class="addr-form-group">
                    <label class="addr-form-label">Email *</label>
                    <input id="f-pf-email" type="email" class="addr-form-input" placeholder="ion@email.com" value="${initial.pf_email || ''}" />
                </div>
                <div class="addr-form-group">
                    <label class="addr-form-label">Telefon *</label>
                    <input id="f-pf-tel" class="addr-form-input" placeholder="07XX XXX XXX" value="${initial.pf_numar_telefon || ''}" />
                </div>
            </div>

            <div class="addr-section-title">Adresă livrare</div>
            <div class="addr-form-group">
                <label class="addr-form-label">Țară *</label>
                <input id="f-pf-tara" class="addr-form-input" placeholder="Romania" value="${initial.pf_tara || 'Romania'}" />
            </div>

            <!-- Județ + Oraș inline -->
            <div class="addr-location-row">
                <div class="addr-form-group">
                    <label class="addr-form-label">Județ *</label>
                    <select id="f-pf-judet" class="addr-form-select">
                        <option value="">Alege județul...</option>
                        ${countiesOptions}
                    </select>
                </div>
                <div class="addr-form-group">
                    <label class="addr-form-label">Oraș *</label>
                    <input
                        id="f-pf-oras-search"
                        class="addr-city-search"
                        placeholder="Caută oraș..."
                        ${!initialCounty ? 'disabled' : ''}
                        value=""
                    />
                    <select id="f-pf-oras" class="addr-city-list" size="4" ${!initialCounty ? 'disabled' : ''}>
                        <option value="">— selectează județul mai întâi —</option>
                        ${citiesOptions}
                    </select>
                </div>
            </div>

            <div class="addr-form-group">
                <label class="addr-form-label">Adresă (stradă, număr, bloc, ap.) *</label>
                <input id="f-pf-adresa" class="addr-form-input" placeholder="Str. Exemplu, nr. 1, bl. A, ap. 2" value="${initial.pf_adresa || ''}" />
            </div>
        </div>

<!-- ── PJ ── -->
<div class="addr-fields-pj ${isPJ ? 'visible' : ''}" id="fields-pj">
    <div class="addr-section-title">Date firmă</div>
    <div class="addr-grid-2">
        <div class="addr-form-group">
            <label class="addr-form-label">Nume firmă *</label>
            <input id="f-pj-firma" class="addr-form-input" placeholder="SC Exemplu SRL" value="${initial.pj_nume_firma || ''}" />
        </div>
        <div class="addr-form-group">
            <label class="addr-form-label">CUI *</label>
            <input id="f-pj-cui" class="addr-form-input" placeholder="RO12345678" value="${initial.pj_cui || ''}" />
        </div>
        <div class="addr-form-group">
            <label class="addr-form-label">Nr. înregistrare *</label>
            <input id="f-pj-nrreg" class="addr-form-input" placeholder="J40/1234/2020" value="${initial.pj_nr_reg || ''}" />
        </div>
        <div class="addr-form-group">
            <label class="addr-form-label">Bancă</label>
            <input id="f-pj-banca" class="addr-form-input" placeholder="BRD" value="${initial.pj_banca || ''}" />
        </div>
        <div class="addr-form-group">
            <label class="addr-form-label">IBAN</label>
            <input id="f-pj-iban" class="addr-form-input" placeholder="RO49 AAAA..." value="${initial.pj_iban || ''}" />
        </div>
        <div class="addr-form-group">
            <label class="addr-form-label">Email *</label>
            <input id="f-pj-email" type="email" class="addr-form-input" placeholder="firma@email.com" value="${initial.pj_email || ''}" />
        </div>
        <div class="addr-form-group">
            <label class="addr-form-label">Telefon *</label>
            <input id="f-pj-tel" class="addr-form-input" placeholder="07XX XXX XXX" value="${initial.pj_numar_telefon || ''}" />
        </div>
    </div>

    <div class="addr-section-title">Adresă firmă</div>

    <!-- Județ + Oraș PJ — același sistem ca PF -->
    <div class="addr-location-row">
        <div class="addr-form-group">
            <label class="addr-form-label">Județ *</label>
            <select id="f-pj-judet" class="addr-form-select">
                <option value="">Alege județul...</option>
                ${romaniaData ? Object.keys(romaniaData).sort().map(c =>
                    `<option value="${c}" ${initial._selectedCounty === c && isPJ ? 'selected' : ''}>${c}</option>`
                ).join('') : ''}
            </select>
        </div>
        <div class="addr-form-group">
            <label class="addr-form-label">Localitate *</label>
            <input
                id="f-pj-oras-search"
                class="addr-city-search"
                placeholder="Caută localitate..."
                ${!(initial._selectedCounty && isPJ) ? 'disabled' : ''}
                value=""
            />
            <select id="f-pj-oras" class="addr-city-list" size="4" ${!(initial._selectedCounty && isPJ) ? 'disabled' : ''}>
                ${romaniaData && initial._selectedCounty && isPJ
                    ? romaniaData[initial._selectedCounty]
                        .map(c => c.name)
                        .filter((v, i, a) => a.indexOf(v) === i)
                        .sort()
                        .map(c => `<option value="${c}" ${c === initial._selectedCity ? 'selected' : ''}>${c}</option>`)
                        .join('')
                    : '<option value="">— selectează județul mai întâi —</option>'
                }
            </select>
        </div>
    </div>

    <div class="addr-form-group">
        <label class="addr-form-label">Adresă firmă *</label>
        <input id="f-pj-adresa" class="addr-form-input" placeholder="Str. Exemplu, nr. 1" value="${initial.pj_adresa || ''}" />
    </div>
    <div class="addr-form-group">
        <label class="addr-form-label">Adresă livrare *</label>
        <input id="f-pj-adresa-liv" class="addr-form-input" placeholder="Str. Livrare, nr. 2" value="${initial.pj_adresa_livrare || ''}" />
    </div>
</div>
    </div>
    `;
}

// ── Deschide modalul de adăugare / editare ────────────────────────────────────
async function openAddressForm(initial = {}, romaniaData, onSave) {
    const { value: formValues } = await Swal.fire({
        title: '',
        width: '760px',
        background: '#ffffff',
        color: '#000000',
        showConfirmButton: true,
        showCancelButton: true,
        confirmButtonText: initial.id ? 'Salvează modificările' : 'Adaugă adresa',
        cancelButtonText: 'Anulează',
        customClass: {
            popup: 'addr-form-popup',
            confirmButton: 'addr-confirm-btn',
            cancelButton: 'addr-cancel-btn',
            htmlContainer: 'premium-html-container',
        },
        html: buildAddressFormHtml(initial, romaniaData),
        didOpen: () => {
            const btnPF = document.getElementById('btn-pf');
            const btnPJ = document.getElementById('btn-pj');
            const fieldsPF = document.getElementById('fields-pf');
            const fieldsPJ = document.getElementById('fields-pj');

            btnPF.addEventListener('click', () => {
                btnPF.classList.add('active');
                btnPJ.classList.remove('active');
                fieldsPF.classList.add('visible');
                fieldsPJ.classList.remove('visible');
            });

            btnPJ.addEventListener('click', () => {
                btnPJ.classList.add('active');
                btnPF.classList.remove('active');
                fieldsPJ.classList.add('visible');
                fieldsPF.classList.remove('visible');
            });

            const judетSelect = document.getElementById('f-pf-judet');
    const orasSearch = document.getElementById('f-pf-oras-search');
    const orasList = document.getElementById('f-pf-oras');

    if (judетSelect && romaniaData) {
        // Funcție care populează orașele
        const populateCities = (county, filterText = '', selectedCity = '') => {
            if (!county || !romaniaData[county]) {
                orasList.innerHTML = '<option value="">— selectează județul mai întâi —</option>';
                orasList.disabled = true;
                orasSearch.disabled = true;
                return;
            }

            const cities = romaniaData[county]
                .map(c => c.name)
                .filter((v, i, a) => a.indexOf(v) === i)
                .sort()
                .filter(c => c.toLowerCase().includes(filterText.toLowerCase()));

            orasList.innerHTML = cities.map(c =>
                `<option value="${c}" ${c === selectedCity ? 'selected' : ''}>${c}</option>`
            ).join('');
            orasList.disabled = false;
            orasSearch.disabled = false;

            // Selectează primul dacă nu e nimic selectat
            if (!selectedCity && cities.length > 0) {
                orasList.value = cities[0];
            }
        };

        const judетSelectPJ = document.getElementById('f-pj-judet');
const orasSearchPJ = document.getElementById('f-pj-oras-search');
const orasListPJ = document.getElementById('f-pj-oras');

if (judетSelectPJ && romaniaData) {
    const populateCitiesPJ = (county, filterText = '', selectedCity = '') => {
        if (!county || !romaniaData[county]) {
            orasListPJ.innerHTML = '<option value="">— selectează județul mai întâi —</option>';
            orasListPJ.disabled = true;
            orasSearchPJ.disabled = true;
            return;
        }
        const cities = romaniaData[county]
            .map(c => c.name)
            .filter((v, i, a) => a.indexOf(v) === i)
            .sort()
            .filter(c => c.toLowerCase().includes(filterText.toLowerCase()));

        orasListPJ.innerHTML = cities.map(c =>
            `<option value="${c}" ${c === selectedCity ? 'selected' : ''}>${c}</option>`
        ).join('');
        orasListPJ.disabled = false;
        orasSearchPJ.disabled = false;

        if (!selectedCity && cities.length > 0) orasListPJ.value = cities[0];
    };

    const currentCountyPJ = judетSelectPJ.value;
    const currentCityPJ = initial._selectedCity || '';
    if (currentCountyPJ) populateCitiesPJ(currentCountyPJ, '', currentCityPJ);

    judетSelectPJ.addEventListener('change', () => {
        orasSearchPJ.value = '';
        populateCitiesPJ(judетSelectPJ.value);
    });

    orasSearchPJ.addEventListener('input', () => {
        populateCitiesPJ(judетSelectPJ.value, orasSearchPJ.value, orasListPJ.value);
    });
}

        // Populează imediat dacă avem județ din editare
        const currentCounty = judетSelect.value;
        const currentCity = initial._selectedCity || '';
        if (currentCounty) populateCities(currentCounty, '', currentCity);

        // Schimbare județ
        judетSelect.addEventListener('change', () => {
            orasSearch.value = '';
            populateCities(judетSelect.value);
        });

        // Search în orașe
        orasSearch.addEventListener('input', () => {
            populateCities(judетSelect.value, orasSearch.value, orasList.value);
        });
    }
        },
        preConfirm: () => {
            const isPJ = document.getElementById('btn-pj').classList.contains('active');

            if (isPJ) {
    // Validare câmpuri text
    const requiredPJ = {
        'f-pj-firma': 'Nume firmă',
        'f-pj-cui': 'CUI',
        'f-pj-nrreg': 'Nr. înregistrare',
        'f-pj-email': 'Email',
        'f-pj-tel': 'Telefon',
        'f-pj-adresa': 'Adresă firmă',
        'f-pj-adresa-liv': 'Adresă livrare',
    };
    for (const [id, label] of Object.entries(requiredPJ)) {
        if (!document.getElementById(id)?.value?.trim())
            return Swal.showValidationMessage(`Câmpul "${label}" este obligatoriu.`);
    }

    // Validare județ/oraș PJ — la fel ca PF
    const judетValPJ = document.getElementById('f-pj-judet')?.value?.trim();
    const orasValPJ = document.getElementById('f-pj-oras')?.value?.trim();
    if (!judетValPJ)
        return Swal.showValidationMessage('Câmpul "Județ" este obligatoriu.');
    if (!orasValPJ)
        return Swal.showValidationMessage('Câmpul "Localitate" este obligatoriu.');

    return {
        billingType: 1,
        label: document.getElementById('f-label').value.trim() || 'Adresă firmă',
        pj_nume_firma: document.getElementById('f-pj-firma').value.trim(),
        pj_cui: document.getElementById('f-pj-cui').value.trim(),
        pj_nr_reg: document.getElementById('f-pj-nrreg').value.trim(),
        pj_banca: document.getElementById('f-pj-banca').value.trim(),
        pj_iban: document.getElementById('f-pj-iban').value.trim(),
        pj_email: document.getElementById('f-pj-email').value.trim(),
        pj_numar_telefon: document.getElementById('f-pj-tel').value.trim(),
        pj_judet: judетValPJ,           // ← din select, nu din input text
        pj_localitate: orasValPJ,       // ← din select, nu din input text
        pj_adresa: document.getElementById('f-pj-adresa').value.trim(),
        pj_adresa_livrare: document.getElementById('f-pj-adresa-liv').value.trim(),
        _selectedCounty: judетValPJ,
        _selectedCity: orasValPJ,
    };
} else {
                const required = {
                    'f-pf-prenume': 'Prenume',
                    'f-pf-nume': 'Nume de familie',
                    'f-pf-email': 'Email',
                    'f-pf-tel': 'Telefon',
                    'f-pf-adresa': 'Adresă',
                };
                for (const [id, label] of Object.entries(required)) {
                    if (!document.getElementById(id)?.value?.trim())
                        return Swal.showValidationMessage(`Câmpul "${label}" este obligatoriu.`);
                }

                const judетVal = document.getElementById('f-pf-judet')?.value?.trim();
const orasVal = document.getElementById('f-pf-oras')?.value?.trim();

if (!judетVal)
    return Swal.showValidationMessage('Câmpul "Județ" este obligatoriu.');
if (!orasVal)
    return Swal.showValidationMessage('Câmpul "Oraș" este obligatoriu.');

                return {
                    billingType: 0,
                    label: document.getElementById('f-label').value.trim() || 'Adresă personală',
                    pf_prenume: document.getElementById('f-pf-prenume').value.trim(),
                    pf_nume_familie: document.getElementById('f-pf-nume').value.trim(),
                    pf_email: document.getElementById('f-pf-email').value.trim(),
                    pf_numar_telefon: document.getElementById('f-pf-tel').value.trim(),
                    pf_tara: document.getElementById('f-pf-tara').value.trim() || 'Romania',
                     pf_judet_oras: `${judетVal}, ${orasVal}`, // format consistent cu Checkout
    _selectedCounty: judетVal,
    _selectedCity: orasVal,
                    pf_adresa: document.getElementById('f-pf-adresa').value.trim(),
                };
            }
        },
    });

    if (formValues) await onSave(formValues);
}

// ── Componenta principală ─────────────────────────────────────────────────────
export default function AccountAddresses() {
      const { t } = useT(); 
      
    const [addresses, setAddresses] = useState([]);
    const [loading, setLoading] = useState(true);
    const [romaniaData, setRomaniaData] = useState(null);

     useEffect(() => {
          fetch('/romania-regions.json')
               .then(res => res.json())
               .then(data => setRomaniaData(data))
               .catch(() => toast.error('Nu s-au putut încărca datele de localizare'));
     }, []);

    const fetchAddresses = async () => {
        try {
            const data = await fetchWrapper.get('/api/users/addresses');
            setAddresses(data.addresses || []);
        } catch {
            toast.error('Eroare la încărcarea adreselor.');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => { fetchAddresses(); }, []);

    const openLocationSelector = async () => {
          if (!romaniaData) {
               toast.error("Se încarcă datele de localizare. Încearcă din nou!");
               return;
          }
    
          const counties = Object.keys(romaniaData).sort();
    
          const { value: selectedCounty } = await Swal.fire({
               title: "Selectează județul",
               input: "select",
               inputOptions: counties.reduce((acc, county) => {
                    acc[county] = county;
                    return acc;
               }, {}),
               inputPlaceholder: "Alege județul",
               showCancelButton: true,
               cancelButtonText: "Anulează",
               confirmButtonText: "Următorul →",
               inputValidator: (value) => {
                    if (!value) {
                         return "Trebuie să selectezi un județ!";
                    }
               },
               customClass: {
                    confirmButton: "swal2-confirm swal2-styled",
                    cancelButton: "swal2-cancel swal2-styled",
               },
          });
    
          if (selectedCounty) {
               const cities = romaniaData[selectedCounty]
                    .map((city) => city.name)
                    .filter((value, index, self) => self.indexOf(value) === index)
                    .sort();
    
               const { value: selectedCity } = await Swal.fire({
                    title: `Selectează orașul din ${selectedCounty}`,
                    html: `
                         <div style="margin-bottom: 15px;">
                              <input 
                                   type="text" 
                                   id="city-search" 
                                   class="swal2-input" 
                                   placeholder="Caută oraș (ex: Cluj, Bucuresti)..." 
                                   style="margin: 0; width: 100%; font-size: 14px;"
                              >
                         </div>
                         <select 
                              id="city-select" 
                              class="swal2-input" 
                              size="12" 
                              style="width: 100%; height: 350px; margin: 0; font-size: 14px; cursor: pointer;"
                         >
                              ${cities.map((city) => `<option value="${city}">${city}</option>`).join("")}
                         </select>
                         <p style="margin-top: 10px; font-size: 12px; color: #666;">
                              💡 Poți da dublu-click pe oraș pentru confirmare rapidă
                         </p>
                    `,
                    showCancelButton: true,
                    cancelButtonText: "← Înapoi",
                    confirmButtonText: "Confirmă",
                    width: "600px",
                    didOpen: () => {
                         const searchInput = document.getElementById("city-search");
                         const citySelect = document.getElementById("city-select");
    
                         searchInput.focus();
    
                         searchInput.addEventListener("input", (e) => {
                              const search = e.target.value.toLowerCase().trim();
                              const options = citySelect.options;
                              let firstVisible = null;
    
                              for (let i = 0; i < options.length; i++) {
                                   const city = options[i].text.toLowerCase();
                                   const matches = city.includes(search);
                                   options[i].style.display = matches ? "" : "none";
    
                                   if (matches && !firstVisible) {
                                        firstVisible = options[i];
                                   }
                              }
    
                              if (firstVisible) {
                                   citySelect.value = firstVisible.value;
                              }
                         });
    
                         citySelect.addEventListener("dblclick", () => {
                              Swal.clickConfirm();
                         });
    
                         searchInput.addEventListener("keydown", (e) => {
                              if (e.key === "Enter" && citySelect.value) {
                                   Swal.clickConfirm();
                              }
                         });
                    },
                    preConfirm: () => {
                         const citySelect = document.getElementById("city-select");
                         const selectedCity = citySelect.value;
                         if (!selectedCity) {
                              Swal.showValidationMessage("Trebuie să selectezi un oraș!");
                              return false;
                         }
                         return selectedCity;
                    },
               });
    
               if (selectedCity) {
                    const locationString = `${selectedCounty}, ${selectedCity}`;
                    setFormData((prev) => ({ ...prev, city: locationString }));
    
                    setErrors((prev) => {
                         const newErrors = { ...prev };
                         delete newErrors.city;
                         return newErrors;
                    });
    
                    toast.success(`Locație selectată: ${locationString}`);
               } else if (selectedCity === undefined) {
                    openLocationSelector();
               }
          }
     };

    // ── Adaugă ──
    const handleAdd = async () => {
        if (addresses.length >= 5) {
            toast.error('Poți salva maxim 5 adrese.');
            return;
        }
        await openAddressForm({}, romaniaData, async (data) => {
            const res = await fetchWrapper.post('/api/users/addresses', data);
            if (res.success) {
                toast.success('Adresă salvată cu succes!');
                fetchAddresses();
            } else {
                toast.error(res.error || 'Eroare la salvarea adresei.');
            }
        });
    };

    // ── Editează ──
    const handleEdit = async (addr) => {
    // Parsează județul și orașul din pf_judet_oras pentru pre-selectare
    const enrichedAddr = { ...addr };
    
    if (addr.billingType === 0 && addr.pf_judet_oras) {
        const parts = addr.pf_judet_oras.split(',').map(s => s.trim());
        enrichedAddr._selectedCounty = parts[0] || '';
        enrichedAddr._selectedCity = parts[1] || '';
    }
    
    // La fel pentru PJ — parsează din pj_judet și pj_localitate (sunt câmpuri separate)
    if (addr.billingType === 1) {
        enrichedAddr._selectedCounty = addr.pj_judet || '';
        enrichedAddr._selectedCity = addr.pj_localitate || '';
    }

    await openAddressForm(enrichedAddr, romaniaData, async (data) => {
        const res = await fetchWrapper.put('/api/users/addresses', { id: addr.id, ...data });
        if (res.success) {
            toast.success('Adresă actualizată!');
            fetchAddresses();
        } else {
            toast.error(res.error || 'Eroare la actualizare.');
        }
    });
};

    // ── Șterge ──
    const handleDelete = async (id) => {
        const result = await Swal.fire({
            title: 'Ștergi adresa?',
            text: 'Această acțiune nu poate fi anulată.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Da, șterge',
            cancelButtonText: 'Anulează',
            confirmButtonColor: '#e53e3e',
            cancelButtonColor: '#718096',
            reverseButtons: true,
            focusCancel: true,
        });
        if (!result.isConfirmed) return;
        const res = await fetchWrapper.delete('/api/users/addresses', { id });
        if (res.success) {
            toast.success('Adresă ștearsă.');
            fetchAddresses();
        }
    };

    // ── Setează implicit ──
    const handleSetDefault = async (id) => {
        const res = await fetchWrapper.put('/api/users/addresses', { id, setDefault: true });
        if (res.success) {
            toast.success('Adresă implicită actualizată.');
            fetchAddresses();
        }
    };

    const labelForAddress = (addr) =>
        addr.billingType === 1
            ? addr.pj_nume_firma || 'Firmă'
            : `${addr.pf_prenume || ''} ${addr.pf_nume_familie || ''}`.trim() || 'Adresă';

    const subtitleForAddress = (addr) =>
        addr.billingType === 1
            ? `${addr.pj_adresa}, ${addr.pj_localitate}, ${addr.pj_judet}`
            : `${addr.pf_adresa}, ${addr.pf_judet_oras}`;

    if (loading) return (
        <div style={{ padding: 40, textAlign: 'center', color: '#999' }}>
            Se încarcă...
        </div>
    );

    return (
        <div className='my-account-content' style={{ marginTop: 20}}>
            {/* Header */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
                <h5 style={{ margin: 0 }}>{t("contul_meu_adresele_mele")}</h5>
                {addresses.length < 5 && (
                    <button onClick={handleAdd}
                        style={{
                            display: 'flex', alignItems: 'center', gap: 8,
                            background: '#000', color: '#fff', padding: '10px 20px',
                            borderRadius: 8, fontSize: 14, fontWeight: 600,
                            border: 'none', cursor: 'pointer'
                        }}>
                        <Plus size={16} /> {t("contul_meu_adauga_adresa")}
                    </button>
                )}
            </div>

            {/* Empty state */}
            {addresses.length === 0 ? (
                <div style={{
                    textAlign: 'center', padding: '60px 20px',
                    background: '#fafafa', borderRadius: 16,
                    border: '2px dashed #e5e5e5'
                }}>
                    <MapPin size={40} color='#ccc' style={{ marginBottom: 16 }} />
                    <p style={{ color: '#999', fontSize: 15, margin: '0 0 20px' }}>
                        Nu ai nicio adresă salvată.
                    </p>
                    <button onClick={handleAdd}
                        style={{
                            background: '#000', color: '#fff',
                            padding: '12px 28px', borderRadius: 8,
                            fontSize: 14, fontWeight: 600,
                            border: 'none', cursor: 'pointer'
                        }}>
                        {t("contul_meu_adauga_adresa")}
                    </button>
                </div>
            ) : (
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 16 }}>
                    {addresses.map(addr => (
                        <div key={addr.id} style={{
                            background: '#fff',
                            border: addr.isDefault ? '2px solid #000' : '2px solid #e5e5e5',
                            borderRadius: 14, padding: 20, position: 'relative',
                            transition: 'all 0.2s ease'
                        }}>
                            {addr.isDefault != 0 && (
                                <span style={{
                                    position: 'absolute', top: 14, right: 14,
                                    background: '#000', color: '#fff',
                                    fontSize: 11, fontWeight: 700, padding: '3px 10px',
                                    borderRadius: 20, letterSpacing: '0.05em'
                                }}>
                                    IMPLICIT
                                </span>
                            )}

                            {/* Icon + tip */}
                            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
                                <div style={{
                                    width: 36, height: 36, background: '#f5f5f5',
                                    borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center'
                                }}>
                                    {addr.billingType === 1
                                        ? <Building2 size={18} color='#555' />
                                        : <User size={18} color='#555' />}
                                </div>
                                <div>
                                    <div style={{ fontSize: 13, fontWeight: 700, color: '#000' }}>
                                        {addr.label || labelForAddress(addr)}
                                    </div>
                                    <div style={{ fontSize: 11, color: '#999' }}>
                                        {addr.billingType === 1 ? 'Persoană juridică' : 'Persoană fizică'}
                                    </div>
                                </div>
                            </div>

                            {/* Detalii */}
                            <div style={{ fontSize: 13, color: '#555', lineHeight: 1.7, marginBottom: 16 }}>
                                <div style={{ fontWeight: 600, color: '#000', marginBottom: 2 }}>
                                    {labelForAddress(addr)}
                                </div>
                                <div>{subtitleForAddress(addr)}</div>
                                <div>{addr.billingType === 1 ? addr.pj_email : addr.pf_email}</div>
                                <div>{addr.billingType === 1 ? addr.pj_numar_telefon : addr.pf_numar_telefon}</div>
                                {addr.billingType === 1 && (
                                    <div style={{ marginTop: 4, fontSize: 12, color: '#888' }}>
                                        CUI: {addr.pj_cui} · {addr.pj_banca}
                                    </div>
                                )}
                            </div>

                            {/* Acțiuni */}
                            <div style={{ display: 'flex', gap: 8 }}>
                                {/* Editează */}
                                <button onClick={() => handleEdit(addr)}
                                    style={{
                                        flex: 1, display: 'flex', alignItems: 'center',
                                        justifyContent: 'center', gap: 6,
                                        padding: '8px 12px', borderRadius: 8,
                                        border: '1px solid #e5e5e5', background: '#fafafa',
                                        fontSize: 12, fontWeight: 600, cursor: 'pointer', color: '#000'
                                    }}>
                                    ✏️ Editează
                                </button>

                                {/* Setează implicit */}
                                {!addr.isDefault && (
                                    <button onClick={() => handleSetDefault(addr.id)}
                                        style={{
                                            flex: 1, display: 'flex', alignItems: 'center',
                                            justifyContent: 'center', gap: 6,
                                            padding: '8px 12px', borderRadius: 8,
                                            border: '1px solid #e5e5e5', background: '#fafafa',
                                            fontSize: 12, fontWeight: 600, cursor: 'pointer', color: '#555'
                                        }}>
                                        <Star size={13} /> Implicit
                                    </button>
                                )}

                                {/* Șterge */}
                                <button onClick={() => handleDelete(addr.id)}
                                    style={{
                                        display: 'flex', alignItems: 'center',
                                        justifyContent: 'center', gap: 6,
                                        padding: '8px 14px', borderRadius: 8,
                                        border: '1px solid #fecaca', background: '#fff5f5',
                                        fontSize: 12, fontWeight: 600, cursor: 'pointer', color: '#e53e3e'
                                    }}>
                                    <Trash2 size={13} />
                                </button>
                            </div>
                        </div>
                    ))}

                    {/* Card slot liber */}
                    {addresses.length < 5 && (
                        <button onClick={handleAdd} style={{
                            display: 'flex', flexDirection: 'column',
                            alignItems: 'center', justifyContent: 'center', gap: 10,
                            border: '2px dashed #e5e5e5', borderRadius: 14,
                            padding: 20, color: '#999', background: 'transparent',
                            minHeight: 180, cursor: 'pointer', width: '100%'
                        }}>
                            <Plus size={28} color='#ccc' />
                            <span style={{ fontSize: 13, fontWeight: 600 }}>
                                {t("contul_meu_adauga_adresa")} ({addresses.length}/5)
                            </span>
                        </button>
                    )}
                </div>
            )}
        </div>
    );
}