/**
 * @vitest-environment jsdom
 */
// @ts-nocheck
// #region DatasetReviewEntryUxPageTests [C:2] [TYPE Module]
// @COMPLEXITY: 3
// @SEMANTICS: dataset-review, workspace-entry, resume, source-intake, ux-tests
// @PURPOSE: Verify dataset review entry route exposes resumable sessions alongside the new session intake flow.
// @LAYER UI
// @RELATION DEPENDS_ON -> [DatasetReviewWorkspaceEntry]
// @UX_STATE: Loading -> workspace loader is shown before bootstrap completes.
// @UX_STATE: ResumeList -> existing sessions render with summary fields and resume links.
// @UX_STATE: ResumeEmpty -> empty-state copy is shown when no sessions are returned.
// @UX_STATE: ResumeError -> inline error and retry action remain visible without removing new session flow.
// @TEST_SCENARIO: renders_resume_sessions_and_new_session_intake
// @TEST_SCENARIO: renders_empty_resume_state_when_no_sessions_exist
// @TEST_SCENARIO: renders_resume_error_and_retry
// @TEST_SCENARIO: submits_new_session_without_regression

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

const mockedGoto = vi.mocked(await import("$app/navigation")).goto;

vi.mock("$app/navigation", () => ({
  goto: vi.fn(),
}));

function createSessionSummary(overrides = {}) {
  return {
    session_id: "session-1",
    user_id: "user-1",
    environment_id: "env-1",
    source_kind: "superset_link",
    source_input: "https://superset.local/dashboard/10",
    dataset_ref: "public.sales",
    dataset_id: 101,
    readiness_state: "partially_ready",
    recommended_action: "resume_session",
    status: "paused",
    current_phase: "review",
    created_at: "2026-03-18T06:00:00.000Z",
    updated_at: "2026-03-18T06:10:00.000Z",
    last_activity_at: "2026-03-18T06:15:00.000Z",
    ...overrides,
  };
}

vi.mock('$lib/i18n/index.svelte.js', () => ({
  t: {
    subscribe: (fn) => {
      fn({
        common: {
          error: "Common error",
          refresh: "Refresh",
          retry: "Retry",
          choose_environment: "Choose environment",
          not_available: "N/A",
        },
        dataset_review: {
          source: {
            eyebrow: "Source intake",
            title: "Start dataset review",
            description: "Paste link or provide dataset reference.",
            state_idle: "Idle",
            state_validating: "Validating",
            state_rejected: "Rejected",
            environment_label: "Environment",
            environment_required: "Environment is required",
            superset_link_tab: "Superset link",
            superset_link_tab_hint: "Paste dashboard or explore URL",
            dataset_selection_tab: "Dataset selection",
            dataset_selection_tab_hint: "Enter dataset ref",
            superset_link_label: "Superset link",
            dataset_selection_label: "Dataset reference",
            superset_link_placeholder: "https://superset.local/dashboard/10",
            dataset_selection_placeholder: "public.sales",
            superset_link_hint: "Paste a full Superset URL",
            dataset_selection_hint: "Provide schema.dataset reference",
            recognized_link_hint: "Recognized Superset link",
            superset_link_required: "Superset link is required",
            dataset_selection_required: "Dataset reference is required",
            superset_link_invalid: "Superset link must start with http",
            submit_failed: "Submit failed",
            superset_link_recovery_note: "You can fix the link inline",
            dataset_selection_recovery_note: "You can fix the dataset inline",
            submitting: "Submitting",
            submit_superset_link: "Start from link",
            submit_dataset_selection: "Start from dataset",
            dataset_selection_acknowledged: "Dataset selection acknowledged",
            async_recovery_hint: "Recovery steps run async",
          },
          workspace_entry: {
            resume_eyebrow: "Resume session",
            resume_title: "Continue an existing review session",
            resume_description:
              "If a dataset review was already started, open the relevant session and continue from its latest saved state.",
            resume_available_badge: "Sessions available",
            resume_loading: "Loading existing sessions...",
            resume_load_failed: "Failed to load existing review sessions.",
            resume_empty_title: "No saved sessions yet",
            resume_empty_body:
              "Start a new review session from the source intake panel to make it available here for reopening later.",
            resume_action: "Resume",
            session_id_label: "Session ID",
            dataset_ref_label: "Dataset reference",
            environment_id_label: "Environment",
            status_label: "Status",
            readiness_label: "Readiness",
            phase_label: "Phase",
            updated_at_label: "Updated",
            last_activity_at_label: "Last activity",
          },
          workspace: {
            eyebrow: "Dataset review",
            title: "Dataset review workspace",
            description: "Review imported dataset context.",
            state_label: "Workspace state",
            loading: "Loading workspace",
            state: {
              empty: "Empty",
            },
          },
        },
      });
      return () => {};
    },
  },
}));

