import lisioClosingChannelHandler from "../../controllers/broadcastChannel/handlers/lisio-closing-channel-handler";
import lisioNavigateChannelHandler from "../../controllers/broadcastChannel/handlers/lisio-navigate-channel-handler";
import { LisioBroadcastChannelController } from "../../controllers/broadcastChannel/lisio-broadcast-channel-controller";
import LisioBroadcastChannelMessagesNames from "../../enums/lisio-broadcast-channel-message-names";
import LisioMessageReceivedName from "../../enums/lisio-message-received-name";
import { LisioConfig } from "../../lisio-init";
import LisioMessageManager from "../../managers/lisio-message-manager";
import { inIframe, isTouchDeviceLisio } from "../../utils";
import LisioTextTreeWalker from "../../walkers/lisio-text-tree-walker";
import LisioAdapter from "../lisio-adapter";
import {
  afterScrollEnd,
  findTopmostAnchor,
  findVisibleTarget,
  scrollElementToTop,
} from "./host-scroll";
import { extractLightContent, LightExtraction } from "./light-extract";
import { LightBlock, LightReaderPayload } from "./light-reader-types";
import { extractPdfBlocks, resolvePdfPlaceholders } from "./pdf-extract";
import { isPdfDocument } from "./pdf-sources";
import { getReaderWindowBounds } from "./reader-window-bounds";
import { createLogger } from "../../utils/debug";

const log = createLogger("reader");

const RESEND_DELAY = 1000;

/**
 * Mode lecture allégé : envoie à la fenêtre de lecture le texte de la page,
 * du premier h1 jusqu'au footer (titres, paragraphes, listes, liens, images).
 * Le texte des PDF (page PDF ou PDF intégrés) est extrait avec pdf.js.
 * L'ancien mode lecture complet est archivé dans src/old-reading-mode/.
 */
class LisioLightReaderAdapter extends LisioAdapter<boolean> {
  // Le mode lecture est demandé (adapt(true)) et pas encore désactivé.
  private _active = false;
  // Éléments source des blocs envoyés, indexés par leur ancre `a` (défilement synchronisé).
  private _anchors: Element[] = [];
  private _askTimeout?: ReturnType<typeof setTimeout>;
  private _broadcastChannel: LisioBroadcastChannelController;
  // Annule le recalage en attente du dernier défilement synchronisé.
  private _cancelScrollCorrection?: () => void;
  // Profil actif encodé (lisioUsernames=…&lisioUsers=…), injecté dans la fenêtre de lecture (site).
  private _encodedUserQuery = "";
  private _lastSent?: string;
  private _lisioConfig: LisioConfig;
  private _onReaderClosed?: () => void;
  // Identifiant de cette page, joint au contenu envoyé et renvoyé par la liseuse (voir isForThisPage).
  private readonly _pageId =
    globalThis.crypto?.randomUUID?.() ??
    `${Date.now()}-${Math.random().toString(36).slice(2)}`;
  private _readerConnected = false;
  private _resendTimeout?: ReturnType<typeof setTimeout>;
  // Numéro du dernier instantané demandé : un PDF lent à lire ne doit pas écraser un envoi plus récent.
  private _snapshotSeq = 0;

