import { useEffect, useRef } from "react";
import type { AppStore } from "@editor/store";
import { createRenderer } from "@renderer/index";

export type CanvasViewportProps = {
  store: AppStore;
};

export function CanvasViewport({ store }: CanvasViewportProps) {
  const canvasRef = useRef<HTMLCanvasElement | null>(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const renderer = createRenderer(canvas);
    renderer.render(store.getState());

    const unsubscribe = store.subscribe((state) => {
      renderer.render(state);
    });

    return () => {
      unsubscribe();
      renderer.dispose();
    };
  }, [store]);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const resizeObserver = new ResizeObserver(([entry]) => {
      if (!entry) return;

      const width = Math.floor(entry.contentRect.width);
      const height = Math.floor(entry.contentRect.height);
      store.dispatch("viewport.setSize", { w: width, h: height });
    });

    resizeObserver.observe(canvas);
    return () => resizeObserver.disconnect();
  }, [store]);

  return <canvas ref={canvasRef} className="h-full w-full" />;
}
