/* @vitest-environment jsdom */

import { act } from "react";
import { hydrateRoot, type Root } from "react-dom/client";
import { renderToString } from "react-dom/server";
import { afterEach, describe, expect, it } from "vitest";

import { SplashButton } from "../splash-button";

describe("SplashButton hydration", () => {
  let root: Root | null = null;

  afterEach(async () => {
    if (root) {
      await act(async () => root?.unmount());
      root = null;
    }
    document.body.innerHTML = "";
  });

  it("stays enabled with stable text during hydration", async () => {
    const tree = <SplashButton onStartChat={() => undefined} />;
    const container = document.createElement("div");
    const hydrationErrors: unknown[] = [];
    container.innerHTML = renderToString(tree);
    document.body.append(container);

    expect(container.querySelector("button")?.disabled).toBe(false);
    expect(container.textContent).toContain("Start Chatting");

    await act(async () => {
      root = hydrateRoot(container, tree, {
        onRecoverableError: (error) => hydrationErrors.push(error),
      });
    });

    expect(hydrationErrors).toEqual([]);
    expect(container.querySelector("button")?.disabled).toBe(false);
    expect(container.textContent).toContain("Start Chatting");
  });
});
