console.log("start");

regexes = [
  "allow",
  "accept",
  "agree",
  "akceptuj",
  "zgadzam",
  "zezwól",
  "zgoda",
  /przejdź(?! do główn).*/,
];
avoid = ["dostosuj", "don't", "nie zga", "nie zezw", "tylko"];

elements = Array.from(document.querySelectorAll("*"));

/*  Tik Tok hides the "accept" button within shadowRoot, so it we need to do some digging */
elements.forEach((element) => {
  if (element.shadowRoot !== null) {
    elements.push(...Array.from(element.shadowRoot.querySelectorAll("*")));
  }
});

buttons = elements.filter(
  (e) =>
    e.textContent.length <
      70 /* FB has a really long one: Zezwól na korzystanie z niezbędnych i opcjonalnych plików cookie */ &&
    regexes.some((regex) => e.textContent.toLowerCase().match(regex) !== null)
);

console.log("buttons after first filter", buttons);

operations = [
  (buttons) =>
    buttons.filter((button) => {
      const rect = button.getBoundingClientRect();
      return (
        rect.top < window.innerHeight &&
        rect.left < window.innerWidth &&
        !(rect.width == 0 && rect.height == 0)
      );
    }),
  (buttons) =>
    buttons.filter((e) =>
      avoid.every((word) => !e.textContent.toLowerCase().includes(word))
    ),
  (buttons) =>
    buttons.filter((e) => !e.textContent.toLowerCase().includes("only")),
  (buttons) => buttons.filter((e) => e.tagName.toLowerCase() === "button"),
  (buttons) =>
    buttons.filter((e) => !e.textContent.toLowerCase().includes("do not")),
  (buttons) => buttons.filter((e) => e.tagName.toLowerCase() === "a"),

  (buttons) =>
    buttons.filter(
      (e) => e.tagName.toLowerCase() === "input" && e.type === "submit"
    ),
];

for (const operation of operations) {
  if (buttons.length === 1) {
    break;
  }
  const result = operation(buttons);
  console.log("RESULT", operation, result);
  if (result.length) {
    buttons = result;
  }
}

buttons;

buttons.forEach((button) => button.click());
buttons.forEach((button) => {
  button.querySelectorAll("input").forEach((child) => child.click());
});
