/**
 * @mergeTarget
 * @module Src/Components/CustomInput/CustomChoice/DyslexiaModeChoiceItem
 */
import { AssetsLoader, LisioComponent, LisioComponentStyles } from "@lisio/lisio-engine";
import {
  LisioBooleanParameterNames,
  LisioProfileFactory,
  LisioProfileNames,
} from "@lisio/lisio-profils";
import { getMessageManager, getUserController, getInputManager, getScreenManager } from "../../../../../managers/manager-registry";
import { MergedCategoriesNames } from "../../../../screens/screen-types";
import { TranslationController } from "../../../../../controllers/translation/translation-controller";
import { customChoiceItemStyles } from "./custom-choice-item.css";
import { dyslexiaModeChoiceItemStyles } from "./dyslexia-mode-choice-item.css";
import { Icon, IconsObject } from "../../../component-types";
import { ErrorCodes } from "../../../../../../misc/error-codes";
import ExtensionPolyfill from "../../../../../../extension-polyfill";

/**
 * Loads one of the two "piquet" example icons ("Highlight" or "Syllabic")
 * from assets/icons/dyslexia-icons.json — same principle (and same
 * AssetsLoader-backed JSON format) as every other icon set under
 * assets/icons/, see custom-icon.ts. Not routed through the `CustomIcon`
 * component itself: that component's own template only exposes a single
 * `<children>` insertion point, already used here for `extraContent` (the
 * RGB letter fields), so this builds the `<svg>` wrapper inline instead —
 * intrinsic viewBox units (263x148, matching the traced letterforms) are
 * kept separate from the small on-screen display size so the badge still
 * renders at a fixed 40px tall next to the title text.
 */
async function loadDyslexiaExampleIcon(name: "Highlight" | "Syllabic"): Promise<Icon> {
  const url = __BUILD_TARGET__ === "extension"
    ? ExtensionPolyfill.current.runtime.getURL(`${AssetsLoader.current.assetsFolderPath}/icons/dyslexia-icons.json`)
    : `${AssetsLoader.current.assetsFolderPath}/icons/dyslexia-icons.json`;
  const iconsObject: IconsObject = await AssetsLoader.current
    .loadAsset<IconsObject>(url)
    .catch(() => {
      throw new Error(
        `Code : ${ErrorCodes.TRANSLATIONS_FILE_NOT_FOUND}. Asset file not found : dyslexia-icons`,
      );
    });
  if (!(name in iconsObject)) {
    throw new Error(`Icone name ${name} not in file dyslexia-icons`);
  }
  return iconsObject[name];
}

function buildExampleSvg(icon: Icon, ariaLabel: string): string {
  return `
    <svg role="img" aria-label="${ariaLabel}" width="71" height="40" viewBox="0 0 ${icon.width} ${icon.height}" xmlns="http://www.w3.org/2000/svg">
      ${icon.svg}
    </svg>
  `;
}

/**
 * True once the widget is embedded inside the reading-mode window itself
 * (the popup opened by LisioReaderAdapter in site builds). Unlike
 * solution/src/lisio.ts (injected directly into the popup's own top-level
 * document, where `window.location.origin === "null"` genuinely reflects
 * that popup), this code runs inside the widget's own iframe — a separate
 * document with its own real URL/origin regardless of which window it's
 * embedded in. So instead of inspecting its own `window.location` (which
 * would never say "null"), it reads the `origin` the client script reported
 * about *its own* window during the INIT_BACK handshake: `lisio-light-message-manager.ts`
 * sends `"*"` there precisely when its own `window.location.origin` is
 * "null" — i.e. when the client script itself is running inside the popup.
 */
async function isInsideReadingMode(): Promise<boolean> {
  if (__BUILD_TARGET__ === "extension") {
    // Extension mode flags the open reading side panel in chrome.storage
    // ("is-reading-mode", also checked in message-manager.ts's sendMessage
    // and checkbox-input.ts) — messages are then redirected to the panel.
    try {
      const isReadingMode = await ExtensionPolyfill.current.storage.local.get("is-reading-mode");
      return isReadingMode["is-reading-mode"] === true;
    } catch {
      return false;
    }
  }
  return getMessageManager().originOfMessages === "*";
}

