// #region TestMigrationDashboard [C:3] [TYPE Module] [SEMANTICS test,migration,ux]
// @BRIEF Verify migration page wizard UX — environment selection, step navigation, error recovery, dry-run flow.
// @RELATION BINDS_TO -> [MigrationPage]
// @LAYER UI
// @RELATION DEPENDS_ON -> [ApiModule]
// @RELATION DEPENDS_ON -> [I18nModule]
// @RELATION DEPENDS_ON -> [EXT:@testing-library/svelte]
// @TEST_CONTRACT: [DashboardSelection + Environment IDs] -> [StepTransition | DryRunResult | ErrorState]
// @TEST_SCENARIO: environments_loaded_on_mount -> Page fetches environments on mount.
// @TEST_SCENARIO: step1_next_disabled_without_env -> Next button disabled when no environments selected.
// @TEST_SCENARIO: api_error_shows_banner -> API failure surfaces error with dismiss button.
// @TEST_SCENARIO: step2_dashboards_shown -> Step 2 content renders when navigated with envs selected.
// @TEST_SCENARIO: step_nav_back_button -> Back button returns to previous step.
// @TEST_EDGE: missing_field -> Empty env selection blocks Next and shows appropriate state.
// @TEST_EDGE: external_fail -> API failure surfaces error banner that can be dismissed.
// @TEST_INVARIANT: migration_guardrails_enforced -> VERIFIED_BY: [step1_next_disabled_without_env, api_error_shows_banner]
// #endregion TestMigrationDashboard

import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, waitFor } 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(),
        getTask: vi.fn()
    }
}));

vi.mock('$lib/i18n/index.svelte.js', () => ({
    t: {
        subscribe: (fn) => {
            fn({
                nav: { migration: 'Migration' },
                migration: {
                    start: 'Start Migration',
                    fix_cross_filters: 'Fix Cross-Filters',
                    replace_db: 'Replace Database',
                    source_env: 'Source Environment',
                    target_env: 'Target Environment',
                    select_dashboards_title: 'Select Dashboards',
                    different_envs: 'Source and target environments must be different.',
                    starting: 'Starting...'
                },
                dashboard: {
                    fix_cross_filters_hint: 'Automatically remap chart and dataset IDs...',
                    mapping_disabled_hint: 'Apply database mappings during migration.',
                    next: 'Next',
                    select_source: 'Select a source env',
                    view_summary: 'Dry Run',
                    settings: 'Options',
                    migrate_modal_title: 'Select environments to start'
                },
                tasks: {
                    summary_report: 'Review',
                    recent: 'Recent Tasks',
                    starting: 'Starting...'
                },
                common: { cancel: 'Cancel', back: 'Back', loading: 'Loading', close: 'Close', refresh: 'Refresh' }
            });
            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>`;
        }
    }
}));

vi.mock('../../components/TaskHistory.svelte', () => ({
    default: class TaskHistoryMock {
        constructor(options) {
            options.target.innerHTML = `<div data-testid="task-history"></div>`;
        }
    }
}));

// #region describe:MigratonDashboard [C:2] [TYPE Block]
// @BRIEF Test suite for migration page UX contract — step wizard, error handling, navigation.
// @RELATION BINDS_TO -> [MigrationPage]
describe('MigrationDashboard.ux.test.js', () => {
    const mockEnvironments = [
        { id: 'env-1', name: 'Source Env', url: 'https://source.example.com' },
        { id: 'env-2', name: 'Target Env', url: 'https://target.example.com' }
    ];

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

    // #region test_renders_and_fetches_envs [C:2] [TYPE Function]
    // @BRIEF Page fetches environments on mount.
    // @TEST_SCENARIO: environments_loaded_on_mount
    it('renders and fetches environments on mount', async () => {
        render(MigrationDashboard);
        expect(api.getEnvironmentsList).toHaveBeenCalled();
    });
    // #endregion test_renders_and_fetches_envs

    // #region test_step1_next_disabled [C:2] [TYPE Function]
    // @BRIEF Next button in step 1 is disabled without environment selection.
    // @TEST_SCENARIO: step1_next_disabled_without_env
    // @TEST_EDGE: missing_field
    it('has step 1 shown by default with Next button disabled', async () => {
        const { getByRole, queryByText } = render(MigrationDashboard);

        // Step 1 is shown by default — find the Next button
        const nextBtn = getByRole('button', { name: /next/i });
        expect(nextBtn).toBeTruthy();
        // Next button should be disabled until environments selected
        expect(nextBtn.hasAttribute('disabled')).toBe(true);

        // Task History toggle should be present
        const taskHistoryBtn = queryByText(/task|последние задачи/i);
        expect(taskHistoryBtn).toBeTruthy();
    });
    // #endregion test_step1_next_disabled

    // #region test_error_state [C:2] [TYPE Function]
    // @BRIEF API failure surfaces error banner that can be dismissed.
    // @TEST_SCENARIO: api_error_shows_banner
    // @TEST_EDGE: external_fail
    it('handles error state gracefully when environments fail to load', async () => {
        api.getEnvironmentsList.mockRejectedValueOnce(new Error('API Error'));
        const { getByText } = render(MigrationDashboard);
        await waitFor(() => {
            expect(getByText('API Error')).toBeTruthy();
        });

        // Error dismiss button should exist (uses <Button variant="ghost"> with aria-label)
        const errorContainer = getByText('API Error').closest('[class*="bg-destructive"]');
        expect(errorContainer).toBeTruthy();
        const dismissBtn = errorContainer?.querySelector('button');
        expect(dismissBtn).toBeTruthy();
    });
    // #endregion test_error_state

    // #region test_ui_has_header_and_toggle [C:2] [TYPE Function]
    // @BRIEF Page header and task history toggle render correctly.
    it('renders page header and task history toggle button', async () => {
        const { getByText } = render(MigrationDashboard);

        // Header title should be present
        expect(getByText('Migration')).toBeTruthy();
        // Task history toggle button should exist
        const toggleBtn = getByText(/task|последние задачи/i);
        expect(toggleBtn).toBeTruthy();
        expect(toggleBtn.tagName).toBe('BUTTON');
    });
    // #endregion test_ui_has_header_and_toggle
});
// #endregion describe:MigratonDashboard
