// [DEF:frontend.src.routes.profile.__tests__.profile_settings_state_integration:Module]
// @TIER: STANDARD
// @SEMANTICS: tests, profile, integration, preload, cancel, reload
// @PURPOSE: Verifies profile settings preload, cancel without persistence, and saved-state reload behavior.
// @LAYER: UI (Tests)
// @RELATION: TESTS -> frontend/src/routes/profile/+page.svelte

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

import ProfilePage from "../+page.svelte";
import { api } from "$lib/api.js";
import { initializeEnvironmentContext } from "$lib/stores/environmentContext.js";

const mockedApi = /** @type {any} */ (api);
const mockedInitializeEnvironmentContext =
  /** @type {any} */ (initializeEnvironmentContext);

vi.mock("$lib/api.js", () => ({
  api: {
    getProfilePreferences: vi.fn(),
    lookupSupersetAccounts: vi.fn(),
    updateProfilePreferences: vi.fn(),
  },
}));

vi.mock("$lib/toasts", () => ({
  addToast: vi.fn(),
}));

vi.mock("$lib/stores/environmentContext.js", () => {
  const context = writable({
    environments: [{ id: "dev", name: "Development" }],
    selectedEnvId: "dev",
    isLoading: false,
    isLoaded: true,
    error: null,
  });

  return {
    environmentContextStore: { subscribe: context.subscribe },
    initializeEnvironmentContext: vi.fn().mockResolvedValue(undefined),
  };
});

vi.mock("$lib/i18n", () => ({
  t: {
    subscribe: (run) => {
      run({
        common: { cancel: "Cancel" },
        profile: {
          title: "Profile",
          description: "Manage your profile preferences, Git integration, and access view.",
          dashboard_preferences: "Dashboard Preferences",
          superset_environment: "Superset Environment",
          superset_environment_placeholder: "Select environment",
          superset_account: "Your Apache Superset Account",
          superset_account_placeholder: "Enter your Apache Superset username",
          lookup_loading: "Loading Superset accounts...",
          lookup_error:
            "Cannot load Superset accounts for this environment right now. You can enter username manually.",
          lookup_button: "Lookup",
          lookup_search_placeholder: "Search account candidates",
          lookup_no_results:
            "No account candidates found. You can enter username manually.",
          show_only_my_dashboards: "Show only my dashboards by default",
          save_preferences: "Save Preferences",
          save_success: "Preferences saved",
          save_error: "Failed to save preferences. Please try again.",
        },
      });
      return () => {};
    },
  },
  _: vi.fn((key) => key),
}));

