// src/components/AppGuard.test.tsx
import React from 'react';
import { screen, waitFor } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { AppGuard } from './AppGuard';
import { useAppInitialization } from '../hooks/useAppInitialization';
import * as apiClient from '../services/apiClient';
import { useModal } from '../hooks/useModal';
import { renderWithProviders } from '../tests/utils/renderWithProviders';

// Must explicitly call vi.mock() for apiClient
vi.mock('../services/apiClient');
vi.mock('../hooks/useAppInitialization');
vi.mock('../hooks/useModal');
vi.mock('./WhatsNewModal', () => ({
  WhatsNewModal: ({ isOpen }: { isOpen: boolean }) =>
    isOpen ? <div data-testid="whats-new-modal-mock" /> : null,
}));
vi.mock('../config', () => ({
  default: {
    app: { version: '1.0.0', commitMessage: 'Test commit' },
  },
}));

const _mockedApiClient = vi.mocked(apiClient);
const mockedUseAppInitialization = vi.mocked(useAppInitialization);
const mockedUseModal = vi.mocked(useModal);

describe('AppGuard', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    // Default mocks
    mockedUseAppInitialization.mockReturnValue({
      isDarkMode: false,
      unitSystem: 'imperial',
    });
    mockedUseModal.mockReturnValue({
      isModalOpen: vi.fn().mockReturnValue(false),
      openModal: vi.fn(),
      closeModal: vi.fn(),
    });
  });

  it('should render children', () => {
    renderWithProviders(
      <AppGuard>
        <div>Child Content</div>
      </AppGuard>,
    );
    expect(screen.getByText('Child Content')).toBeInTheDocument();
  });

  it('should render WhatsNewModal when it is open', () => {
    mockedUseModal.mockReturnValue({
      ...mockedUseModal(),
      isModalOpen: (modalId) => modalId === 'whatsNew',
    });
    renderWithProviders(
      <AppGuard>
        <div>Child</div>
      </AppGuard>,
    );
    expect(screen.getByTestId('whats-new-modal-mock')).toBeInTheDocument();
  });

  it('should set dark mode styles for toaster', async () => {
    mockedUseAppInitialization.mockReturnValue({
      isDarkMode: true,
      unitSystem: 'imperial',
    });
    renderWithProviders(
      <AppGuard>
        <div>Child</div>
      </AppGuard>,
    );
    await waitFor(() => {
      const styleTag = document.querySelector('style');
      expect(styleTag).not.toBeNull();
      expect(styleTag!.innerHTML).toContain('--toast-bg: #4B5563');
      expect(styleTag!.innerHTML).toContain('--toast-color: #F9FAFB');
    });
  });

  it('should set light mode styles for toaster', async () => {
    renderWithProviders(
      <AppGuard>
        <div>Child</div>
      </AppGuard>,
    );
    await waitFor(() => {
      const styleTag = document.querySelector('style');
      expect(styleTag).not.toBeNull();
      expect(styleTag!.innerHTML).toContain('--toast-bg: #FFFFFF');
      expect(styleTag!.innerHTML).toContain('--toast-color: #1F2937');
    });
  });
});
