class TelBox extends HTMLElement {
    constructor() {
        super();

        this.wrapper = document.createElement('div');
        this.wrapper.classList.add('tel-box');

        this.select = document.createElement('select');
        this.input = document.createElement('input');

        this.input.type = 'tel';
        this.input.autocomplete = 'off';

        this.wrapper.appendChild(this.select);
        this.wrapper.appendChild(this.input);
        this.appendChild(this.wrapper);
    }

    connectedCallback() {
        this.renderCountries();

        this.input.name = this.id;
        this.input.id = this.id;

        const valueAttr = this.getAttribute('value');
        if (valueAttr)
            this.setValue(valueAttr);

        this.select.addEventListener('change', () => this.updateValue());
        this.input.addEventListener('input', () => this.updateValue());

        this.input.addEventListener('blur', () => this.applyFinalFormat());

        // (optionnel mais recommandé)
        this.input.addEventListener('focus', () => this.restoreLocalNumber());
    }

    renderCountries() {
        const countries = [
            {code: '+33', label: '🇫🇷 +33'},
            {code: '+32', label: '🇧🇪 +32'},
            {code: '+41', label: '🇨🇭 +41'},
            {code: '+1', label: '🇺🇸 +1'},
            {code: '+44', label: '🇬🇧 +44'},
            {code: '+49', label: '🇩🇪 +49'}
        ];

        countries.forEach(c => {
            const opt = document.createElement('option');
            opt.value = c.code;
            opt.textContent = c.label;
            this.select.appendChild(opt);
        });
    }

    setValue(val) {
        const match = val.match(/^(\+\d+)\s*(.*)$/);
        if (!match)
            return;

        const [, code, number] = match;
        this.select.value = code;
        this.input.value = number;
    }

    updateValue() {
        const fullValue = `${this.select.value} ${this.input.value}`;
        this.setAttribute('value', fullValue);
    }

    get value() {
        return `${this.select.value} ${this.input.value}`;
    }

    set value(val) {
        this.setValue(val);
        this.setAttribute('value', val);
    }

    restoreLocalNumber() {
        const match = this.input.value.match(/^\+33\s(.+)$/);
        if (match) {
            this.select.value = '+33';
            this.input.value = '0' + match[1].replace(/\s/g, '');
        }
    }

    applyFinalFormat() {
        let number = this.input.value;

        // format FR uniquement si +33
        if (this.select.value === '+33') {
            const formatted = this.formatFrenchNumber(number);
            if (!formatted)
                return;

            this.input.value = formatted;
            this.setAttribute('value', formatted);
            return;
        }

        // fallback autres pays
        number = number.replace(/\s+/g, '');
        const fullValue = `${this.select.value} ${number}`;
        this.input.value = fullValue;
        this.setAttribute('value', fullValue);
    }
    
    formatFrenchNumber(raw) {
  // garder uniquement les chiffres
  let digits = raw.replace(/\D/g, '');

  // retirer le 0 initial
  if (digits.startsWith('0')) {
    digits = digits.substring(1);
  }

  // sécurité longueur
  if (digits.length !== 9) return null;

  return `+33 ${digits[0]} ${digits.slice(1,3)} ${digits.slice(3,5)} ${digits.slice(5,7)} ${digits.slice(7,9)}`;
}
}


var TelPuzzleBox = TelBox;
