/**
 * @vitest-environment jsdom
 */
// @ts-nocheck
// #region DatasetReviewUs2WorkspaceUxTests:Module [TYPE Function]
// @SEMANTICS: dataset-review, semantics, assistant, workspace, ux-tests, mapping-review
// @PURPOSE: Verify US2 dataset review surfaces keep semantic review actionable, route clarification through AssistantChatPanel, and preserve explicit preview/mapping gates.
// @LAYER UI
// @RELATION DEPENDS_ON -> [SemanticLayerReview]
// @RELATION DEPENDS_ON -> [ExecutionMappingReview]
// @TEST_SCENARIO: semantic_review_surfaces_active_value_and_candidates -> Field-level semantic review shows provenance, candidates, and mutation callbacks.
// @TEST_SCENARIO: mapping_review_marks_row_focused_and_requires_explicit_approval -> Mapping review keeps warning approvals explicit and highlightable.
// @TEST_EDGE: external_fail -> Failed request surfaces inline recovery message.

import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent, waitFor } from "@testing-library/svelte";
import SemanticLayerReview from "../SemanticLayerReview.svelte";
import ExecutionMappingReview from "../ExecutionMappingReview.svelte";

vi.mock('$lib/i18n/index.svelte.js', () => ({
  t: {
    subscribe: (fn) => {
      fn({
        common: {
          error: "Common error",
          cancel: "Cancel",
          unknown: "Unknown",
          not_available: "N/A",
        },
        dataset_review: {
          assistant: {
            ask_ai_action: "✨ Ask AI",
            improve_action: "✨ Improve",
          },
          semantics: {
            eyebrow: "Semantic layer",
            title: "Review semantic field values",
            description: "Review semantic candidates",
            field_count_label: "Fields in review",
            empty: "No semantic fields",
            unknown_source: "Unknown source",
            active_value_label: "Active semantic value",
            provenance_label: "Provenance",
            confidence_label: "Confidence",
            confidence_unset: "No confidence rank",
            confidence_rank_label: "Rank",
            source_label: "Source",
            changed_by_label: "Changed by",
            locked_badge: "Locked",
            unlocked_badge: "Unlocked",
            conflict_badge: "Conflict",
            needs_review_badge: "Needs review",
            manual_verbose_name_label: "Manual verbose name",
            manual_description_label: "Manual description",
            manual_display_format_label: "Manual display format",
            manual_override_action: "Manual override",
            save_manual_action: "Save manual value",
            lock_action: "Lock field",
            unlock_action: "Unlock field",
            feedback_up_action: "Thumbs up",
            feedback_down_action: "Thumbs down",
            candidates_title: "Candidate options",
            candidates_empty: "No candidates",
            candidate_description_empty: "No candidate description",
            display_format_label: "Display format",
            score_label: "Score",
            apply_candidate_action: "Apply",
            apply_and_lock_action: "Apply and lock",
            empty_value: "No value",
            provenance: {
              unresolved: "Unresolved",
              dictionary_exact: "Dictionary exact match",
              manual_override: "Manual override",
            },
            candidate_status: {
              pending: "Pending",
            },
            messages: {
              saving: "Saving semantic decision...",
              save_failed: "Failed to save semantic decision.",
              candidate_applied: "Candidate value applied.",
            },
          },
          mapping: {
            eyebrow: "Template mapping",
            title: "Review filter-to-template mappings",
            description: "Verify imported values",
            state_label: "Mapping state",
            state: {
              Incomplete: "Incomplete",
              WarningApproval: "Approval required",
              Approved: "Approved",
            },
            pending_approvals_label: "Pending approvals",
            required_values_label: "Missing required values",
            empty: "No mappings",
            required_blockers_notice: "{count} required values missing",
            approval_notice: "{count} approvals needed",
            to_variable_label: "To variable",
            required_badge: "Required",
            approval_required_badge: "Approval required",
            approved_badge: "Approved",
            source_filter_label: "Source filter",
            source_value_label: "Source value",
            confidence_label: "Confidence",
            recovery_label: "Recovery",
            effective_value_label: "Effective value",
            method_label: "Method",
            approval_label: "Approval",
            warning_label: "Warning",
            transformation_note_label: "Transformation note",
            missing_required_value: "Missing required value",
            manual_value_label: "Manual effective value",
            manual_note_label: "Manual note",
            save_override_action: "Save manual override",
            manual_override_action: "Manual override",
            approve_action: "Approve mapping",
            approve_all_action: "Approve all pending mappings",
            approval_state: {
              pending: "Pending",
              approved: "Approved",
            },
            warning_level: {
              high: "High",
            },
            method: {
              heuristic_match: "Heuristic match",
              manual_override: "Manual override",
            },
            messages: {
              saving: "Saving mapping decision...",
              approval_saved: "Mapping approval recorded.",
              approval_failed: "Failed to save mapping approval.",
              override_saved: "Manual mapping override saved. Preview should be refreshed.",
              override_failed: "Failed to save manual mapping override.",
              required_value_missing: "Provide a required value before saving the manual override.",
            },
          },
        },
      });
      return () => {};
    },
  },
}));