/**
 * Single mode-choice row. Renders the exact `li.lisio-custom-choice-item` /
 * `label` / `input[type=radio].lisio-custom-input` markup {@link CustomChoiceItem}/
 * {@link RadioInput} render, so it looks and behaves identically (border
 * only when checked, grey hover, same radio dot, vertically centered),
 * without touching those shared components — which are hard-typed to a
 * single `LisioStringParameterNames` with a shared "name", not two
 * independent boolean toggles.
 *
 * Each item drives its own profile or boolean parameter directly. Radio
 * inputs sharing one `name` give native, browser-guaranteed single-selection
 * for free; the only thing native grouping doesn't do is fire "change" (or
 * send the "off" message) on the item that gets deselected, which is why
 * `onSelect` exists — the screen wires it to call `deselect()` on the other
 * item.
 *
 * `extraContent`, when given, renders as a `.infobox-radio` sibling of the
 * label — the exact class the real CustomChoiceItem uses for its own
 * reveal-on-select panel, already shown/hidden by
 * `li.checked div.infobox-radio` in custom-choice-item.css.ts, so no extra
 * show/hide plumbing is needed here either.
 */
class DyslexiaModeChoiceItem extends LisioComponent {
  private _name: LisioProfileNames;
  private _radioValue: string;
  private _checked: boolean;
  private _badgeId: string;
  private _titleId: string;
  private _descriptionId: string;
  private _hasExtraContent: boolean;
  private _screenName: string;
  private _categoryName: MergedCategoriesNames;
  private _parentScreenName: string;
  private _isRestoring = false;

  public get checked(): boolean {
    return this._checked;
  }

  public get name(): LisioProfileNames {
    return this._name;
  }

  /**
   * Whether this item currently shows as selected. Same as `checked`, except
   * right after a click: the browser has already checked the native radio
   * while `_checked` only flips once the sibling has been deselected (see
   * the "change" handler), so the screen must not treat that window as
   * "no mode selected".
   */
  public get isDisplayedChecked(): boolean {
    return (
      this._htmlElement?.querySelector<HTMLInputElement>("input")?.checked ??
      this._checked
    );
  }

  /**
   * Called after every checked-state change, whatever triggered it (click,
   * sibling switch, reset-all, declining/closing the reading mode, boot replay).
   */
  public onCheckedChange?: () => void;

