/* @vitest-environment jsdom */

import { act, useState } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it } from "vitest";

import {
  GiftProductSchema,
  type GiftProduct,
} from "@/data/schemas/payment";

import { TipGiftProductSelector } from "../tip-gift-product-selector";

const products: readonly GiftProduct[] = [
  makeProduct("gift_small", "Velvet Espresso", 499),
  makeProduct("gift_medium", "Golden Reserve", 999),
  makeProduct("gift_large", "Imperial Grand Cru", 1999),
];

function Harness() {
  const [selectedPlanId, setSelectedPlanId] = useState("gift_small");
  return (
    <TipGiftProductSelector
      disabled={false}
      products={products}
      onChange={setSelectedPlanId}
      selectedPlanId={selectedPlanId}
    />
  );
}

describe("TipGiftProductSelector", () => {
  let container: HTMLDivElement;
  let root: Root;

  beforeEach(() => {
    (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean })
      .IS_REACT_ACT_ENVIRONMENT = true;
    container = document.createElement("div");
    document.body.append(container);
    root = createRoot(container);
  });

  afterEach(() => {
    act(() => root.unmount());
    container.remove();
  });

  it("renders backend products and selects the first product", () => {
    act(() => root.render(<Harness />));

    expect(container.textContent).toContain("Velvet Espresso");
    expect(container.textContent).toContain("Golden Reserve");
    expect(container.textContent).toContain("Imperial Grand Cru");
    expect(
      container.querySelector<HTMLInputElement>('input[value="gift_small"]')
        ?.checked,
    ).toBe(true);
  });

  it("switches the selected backend plan id", () => {
    act(() => root.render(<Harness />));
    const medium = container.querySelector<HTMLInputElement>(
      'input[value="gift_medium"]',
    );
    act(() => medium?.click());
    expect(medium?.checked).toBe(true);
  });
});

function makeProduct(
  planId: string,
  planName: string,
  amountCents: number,
): GiftProduct {
  return GiftProductSchema.parse({
    planId,
    planName,
    orderType: "tip",
    tipType: planId,
    category: "coffee",
    characterId: "elio",
    description: `${planName} description`,
    imageUrl: null,
    amountCents,
    currency: "USD",
    autoRenew: false,
    isFirstRechargeOffer: false,
    firstRechargeDiscountPercent: 0,
    promotionType: null,
  });
}
