import { VermineReliability } from '../reliability.mjs';

const { HandlebarsApplicationMixin } = foundry.applications.api;

/**
 * Dialogue de Test de Fiabilité / Réparation d'un item.
 * Mode "test" : choix de la gravité des Dommages matériels (Mineurs/Graves/Critiques)
 * + case Immersion (Trait Étanche). Mode "repair" : type de réparation
 * (classique/de fortune) + compétence utilisée.
 */
export default class ReliabilityDialog extends HandlebarsApplicationMixin(foundry.applications.api.ApplicationV2) {
  #item;
  #mode;

  static DEFAULT_OPTIONS = {
    classes: ['vermine-roll', 'reliability'],
    tag: 'form',
    window: {
      icon: 'fas fa-tools',
      resizable: false,
    },
    position: {
      width: 460,
      height: 'auto',
    },
    actions: {
      run: ReliabilityDialog.#onRun,
      cancel: ReliabilityDialog.#onCancel,
    },
  };

  static PARTS = {
    main: { template: 'systems/vermine2047/templates/dialogs/reliability-dialog.hbs', scrollable: [''] },
  };

  static async create({ item, mode = 'test' }) {
    return new ReliabilityDialog({ item, mode });
  }

  constructor(options = {}) {
    super(options);
    this.#item = options.item;
    this.#mode = options.mode ?? 'test';
  }

  get title() {
    return game.i18n.localize(this.#mode === 'repair' ? 'VERMINE.reliability_repair' : 'VERMINE.reliability_test');
  }

  async _prepareContext() {
    const hasEtanche = !!this.#item.system?.traits?.etanche;
    const hasActor = !!this.#item.actor;
    const coque = this.#item.system?.traits?.coque ?? {};
    const hasBrokenCoque = this.#mode === 'repair' && (parseInt(coque?.value ?? 0, 10) || 0) === 0 && (parseInt(coque?.max ?? 0, 10) || 0) > 0;
    const storedSkill = (this.#item.system?.needSkill?.value && this.#item.system?.needSkill?.skill)
      || this.#item.system?.skill || '';
    const severities = ['mineurs', 'graves', 'critiques'].map((key) => ({
      key,
      label: game.i18n.localize(`VERMINE.reliability_severity_${key}`),
      selected: key === 'graves',
    }));
    const skills = VermineReliability.REPAIR_SKILLS.map((key) => ({
      key,
      label: game.i18n.localize(`SKILLS.${key}.name`),
      selected: key === storedSkill && VermineReliability.REPAIR_SKILLS.includes(storedSkill),
    }));
    return {
      mode: this.#mode,
      isTest: this.#mode === 'test',
      isRepair: this.#mode === 'repair',
      hasEtanche,
      hasActor,
      hasBrokenCoque,
      coqueMax: parseInt(coque?.max ?? 0, 10) || 0,
      severities,
      skills,
    };
  }

  #getOptions() {
    const el = this.element;
    if (this.#mode === 'test') {
      return {
        severity: el.querySelector('input[name="severity"]:checked')?.value ?? 'graves',
        immersion: !!el.querySelector('#reliability-immersion')?.checked,
      };
    }
    return {
      mode: el.querySelector('input[name="repairMode"]:checked')?.value ?? 'classique',
      skill: el.querySelector('#reliability-skill')?.value ?? 'technology',
    };
  }

  static async #onRun() {
    const options = this.#getOptions();
    if (this.#mode === 'test') {
      await VermineReliability.test(this.#item, options);
    } else {
      await VermineReliability.repair(this.#item, options);
    }
    this.close();
  }

  static #onCancel() {
    this.close();
  }
}
