import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import PublicPage from '../PublicPage';

// Mock the hook
vi.mock('../../hooks/useSites', () => ({
  usePublicPage: vi.fn(),
}));

// Mock Puck Render component
vi.mock('@measured/puck', () => ({
  Render: ({ data }: { data: unknown }) => (
    <div data-testid="puck-render">{JSON.stringify(data)}</div>
  ),
}));

// Mock puckConfig
vi.mock('../../puckConfig', () => ({
  config: {},
}));

// Mock lucide-react
vi.mock('lucide-react', () => ({
  Loader2: ({ className }: { className: string }) => (
    <div data-testid="loader" className={className}>Loading</div>
  ),
}));

import { usePublicPage } from '../../hooks/useSites';

const mockUsePublicPage = usePublicPage as ReturnType<typeof vi.fn>;

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

  it('renders loading state', () => {
    mockUsePublicPage.mockReturnValue({
      data: null,
      isLoading: true,
      error: null,
    });

    render(<PublicPage />);
    expect(screen.getByTestId('loader')).toBeInTheDocument();
    expect(screen.getByTestId('loader')).toHaveClass('animate-spin');
  });

  it('renders error state when error occurs', () => {
    mockUsePublicPage.mockReturnValue({
      data: null,
      isLoading: false,
      error: new Error('Failed to load'),
    });

    render(<PublicPage />);
    expect(screen.getByText('Page not found or site disabled.')).toBeInTheDocument();
  });

  it('renders error state when no data', () => {
    mockUsePublicPage.mockReturnValue({
      data: null,
      isLoading: false,
      error: null,
    });

    render(<PublicPage />);
    expect(screen.getByText('Page not found or site disabled.')).toBeInTheDocument();
  });

  it('renders Puck content when data is available', () => {
    const mockPuckData = { content: 'test content' };
    mockUsePublicPage.mockReturnValue({
      data: { puck_data: mockPuckData },
      isLoading: false,
      error: null,
    });

    render(<PublicPage />);
    expect(screen.getByTestId('puck-render')).toBeInTheDocument();
    expect(screen.getByTestId('puck-render')).toHaveTextContent(JSON.stringify(mockPuckData));
  });

  it('applies correct class to public page container', () => {
    const mockPuckData = { content: 'test' };
    mockUsePublicPage.mockReturnValue({
      data: { puck_data: mockPuckData },
      isLoading: false,
      error: null,
    });

    const { container } = render(<PublicPage />);
    expect(container.querySelector('.public-page')).toBeInTheDocument();
  });
});
