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";
import { Badge } from "./badge";
import { Input } from "./input";
import { Label } from "./label";
import { Separator } from "./separator";
import { Switch } from "./switch";
import {
  Table,
  TableBody,
  TableCaption,
  TableCell,
  TableFooter,
  TableHead,
  TableHeader,
  TableRow,
} from "./table";
import { Textarea } from "./textarea";

globalThis.IS_REACT_ACT_ENVIRONMENT = true;

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("orgfront UI wrappers", () => {
  it("renders form, badge, avatar, switch, separator, and table wrappers", async () => {
    const root = await render(
      <div>
        <Badge className="custom-badge" variant="secondary">
          Active
        </Badge>
        <Avatar className="custom-avatar">
          <AvatarImage alt="Org user" src="/avatar.png" />
          <AvatarFallback>OU</AvatarFallback>
        </Avatar>
        <Label className="custom-label" htmlFor="name">
          Name
        </Label>
        <Input id="name" className="custom-input" defaultValue="Org User" />
        <Textarea className="custom-textarea" defaultValue="Memo" />
        <Switch className="custom-switch" defaultChecked />
        <Separator className="custom-separator" />
        <Table className="custom-table">
          <TableCaption>Members</TableCaption>
          <TableHeader>
            <TableRow>
              <TableHead>Name</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            <TableRow>
              <TableCell>Org User</TableCell>
            </TableRow>
          </TableBody>
          <TableFooter>
            <TableRow>
              <TableCell>Total</TableCell>
            </TableRow>
          </TableFooter>
        </Table>
      </div>,
    );

    expect(container?.textContent).toContain("Active");
    expect(container?.textContent).toContain("OU");
    expect(container?.querySelector(".custom-input")).not.toBeNull();
    expect(container?.querySelector(".custom-switch")).not.toBeNull();
    expect(container?.querySelector(".custom-separator")).not.toBeNull();
    expect(container?.textContent).toContain("Members");
    expect(container?.textContent).toContain("Total");

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