import "./atlas.js";
import "./block-picker.js";
import "./configuration.js";
import "./dev-mode.js";
import "./dialogs.js";
import "./dom-list.js";
import { debounce, getElements } from "./dom-utils.js";
import "./errors.js";
import { awaitEvent, emitEvent, listenTo } from "./events.js";
import "./files.js"
import "./js-utils.js"
import "./menu-bar.js";
import "./ncpf-utils.js";
import "./planner.js";
import "./planner-resize.js";
import "./recipe-selector.js";
import "./resize-menus.js";
import "./solver.js";
import { getState, setState, STATE } from "./state.js";
import "./storage.js";
import "./tooltip.js";

let loadCallbacks = [];
export function registerLoadCallback(cb) {
  queueMicrotask(() => {
    loadCallbacks.push(cb);
  });
}
function runLoadCallbacks() {
  loadCallbacks.forEach(cb => cb());
}

window.addEventListener("load", () => {
  emitEvent("setup:start");

  getElements("state", "*").forEach(e => {
    e.classList.add("hidden");
    if (e.dataset.state === getState()) {
      e.classList.remove("hidden");
    }
  });

  listenTo("state", () => {
    console.log("State changed", getState());
    getElements("state", "*").forEach(e => {
      e.classList.add("hidden");
      if (e.dataset.state === getState()) {
        e.classList.remove("hidden");
      }
    });
  });

  getElements("button", "*").forEach(elem => {
    elem.addEventListener("click", e => {
      emitEvent(elem.dataset.button, e);
    });
  });
  getElements("toggle", "*").forEach(elem => {
    elem.addEventListener("click", e => {
      const wasChecked = e.currentTarget.dataset.toggled === "true";
      const newState = !wasChecked;
      e.currentTarget.dataset.toggled = newState.toString();
      emitEvent(elem.dataset.toggle, { state: newState, event: e });
    });
  });
  getElements("input", "*").forEach(elem => {
    elem.addEventListener("keydown", e => e.stopPropagation());
    elem.addEventListener("input", debounce(e => {
      emitEvent(elem.dataset.input + ":input", e);
    }));
    elem.addEventListener("change", e => {
      emitEvent(elem.dataset.input + ":change", e);
    });
  });
  getElements("form", "*").forEach(elem => {
    elem.addEventListener("submit", e => {
      e.preventDefault();
      emitEvent(elem.dataset.form + ":submit", e);
    });
  });
  getElements("enable-on", "*").forEach(elem => {
    elem.disabled = true;
    awaitEvent(elem.dataset.enableOn).then(() => {
      elem.disabled = false;
    });
  });

  listenTo("config:end", () => setState(STATE.planning));

  runLoadCallbacks();

  emitEvent("setup:end");
});
