// src/components/AppGuard.test.tsx
import React from 'react';
import { render, screen, waitFor } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { AppGuard } from './AppGuard';
import { useAppInitialization } from '../hooks/useAppInitialization';
import { useModal } from '../hooks/useModal';

// Mock dependencies
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 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', () => {
    render(
      <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',
    });
    render(
      <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',
    });
    render(
      <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 () => {
    render(
      <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');
    });
  });
});
