/**
 * @jest-environment jsdom
 */
import {
  afterScrollEnd,
  findTopmostAnchor,
  findVisibleTarget,
  getFixedTopOffset,
  scrollElementToTop,
} from "../../../src/adapters/reader/host-scroll";

// jsdom n'a pas de mise en page : boîtes et défilement sont simulés.
function setRect(element: Element, top: number, height = 20, width = 100) {
  element.getBoundingClientRect = () =>
    ({ top, bottom: top + height, height, width, left: 0, right: width }) as DOMRect;
}

function makeScroller(element: HTMLElement, top: number) {
  element.style.overflowY = "auto";
  Object.defineProperty(element, "scrollHeight", { value: 1000 });
  Object.defineProperty(element, "clientHeight", { value: 200 });
  setRect(element, top, 200);
  element.scrollBy = jest.fn();
  return element.scrollBy as jest.Mock;
}

/** Élément `position: fixed` qui couvre les lignes [top, top + height[ de la fenêtre. */
function addFixed(top: number, height: number, width = 1000) {
  const element = document.createElement("div");
  element.style.position = "fixed";
  document.body.append(element);
  setRect(element, top, height, width);
  fixedElements.push(element);
  return element;
}

let fixedElements: HTMLElement[];
let windowScrollBy: jest.Mock;

beforeAll(() => {
  Object.defineProperty(document.documentElement, "clientWidth", { value: 1000 });
});

beforeEach(() => {
  document.body.innerHTML = "";
  fixedElements = [];
  // Simule le test de collision : éléments fixes dont la boîte contient la ligne y.
  document.elementsFromPoint = (_x: number, y: number) =>
    fixedElements.filter((element) => {
      const rect = element.getBoundingClientRect();
      return rect.top <= y && rect.bottom > y;
    });
  windowScrollBy = jest.fn();
  window.scrollBy = windowScrollBy;
});

describe("scrollElementToTop", () => {
  it("scrolls the page vertically by the element's offset", () => {
    const target = document.createElement("p");
    document.body.append(target);
    setRect(target, 500);

    scrollElementToTop(target);

    expect(windowScrollBy).toHaveBeenCalledWith({ top: 500, behavior: "smooth" });
  });

  it("never scrolls a horizontal carousel", () => {
    const track = document.createElement("div");
    track.style.overflow = "hidden";
    track.scrollBy = jest.fn();
    const slide = document.createElement("p");
    track.append(slide);
    document.body.append(track);
    setRect(slide, 300);

    scrollElementToTop(slide);

    expect(track.scrollBy).not.toHaveBeenCalled();
    expect(windowScrollBy).toHaveBeenCalledWith({ top: 300, behavior: "smooth" });
  });

  it("scrolls an inner scroller, then the page up to it", () => {
    const app = document.createElement("div");
    const target = document.createElement("p");
    app.append(target);
    document.body.append(app);
    const appScrollBy = makeScroller(app, 100);
    setRect(target, 700);

    scrollElementToTop(target, 0, "instant");

    expect(appScrollBy).toHaveBeenCalledWith({ top: 600, behavior: "instant" });
    expect(windowScrollBy).toHaveBeenCalledWith({ top: 100, behavior: "instant" });
  });
});

describe("findVisibleTarget", () => {
  it("keeps an element that has a box", () => {
    const target = document.createElement("p");
    document.body.append(target);
    setRect(target, 50);

    expect(findVisibleTarget(target)).toBe(target);
  });

  it("falls back to the carousel around a hidden slide", () => {
    // Bootstrap 3 : `.carousel-inner > .item:not(.active)` est en display:none.
    const carousel = document.createElement("div");
    const slide = document.createElement("div");
    const h1 = document.createElement("h1");
    slide.append(h1);
    carousel.append(slide);
    document.body.append(carousel);
    setRect(h1, 0, 0, 0);
    setRect(slide, 0, 0, 0);
    setRect(carousel, 120, 400, 800);

    expect(findVisibleTarget(h1)).toBe(carousel);
  });

  it("falls back to the parent of a 1px screen-reader-only text", () => {
    const section = document.createElement("section");
    const srOnly = document.createElement("h1");
    section.append(srOnly);
    document.body.append(section);
    setRect(srOnly, -10000, 1, 1);
    setRect(section, 300, 500, 800);

    expect(findVisibleTarget(srOnly)).toBe(section);
  });

  it("returns undefined when nothing is displayed", () => {
    const target = document.createElement("p");
    document.body.append(target);
    for (const element of [target, document.body, document.documentElement]) {
      setRect(element, 0, 0, 0);
    }

    expect(findVisibleTarget(target)).toBeUndefined();
  });
});

