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

import { ControlsPanelCollectionItemFields } from "./controls-panel-collection-item-fields";

describe("ControlsPanelCollectionItemFields", () => {
  it("commits one complete record while preserving sibling and unknown keys", () => {
    const onChange = vi.fn();

    render(
      <ControlsPanelCollectionItemFields
        controls={{
          strength: {
            defaultValue: 0.5,
            label: "Strength",
            max: 1,
            min: 0,
            step: 0.1,
            type: "slider",
          },
          invert: {
            defaultValue: false,
            label: "Invert",
            type: "switch",
          },
          tint: {
            defaultValue: { hex: "#FFFFFF", opacity: 100 },
            label: "Tint",
            type: "colorOpacity",
          },
        }}
        id="surface.layers:0"
        onChange={onChange}
        target="surface.layers"
        value={{
          invert: true,
          rendererToken: "keep",
          strength: 0.4,
          tint: { hex: "#EEDDCC", opacity: 80 },
        }}
      />,
    );

    fireEvent.click(screen.getByRole("button", { name: "Edit Strength value" }));
    const editor = screen.getByRole("textbox", { name: "Strength value" });
    editor.textContent = "0.7";
    fireEvent.keyDown(editor, { key: "Enter" });

    expect(onChange).toHaveBeenCalledWith(
      {
        invert: true,
        rendererToken: "keep",
        strength: 0.7,
        tint: { hex: "#EEDDCC", opacity: 80 },
      },
      "Strength",
      undefined,
    );
    expect(screen.getByText("Invert")).toBeTruthy();
    expect(screen.getByText("Tint")).toBeTruthy();
    expect(screen.queryByText(/Item 1/u)).toBeNull();
  });
});
