/**
 * @mergeTarget
 * @module Src/Components/CustomInput/CustomChoice/DyslexiaModeNoneItem
 */
import { LisioComponent, LisioComponentStyles } from "@lisio/lisio-engine";
import { TranslationController } from "../../../../../controllers/translation/translation-controller";
import { customChoiceItemStyles } from "./custom-choice-item.css";

/**
 * "Aucun" row of the dyslexia mode choice — same role, translation key and
 * `default-choice-item` class as the default item {@link CustomChoice}
 * prepends to its own lists. Holds no profile itself: selecting it turns off
 * whichever mode was active (wired in DyslexiaScreen), and it shows as
 * checked whenever neither mode is.
 */
class DyslexiaModeNoneItem extends LisioComponent {
  private _checked: boolean;

  public setChecked(checked: boolean): void {
    this._checked = checked;
    if (checked) {
      this.addClasses(["checked"]);
    } else {
      this.removeClasses(["checked"]);
    }
    const input = this._htmlElement?.querySelector<HTMLInputElement>("input");
    if (input != undefined) {
      input.checked = checked;
      input.setAttribute("aria-checked", String(checked));
    }
  }

  public async render(): Promise<string> {
    return `
      <li class="lisio-custom-choice-item default-choice-item ${this._checked ? "checked" : ""} ${this.renderClasses()}">
        <label for="${this._id}-input">
          <input
            type="radio"
            name="dyslexia-mode"
            id="${this._id}-input"
            class="lisio-custom-input"
            value="default"
            ${this._checked ? "checked" : ""}
            aria-checked="${this._checked}"
          />
          <p class="lisio-custom-text regular">${TranslationController.current.getTranslation("default-text")}</p>
        </label>
      </li>
    `;
  }

  /**
   * @param id - Base id for this item (also used for the `<label for>`/`<input id>` pair)
   * @param checked - Initial checked state
   * @param onSelect - Called once this item becomes checked from a real user interaction
   */
  constructor(id: string, checked: boolean, onSelect: () => Promise<void> | void) {
    super(DyslexiaModeNoneItem.name, id);
    this._checked = checked;
    this._eventListeners.push({
      type: "change",
      handler: (event: unknown) => {
        if (!(event instanceof Event) || !(event.target as HTMLInputElement).checked) {
          return;
        }
        this.setChecked(true);
        void onSelect();
      },
    });
  }
}

new LisioComponentStyles(DyslexiaModeNoneItem.name, customChoiceItemStyles);

export { DyslexiaModeNoneItem };