  /**
   * @param {LisioBroadcastChannelController} broadcastChannel - A broadcast channel controler to communicate with reader
   * @param {LisioConfig} lisioConfig - Client configuration, injected in the reader window (site build)
   * @param {() => void} onReaderClosed - Called when the extension reports the reader panel closed
   */
  constructor(
    broadcastChannel: LisioBroadcastChannelController,
    lisioConfig: LisioConfig,
    onReaderClosed?: () => void,
  ) {
    super();
    this._broadcastChannel = broadcastChannel;
    this._lisioConfig = lisioConfig;
    this._onReaderClosed = onReaderClosed;
    this._broadcastChannel.attachHandler(
      LisioBroadcastChannelMessagesNames.BCMS_READY,
      this.lisioReadyChannelHandler.bind(this),
    );
    this._broadcastChannel.attachHandler(
      LisioBroadcastChannelMessagesNames.BCMS_NAV_RESPONSE,
      lisioClosingChannelHandler.bind(this),
    );
    this._broadcastChannel.attachHandler(
      LisioBroadcastChannelMessagesNames.BCMS_NAVIGATE,
      async (datas: string) => {
        if (this.isForThisPage(datas)) {
          await lisioNavigateChannelHandler.call(this, datas);
        }
      },
    );
    this._broadcastChannel.attachHandler(
      LisioBroadcastChannelMessagesNames.BCMS_SCROLL_TO,
      async (datas: string) => {
        if (this.isForThisPage(datas)) {
          await this.lisioScrollChannelHandler(datas);
        }
      },
    );
    this._broadcastChannel.attachHandler(
      LisioBroadcastChannelMessagesNames.BCMS_READER_CLOSED,
      this.lisioReaderClosedChannelHandler.bind(this),
    );
    if (__BUILD_TARGET__ === "site") {
      // Sur site, la liseuse suit l'onglet affiché (comme le panneau de l'extension) :
      // un onglet qui passe en arrière-plan la laisse à l'onglet regardé, et celui
      // qui revient au premier plan la reprend.
      document.addEventListener("visibilitychange", () => {
        if (document.visibilityState === "visible") {
          if (this._active) {
            this.open();
          } else if (
            window.localStorage.getItem("lisio_reading_mode") === "1"
          ) {
            // Mode lecture activé depuis un autre onglet du site (son widget n'est
            // pas celui de cet onglet) : on rejoint sa liseuse si elle répond
            // (BCMS_READY connecte cet onglet), sans jamais en ouvrir une nouvelle.
            this._broadcastChannel.sendAnyoneThereMessage({
              value: window.location.hostname,
            });
          }
        } else {
          clearTimeout(this._resendTimeout);
          this._readerConnected = false;
        }
      });
    }
  }

  /**
   * Whether a reader message (link, scroll) is about this page. On site, the
   * channel reaches every tab of the same site: only the page whose content the
   * reader displays must react. The extension background already routes them to
   * the right tab. A message without pageId (older reader) is accepted.
   * @param {string} datas - The message payload, with the `pageId` of the displayed page
   * @returns Returns true if this page must handle the message
   */
  private isForThisPage(datas: string): boolean {
    if (__BUILD_TARGET__ !== "site") {
      return true;
    }
    const { pageId } = JSON.parse(datas) as { pageId?: string };
    return pageId == undefined || pageId === this._pageId;
  }

  /**
   * Public method implementing abstract method adapt of Adapter.
   * Enabling an already active reader does nothing: adapt runs once per walker
   * and on every re-application, and each run would restart the handshake
   * (and re-send the whole page). Use open() to reconnect on purpose.
   * @param {LisioTextTreeWalker} _walker - A walker to explore the DOM (unused)
   * @param {boolean} value - Value of the functionality
   * @returns Returns nothing
   */
  public adapt(_walker: LisioTextTreeWalker, value: boolean): void {
    if (!value) {
      this.close();
    } else if (!this._active) {
      this.open();
    }
  }

  /**
   * Asks for the reader (handshake BCMR_ANYONE_THERE → BCMS_READY), and opens
   * it if nobody answers. Called on activation, and again by the extension
   * when this page becomes the one shown by the reader (tab switch, reload).
   */
  public open() {
    this._active = true;
    clearTimeout(this._askTimeout);
    this._broadcastChannel.sendAnyoneThereMessage({
      value: window.location.hostname,
    });
    if (__BUILD_TARGET__ === "site") {
      // Le widget de la fenêtre de lecture ne retrouve pas toujours le profil
      // actif de la page : on le demande au widget pour le lui transmettre.
      LisioMessageManager.current.attachHandler(
        LisioMessageReceivedName.ALL_ENCODED_RESPONSE,
        (datas: string) => {
          this._encodedUserQuery = datas;
          LisioMessageManager.current.detachHandler(
            LisioMessageReceivedName.ALL_ENCODED_RESPONSE,
          );
        },
      );
      LisioMessageManager.current.sendAllEncodedMessage();
    }
    this._askTimeout = setTimeout(() => {
      if (__BUILD_TARGET__ === "extension") {
        if (!inIframe()) {
          LisioMessageManager.current.sendOpenSidePanel();
        }
      } else if (document.visibilityState === "visible") {
        // Un onglet en arrière-plan (ex. ouvert d'un clic molette) n'ouvre pas de
        // seconde liseuse : il se connectera quand il sera affiché.
        this.openReadingWindow();
      }
    }, 1000);
  }

