import { IslandGrid } from "./island/grid";
import { renderIslands } from "./island/render";
import { canvas2d, h } from "./lib/html";

const BLOWUP = 4;
const WIDTH = 240;
const HEIGHT = 135;

const DEFAULT_SEED = 128;

export function IslandApplet() {
  // STATE

  let timerId: number;
  let islands = new IslandGrid(WIDTH, HEIGHT, DEFAULT_SEED);

  // UI

  const [canvas, cx] = canvas2d({
    width: WIDTH * BLOWUP,
    height: HEIGHT * BLOWUP,
  });
  cx.scale(BLOWUP, BLOWUP);

  const seedInput = h("input", { type: "number", valueAsNumber: DEFAULT_SEED });
  const seedLabel = h("label", {}, "Seed:", seedInput);
  const generateButton = h(
    "button",
    {
      onclick: () => {
        clearInterval(timerId);

        islands = new IslandGrid(WIDTH, HEIGHT, seedInput.valueAsNumber);

        timerId = setInterval(function tick() {
          islands.step();
          islands.step();
          islands.step();
          if (islands.done) {
            clearInterval(timerId);
          }

          renderIslands(islands, cx);
        }, 1000 / 30);
      },
    },
    "Generate"
  );

  renderIslands(islands, cx);

  return [canvas, seedLabel, generateButton];
}

(globalThis as any).IslandApplet = IslandApplet;