import type React from "react";
import { act } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, describe, expect, it } from "vitest";
import { Avatar, AvatarFallback, AvatarImage } from "./avatar";

let container: HTMLDivElement | null = null;

const render = async (element: React.ReactElement) => {
  container = document.createElement("div");
  document.body.appendChild(container);
  const root = createRoot(container);
  await act(async () => {
    root.render(element);
  });
  return root;
};

afterEach(() => {
  if (container) {
    container.remove();
    container = null;
  }
});

describe("Avatar", () => {
  it("renders image and fallback with merged classes", async () => {
    const root = await render(
      <Avatar className="custom-root" data-testid="avatar">
        <AvatarImage
          alt="Admin user"
          className="custom-image"
          src="/avatar.png"
        />
        <AvatarFallback className="custom-fallback">AU</AvatarFallback>
      </Avatar>,
    );

    const avatar = container?.querySelector("[data-testid='avatar']");
    const fallback = container?.textContent;

    expect(avatar?.className).toContain("custom-root");
    expect(fallback).toContain("AU");

    await act(async () => {
      root.unmount();
    });
  });
});
