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

const { createCheckoutHandoff, openUrlWithExternalBrowser } = vi.hoisted(
  () => ({
    createCheckoutHandoff: vi.fn(),
    openUrlWithExternalBrowser: vi.fn(),
  }),
);

vi.mock("@/lib/auth/checkout_handoff", () => ({ createCheckoutHandoff }));
vi.mock("@/utils/url-launcher-util", () => ({
  UrlLauncherUtil: { openUrlWithExternalBrowser },
}));
vi.mock("@/utils/browser-detect", () => ({
  BrowserDetector: { isFacebookInAppBrowser: () => true },
}));

import { ExternalBrowserCheckoutButton } from "../external-browser-checkout-button";

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

  beforeEach(() => {
    vi.clearAllMocks();
    createCheckoutHandoff.mockResolvedValue({
      success: true,
      data: {
        externalUrl:
          "https://cozsweet.com/external-entry?target=checkout&handoffToken=opaque",
        expiresAt: "2026-07-28T16:00:00+00:00",
      },
    });
    (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean })
      .IS_REACT_ACT_ENVIRONMENT = true;
    container = document.createElement("div");
    document.body.appendChild(container);
    root = createRoot(container);
  });

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

  it("creates only a handoff before opening the external browser", async () => {
    await act(async () => {
      root.render(
        <ExternalBrowserCheckoutButton
          characterSlug="maya"
          checkoutIntent={{
            planId: "vip_monthly",
            autoRenew: true,
            commercialOfferId: "offer-1",
          }}
        />,
      );
    });

    const button = container.querySelector("button");
    expect(button?.textContent).toContain(
      "Open in browser for more payment methods",
    );
    await act(async () => button?.click());

    expect(createCheckoutHandoff).toHaveBeenCalledWith({
      planId: "vip_monthly",
      autoRenew: true,
      commercialOfferId: "offer-1",
    });
    expect(openUrlWithExternalBrowser).toHaveBeenCalledWith(
      "https://cozsweet.com/external-entry?target=checkout&handoffToken=opaque&character=maya",
    );
  });
});
