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

function renderPanel() {
  const onClose = vi.fn();
  render(
    <ComparisonCodePanel
      activeFlavour="ecmascript"
      activeFlags={["g", "u"]}
      activeOptions={{}}
      pattern={"(?<word>\\p{Letter}+)"}
      subject="Grüße"
      replacement="$<word>!"
      scanAll
      timeoutMs={2_000}
      onClose={onClose}
    />,
  );
  return { onClose };
}

describe("ComparisonCodePanel", () => {
  it("exposes comparison and reviewed PCRE2 C generation through one usable path", () => {
    renderPanel();

    expect(
      screen.getByRole("tab", { name: "Compare engines" }),
    ).toHaveAttribute("aria-selected", "true");
    expect(
      screen.getByRole("textbox", { name: "Shared comparison pattern" }),
    ).toHaveValue("(?<word>\\p{Letter}+)");
    expect(
      screen.getByRole("button", { name: "Run comparison" }),
    ).toBeEnabled();

    fireEvent.click(screen.getByRole("tab", { name: "PCRE2 C code" }));
    fireEvent.click(
      screen.getByRole("button", { name: "Generate reviewed C17" }),
    );

    expect(screen.getByText("PCRE2 10.47 8-bit · all-matches")).toBeVisible();
    expect(screen.getByText("Exact UTF-8 byte arrays")).toBeVisible();
    expect(
      screen.getByText(/PCRE2_UTF and PCRE2_UCP are mandatory/u),
    ).toBeVisible();
    const source = screen.getByText(
      /This generated program requires PCRE2 10\.47 exactly/u,
    );
    expect(source).toHaveTextContent("pcre2_set_match_limit");
    expect(source).not.toHaveTextContent("(?<word>\\p{Letter}+)");
  });

  it("uses the explicit PCRE2 variant without rewriting it", () => {
    renderPanel();
    fireEvent.change(screen.getByLabelText("Pattern model"), {
      target: { value: "variants" },
    });
    const pcrePattern = screen.getByLabelText("PCRE2 pattern variant");
    fireEvent.change(pcrePattern, {
      target: { value: "(?<word>\\w++)" },
    });
    fireEvent.click(screen.getByRole("tab", { name: "PCRE2 C code" }));
    fireEvent.click(
      screen.getByRole("button", { name: "Generate reviewed C17" }),
    );

    const source = screen.getByText(
      /This generated program requires PCRE2 10\.47 exactly/u,
    );
    expect(source).toHaveTextContent("0x2b, 0x2b");
    expect(source).not.toHaveTextContent("(?<word>\\w++)");
  });

  it("closes through the dialog action", () => {
    const { onClose } = renderPanel();
    fireEvent.click(
      screen.getByRole("button", { name: "Close compare and generate" }),
    );
    expect(onClose).toHaveBeenCalledOnce();
  });
});
