(() => {
  if(elem = document.querySelector("#my-video")) {
    const video = new v0ck(elem);
    document.addEventListener("keydown", e => {
      if(e.key === " " && e.target.tagName !== "INPUT") {
        video[video.paused ? 'play' : 'pause']();
        document.querySelector('.v0ck_overlay').classList[video.paused ? 'remove' : 'add']('v0ck_hidden');
      }
    });
  }

  let tt = false;
  const stimeout = 500;
  const changePage = (e, pbwork = true) => {
    pbwork && document.querySelector("nav.navbar").classList.add("pbwork");
    !tt && (tt = setTimeout(() => e.click(), stimeout));
  };

  // <keybindings>
  const clickOnElementBinding = selector => () => (elem = document.querySelector(selector)) ? elem.click() : null;
  const keybindings = {
    "ArrowLeft": clickOnElementBinding("#next"),
    "a": clickOnElementBinding("#next"),
    "ArrowRight": clickOnElementBinding("#prev"),
    "d": clickOnElementBinding("#prev"),
    "r": clickOnElementBinding("#random")
  };
  document.addEventListener("keydown", e => {
    if(e.key in keybindings && e.target.tagName !== "INPUT") {
      e.preventDefault();
      keybindings[e.key]();
    }
  });
  // </keybindings>

  // <image-responsive>
  const imgSize = e => new Promise((res, _) => {
    const i = new Image();
    i.addEventListener('load', function() {
      res({ width: this.width, height: this.height });
    });
    i.src = e.src;
  });

  if(f0ckimage = document.querySelector("img#f0ck-image")) {
    const f0ckimagescroll = document.querySelector("#image-scroll");
    f0ckimage.addEventListener("click", async e => {
      e.preventDefault();
      const img = await imgSize(f0ckimage);
      if(img.width > img.height)
        return;
      f0ckimagescroll.hasAttribute("style")
        ? f0ckimagescroll.removeAttribute("style")
        : f0ckimagescroll.setAttribute("style", "overflow-y: scroll");
      f0ckimage.hasAttribute("style")
        ? f0ckimage.removeAttribute("style")
        : f0ckimage.setAttribute("style", "max-height: none; height: auto; width: 100%; position: absolute; left: 0;");
    });
  }
  // </image-responsive>

  // <scroller>
  if(document.querySelector("div#posts")) {
    document.addEventListener("wheel", e => {
      if((window.innerHeight + window.scrollY) >= document.body.offsetHeight && e.deltaY > 0) {
        if(elem = document.querySelector(".pagination > .next:not(.disabled)"))
          changePage(elem);
      }
      else if(window.scrollY <= 0 && e.deltaY < 0) {
        if(elem = document.querySelector(".pagination > .prev:not(.disabled)"))
          changePage(elem);
      }
    });
  }
  // </scroller>

  // <swipe>
  let lastTap = 0;
  let xDown = null;
  let yDown = null;
  document.addEventListener('touchstart', e => {
    const firstTouch = (e.touches ?? e.originalEvent.touches)[0];
    xDown = firstTouch.clientX;
    yDown = firstTouch.clientY;

    const currentTime = new Date().getTime();
    const tapLength = currentTime - lastTap;
    if(tapLength < 500 && tapLength > 0)
      if(elem = document.querySelector("#random"))
        changePage(elem);
    lastTap = currentTime;
  }, false);

  document.addEventListener('touchmove', e => {
    if(!xDown || !yDown)
      return;
    const xDiff = xDown - e.touches[0].clientX;
    const yDiff = yDown - e.touches[0].clientY;
    let elem = false;
    if(Math.abs(xDiff) > Math.abs(yDiff)) {
      if(xDiff > 0) // left
        elem = document.querySelector(".pagination > .next:not(.disabled)");
      else // right
        elem = document.querySelector(".pagination > .prev:not(.disabled)");
    }
    else {
      if(navbar = document.querySelector("nav.navbar") && document.querySelector("div#posts")) {
        if(yDiff > 0 && (window.innerHeight + window.scrollY) >= document.body.offsetHeight) // up
          elem = document.querySelector(".pagination > .next:not(.disabled)");
        else if(yDiff <= 0 && window.scrollY <= 0 && document.querySelector("div#posts")) // down
          elem = document.querySelector(".pagination > .prev:not(.disabled)");
      }
    }
    if(elem)
      changePage(elem);
    xDown = yDown = null;
  }, false);
  // </swipe>

  // <testzone>
  if(audioElement = document.querySelector("audio")) {
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    canvas.width = 1920;
    canvas.height = 1080;

    setTimeout(() => {
      document.querySelector(".v0ck").insertAdjacentElement("afterbegin", canvas);
    }, 400);

    const audioCtx = new AudioContext();
    const analyser = audioCtx.createAnalyser();
    analyser.fftSize = 2048;

    const source = audioCtx.createMediaElementSource(audioElement);
    source.connect(analyser);
    source.connect(audioCtx.destination);

    let data = new Uint8Array(analyser.frequencyBinCount);
    requestAnimationFrame(loopingFunction);

    function loopingFunction() {
      requestAnimationFrame(loopingFunction);
      analyser.getByteFrequencyData(data);
      draw(data);
    }
    function draw(data) {
      data = [ ...data ];
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.fillStyle = getComputedStyle(document.body).getPropertyValue("--accent");
      data.forEach((value, i) => {
        const percent = value / 256;
        const height = (canvas.height * percent / 2) - 40;
        const offset = canvas.height - height - 1;
        const barWidth = canvas.width / analyser.frequencyBinCount;
        ctx.fillRect(i * barWidth, offset, barWidth, height);
      });
    }
    audioElement.onplay = () => {
      audioCtx.resume();
    };
  }
  // </testzone>
})();
