// #region ProfileSettingsStateIntegrationTest [C:2] [TYPE Module]
// @COMPLEXITY: 3
// @SEMANTICS: tests, profile, integration, load, change, save
// @PURPOSE: Verifies profile loads preferences, allows changes, and saves correctly.
// @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-settings-state.integration", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockedApi.getProfilePreferences.mockResolvedValue({
      status: "success",
      preference: {
        user_id: "u-1",
        start_page: "dashboards",
      },
    });
  });

  it("loads saved preferences and displays them", async () => {
    render(ProfilePage);

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

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

  it("saves changed preferences 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: "reports" } });

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

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

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

// #endregion ProfileSettingsStateIntegrationTest
