import { cleanup, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest";

import { defineToolcraft } from "../../schema/define-toolcraft";
import { ToolcraftApp } from "./toolcraft-app";

afterEach(cleanup);

const ProductModelCanvas = () => <span data-testid="product-model-canvas" />;

function createModelCanvasSchema() {
  return defineToolcraft({
    canvas: { enabled: true, size: { height: 180, unit: "px", width: 320 } },
    panels: {
      controls: {
        sections: [{
          controls: {
            model: {
              assetKind: "model",
              target: "source.model",
              type: "fileDrop",
            },
          },
          title: "Source",
        }],
        title: "Controls",
      },
    },
  });
}

describe("Toolcraft model presentation composition", () => {
  it.each([
    ["default", undefined],
    ["explicit runtime", { mode: "runtime" as const }],
  ])(
    "keeps the %s renderer mounted when generic media is disabled",
    (_label, modelPresentation) => {
      const { container } = render(
        <ToolcraftApp
          canvasContent={<ProductModelCanvas />}
          modelPresentation={modelPresentation}
          renderDefaultCanvasMedia={false}
          schema={createModelCanvasSchema()}
        />,
      );

      expect(container.querySelector(
        '[data-canvas-model-prewarm-target="source.model"]',
      )).not.toBeNull();
      expect(screen.getByTestId("product-model-canvas")).toBeTruthy();
    },
  );

  it("suppresses standard layers only for declared custom targets", () => {
    const schema = defineToolcraft({
      canvas: { enabled: true, size: { height: 180, unit: "px", width: 320 } },
      panels: {
        controls: {
          sections: [{
            controls: {
              environment: {
                assetKind: "model",
                target: "source.environment",
                type: "fileDrop",
              },
              model: {
                assetKind: "model",
                target: "source.model",
                type: "fileDrop",
              },
            },
            title: "Source",
          }],
          title: "Controls",
        },
      },
    });
    const { container } = render(
      <ToolcraftApp
        canvasContent={<ProductModelCanvas />}
        modelPresentation={{
          consumers: [{ id: "product-model", sourceTarget: "source.model" }],
          mode: "custom",
        }}
        renderDefaultCanvasMedia={false}
        schema={schema}
      />,
    );

    expect(container.querySelector(
      '[data-canvas-model-prewarm-target="source.model"]',
    )).toBeNull();
    expect(container.querySelector(
      '[data-canvas-model-prewarm-target="source.environment"]',
    )).not.toBeNull();
    expect(screen.getByTestId("product-model-canvas")).toBeTruthy();
  });
});
