class C_Date {
  constructor(inputId) {
    this.input = document.getElementById(inputId);
    if (!this.input) throw new Error(`Element #${inputId} not found`);

    // Forcer le type date
    this.input.type = 'date';

    this.events = { onShow: [], onChange: [], onButtonClick: [] };
    this._initListeners();
  }

  _initListeners() {
    this.input.addEventListener('focus', () => this._fireEvent('onShow'));
    this.input.addEventListener('change', () => {
      const date = this.getDate();
      this._fireEvent('onChange', date);
      this._fireEvent('onButtonClick', date);
    });
  }

  _fireEvent(eventName, payload) {
    this.events[eventName]?.forEach(cb => cb(payload));
  }

  attachEvent(eventName, callback) {
    if (this.events[eventName]) this.events[eventName].push(callback);
  }

  setDateFormat(format) {
    // console.warn('setDateFormat() non supporté avec input type="date" natif');
  }

  hideTime() { /* inutile ici */ }

  showToday() {
    const today = new Date().toISOString().split('T')[0];
    this.input.value = today;
  }

  getDate() {
    const val = this.input.value;
    return val ? new Date(val) : null;
  }

  setDate(date) {
    const iso = (date instanceof Date)
      ? date.toISOString().split('T')[0]
      : date;
    this.input.value = iso;
  }

  hide() {
    this.input.blur();
  }

  clear() {
    this.input.value = '';
  }

  show() {
    this.input.focus();
  }
}
