class TimeBox extends HTMLElement {
  constructor() {
    super();
    this.input = document.createElement('input');
    this.picker = document.createElement('div');
    this.picker.classList.add('time-picker');
    this.format = this.getAttribute('format') || 'fr';
    this.appendChild(this.input);
    this.appendChild(this.picker);
    this.input.name = this.id;
    this.input.id = this.id;
  }

  connectedCallback() {
    const valueAttr = this.getAttribute('value');
    if (valueAttr) this.input.value = valueAttr;

    // Afficher le picker au focus ou clic
    this.input.addEventListener('focus', () => this.showPicker());
    this.input.addEventListener('click', () => this.showPicker());

    // Fermer le picker si on clique en dehors
    document.addEventListener('click', (e) => {
      if (!this.contains(e.target)) this.hidePicker();
    });

    this.renderPicker();
  }

  renderPicker() {
    const isFrench = this.format.toLowerCase() === 'fr';

    let hours = '';
    let minutes = '';

    if (isFrench) {
      for (let h = 0; h < 24; h++) {
        const label = h.toString().padStart(2, '0');
        hours += `<option value="${label}">${label}</option>`;
      }
    } else {
      for (let h = 1; h <= 12; h++) {
        const label = h.toString().padStart(2, '0');
        hours += `<option value="${label}">${label}</option>`;
      }
    }

    for (let m = 0; m < 60; m += 5) {
      const label = m.toString().padStart(2, '0');
      minutes += `<option value="${label}">${label}</option>`;
    }

    const ampmSelect = !isFrench
      ? `<select id="ampm"><option>AM</option><option>PM</option></select>`
      : '';

    this.picker.innerHTML = `
      <div class="selects">
        <select id="hour">${hours}</select>
        <span>:</span>
        <select id="minute">${minutes}</select>
        ${ampmSelect}
      </div>
      <button id="okBtn">OK</button>
    `;

    const hourSel = this.picker.querySelector('#hour');
    const minSel = this.picker.querySelector('#minute');
    const ampmSel = this.picker.querySelector('#ampm');

    // Pré-remplir avec la valeur actuelle
    if (this.input.value) {
      const parsed = this.parseValue(this.input.value);
      if (parsed) {
        hourSel.value = parsed.hour;
        minSel.value = parsed.minute;
        if (ampmSel && parsed.ampm) ampmSel.value = parsed.ampm;
      }
    }

    // OK bouton
    this.picker.querySelector('#okBtn').onclick = (e) => {
        e.preventDefault();
      const hour = hourSel.value;
      const minute = minSel.value;
      let value = '';
      if (isFrench) {
        value = `${hour}:${minute}`;
      } else {
        const ampm = ampmSel.value;
        value = `${hour}:${minute} ${ampm}`;
      }
      this.input.value = value;
      this.setAttribute('value', value);
      this.hidePicker();
      
      return false;
    };
  }

  parseValue(val) {
    const match = val.match(/^(\d{1,2}):(\d{2})(?:\s?(AM|PM))?$/i);
    if (!match) return null;
    const [, h, m, ap] = match;
    return {
      hour: h.padStart(2, '0'),
      minute: m.padStart(2, '0'),
      ampm: ap ? ap.toUpperCase() : null
    };
  }

  showPicker() {
    this.picker.style.display = 'block';
  }

  hidePicker() {
    this.picker.style.display = 'none';
  }

  get value() {
    return this.input.value;
  }

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

var DateTimePuzzleBox = TimeBox;

customElements.define('time-box', DateTimePuzzleBox);