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

import { ProfilePageView } from "@/components/dashboard/profile/profile-page-view";

const { refetch, useProfile } = vi.hoisted(() => ({ refetch: vi.fn(), useProfile: vi.fn() }));

vi.mock("next-intl", () => ({ useTranslations: () => (key: string) => key }));
vi.mock("@/components/dashboard/profile/profile-api", () => ({ useProfile }));
vi.mock("@/components/dashboard/profile/profile-edit-dialog", () => ({ ProfileEditDialog: () => null }));
vi.mock("@/components/dashboard/profile/profile-contact-dialog", () => ({ ProfileContactDialog: () => null }));
vi.mock("@/components/dashboard/profile/profile-password-dialog", () => ({ ProfilePasswordDialog: () => null }));

describe("ProfilePageView", () => {
  it("renders live fields without fixture fallbacks", () => {
    useProfile.mockReturnValue({ profile: { id: 1, first_name: "Mohammed", last_name: "Alotaibi", email: "m@maaal.com" }, isLoading: false, refetch });
    render(<ProfilePageView />);
    expect(screen.getByText("Mohammed")).toBeInTheDocument();
    expect(screen.getByText("Alotaibi")).toBeInTheDocument();
    expect(screen.getByText("m@maaal.com")).toBeInTheDocument();
    expect(screen.queryByText("Mohamed_12")).not.toBeInTheDocument();
  });

  it("renders the name from a backend role object", () => {
    useProfile.mockReturnValue({
      profile: {
        id: 1,
        first_name: "Mohammed",
        role: { id: 2, name: "Administrator", slug: "administrator" },
      },
      isLoading: false,
      refetch,
    });

    render(<ProfilePageView />);

    expect(screen.getByText("Administrator")).toBeInTheDocument();
  });

  it("keeps social links inside the Figma basic-information card", () => {
    useProfile.mockReturnValue({
      profile: {
        id: 1,
        first_name: "Mohammed",
        linkedin_url: "https://linkedin.com/in/m",
        x_url: "https://x.com/m",
      },
      isLoading: false,
      refetch,
    });

    render(<ProfilePageView />);

    const basicCard = screen.getByRole("heading", { name: "sections.basic" }).closest("section")!;
    expect(within(basicCard).getByText("https://linkedin.com/in/m")).toBeInTheDocument();
    expect(within(basicCard).getByText("https://x.com/m")).toBeInTheDocument();
  });

  it("renders loading and retry states", () => {
    useProfile.mockReturnValueOnce({ isLoading: true, refetch });
    const { rerender } = render(<ProfilePageView />);
    expect(screen.getByRole("status")).toBeInTheDocument();
    useProfile.mockReturnValue({ isLoading: false, error: new Error("Unavailable"), refetch });
    rerender(<ProfilePageView />);
    fireEvent.click(screen.getByRole("button", { name: /actions.retry/ }));
    expect(refetch).toHaveBeenCalled();
  });
});
