import React from 'react';
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { act, render, screen, waitFor } from '@testing-library/react';
import '@testing-library/jest-dom';
import type { TFunction } from 'i18next';
import { PaddleCheckout } from '../pages/WelcomeOrderSummaryPage';

vi.mock('../../auth/context', () => ({
  useAuth: () => ({ status: 'authenticated', user: { name: 'Test User' } }),
}));

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

vi.mock('../../api', () => ({
  assignFreeTenantPackage: vi.fn(),
  createTenantPaddleCheckout: createPaddleCheckoutMock,
}));

describe('PaddleCheckout', () => {
  beforeEach(() => {
    createPaddleCheckoutMock.mockReset();
  });

  it('opens Paddle checkout when created successfully', async () => {
    createPaddleCheckoutMock.mockResolvedValue({ checkout_url: 'https://paddle.example/checkout' });
    const onSuccess = vi.fn();
    const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null);
    const tMock = ((key: string) => key) as unknown as TFunction;

    render(
      <PaddleCheckout
        packageId={99}
        onSuccess={onSuccess}
        t={tMock}
      />
    );

    await act(async () => {
      screen.getByRole('button').click();
    });

    await waitFor(() => {
      expect(createPaddleCheckoutMock).toHaveBeenCalledWith(99);
      expect(openSpy).toHaveBeenCalledWith('https://paddle.example/checkout', '_blank', 'noopener');
      expect(onSuccess).toHaveBeenCalled();
    });

    openSpy.mockRestore();
  });

  it('shows an error message on failure', async () => {
    createPaddleCheckoutMock.mockRejectedValue(new Error('boom'));
    const tMock = ((key: string) => key) as unknown as TFunction;

    render(
      <PaddleCheckout
        packageId={99}
        onSuccess={vi.fn()}
        t={tMock}
      />
    );

    await act(async () => {
      screen.getByRole('button').click();
    });

    await waitFor(() => {
      expect(screen.getByRole('alert')).toHaveTextContent('boom');
    });
  });
});
