// @vitest-environment jsdom
import { beforeEach, describe, expect, it, vi, afterEach } from 'vitest';
import { render, screen, waitFor, fireEvent } from '@testing-library/react';
import { GlobalConfigManager } from './GlobalConfigManager';

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

vi.mock('../lib/dynamicConfigApi', () => ({
    fetchDynamicConfigItems: fetchDynamicConfigItemsMock,
    upsertDynamicConfigItems: upsertDynamicConfigItemsMock,
}));

describe('GlobalConfigManager DOM behavior', () => {
    beforeEach(() => {
        vi.clearAllMocks();
        fetchDynamicConfigItemsMock.mockResolvedValue([
            { key: 'BOT_MODE', value: 'paper', description: 'Trading mode' },
            { key: 'MAX_POSITIONS', value: '5', description: 'Max positions' }
        ]);
        upsertDynamicConfigItemsMock.mockResolvedValue(undefined);
    });

    afterEach(() => {
        vi.useRealTimers();
    });

    it('loads and displays configuration items', async () => {
        render(<GlobalConfigManager />);

        // Wait for removal of loading state
        await waitFor(() => {
            expect(screen.queryByText(/Loading system configuration/i)).not.toBeInTheDocument();
        }, { timeout: 3000 });

        expect(screen.getByText(/Global Bot Configuration/i)).toBeInTheDocument();
        expect(screen.getByText('BOT_MODE')).toBeInTheDocument();
        expect(screen.getByDisplayValue('paper')).toBeInTheDocument();
    });

    it('saves configuration successfully', async () => {
        render(<GlobalConfigManager />);
        await waitFor(() => expect(screen.getByText(/Global Bot Configuration/i)).toBeInTheDocument());

        const saveButtons = screen.getAllByRole('button', { name: /Save/i });
        fireEvent.click(saveButtons[0]);

        await waitFor(() => {
            expect(upsertDynamicConfigItemsMock).toHaveBeenCalledWith([
                { key: 'BOT_MODE', value: 'paper', description: 'Trading mode' }
            ]);
        });

        expect(screen.getByText(/updated successfully/i)).toBeInTheDocument();
    });

    it('handles save failure', async () => {
        upsertDynamicConfigItemsMock.mockRejectedValue(new Error('Write Denied'));
        render(<GlobalConfigManager />);
        await waitFor(() => expect(screen.getByText(/Global Bot Configuration/i)).toBeInTheDocument());

        const saveButtons = screen.getAllByRole('button', { name: /Save/i });
        fireEvent.click(saveButtons[0]);

        await waitFor(() => {
            expect(screen.getByText(/Failed to save BOT_MODE: Write Denied/i)).toBeInTheDocument();
        });
    });

    it('handles service unavailable error', async () => {
        fetchDynamicConfigItemsMock.mockRejectedValue(new Error('Dynamic config service unavailable.'));

        render(<GlobalConfigManager />);

        await waitFor(() => {
            expect(screen.getByText(/Dynamic config service unavailable./i)).toBeInTheDocument();
        });
    });
});