describe("getFixedTopOffset", () => {
  it("is 0 without fixed header", () => {
    expect(getFixedTopOffset()).toBe(0);
  });

  it("adds up a fixed info bar and the fixed menu below it", () => {
    // autoecole-du-griffe.fr : `.fixed-top-infos` puis `.navbar-fixed-top`.
    addFixed(0, 40);
    addFixed(40, 60);

    expect(getFixedTopOffset()).toBe(100);
  });

  it("counts a header made fixed through an ancestor", () => {
    const header = addFixed(0, 80);
    const link = document.createElement("a");
    header.append(link);
    document.elementsFromPoint = (_x: number, y: number) => (y < 80 ? [link] : []);

    expect(getFixedTopOffset()).toBe(80);
  });

  it("ignores full-screen overlays and narrow widgets", () => {
    addFixed(0, 700);
    addFixed(0, 50, 120);

    expect(getFixedTopOffset()).toBe(0);
  });

  it("ignores Lisio's own interface", () => {
    addFixed(0, 60).id = "lisio-shadow-env";

    expect(getFixedTopOffset()).toBe(0);
  });

  it("stops the scrolled element below the header", () => {
    addFixed(0, 100);
    const target = document.createElement("p");
    document.body.append(target);
    setRect(target, 500);

    scrollElementToTop(target);

    expect(windowScrollBy).toHaveBeenCalledWith({ top: 400, behavior: "smooth" });
  });
});

describe("position inside the block", () => {
  it("scrolls to the same point of a long paragraph", () => {
    const target = document.createElement("p");
    document.body.append(target);
    setRect(target, 500, 1000);

    scrollElementToTop(target, 0.25);

    expect(windowScrollBy).toHaveBeenCalledWith({ top: 750, behavior: "smooth" });
  });
});

describe("afterScrollEnd", () => {
  beforeEach(() => jest.useFakeTimers());
  afterEach(() => jest.useRealTimers());

  it("runs once on scrollend, from the page or a container", () => {
    const callback = jest.fn();
    afterScrollEnd(window, callback);
    const container = document.createElement("div");
    document.body.append(container);

    container.dispatchEvent(new Event("scrollend"));
    window.dispatchEvent(new Event("scrollend"));
    jest.runAllTimers();

    expect(callback).toHaveBeenCalledTimes(1);
  });

  it("falls back to a timeout without scrollend", () => {
    const callback = jest.fn();
    afterScrollEnd(window, callback, 500);

    jest.advanceTimersByTime(499);
    expect(callback).not.toHaveBeenCalled();
    jest.advanceTimersByTime(1);
    expect(callback).toHaveBeenCalledTimes(1);
  });

  it("can be cancelled by a newer scroll", () => {
    const callback = jest.fn();
    const cancel = afterScrollEnd(window, callback);

    cancel();
    window.dispatchEvent(new Event("scrollend"));
    jest.runAllTimers();

    expect(callback).not.toHaveBeenCalled();
  });
});

describe("findTopmostAnchor", () => {
  function addBlocks(...rects: [top: number, height: number][]) {
    return rects.map(([top, height]) => {
      const element = document.createElement("p");
      document.body.append(element);
      setRect(element, top, height);
      return element;
    });
  }

  it("takes the block crossing the top of the viewport, with the position inside it", () => {
    const anchors = addBlocks([-300, 100], [-200, 400], [200, 50]);
    expect(findTopmostAnchor(anchors)).toEqual({ a: 1, ratio: 0.5 });
  });

  it("prefers the innermost block (a list item over its list)", () => {
    const anchors = addBlocks([-100, 500], [-20, 40], [20, 40]);
    expect(findTopmostAnchor(anchors)).toEqual({ a: 1, ratio: 0.5 });
  });

  it("takes the first block below when none crosses the top", () => {
    const anchors = addBlocks([300, 20], [120, 20], [-50, 20]);
    expect(findTopmostAnchor(anchors)).toEqual({ a: 1, ratio: 0 });
  });

  it("measures from below the fixed header", () => {
    addFixed(0, 80);
    const anchors = addBlocks([0, 60], [60, 40]);
    expect(findTopmostAnchor(anchors)).toEqual({ a: 1, ratio: 0.5 });
  });

  it("skips hidden and off-screen elements", () => {
    const anchors = addBlocks([-10, 1], [-10, 100], [50, 20]);
    // Diapositive de carrousel décalée hors de l'écran.
    anchors[1].getBoundingClientRect = () =>
      ({ top: -10, bottom: 90, height: 100, width: 100, left: 1200, right: 1300 }) as DOMRect;
    expect(findTopmostAnchor(anchors)).toEqual({ a: 2, ratio: 0 });
  });

  it("goes to the end when the page is scrolled past the content", () => {
    const anchors = addBlocks([-500, 100], [-300, 100]);
    expect(findTopmostAnchor(anchors)).toEqual({ a: 1, ratio: 1 });
  });

  it("is undefined without displayed source element", () => {
    expect(findTopmostAnchor([])).toBeUndefined();
  });
});