  /**
   * Ferme le mode lecture (panneau latéral ou fenêtre de lecture), annule
   * une ouverture en attente et efface son état du localStorage.
   */
  public close() {
    this.reset();
    this._broadcastChannel.sendCloseMessage();
  }

  /**
   * The extension closed the reader (panel closed, profile disabled…): stop
   * extracting the page for it. Nothing to close on our side.
   */
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  public async lisioReaderClosedChannelHandler(_: string) {
    if (!this._active && !this._readerConnected) {
      return;
    }
    this.reset();
    this._onReaderClosed?.();
  }

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  public async lisioReadyChannelHandler(_: string) {
    // Le lecteur envoie aussi BCMS_READY à son chargement : un panneau
    // latéral ouvert (ou resté ouvert) après la désactivation est refermé.
    if (
      !this._active &&
      window.localStorage.getItem("lisio_reading_mode") !== "1"
    ) {
      this._broadcastChannel.sendCloseMessage();
      return;
    }
    // Sur site, tous les onglets du site reçoivent ce message : seul l'onglet
    // affiché se connecte, sinon la liseuse alternerait entre leurs contenus.
    if (__BUILD_TARGET__ === "site" && document.visibilityState !== "visible") {
      return;
    }
    window.localStorage.setItem("lisio_reading_mode", "1");
    clearTimeout(this._askTimeout);
    this._active = true;
    this._readerConnected = true;
    // A (re)connected reader has nothing displayed yet: always send.
    this._lastSent = undefined;
    void this.sendSnapshot();
  }

  /**
   * The reader scrolled: brings the same point of the source element of its
   * topmost visible block to the top of the main page.
   * @param {string} datas - `{ target, ratio }`, the block's anchor and the
   * position of the reader's top inside that block (0 to 1)
   */
  public async lisioScrollChannelHandler(datas: string) {
    const { target, ratio } = JSON.parse(datas) as {
      target: string;
      ratio?: number;
    };
    this._cancelScrollCorrection?.();
    this._cancelScrollCorrection = undefined;
    const element = this._anchors[Number.parseInt(target, 10)];
    // Ex. un h1 dans une diapositive de carrousel inactive : on vise le carrousel.
    const visible = element?.isConnected
      ? findVisibleTarget(element)
      : undefined;
    if (visible == undefined) {
      return;
    }
    // La position dans le bloc n'a pas de sens dans un ancêtre de celui-ci.
    const blockRatio =
      visible === element ? Math.min(1, Math.max(0, Number(ratio) || 0)) : 0;
    scrollElementToTop(visible, blockRatio);
    // Images chargées pendant le défilement, en-tête qui rétrécit… : une fois
    // arrivé, l'élément a pu bouger, on le recale.
    this._cancelScrollCorrection = afterScrollEnd(window, () => {
      this._cancelScrollCorrection = undefined;
      if (visible.isConnected) {
        scrollElementToTop(visible, blockRatio, "instant");
      }
    });
  }

  /**
   * Re-sends the page content once the host DOM has settled (called by
   * LisioMutationObserverController). No-op while no reader is connected.
   */
  public scheduleResend() {
    if (!this._readerConnected) {
      return;
    }
    // Onglet en arrière-plan : il ne doit pas remplacer le contenu de l'onglet affiché.
    if (__BUILD_TARGET__ === "site" && document.visibilityState !== "visible") {
      return;
    }
    clearTimeout(this._resendTimeout);
    this._resendTimeout = setTimeout(() => {
      this._resendTimeout = undefined;
      void this.sendSnapshot();
    }, RESEND_DELAY);
  }

  // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-empty-function
  protected adaptFunction(_element: HTMLElement, _value: boolean): void {}

  /** Forgets the reader: pending opening and re-sends, anchors, localStorage flag. */
  private reset() {
    this._active = false;
    clearTimeout(this._askTimeout);
    clearTimeout(this._resendTimeout);
    this._cancelScrollCorrection?.();
    this._cancelScrollCorrection = undefined;
    this._snapshotSeq++;
    this._readerConnected = false;
    this._lastSent = undefined;
    this._anchors = [];
    window.localStorage.removeItem("lisio_reading_mode");
  }

