import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/svelte';
import MigrationDashboard from '../+page.svelte';
import { api } from '$lib/api';

// Mock dependencies
vi.mock('$lib/api', () => ({
    api: {
        getEnvironmentsList: vi.fn(),
        requestApi: vi.fn(),
        postApi: vi.fn()
    }
}));

vi.mock('$lib/i18n', () => ({
    t: {
        subscribe: (fn) => {
            fn({
                nav: { migration: 'Migration' },
                migration: {
                    start: 'Start Migration',
                    fix_cross_filters: 'Fix Cross-Filters (Auto-repair broken links during migration)',
                    replace_db: 'Replace Database (Apply Mappings)'
                },
                common: { cancel: 'Cancel' }
            });
            return () => { };
        }
    },
    _: vi.fn((key) => key)
}));

vi.mock('../../components/EnvSelector.svelte', () => ({
    default: class EnvSelectorMock {
        constructor(options) {
            options.target.innerHTML = `<div data-testid="env-selector-${options.props.label || 'unknown'}"></div>`;
        }
    }
}));

vi.mock('../../components/DashboardGrid.svelte', () => ({
    default: class DashboardGridMock {
        constructor(options) {
            options.target.innerHTML = `<div data-testid="dashboard-grid"></div>`;
        }
    }
}));

describe('MigrationDashboard.ux.test.js', () => {
    const mockEnvironments = [
        { id: 'env-1', name: 'Source Env' },
        { id: 'env-2', name: 'Target Env' }
    ];

    beforeEach(() => {
        vi.clearAllMocks();
        api.getEnvironmentsList.mockResolvedValue(mockEnvironments);
        api.requestApi.mockResolvedValue([]);
    });

    it('renders and fetches environments on mount', async () => {
        render(MigrationDashboard);
        expect(api.getEnvironmentsList).toHaveBeenCalled();
    });

    it('shows missing environments error when trying to start migration without selection', async () => {
        const { getByText } = render(MigrationDashboard);

        // Checkboxes should exist and fix_cross_filters is checked by default
        const fixFiltersCheckbox = screen.getByLabelText('Fix Cross-Filters (Auto-repair broken links during migration)');
        expect(fixFiltersCheckbox.checked).toBe(true);

        const replaceDbCheckbox = screen.getByLabelText('Replace Database (Apply Mappings)');
        expect(replaceDbCheckbox.checked).toBe(false);

        // Initial state prevents clicking start. Forcing click by getting element
        const startButton = getByText('Start Migration');
        expect(startButton.disabled).toBe(true);
    });
});
