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

import {
  cleanupLayersPanelTestEnv,
  installLayersPanelMatchMedia,
  renderLayersPanel,
} from "./layers-panel-test-utils";

beforeAll(() => {
  installLayersPanelMatchMedia();
});

afterEach(() => {
  cleanupLayersPanelTestEnv();
});

describe("LayersPanel editing", () => {
  it("renames layers on double click", () => {
    renderLayersPanel();

    fireEvent.doubleClick(screen.getByRole("option", { name: "Layer 1" }));
    const input = screen.getByLabelText("Layer name for Layer 1");

    fireEvent.change(input, { target: { value: "Updated Layer" } });
    fireEvent.keyDown(input, { key: "Enter" });

    expect(screen.getByText("Updated Layer")).toBeTruthy();
  });

  it("adds and deletes layers", () => {
    renderLayersPanel({ groupCreation: false });

    fireEvent.click(screen.getByRole("button", { name: "Add layer" }));
    expect(screen.getByTestId("layer-count").textContent).toBe("4");
    expect(screen.getByText("Layer 3")).toBeTruthy();

    fireEvent.click(screen.getByRole("button", { name: "Delete Layer 3" }));
    expect(screen.getByTestId("layer-count").textContent).toBe("3");
  });
});
