import * as React from "react";

import { defineToolcraft } from "../../schema/define-toolcraft";
import { useToolcraft } from "./use-toolcraft";

export function installToolcraftAppTestWindow(): void {
  Object.defineProperty(window, "matchMedia", {
    value: (query: string) => ({
      addEventListener: () => undefined,
      addListener: () => undefined,
      dispatchEvent: () => false,
      matches: query === "(prefers-reduced-motion: reduce)",
      media: query,
      onchange: null,
      removeEventListener: () => undefined,
      removeListener: () => undefined,
    }),
    writable: true,
  });
  window.requestAnimationFrame ??= ((callback: FrameRequestCallback) =>
    window.setTimeout(
      () => callback(performance.now()),
      16,
    )) as typeof window.requestAnimationFrame;
  window.cancelAnimationFrame ??= ((handle: number) =>
    window.clearTimeout(handle)) as typeof window.cancelAnimationFrame;
}

export function createToolcraftAppTestSchema() {
  return defineToolcraft({
    canvas: {
      enabled: true,
      size: { height: 180, unit: "px", width: 320 },
      upload: true,
    },
    panels: {
      controls: {
        sections: [
          {
            controls: {
              prompt: {
                defaultValue: "Initial prompt",
                label: "Prompt",
                target: "generation.prompt",
                type: "text",
              },
            },
            title: "Basic",
          },
        ],
        title: "Controls",
      },
      layers: true,
      timeline: true,
    },
  });
}

export function PanelWorkspaceProbe(): React.JSX.Element {
  const { state } = useToolcraft();

  return (
    <>
      <span data-testid="panel-workspace-state">
        {JSON.stringify(state.panels)}
      </span>
      <span data-testid="panel-workspace-history">
        {state.history.undo.length}
      </span>
    </>
  );
}