vi.mock("$lib/api/datasetReview.js", () => ({
  requestDatasetReviewApi: vi.fn(),
}));

describe("Dataset review US2 workspace surfaces", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("semantic_review_surfaces_active_value_and_candidates", async () => {
    const { requestDatasetReviewApi } = await import("$lib/api/datasetReview.js");
    requestDatasetReviewApi.mockResolvedValue({
      field_id: "field-1",
      field_name: "customer_name",
      verbose_name: "Customer name",
      description: "Customer display name",
      display_format: "text",
      provenance: "dictionary_exact",
      source_id: "source-1",
      confidence_rank: 1,
      is_locked: false,
      has_conflict: false,
      needs_review: false,
      last_changed_by: "user",
      candidates: [],
      session_version: 5,
    });

    const onupdated = vi.fn();

    render(SemanticLayerReview, {
      sessionId: "session-1",
      sessionVersion: 4,
      semanticSources: [
        { source_id: "source-1", display_name: "Trusted dictionary", source_version: "v1" },
      ],
      fields: [
        {
          field_id: "field-1",
          field_name: "customer_name",
          field_kind: "dimension",
          verbose_name: "Customer name",
          description: "Resolved from trusted dictionary",
          display_format: "text",
          provenance: "dictionary_exact",
          source_id: "source-1",
          confidence_rank: 1,
          is_locked: false,
          has_conflict: true,
          needs_review: true,
          last_changed_by: "system",
          candidates: [
            {
              candidate_id: "candidate-1",
              match_type: "exact",
              confidence_score: 0.98,
              proposed_verbose_name: "Customer name",
              proposed_description: "Customer display name",
              proposed_display_format: "text",
              status: "pending",
            },
          ],
        },
      ],
      focusTarget: { target: "field:field-1", source: "test" },
      onupdated,
    });

    expect(screen.getByText("Review semantic field values")).toBeDefined();
    expect(screen.getByText("customer_name")).toBeDefined();
    expect(document.querySelector('[data-focus-target="field:field-1"]')).toBeTruthy();

    await fireEvent.click(screen.getByRole("button", { name: "Apply" }));

    await waitFor(() => {
      expect(requestDatasetReviewApi).toHaveBeenCalledWith(
        "/dataset-orchestration/sessions/session-1/fields/field-1/semantic",
        "PATCH",
        { candidate_id: "candidate-1", lock_field: false },
        4,
      );
    });

    expect(onupdated).toHaveBeenCalled();
    expect(screen.getByText("Candidate value applied.")).toBeDefined();
  });

  it("mapping_review_marks_row_focused_and_requires_explicit_approval", async () => {
    const { requestDatasetReviewApi } = await import("$lib/api/datasetReview.js");
    requestDatasetReviewApi.mockResolvedValue({
      mapping_id: "mapping-1",
      filter_id: "filter-1",
      variable_id: "variable-1",
      approval_state: "approved",
      requires_explicit_approval: true,
      warning_level: "high",
      mapping_method: "heuristic_match",
      effective_value: "EU",
      session_version: 6,
    });

    const onupdated = vi.fn();
    const onaskai = vi.fn();

    render(ExecutionMappingReview, {
      sessionId: "session-1",
      sessionVersion: 5,
      mappings: [
        {
          mapping_id: "mapping-1",
          filter_id: "filter-1",
          variable_id: "variable-1",
          approval_state: "pending",
          requires_explicit_approval: true,
          warning_level: "high",
          mapping_method: "heuristic_match",
          transformation_note: "Europe → EU",
          effective_value: "EU",
        },
      ],
      importedFilters: [
        {
          filter_id: "filter-1",
          filter_name: "region",
          display_name: "Region",
          raw_value: "Europe",
          confidence_state: "mostly_confirmed",
          recovery_status: "partial",
        },
      ],
      templateVariables: [
        {
          variable_id: "variable-1",
          variable_name: "region_code",
          is_required: true,
        },
      ],
      focusTarget: { target: "mapping:mapping-1", source: "test" },
      onupdated,
      onaskai,
    });

    expect(document.querySelector('[data-focus-target="mapping:mapping-1"]')).toBeTruthy();
    expect(screen.getByText("Approval required")).toBeDefined();

    await fireEvent.click(screen.getByRole("button", { name: "✨ Ask AI" }));
    expect(onaskai).toHaveBeenCalled();

    await fireEvent.click(screen.getByRole("button", { name: "Approve mapping" }));

    await waitFor(() => {
      expect(requestDatasetReviewApi).toHaveBeenCalledWith(
        "/dataset-orchestration/sessions/session-1/mappings/mapping-1/approve",
        "POST",
        { approval_note: "Europe → EU" },
        5,
      );
    });

    expect(onupdated).toHaveBeenCalledWith(
      expect.objectContaining({ preview_state: "unchanged" }),
    );
  });
});
// #endregion DatasetReviewUs2WorkspaceUxTests:Module
