/* eslint-disable import-x/order */
import { render, screen, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';

// Mock next-intl with Vietnamese messages
const viMessages = await import('@/messages/vi.json');
vi.mock('next-intl', () => ({
  useTranslations: (namespace?: string) => {
    const messages = viMessages.default ?? viMessages;
    const ns = namespace
      ? (messages[namespace as keyof typeof messages] as Record<string, unknown> | undefined)
      : (messages as unknown as Record<string, unknown>);
    return (key: string, params?: Record<string, unknown>) => {
      if (!ns) return key;
      const parts = key.split('.');
      let val: unknown = ns;
      for (const p of parts) {
        val = (val as Record<string, unknown>)?.[p];
      }
      if (typeof val === 'string' && params) {
        return val.replace(/\{(\w+)\}/g, (_, k: string) => String(params[k] ?? `{${k}}`));
      }
      return typeof val === 'string' ? val : key;
    };
  },
  useLocale: () => 'vi',
  NextIntlClientProvider: ({ children }: { children: React.ReactNode }) => children,
}));

vi.mock('next/link', () => ({
  default: ({ children, href, ...props }: { children: React.ReactNode; href: string; [key: string]: unknown }) => (
    <a href={href} {...props}>{children}</a>
  ),
}));

vi.mock('@/i18n/navigation', () => ({
  Link: ({ children, href, ...props }: { children: React.ReactNode; href: string; [key: string]: unknown }) => (
    <a href={href} {...props}>{children}</a>
  ),
  useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
  usePathname: () => '/pricing',
  redirect: vi.fn(),
}));

vi.mock('lucide-react', () => ({
  AlertCircle: () => <span data-testid="icon-alert-circle" />,
  Check: () => <span data-testid="icon-check">✓</span>,
  CreditCard: () => <span data-testid="icon-credit-card" />,
  Crown: () => <span data-testid="icon-crown" />,
  Loader2: () => <span data-testid="icon-loader2" />,
  Rocket: () => <span data-testid="icon-rocket" />,
  Shield: () => <span data-testid="icon-shield" />,
  Smartphone: () => <span data-testid="icon-smartphone" />,
  Wallet: () => <span data-testid="icon-wallet" />,
  X: () => <span data-testid="icon-x">✗</span>,
  Zap: () => <span data-testid="icon-zap" />,
}));

const mockPlans = [
  {
    id: 'plan-free',
    tier: 'FREE',
    name: 'Miễn phí',
    priceMonthlyVND: '0',
    priceYearlyVND: '0',
    maxListings: 3,
    maxSavedSearches: 5,
    features: { basicSearch: true, listingPost: true, maxPhotos: 5, analytics: false, prioritySupport: false, aiValuation: false, featuredListing: false },
    isActive: true,
  },
  {
    id: 'plan-pro',
    tier: 'AGENT_PRO',
    name: 'Agent Pro',
    priceMonthlyVND: '499000',
    priceYearlyVND: '4990000',
    maxListings: 50,
    maxSavedSearches: 30,
    features: { basicSearch: true, listingPost: true, maxPhotos: 30, analytics: true, prioritySupport: true, aiValuation: true, featuredListing: true },
    isActive: true,
  },
];

vi.mock('@/lib/hooks/use-subscription', () => ({
  usePlans: vi.fn(() => ({ data: mockPlans, isLoading: false, error: null })),
  useBillingHistory: vi.fn(() => ({ data: [], isLoading: false, error: null })),
}));

vi.mock('@/lib/subscription-api', () => ({
  subscriptionApi: { createCheckout: vi.fn() },
}));

vi.mock('@/lib/payment-api', () => ({
  createPayment: vi.fn(),
  getPaymentMethods: vi.fn(() => []),
}));

vi.mock('@/lib/auth-store', () => ({
  useAuthStore: vi.fn(() => ({ user: null, token: null })),
}));

import PricingPage from '../pricing/page';

describe('PricingPage', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('renders pricing page', () => {
    render(<PricingPage />);
    // The page uses translation keys - just verify it renders without error
    expect(document.body.querySelector('.bg-background')).toBeTruthy();
  });

  it('renders billing cycle toggle buttons', () => {
    render(<PricingPage />);
    // Buttons exist in the page
    const buttons = screen.getAllByRole('button');
    expect(buttons.length).toBeGreaterThan(0);
  });

  it('renders plan cards', async () => {
    render(<PricingPage />);

    // Should render two plans as cards
    await waitFor(() => {
      const cards = document.querySelectorAll('[class*="card"]');
      expect(cards.length).toBeGreaterThan(0);
    });
  });

  it('renders feature comparison table', () => {
    render(<PricingPage />);
    const tables = document.querySelectorAll('table');
    expect(tables.length).toBeGreaterThan(0);
  });
});