  private openReadingWindow() {
    const { left, top: screenTop, width, height } = getReaderWindowBounds();
    const reading_page = window.open(
      "",
      "_blank",
      `popup=yes,left=${left},top=${screenTop},width=${width},height=${height},scrollbars=yes,status=yes`,
    );
    if (reading_page == undefined) {
      log.log("can't open popup");
      return;
    }
    // Les dimensions passées à window.open s'appliquent au contenu : on corrige
    // la taille extérieure (bordures, barre de titre) pour coller au bord droit.
    try {
      reading_page.resizeTo(width, height);
      reading_page.moveTo(left, screenTop);
    } catch {
      // Le navigateur peut refuser le déplacement : la position initiale reste correcte.
    }
    const style = document.createElement("style");
    style.textContent += `h1, h2, h3 {color: ${this._lisioConfig.userSettings.colorPrimary}}`;
    reading_page.document.body.append(style);
    const script2 = document.createElement("script");
    script2.textContent = `
            window.lisioAccesskey = "${window.lisioAccesskey}";
            window.lisioReadingModeUserQuery = ${JSON.stringify(
              this._encodedUserQuery,
            )};
            const lisioConfig = JSON.parse(\`${JSON.stringify(
              this._lisioConfig,
            )}\`)`;
    reading_page.document.body.append(script2);
    const script = document.createElement("script");
    script.src = `${
      import.meta.env.VITE_LISIO_DOMAIN
    }/solution/dist-site/readingMode.js`;
    script.type = "module";
    reading_page.document.body.append(script);
    const script1 = document.createElement("script");
    script1.src = `${
      import.meta.env.VITE_LISIO_DOMAIN
    }/solution/dist-site/lisioinit.js`;
    script1.type = "module";
    reading_page.document.body.append(script1);
  }

  /**
   * Blocs de la page : texte du PDF si la page est un PDF, sinon extraction
   * h1 → footer avec le texte des PDF intégrés. `undefined` si rien n'est lisible.
   */
  private async extractBlocks(): Promise<
    { anchors: Element[]; blocks: LightBlock[] } | undefined
  > {
    // pdf.js n'est embarqué que dans l'extension (le script site n'est jamais sur une page PDF).
    if (__BUILD_TARGET__ === "extension" && isPdfDocument(document)) {
      // Visionneuse PDF du navigateur : pas d'élément source pour le défilement synchronisé.
      const blocks = await extractPdfBlocks(window.location.href);
      return blocks == undefined || blocks.length === 0
        ? undefined
        : { anchors: [], blocks };
    }
    let extraction: LightExtraction | undefined;
    try {
      extraction = extractLightContent(document);
    } catch (error) {
      console.error("[reading-mode] extraction failed", error);
      return undefined;
    }
    if (extraction == undefined) {
      return undefined;
    }
    return {
      anchors: extraction.anchors,
      blocks: await resolvePdfPlaceholders(extraction.blocks),
    };
  }

  private async sendSnapshot() {
    const seq = ++this._snapshotSeq;
    // Runs as a fire-and-forget channel callback / timer: never throw.
    try {
      const extraction = await this.extractBlocks();
      if (seq !== this._snapshotSeq) {
        return;
      }
      // Always refreshed, even when the payload is unchanged: the host DOM
      // may have been re-rendered with the same content (new elements).
      this._anchors = extraction?.anchors ?? [];
      const blocks = extraction?.blocks;
      const payload: LightReaderPayload = {
        url: window.location.href,
        lang: document.documentElement.lang,
        pageId: this._pageId,
        domain: window.location.hostname,
        isMobile: isTouchDeviceLisio(),
        status: blocks == undefined ? "failed" : "ok",
        blocks: blocks ?? [],
      };
      const serialized = JSON.stringify(payload);
      if (serialized === this._lastSent) {
        return;
      }
      // Premier envoi à une liseuse (re)connectée : elle s'ouvre sur le
      // texte lu en haut de la page, pas en haut de son contenu.
      const scroll =
        this._lastSent == undefined
          ? findTopmostAnchor(this._anchors)
          : undefined;
      this._lastSent = serialized;
      this._broadcastChannel.sendInitHTMLMessage(
        scroll == undefined ? payload : { ...payload, scroll },
      );
    } catch (error) {
      console.error("[reading-mode] could not send page content", error);
    }
  }
}

export { LisioLightReaderAdapter };
