/**
 * @vitest-environment jsdom
 */
// #region SourceIntakePanelUxTests:Module [TYPE Function]
// @SEMANTICS: dataset-review, source-intake, ux-tests, validation, recovery
// @PURPOSE: Verify source intake entry paths, validation feedback, and submit payload behavior for US1.
// @LAYER UI
// @RELATION DEPENDS_ON -> [SourceIntakePanel]
// @UX_STATE: Idle -> Default intake renders both entry paths and waits for user input.
// @UX_STATE: Validating -> Inline feedback confirms recognized links and local payload validation.
// @UX_STATE: Rejected -> Invalid source input remains local and exposes recovery guidance.
// @TEST_CONTRACT: SourceIntakePanelProps -> ObservableIntakeUX
// @TEST_SCENARIO: invalid_superset_link_shows_rejected_state -> Invalid URL input keeps submit local and shows rejection feedback.
// @TEST_SCENARIO: recognized_superset_link_submits_payload -> Recognized link path submits normalized payload.
// @TEST_SCENARIO: dataset_selection_mode_changes_cta -> Dataset selection path switches CTA and payload source kind.
// @TEST_EDGE: missing_environment -> Required environment guard blocks submit.
// @TEST_EDGE: invalid_type -> Invalid Superset URL shows recovery hint.
// @TEST_EDGE: external_fail -> Submit callback failure is rendered inline.
// @TEST_INVARIANT: intake_contract_remains_observable -> VERIFIED_BY: [invalid_superset_link_shows_rejected_state, recognized_superset_link_submits_payload, dataset_selection_mode_changes_cta]

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

vi.mock('$lib/i18n/index.svelte.js', () => ({
  t: {
    subscribe: (fn) => {
      fn({
        common: {
          choose_environment: "Choose environment",
          error: "Common error",
        },
        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",
          },
        },
      });
      return () => {};
    },
  },
}));

describe("SourceIntakePanel UX Contract", () => {
  const environments = [{ id: "env-1", name: "DEV" }];

  it("invalid_superset_link_shows_rejected_state", async () => {
    const onsubmit = vi.fn();
    const { container } = render(SourceIntakePanel, {
      environments,
      onsubmit,
    });

    await fireEvent.change(screen.getByRole("combobox"), {
      target: { value: "env-1" },
    });
    await fireEvent.input(screen.getByPlaceholderText("https://superset.local/dashboard/10"), {
      target: { value: "not-a-url" },
    });
    await fireEvent.submit(container.querySelector("form"));

    expect(onsubmit).not.toHaveBeenCalled();
    expect(screen.getByText("Rejected")).toBeDefined();
    expect(screen.getByText("Superset link must start with http")).toBeDefined();
  });

  it("recognized_superset_link_submits_payload", async () => {
    const onsubmit = vi.fn().mockResolvedValue(undefined);
    const { container } = render(SourceIntakePanel, {
      environments,
      selectedEnvironmentId: "env-1",
      acknowledgment: "Recognized Superset link",
      onsubmit,
    });

    await fireEvent.input(screen.getByPlaceholderText("https://superset.local/dashboard/10"), {
      target: { value: "https://demo.local/superset/dashboard/42 " },
    });
    await fireEvent.submit(container.querySelector("form"));

    expect(onsubmit).toHaveBeenCalledWith({
      environment_id: "env-1",
      source_input: "https://demo.local/superset/dashboard/42",
      source_kind: "superset_link",
    });
    expect(screen.getByText("Recognized Superset link")).toBeDefined();
  });

  it("dataset_selection_mode_changes_cta", async () => {
    const onsubmit = vi.fn().mockResolvedValue(undefined);
    const { container } = render(SourceIntakePanel, {
      environments,
      onsubmit,
    });

    await fireEvent.click(
      screen.getByRole("button", {
        name: "Dataset selection Enter dataset ref",
      }),
    );
    await fireEvent.change(screen.getByRole("combobox"), {
      target: { value: "env-1" },
    });
    await fireEvent.input(screen.getByPlaceholderText("public.sales"), {
      target: { value: " public.sales " },
    });
    await fireEvent.submit(container.querySelector("form"));

    expect(onsubmit).toHaveBeenCalledWith({
      environment_id: "env-1",
      source_input: "public.sales",
      source_kind: "dataset_selection",
    });
  });

  it("external_fail_renders_inline_error", async () => {
    const onsubmit = vi.fn().mockRejectedValue(new Error("Backend rejected source"));
    const { container } = render(SourceIntakePanel, {
      environments,
      selectedEnvironmentId: "env-1",
      onsubmit,
    });

    await fireEvent.input(screen.getByPlaceholderText("https://superset.local/dashboard/10"), {
      target: { value: "https://demo.local/dashboard/42" },
    });
    await fireEvent.submit(container.querySelector("form"));

    expect(screen.getByText("Backend rejected source")).toBeDefined();
  });
});
// #endregion SourceIntakePanelUxTests:Module
