export class DevisManager extends HTMLDivElement {
    connectedCallback() {
        this.customerSelect = this.querySelector('select');
        // On s'assure de bien cibler les éléments dans le DOM
        this.billAddress = this.parentElement.parentElement.querySelector('#billAddress');
        this.shipAddress = this.parentElement.parentElement.querySelector('#shipAddress');

        this.setAddressPlaceholder("Sélectionnez un client...");

        if (this.customerSelect) {
            // Utiliser TomSelect si présent sur le client, sinon l'event natif
            if (this.customerSelect.tomselect) {
                this.customerSelect.tomselect.on('change', (value) => this.updateCustomerInfo(value));
            } else {
                this.customerSelect.addEventListener('change', (e) => this.updateCustomerInfo(e.target.value));
            }
        }
    }

    setAddressPlaceholder(text) {
        [this.billAddress, this.shipAddress].forEach(el => {
            if (el && el.tomselect) {
                el.tomselect.settings.placeholder = text;
                el.tomselect.inputState();
            }
        });
    }

    async updateCustomerInfo(customerId) {
        // Vider les options actuelles proprement
        [this.billAddress, this.shipAddress].forEach(el => {
            if (el && el.tomselect) {
                el.tomselect.clear();
                el.tomselect.clearOptions();
                // On désactive pendant le chargement pour éviter une saisie erronée
                el.tomselect.disable();
            }
        });

        if (!customerId) {
            this.setAddressPlaceholder("Sélectionnez un client...");
            return;
        }

        this.setAddressPlaceholder("Chargement des adresses...");

        try {
            const resp = await fetch("/crm/customer/address/" + customerId);
            const data = await resp.json();

            [this.billAddress, this.shipAddress].forEach(el => el?.tomselect?.enable());

            if (data.addressList && data.addressList.length > 0) {
                this.setAddressPlaceholder("Choisir une adresse...");

                data.addressList.forEach(itemList => {
                    const option = { value: itemList.id, text: itemList.label }; // Adapté aux valueField/labelField par défaut
                    const option2 = { value: itemList.id, text: itemList.label }; // Adapté aux valueField/labelField par défaut
                    if (this.billAddress.tomselect) this.billAddress.tomselect.addOption(option);
                    if (this.shipAddress.tomselect) this.shipAddress.tomselect.addOption(option2);
                });

                // --- SÉLECTION ET SYNCHRONISATION ---
                const firstId = data.addressList[0].id;

                if (this.billAddress.tomselect) {

                    this.billAddress.tomselect.setValue(firstId);
                    this.billAddress.dispatchEvent(new Event('change', { bubbles: true }));
                }

                if (this.shipAddress.tomselect) {
                    this.shipAddress.tomselect.setValue(firstId);
                    this.shipAddress.dispatchEvent(new Event('change', { bubbles: true }));
                }

            } else {
                this.setAddressPlaceholder("Aucune adresse trouvée");
            }

        } catch (error) {
            console.error("Erreur adresses:", error);
            this.setAddressPlaceholder("Erreur de chargement");
            [this.billAddress, this.shipAddress].forEach(el => el?.tomselect?.enable());
        }
    }
}
