// @vitest-environment happy-dom
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;

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

// happy-dom keeps `document.body` between tests; without cleanup,
// `screen.getByRole("button")` finds buttons from earlier renders.
afterEach(() => cleanup());

describe("DrillableCell", () => {
  it("renders children, applies hover affordance classes, calls onClick", () => {
    const onClick = vi.fn();
    render(
      <DrillableCell onClick={onClick}>
        <span>CLM-114</span>
      </DrillableCell>,
    );
    const btn = screen.getByRole("button") as HTMLButtonElement;
    expect(btn.classList.contains("drillable")).toBe(true);
    fireEvent.click(btn);
    expect(onClick).toHaveBeenCalledOnce();
  });

  it("disabled state hides affordance and blocks click", () => {
    const onClick = vi.fn();
    render(
      <DrillableCell onClick={onClick} disabled>
        <span>unavailable</span>
      </DrillableCell>,
    );
    const btn = screen.getByRole("button") as HTMLButtonElement;
    expect(btn.disabled).toBe(true);
    expect(btn.classList.contains("drillable")).toBe(false);
  });

  // ---------------------------------------------------------------------
  // Regression for Task 2.4 — event bubbling.
  //
  // DrillableCell renders a <button>, and <button> clicks bubble up the
  // DOM by default. Claims wraps each row in a <TableRow onClick={...}>
  // so a click on the provider cell used to (1) navigate to /providers
  // and then (2) bubble to the row and re-fire buildUrl() on the now-
  // /providers URL, appending a phantom ?claim=… param. We fix it at
  // the DrillableCell level so future tables that adopt the component
  // are correct by default.
  // ---------------------------------------------------------------------
  it("test_click_does_not_bubble_to_parent", () => {
    const parentClick = vi.fn();
    const { container } = render(
      <div onClick={parentClick}>
        <DrillableCell onClick={() => {}}>Click me</DrillableCell>
      </div>,
    );
    const btn = container.querySelector("button")!;
    fireEvent.click(btn);
    expect(parentClick).not.toHaveBeenCalled();
  });
});
