import { useEffect, useRef } from "react";

let wasmStarted = false;

export function CgolCanvas() {
  const canvasRef = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    if (wasmStarted) return;
    wasmStarted = true;

    import("cgol").then(async (cgolModule) => {
      if (typeof cgolModule.default === "function") {
        await cgolModule.default();
      }
      if (typeof cgolModule.start === "function") {
        cgolModule.start();
      }
    }).catch((error: unknown) => {
      console.error("Failed to initialize CGOL WebAssembly module:", error);
      wasmStarted = false;
    });
  }, []);

  return (
    <canvas
      ref={canvasRef}
      id="canvas"
      className="fixed top-0 left-0 -z-10 h-screen w-screen"
      aria-hidden="true"
    />
  );
}