  /**
   * Syncs the visual/ARIA checked state. Doesn't touch the native
   * `input.checked` when called from this item's own "change" handler (the
   * browser already set it); does when called externally (e.g. deselecting
   * the sibling, or the initial render).
   */
  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));
    }
    this.onCheckedChange?.();
  }

  /**
   * Turns this item off without user interaction — called on the
   * previously-selected sibling when another mode gets picked. Native radio
   * grouping already unchecks it in the DOM, but never fires "change" on it,
   * so nothing else would notice.
   */
  public async deselect(): Promise<void> {
    await this.toggle<boolean>(false, true, true, false);
  }

  /**
   * Turns this item off for good ("Aucun"). Inside the reading-mode window,
   * the "off" bulk keeps READING_MODE:false this time, so the client script
   * closes the window — the same path as switching off any other
   * reading-mode profile from inside it.
   */
  public async deselectAndCloseReadingMode(): Promise<void> {
    if (!this._checked) {
      return;
    }
    if (!(await isInsideReadingMode())) {
      await this.deselect();
      return;
    }
    await this.toggle<boolean>(false, false, true, false);
    await this.adaptSettingsParameters(false);
    await getMessageManager().profileAdaptMessage(this._name, false);
  }

  /**
   * Public entry point matching the shape InputManager's generic sweeps
   * (`disableAll`, `disableAllBookPageOrReading`, `initInputs`,
   * `refreshInputs`) call on every other registered input
   * (CheckboxInput/RadioInput/...) — see `GenericToggleInput` in
   * input-manager.ts. Registering here instead of reacting to one-off
   * `window` events per scenario means every place that already knows how to
   * reset/replay a real CheckboxInput (reset-all, declining the reading-mode
   * popup, closing it, boot-time replay) reaches this item too, for free.
   * @param value - Target checked state (only `boolean` is meaningful here)
   * @param hasToHandleOnChange - Whether to run the side effects in {@link handleOnChange} (persisting live adapt messages / the redirect-to-reading-mode flow)
   * @param hasToUpdateUser - Whether to persist the new state to storage
   * @param hasToEnableActiveInput - Whether to also flip the global IS_ACTIVE parameter on
   */
  public async toggle<T extends boolean | number | string>(
    value: T,
    hasToHandleOnChange: boolean,
    hasToUpdateUser: boolean,
    hasToEnableActiveInput: boolean,
  ): Promise<void> {
    if (typeof value !== "boolean" || value === this._checked) {
      return;
    }
    this.setChecked(value);
    if (hasToUpdateUser) {
      await getUserController().updateUserBoolean(this._name, value);
    }
    getInputManager().addOrRemoveEnabledInput(this._name, value);
    // The RGB letter fields belong to this mode (same as CheckboxInput did
    // for UNDERLINE): left filled, they'd keep "Confort dyslexie" flagged
    // active after the mode is turned off (e.g. on closing reading mode).
    // Skipped when not persisting (refreshInputs' off/on replay).
    if (
      !value &&
      hasToUpdateUser &&
      this._name === LisioProfileNames.UNDERLINE
    ) {
      getInputManager().clearAllUnderlineTextInputs();
    }
    // Same call CustomInput.generalToggleBehavior makes for every other
    // input: marks "Confort dyslexie" as active in Confort, up the screen
    // tree, and on the matching nav tab.
    getScreenManager().breadcrumb(
      this._name,
      this._screenName,
      this._categoryName,
      this._parentScreenName,
      value,
    );
    if (hasToEnableActiveInput) {
      getInputManager().toggleIsActiveInput(true, false);
    }
    if (hasToHandleOnChange) {
      await this.adaptSettingsParameters(value);
      await this.handleOnChange();
    }
  }

  /**
   * Mirrors this profile's parameters (font family, word spacing, ...) onto
   * the matching settings inputs, exactly like CheckboxInput.handleOnChange
   * does for every other profile, so the settings tab reflects the mode.
   * @param value - Whether the profile is being turned on or off
   */
  private async adaptSettingsParameters(value: boolean): Promise<void> {
    const profile = LisioProfileFactory.current.buildLisioProfile(this._name);
    await getInputManager().adaptParameters(
      this._name,
      Array.from(profile.parameters.values()),
      value,
      false,
      this._isRestoring,
    );
  }

  /**
   * Either applies the choice immediately (already inside the reading-mode
   * window) or routes towards the same "you're about to be redirected to
   * reading mode" confirmation used by the READING profile — this mode only
   * ever takes visual effect inside the liseuse, never on the page the
   * widget is embedded in.
   *
   * When this item has extra content (the RGB letter fields), the
   * confirmation is deferred to an explicit "continue" button instead of
   * firing immediately: the fields only just became visible, and the user
   * hasn't had a chance to fill them in yet.
   */
  private async handleOnChange(): Promise<void> {
    if (this._checked) {
      if (await isInsideReadingMode()) {
        await this.sendAdaptMessage(true);
      } else if (!this._hasExtraContent) {
        this.goToReadingMode();
      }
    } else if (await isInsideReadingMode()) {
      await this.sendAdaptMessage(false);
    }
  }

  /**
   * Called by `InputManager.initInputs()` on boot (once this component is
   * registered — see the constructor) to replay whatever was already active
   * for the current user, exactly like CheckboxInput.handleOnInit does.
   */
  public async handleOnInit(hasToEnableActiveInput: boolean): Promise<void> {
    if (this._checked) {
      this._checked = false;
      // Restoring the saved state: parameters the user customized in the
      // settings tab keep their value instead of the profile's.
      this._isRestoring = true;
      try {
        await this.toggle<boolean>(true, true, false, hasToEnableActiveInput);
      } finally {
        this._isRestoring = false;
      }
    }
  }

  private goToReadingMode(): void {
    // Same "infobox-<profile-name>" key CheckboxInput uses for the popup text
    // ("infobox-underline", "infobox-syllabs-dyslexia"): getTranslation throws
    // on a missing key, which silently aborted the whole activation.
    getMessageManager().sendTransBannerPopupMessage(
      this._name.replace(/_/g, "-"),
      LisioBooleanParameterNames.READING_MODE,
      this._id!,
    );
  }

  private async sendAdaptMessage(value: boolean): Promise<void> {
    // Always called from inside the reading-mode window itself (see
    // handleOnChange) — both mode profiles bundle READING_MODE:true like
    // several other profiles do, but here it's never the user leaving
    // reading mode, only switching to the sibling mode while staying in it.
    // Keep BOOK_PAGE/READING_MODE out of the bulk so the client script
    // doesn't mistake this for "exit reading mode" and close the window.
    await getMessageManager().profileAdaptMessage(this._name, value, false, true);
  }

  public async render(): Promise<string> {
    const badgeText = TranslationController.current.getTranslation(
      this._badgeId,
    );
    const titleText = TranslationController.current.getTranslation(
      this._titleId,
    );
    const descriptionText = TranslationController.current.getTranslation(
      this._descriptionId,
    );
    const exampleIcon = await loadDyslexiaExampleIcon(
      this._name === LisioProfileNames.UNDERLINE ? "Highlight" : "Syllabic",
    );
    const exampleSvg = buildExampleSvg(exampleIcon, badgeText);
    return `
      <li class="lisio-custom-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="${this._radioValue}"
            ${this._checked ? "checked" : ""}
            aria-checked="${this._checked}"
          />
          <div class="lisio-elements-container transparent column mode-card-content">
            <div class="lisio-elements-container row mode-card-title-row">
              <p class="lisio-custom-text bold">${titleText} :</p>
              <span class="mode-card-badge">${exampleSvg}</span>
            </div>
            <p class="lisio-custom-text small mode-card-description">${descriptionText}</p>
          </div>
        </label>
        ${
          this._hasExtraContent
            ? `<div class="infobox-radio">
                <children></children>
                <button type="button" class="lisio-custom-button btn-pill btn-back transparent btn-outline-grey mode-card-continue-button" id="${this._id}-continue-button">
                  <p class="lisio-custom-text regular">${TranslationController.current.getTranslation(`${this._id}-continue-button`)}</p>
                </button>
              </div>`
            : ""
        }
      </li>
    `;
  }

  postRender(): void {
    this._htmlElement
      ?.querySelector(`#${this._id}-continue-button`)
      ?.addEventListener("click", () => this.goToReadingMode());
  }

  /**
   * @param id - Base id for this item (also used for the `<label for>`/`<input id>` pair)
   * @param name - Profile this item activates/deactivates
   * @param radioValue - Stable `value` attribute for the native radio input
   * @param checked - Initial checked state
   * @param screenName - Screen including this item
   * @param categoryName - Category of that screen, flagged active in its parent screen while this item is checked
   * @param parentScreenName - Parent screen in the screen tree
   * @param badgeId - Translation key for the small preview example
   * @param titleId - Translation key for the mode's title
   * @param descriptionId - Translation key for the mode's description
   * @param onSelect - Called once this item becomes checked from a real user interaction
   * @param extraContent - Revealed only while this item is checked (e.g. the RGB letter fields for the highlight mode)
   */
  constructor(
    id: string,
    name: LisioProfileNames,
    radioValue: string,
    checked: boolean,
    screenName: string,
    categoryName: MergedCategoriesNames,
    parentScreenName: string,
    badgeId: string,
    titleId: string,
    descriptionId: string,
    onSelect: (self: DyslexiaModeChoiceItem) => Promise<void> | void,
    extraContent?: LisioComponent,
  ) {
    super(DyslexiaModeChoiceItem.name, id);
    this._name = name;
    this._radioValue = radioValue;
    this._checked = checked;
    this._screenName = screenName;
    this._categoryName = categoryName;
    this._parentScreenName = parentScreenName;
    this._badgeId = badgeId;
    this._titleId = titleId;
    this._descriptionId = descriptionId;
    this._hasExtraContent = extraContent != undefined;
    this._children = extraContent != undefined ? [extraContent] : [];
    // Registers with InputManager exactly like CheckboxInput/RadioInput do,
    // so the generic sweeps (disableAll on "Réinitialiser tout",
    // disableAllBookPageOrReading on declining/closing the reading-mode
    // popup, initInputs on boot) reach this item too — see toggle()/
    // handleOnInit() and GenericToggleInput in input-manager.ts.
    getInputManager().addInputInMap(name, this);
    if (checked) {
      getInputManager().addOrRemoveEnabledInput(name, true);
    }
    this._eventListeners.push({
      type: "change",
      handler: (event: unknown) => {
        if (!(event instanceof Event)) {
          return;
        }
        const target = event.target as HTMLInputElement;
        if (!target.checked) {
          return;
        }
        void (async () => {
          // Must fully finish before this item activates: both send a
          // postMessage the client script applies with a synchronous,
          // expensive full-page DOM walk (see LisioSyllabsSplitterAdapter/
          // LisioDyslexiaAdapter). Firing both toggles concurrently (as
          // "void onSelect(this); void this.toggle(...)" used to) raced two
          // independent, differently-long async chains (each doing its own
          // storage reads before the message is even sent), so the "turn
          // off the other mode" message could arrive after — or interleave
          // with — the "turn this one on" message, leaving both colorations
          // applied at once and roughly doubling the DOM work in flight.
          await onSelect(this);
          await this.toggle<boolean>(true, true, true, true);
        })();
      },
    });
  }
}

new LisioComponentStyles(DyslexiaModeChoiceItem.name, {
  ...customChoiceItemStyles,
  ...dyslexiaModeChoiceItemStyles,
});

export { DyslexiaModeChoiceItem };
