import intlTelInput from "intl-tel-input";
import "intl-tel-input/styles";

window.intlTelInput = intlTelInput;

export function initPhoneInputs() {
    document.querySelectorAll('[data-phone-input]').forEach((input) => {
        if (input.dataset.itiInitialized === 'true') return;

        input.dataset.itiInitialized = 'true';

        const iti = intlTelInput(input, {
            initialCountry: 'gb',
            separateDialCode: true,
            nationalMode: false,
            loadUtils: () => import('intl-tel-input/utils'),
        });

        if (input.value) {
            iti.setNumber(input.value);
        }

        input.addEventListener('blur', () => {
            const componentEl = input.closest('[wire\\:id]');
            if (!componentEl || !window.Livewire) return;

            const component = Livewire.find(
                componentEl.getAttribute('wire:id')
            );

            if (!component) return;

            component.set(input.dataset.model, iti.getNumber());
        });
    });
}

export function bootPhoneInputs() {
    document.addEventListener('DOMContentLoaded', () => {
        setTimeout(initPhoneInputs, 100);
        setTimeout(initPhoneInputs, 500);
        setTimeout(initPhoneInputs, 1000);
    });

    document.addEventListener('livewire:init', () => {
        initPhoneInputs();

        if (window.Livewire) {
            Livewire.hook('morph.updated', () => {
                setTimeout(initPhoneInputs, 50);
            });
        }
    });

    document.addEventListener('livewire:initialized', () => {
        setTimeout(initPhoneInputs, 100);
    });

    document.addEventListener('livewire:navigated', () => {
        setTimeout(initPhoneInputs, 100);
    });
}