const { ApplicationV2, HandlebarsApplicationMixin } = foundry.applications.api;
const MODULE_ID = 'mgt2-compendium-amiral-denisov';

export class JournalNoteDialog extends HandlebarsApplicationMixin(ApplicationV2) {
  static DEFAULT_OPTIONS = {
    id: 'mgt2-journal-note',
    classes: ['mgt2-calendar'],
    position: { width: 320, height: 'auto' },
    window: {
      icon: 'fas fa-pen',
      title: 'Note de bord',
      resizable: false,
    },
  };

  static PARTS = {
    main: {
      template: `modules/${MODULE_ID}/templates/journal-note-dialog.hbs`,
      root: true,
    },
  };

  constructor({ imperialDate, realDate, onSave } = {}) {
    super();
    this._imperialDate = imperialDate;
    this._realDate = realDate;
    this._onSave = onSave;
  }

  get title() {
    return 'Note de bord';
  }

  async _prepareContext() {
    return {
      imperialDate: this._imperialDate,
      realDate: this._realDate,
    };
  }

  async _onRender(context, options) {
    await super._onRender(context, options);
    const html = $(this.element);

    html.find('[data-action="save"]').on('click', async () => {
      const content = html.find('[name="content"]').val()?.trim();
      try {
        await this._onSave?.(content);
      } catch (err) {
        console.error(`${MODULE_ID} | Erreur sauvegarde note:`, err);
      }
    });
  }

  close() {
    this._onSave = null;
    return super.close();
  }
}