import { recall, save } from "./storage.js";
import { registerLoadCallback } from "./main.js";

registerLoadCallback(() => {
  const handles = document.querySelectorAll('[data-resize]');
  handles.forEach(handle => {
    handle.addEventListener("mousedown", startResize);
    const stored = recall(`${handle.dataset.resize}-size`);
    if (stored) {
      document.body.style.setProperty(`--${handle.dataset.resize}-size`, stored);
    }
  });
});

function startResize(e) {
  window.addEventListener("mouseup", endResize);
  window.addEventListener("mousemove", resize);
  document.body.dataset.resizing = e.target.dataset.resize;
}

function resize(e) {
  const resizing = document.body.dataset.resizing;
  const element = document.getElementById(resizing);
  const sizeMin = Number(element.dataset.resizeMin ?? 0.05);
  const sizeMax = Number(element.dataset.resizeMax ?? 0.5);
  const elementBoundingBox = element.getBoundingClientRect();
  let size = 0.25;
  switch (resizing) {
    case "left-menu":
      size = e.pageX / window.innerWidth;
      break;
    case "right-menu":
      size = 1 - e.pageX / window.innerWidth;
      break;
    case "bottom-menu":
      size = 1 - (e.pageY + window.innerHeight - elementBoundingBox.bottom) / window.innerHeight;
      break;
  }
  size = Math.max(sizeMin, Math.min(size, sizeMax));
  document.body.style.setProperty(`--${resizing}-size`, `${size*100}%`);
  save(`${resizing}-size`, `${size*100}%`);
}

function endResize() {
  window.removeEventListener("mouseup", endResize);
  window.removeEventListener("mousemove", resize);
  delete document.body.dataset.resizing;
}
