import type { ComponentProps, ReactNode } from "react";
import { createRoot, type Root } from "react-dom/client";
import { act } from "react-dom/test-utils";
import { afterEach, describe, expect, it, vi } from "vitest";
import { ClientLogo } from "./ClientLogo";

vi.mock("../../../components/ui/avatar", () => ({
  Avatar: ({ children }: { children: ReactNode }) => (
    <div data-testid="avatar">{children}</div>
  ),
  AvatarImage: (props: ComponentProps<"img">) => <img alt="" {...props} />,
  AvatarFallback: ({ children }: { children: ReactNode }) => (
    <div data-testid="fallback">{children}</div>
  ),
}));

const roots: Root[] = [];

afterEach(() => {
  for (const root of roots.splice(0)) {
    act(() => {
      root.unmount();
    });
  }
  document.body.innerHTML = "";
});

function renderLogo(client: Parameters<typeof ClientLogo>[0]["client"]) {
  const container = document.createElement("div");
  document.body.appendChild(container);
  const root = createRoot(container);
  roots.push(root);

  act(() => {
    root.render(<ClientLogo client={client} />);
  });

  return container;
}

describe("ClientLogo", () => {
  it("renders the fallback icon when no logo url exists", () => {
    const container = renderLogo({
      name: "",
      type: "private",
      metadata: {},
    });

    expect(container.querySelectorAll("svg").length).toBeGreaterThan(0);
  });

  it("uses the logo image when a trimmed url is provided", () => {
    const container = renderLogo({
      name: "Gitea",
      type: "pkce",
      metadata: { logo_url: "  https://example.com/logo.png  " },
    });

    const image = container.querySelector("img");
    expect(image).not.toBeNull();
    expect(container.querySelector("[data-testid='fallback']")).not.toBeNull();
    expect(image?.getAttribute("alt")).toContain("Gitea");
    expect(image?.getAttribute("src")).toBe("https://example.com/logo.png");
  });
});
