
class DateBox extends HTMLElement {
  constructor() {
    super();
    this.input = document.createElement('input');
    this.calendar = document.createElement('div');
    this.calendar.classList.add('calendar');
    this.date = new Date();
    this.format = this.getAttribute('format') || 'yyyy-mm-dd';
    this.input.name = this.id;
    this.input.id = this.id;
    }

  connectedCallback() {
    this.appendChild(this.input);
    this.appendChild(this.calendar);

    const valueAttr = this.getAttribute('value');
    if (valueAttr) {
      const parsed = this.parseValue(valueAttr);
      if (parsed) {
        this.date = parsed;
        this.input.value = this.formatDate(this.date);
      }
    }

    this.input.addEventListener('focus', () => this.showCalendar());
    this.input.addEventListener('click', () => this.showCalendar());
    document.addEventListener('click', (e) => {
      if (!this.contains(e.target)) this.hideCalendar();
    });

    this.renderCalendar();
  }

  renderCalendar() {
    const year = this.date.getFullYear();
    const month = this.date.getMonth();
    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);
    const days = ['D', 'L', 'M', 'M', 'J', 'V', 'S'];

    let html = `
      <div class="header">
        <button class="prev" title="Mois précédent">&lt;</button>
        <span>${year} - ${month + 1}</span>
        <button class="next" title="Mois suivant">&gt;</button>
      </div>
      <table>
        <thead><tr>${days.map(d => `<th>${d}</th>`).join('')}</tr></thead>
        <tbody>
    `;

    let day = 1;
    for (let i = 0; i < 6; i++) {
      html += '<tr>';
      for (let j = 0; j < 7; j++) {
        const current = new Date(year, month, day);
        if ((i === 0 && j < firstDay.getDay()) || day > lastDay.getDate()) {
          html += '<td></td>';
        } else {
          html += `<td data-day="${day}">${day}</td>`;
          day++;
        }
      }
      html += '</tr>';
    }

    html += '</tbody></table>';
    this.calendar.innerHTML = html;

    // ✅ Correction : Réinitialiser le jour à 1 avant de changer de mois
    this.calendar.querySelector('.prev').onclick = (e) => {
       e.preventDefault();
       e.stopPropagation();
   
       this.date.setDate(1);
      this.date.setMonth(this.date.getMonth() - 1);
      this.renderCalendar();
      return false;
    };

    this.calendar.querySelector('.next').onclick = (e) => {
       e.preventDefault();
       e.stopPropagation();
        
      this.date.setDate(1);
      this.date.setMonth(this.date.getMonth() + 1);
      this.renderCalendar();
      
      return false;
    };

    // Sélection d’un jour
    this.calendar.querySelectorAll('td[data-day]').forEach(td => {
      td.onclick = () => {
        const d = new Date(this.date.getFullYear(), this.date.getMonth(), td.dataset.day);
        this.date = d;
        this.input.value = this.formatDate(d);
        this.setAttribute('value', this.input.value);
        this.hideCalendar();
      };
    });
  }

  formatDate(date) {
    const dd = String(date.getDate()).padStart(2, '0');
    const mm = String(date.getMonth() + 1).padStart(2, '0');
    const yyyy = date.getFullYear();
    return this.format
      .replace('dd', dd)
      .replace('mm', mm)
      .replace('yyyy', yyyy);
  }

  parseValue(val) {
    const parts = val.match(/\d+/g);
    if (!parts) return null;
    if (this.format === 'dd/mm/yyyy') {
      return new Date(parts[2], parts[1] - 1, parts[0]);
    } else if (this.format === 'mm-dd-yyyy') {
      return new Date(parts[2], parts[0] - 1, parts[1]);
    } else {
      return new Date(parts[0], parts[1] - 1, parts[2]);
    }
  }

  showCalendar() {
    this.calendar.style.display = 'block';
  }

  hideCalendar() {
    this.calendar.style.display = 'none';
  }

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

  set value(val) {
    const parsed = this.parseValue(val);
    if (parsed) {
      this.date = parsed;
      this.input.value = this.formatDate(parsed);
      this.setAttribute('value', this.input.value);
    }
  }
};


var DatePuzzleBox = DateBox;

customElements.define('date-box', DatePuzzleBox);