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

import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { describe, expect, it } from "vitest";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ClaimPaymentsTable } from "./ClaimPaymentsTable";
import type { RemitDetail } from "@/hooks/useRemitDetail";

function renderIntoContainer(element: React.ReactElement): {
  container: HTMLDivElement;
  unmount: () => void;
} {
  const container = document.createElement("div");
  document.body.appendChild(container);
  const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
  const root: Root = createRoot(container);
  act(() => {
    root.render(
      React.createElement(QueryClientProvider, { client: qc }, element)
    );
  });
  return {
    container,
    unmount: () => {
      act(() => root.unmount());
      container.remove();
    },
  };
}

describe("ClaimPaymentsTable", () => {
  it("renders_headline_row_and_carc_breakdown", () => {
    const sample: RemitDetail = {
      id: "REM-1",
      claimId: "CLM-1",
      payerClaimControlNumber: "PCN-1",
      payerName: "Medicaid",
      paidAmount: 100,
      adjustmentAmount: 25,
      totalCharge: 125,
      receivedDate: "2026-01-15T00:00:00Z",
      checkNumber: "EFT-1",
      status: "received",
      adjustments: [
        { group: "CO", reason: "45", label: "Charge exceeds fee schedule", amount: 50, quantity: null },
        { group: "PR", reason: "1", label: "Deductible", amount: 10, quantity: 1 },
        { group: "CO", reason: "45", label: "Charge exceeds fee schedule", amount: -35, quantity: null },
      ],
    };

    const { container, unmount } = renderIntoContainer(
      <ClaimPaymentsTable remit={sample} />
    );

    // Headline table is present.
    expect(
      container.querySelector('[data-testid="claim-payments-table"]')
    ).not.toBeNull();
    expect(
      container.querySelector('[data-testid="claim-payments-row"]')
    ).not.toBeNull();

    // CARC breakdown groups the two CO-45 hits into one row.
    const carcRows = container.querySelectorAll('[data-testid="carc-row"]');
    expect(carcRows.length).toBe(2);

    // CO-45 rows: two of them with a cumulative amount of 50 + -35 = 15
    const co45 = Array.from(carcRows).find((row) =>
      row.getAttribute("data-carc") === "CO-45"
    );
    expect(co45).toBeDefined();
    expect(co45?.textContent).toContain("×2");
    // The cumulative amount shows $15.00 (formatted by usdPrecise).
    expect(co45?.textContent).toContain("15");

    unmount();
  });

  it("omits_carc_breakdown_when_no_adjustments", () => {
    const sample: RemitDetail = {
      id: "REM-1",
      claimId: "CLM-1",
      payerClaimControlNumber: "PCN-1",
      payerName: "Medicaid",
      paidAmount: 100,
      adjustmentAmount: 0,
      receivedDate: "2026-01-15T00:00:00Z",
      checkNumber: "EFT-1",
      status: "received",
      adjustments: [],
    };

    const { container, unmount } = renderIntoContainer(
      <ClaimPaymentsTable remit={sample} />
    );

    expect(
      container.querySelector('[data-testid="claim-payments-table"]')
    ).not.toBeNull();
    expect(
      container.querySelector('[data-testid="claim-payments-carc-summary"]')
    ).toBeNull();

    unmount();
  });
});
