const faviconImageId = "faviconImage";

const getFaviconUrl = (document) => {
  const faviconElement = document.querySelector('link[rel="icon"]');
  return faviconElement.href;
};

const compareFavicon = (snapshotName) => {
  cy.log(`Compare favicon ${snapshotName}`);

  cy.document({ log: false }).then((document) => {
    const oldImage = document.getElementById(faviconImageId);
    oldImage && oldImage.remove();

    const faviconImage = document.createElement("img");
    faviconImage.id = faviconImageId;
    faviconImage.onload = () => document.body.appendChild(faviconImage);
    faviconImage.src = getFaviconUrl(document);
  });

  const browser =
    Cypress.browser.name + (Cypress.browser.isHeadless ? "-headless" : "");
  cy.get(`#${faviconImageId}`, { log: false }).compareSnapshot(
    `${browser}-${snapshotName}`,
    0.1
  );
};

describe("Example", () => {
  beforeEach(() => {
    cy.viewport(200, 200, { log: false });
    cy.visit("/", { log: false });
  });

  it("adds overlay on mousemove", () => {
    compareFavicon("original-favicon");

    cy.log("move mouse")
      .get("html", { log: false })
      .trigger("mousemove", { log: false, clientX: 100, clientY: 100 })
      .trigger("mousemove", { log: false, clientX: 100, clientY: 100 });

    compareFavicon("with-overlay");
  });
});