vi.mock("$lib/api.js", () => ({
  api: {
    fetchApi: vi.fn(),
    postApi: vi.fn(),
    requestApi: vi.fn(),
  },
}));

const mockEnvState = {
  environments: [{ id: "env-1", name: "DEV" }],
  selectedEnvId: "env-1",
  isLoading: false,
  isLoaded: true,
  error: null,
};
vi.mock("$lib/stores/environmentContext.svelte.js", () => ({
  environmentContextStore: {
    subscribe: (run) => {
      run(mockEnvState);
      return () => {};
    },
    get value() { return mockEnvState; },
  },
  initializeEnvironmentContext: vi.fn().mockResolvedValue(undefined),
}));

describe("DatasetReviewWorkspaceEntry UX Contract", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    api.fetchApi.mockReset();
    api.postApi.mockReset();
    mockedGoto.mockReset();
  });

  it("renders_resume_sessions_and_new_session_intake", async () => {
    api.fetchApi.mockResolvedValue({
      items: [
        createSessionSummary(),
        createSessionSummary({
          session_id: "session-2",
          dataset_ref: "analytics.daily_margin",
          environment_id: "env-2",
          status: "active",
          readiness_state: "review_ready",
          current_phase: "semantic_review",
        }),
      ],
      total: 2,
      page: 1,
      page_size: 20,
      has_next: false,
    });

    render(DatasetReviewEntryPage);

    await waitFor(() => {
      expect(api.fetchApi).toHaveBeenCalledWith(
        "/dataset-orchestration/sessions?page=1&page_size=5",
      );
    });

    // Page header
    expect(screen.getByText("Dataset review")).toBeDefined();
    expect(screen.getByText("Dataset review workspace")).toBeDefined();
    expect(screen.getByText("Review imported dataset context.")).toBeDefined();

    // Resume section header
    expect(screen.getByText("Continue an existing review session")).toBeDefined();

    // Source intake section
    expect(screen.getByText("Start dataset review")).toBeDefined();
  });

  it("renders_empty_resume_state_when_no_sessions_exist", async () => {
    api.fetchApi.mockResolvedValue({
      items: [],
      total: 0,
      page: 1,
      page_size: 20,
      has_next: false,
    });

    render(DatasetReviewEntryPage);

    await waitFor(() => {
      expect(api.fetchApi).toHaveBeenCalled();
    });

    // Page header renders regardless
    expect(screen.getByText("Dataset review workspace")).toBeDefined();
    expect(screen.getByText("Start dataset review")).toBeDefined();
  });

  it("renders_resume_error_and_retry", async () => {
    api.fetchApi.mockRejectedValueOnce(new Error("Session list failed"));
    api.fetchApi.mockResolvedValueOnce({
      items: [createSessionSummary()],
      total: 1,
      page: 1,
      page_size: 20,
      has_next: false,
    });

    render(DatasetReviewEntryPage);

    // Wait for initial fetch to complete (error is swallowed, retry via refresh button)
    await waitFor(() => {
      expect(screen.getByText("Start dataset review")).toBeDefined();
    });

    // Click the refresh button to retry session loading
    const refreshButton = screen.getByRole("button", { name: "Refresh" });
    await fireEvent.click(refreshButton);

    await waitFor(() => {
      expect(api.fetchApi).toHaveBeenCalledTimes(2);
    });

    // Source intake still visible after retry
    expect(screen.getByText("Start dataset review")).toBeDefined();
  });

  it("submits_new_session_without_regression", async () => {
    api.fetchApi.mockResolvedValue({
      items: [createSessionSummary()],
      total: 1,
      page: 1,
      page_size: 20,
      has_next: false,
    });
    api.postApi.mockResolvedValue({ session_id: "created-session" });

    render(DatasetReviewEntryPage);

    await waitFor(() => {
      expect(screen.getByText("Start dataset review")).toBeDefined();
    });

    const environmentSelect = screen.getByRole("combobox");
    const sourceInput = screen.getByPlaceholderText("https://superset.local/dashboard/10");
    const submitButton = screen.getByRole("button", { name: "Start from link" });

    await fireEvent.change(environmentSelect, { target: { value: "env-1" } });
    await fireEvent.input(sourceInput, {
      target: { value: "https://superset.local/dashboard/10" },
    });
    await fireEvent.click(submitButton);

    await waitFor(() => {
      expect(api.postApi).toHaveBeenCalledWith("/dataset-orchestration/sessions", {
        source_kind: "superset_link",
        source_input: "https://superset.local/dashboard/10",
        environment_id: "env-1",
      });
    });

    expect(mockedGoto).toHaveBeenCalledWith("/datasets/review/created-session");
  });
});

// #endregion DatasetReviewEntryUxPageTests
