import { describe, expect, it } from "vitest";
import {
  defineToolcraft,
  fireEvent,
  renderControlsPanelWithSchema,
  screen,
  waitFor,
} from "../testing/controls-panel-test-utils";
import { formatControlValueLabel } from "../values/controls-panel-value-labels";

function createTabsSchema(withInlineLayout = false) {
  return defineToolcraft({
    canvas: { enabled: false },
    panels: {
      controls: {
        sections: [
          {
            controls: {
              includeTemplate: {
                defaultValue: true,
                label: "Include",
                target: "template.enabled",
                type: "switch",
              },
              templateView: {
                defaultValue: "simple",
                label: "Template view",
                options: [
                  { label: "Simple", value: "simple" },
                  { label: "Mega", value: "mega" },
                ],
                target: "template.view",
                type: "tabs",
              },
            },
            layoutGroups: withInlineLayout
              ? [
                  {
                    columns: 2,
                    controls: ["includeTemplate", "templateView"],
                    layout: "inline",
                  },
                ]
              : undefined,
            title: "Template Library",
          },
        ],
        title: "Controls",
      },
    },
  });
}

describe("ControlsPanel tabs", () => {
  it("renders label-free semantic tabs and commits the selected content view", async () => {
    renderControlsPanelWithSchema(createTabsSchema());

    expect(screen.getByRole("tablist", { name: "Template view" })).toBeTruthy();
    expect(screen.queryByText("Template view")).toBeNull();
    expect(
      screen.getByRole("tab", { name: "Simple" }).getAttribute("aria-selected"),
    ).toBe("true");

    fireEvent.click(screen.getByRole("tab", { name: "Mega" }));

    await waitFor(() => {
      expect(screen.getByTestId("values-json").textContent).toContain(
        '"template.view":"mega"',
      );
    });
  });

  it("keeps tabs full-width when an inline layout is requested", () => {
    const { container } = renderControlsPanelWithSchema(createTabsSchema(true));

    expect(
      container.querySelector('[data-control-layout="inline"]'),
    ).toBeNull();
    expect(screen.getByRole("tablist", { name: "Template view" })).toBeTruthy();
  });

  it("formats the selected tab with its option label", () => {
    const control = createTabsSchema()
      .panels.controls?.sections.map((section) => section.controls.templateView)
      .find((candidate) => candidate !== undefined);

    if (!control) {
      throw new Error("Missing tabs test control");
    }

    expect(formatControlValueLabel(control, "mega")).toBe("Mega");
  });
});