describe("profile-settings-state.integration", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockedApi.lookupSupersetAccounts.mockResolvedValue({
      status: "success",
      environment_id: "dev",
      page_index: 0,
      page_size: 20,
      total: 0,
      items: [],
    });
  });

  it("preloads saved values and cancel restores snapshot without persistence", async () => {
    mockedApi.getProfilePreferences.mockResolvedValue({
      status: "success",
      preference: {
        user_id: "u-1",
        superset_username: "john_doe",
        show_only_my_dashboards: true,
        git_username: null,
        git_email: null,
        has_git_personal_access_token: false,
        git_personal_access_token_masked: null,
        start_page: "dashboards",
        auto_open_task_drawer: true,
        dashboards_table_density: "comfortable",
      },
      security: {
        read_only: true,
        auth_source: "adfs",
        current_role: "Data Engineer",
        role_source: "adfs",
        roles: ["Data Engineer"],
        permissions: [],
      },
    });

    render(ProfilePage);

    await waitFor(() => {
      expect(mockedInitializeEnvironmentContext).toHaveBeenCalledTimes(1);
      expect(mockedApi.getProfilePreferences).toHaveBeenCalledTimes(1);
    });

    const usernameInput = /** @type {HTMLInputElement} */ (
      screen.getByPlaceholderText("Enter your Apache Superset username")
    );
    const toggleInput = /** @type {HTMLInputElement} */ (
      screen.getByLabelText("Show only my dashboards by default")
    );

    expect(usernameInput.value).toBe("john_doe");
    expect(toggleInput.checked).toBe(true);

    await fireEvent.input(usernameInput, { target: { value: "temp_user" } });
    await fireEvent.click(toggleInput); // true -> false
    expect(usernameInput.value).toBe("temp_user");
    expect(toggleInput.checked).toBe(false);

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

    await waitFor(() => {
      expect(usernameInput.value).toBe("john_doe");
      expect(toggleInput.checked).toBe(true);
    });

    expect(mockedApi.updateProfilePreferences).not.toHaveBeenCalled();
  });

  it("reloads persisted values after successful save", async () => {
    mockedApi.getProfilePreferences
      .mockResolvedValueOnce({
        status: "success",
        preference: {
          user_id: "u-1",
          superset_username: "john_doe",
          show_only_my_dashboards: true,
          git_username: null,
          git_email: null,
          has_git_personal_access_token: false,
          git_personal_access_token_masked: null,
          start_page: "dashboards",
          auto_open_task_drawer: true,
          dashboards_table_density: "comfortable",
        },
        security: {
          read_only: true,
          auth_source: "adfs",
          current_role: "Data Engineer",
          role_source: "adfs",
          roles: ["Data Engineer"],
          permissions: [],
        },
      })
      .mockResolvedValueOnce({
        status: "success",
        preference: {
          user_id: "u-1",
          superset_username: "new_user",
          show_only_my_dashboards: true,
          git_username: null,
          git_email: null,
          has_git_personal_access_token: false,
          git_personal_access_token_masked: null,
          start_page: "dashboards",
          auto_open_task_drawer: true,
          dashboards_table_density: "comfortable",
        },
        security: {
          read_only: true,
          auth_source: "adfs",
          current_role: "Data Engineer",
          role_source: "adfs",
          roles: ["Data Engineer"],
          permissions: [],
        },
      });

    mockedApi.updateProfilePreferences.mockResolvedValue({
      status: "success",
      preference: {
        user_id: "u-1",
        superset_username: "new_user",
        show_only_my_dashboards: true,
        git_username: null,
        git_email: null,
        has_git_personal_access_token: false,
        git_personal_access_token_masked: null,
        start_page: "dashboards",
        auto_open_task_drawer: true,
        dashboards_table_density: "comfortable",
      },
      security: {
        read_only: true,
        auth_source: "adfs",
        current_role: "Data Engineer",
        role_source: "adfs",
        roles: ["Data Engineer"],
        permissions: [],
      },
    });

    const firstRender = render(ProfilePage);

    await waitFor(() => {
      expect(mockedApi.getProfilePreferences).toHaveBeenCalledTimes(1);
    });

    const usernameInput = /** @type {HTMLInputElement} */ (
      screen.getByPlaceholderText("Enter your Apache Superset username")
    );
    await fireEvent.input(usernameInput, { target: { value: "new_user" } });

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

    await waitFor(() => {
      expect(mockedApi.updateProfilePreferences).toHaveBeenCalledWith({
        superset_username: "new_user",
        show_only_my_dashboards: true,
        git_username: null,
        git_email: null,
        start_page: "dashboards",
        auto_open_task_drawer: true,
        dashboards_table_density: "comfortable",
      });
    });

    firstRender.unmount();

    render(ProfilePage);

    await waitFor(() => {
      expect(mockedApi.getProfilePreferences).toHaveBeenCalledTimes(2);
    });

    const reloadedInput = /** @type {HTMLInputElement} */ (
      screen.getByPlaceholderText("Enter your Apache Superset username")
    );
    const reloadedToggle = /** @type {HTMLInputElement} */ (
      screen.getByLabelText("Show only my dashboards by default")
    );

    expect(reloadedInput.value).toBe("new_user");
    expect(reloadedToggle.checked).toBe(true);
  });
});

// [/DEF:frontend.src.routes.profile.__tests__.profile_settings_state_integration:Module]