// #region ProfilePreferencesIntegrationTest [C:2] [TYPE Module]
// @COMPLEXITY: 3
// @SEMANTICS: tests, profile, integration, load, save
// @PURPOSE: Verifies profile page loads preferences and saves them.
// @LAYER UI (Tests)
// @RELATION DEPENDS_ON -> [ProfilePage]

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

const mockedApi = /** @type {any} */ (api);
const mockedAddToast = /** @type {any} */ (addToast);

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

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

vi.mock("$lib/auth/store.svelte.js", () => ({
  auth: { subscribe: (run) => { run({ current: { user: { id: "u-1" } } }); return () => {}; } },
}));

vi.mock('$lib/i18n/index.svelte.js', () => ({
  t: {
    subscribe: (run) => {
      run({
        common: { save: "Save", cancel: "Cancel" },
        nav: { profile: "Profile", dashboards: "Dashboards", datasets: "Datasets", reports: "Reports" },
        profile: {
          saved: "Preferences saved",
          preferences: "Preferences",
          start_page: "Start page",
        },
      });
      return () => {};
    },
  },
  _: vi.fn((key) => key),
}));

describe("profile-preferences.integration", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockedApi.getProfilePreferences.mockResolvedValue({
      status: "success",
      preference: {
        user_id: "u-1",
        start_page: "dashboards",
      },
    });
  });

  it("loads preferences and renders the profile form", async () => {
    render(ProfilePage);

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

    expect(screen.getByText("Profile")).toBeDefined();
    expect(screen.getByText("Preferences")).toBeDefined();
    expect(screen.getByText("Start page")).toBeDefined();
    const select = /** @type {HTMLSelectElement} */ (screen.getByRole("combobox"));
    expect(select.value).toBe("dashboards");
  });

  it("saves preferences via API and shows success toast", async () => {
    mockedApi.postApi.mockResolvedValue({ status: "success" });

    render(ProfilePage);

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

    const select = /** @type {HTMLSelectElement} */ (screen.getByRole("combobox"));
    await fireEvent.change(select, { target: { value: "datasets" } });

    await fireEvent.click(screen.getByText("Save"));

    await waitFor(() => {
      expect(mockedApi.postApi).toHaveBeenCalledWith("/profile/preferences", {
        preference: expect.objectContaining({ start_page: "datasets" }),
      });
    });

    expect(mockedAddToast).toHaveBeenCalledWith("Preferences saved", "success");
  });
});

// #endregion ProfilePreferencesIntegrationTest
