import { jsx, jsxs } from "react/jsx-runtime";
import { Fragment, forwardRef, useRef, isValidElement, act } from "react";
import { renderToReadableStream } from "react-dom/server";
import { JSDOM } from "jsdom";
import { render, screen } from "@testing-library/react";
import "@testing-library/jest-dom";
import { ServerInsertedHTMLContext } from "next/navigation";
import { ReactRuntime } from "../../../../react";
import { MakeswiftComponent } from "../../../../runtimes/react/components/MakeswiftComponent";
import { Page } from "../../page";
import { isServer } from "../../../../utils/is-server";
import * as Testing from "../../../testing";
const ROOT_ID = "00000000-0000-0000-0000-000000000000";
const ELEMENT_ID = "11111111-1111-1111-1111-111111111111";
const renderProp = (prop) => prop === void 0 ? "undefined" : isValidElement(prop) ? prop : JSON.stringify(prop);
const propSnapshot = (prop) => prop?.childElementCount ? prop.childNodes : parseStringifiedProp(prop?.textContent ?? "");
const parseStringifiedProp = (prop) => prop === "undefined" ? void 0 : JSON.parse(prop);
async function streamToString(stream) {
  const reader = stream.getReader();
  const decoder = new TextDecoder();
  let result = "";
  while (true) {
    const { done, value } = await reader.read();
    if (done)
      break;
    result += decoder.decode(value, { stream: true });
  }
  return result;
}
async function renderToString(element) {
  return await streamToString(await renderToReadableStream(element));
}
async function serverSideRender(children) {
  const serverInsertedCallbacks = [];
  const elementTree = /* @__PURE__ */ jsx(ServerInsertedHTMLContext.Provider, { value: (handler) => serverInsertedCallbacks.push(handler), children });
  const elementsHTML = await renderToString(elementTree);
  const serverInsertedNodes = serverInsertedCallbacks.map((callback, index) => /* @__PURE__ */ jsx(Fragment, { children: callback() }, "__next_server_inserted__" + index));
  const headHTML = await renderToString(serverInsertedNodes);
  const dom = new JSDOM(
    `<!DOCTYPE html><head>${headHTML}</head><body><div id="root">${elementsHTML}</div></body></div>`,
    {
      runScripts: "dangerously"
    }
  );
  return dom.window.document;
}
async function testPageControlPropRendering(controlDefinition, {
  toData,
  value,
  locale,
  cacheData,
  expectedRenders,
  registerComponents,
  action,
  rootElements = []
}) {
  const controlData = value !== void 0 ? toData ? toData(value) : controlDefinition.toData(value) : void 0;
  const testComponentMeta = {
    type: "TestComponent",
    label: "Test Component"
  };
  const testId = "test-id";
  const renderCountTestId = "render-count-test-id";
  const elementData = {
    key: ELEMENT_ID,
    type: testComponentMeta.type,
    props: {
      propKey: controlData
    }
  };
  const runtime = new ReactRuntime();
  registerComponents?.(runtime);
  runtime.registerComponent(
    forwardRef(({ propKey }, ref) => {
      const renderCount = useRef(0);
      ++renderCount.current;
      return /* @__PURE__ */ jsxs("div", { ref, children: [
        /* @__PURE__ */ jsx("div", { "data-testid": renderCountTestId, children: renderCount.current }),
        /* @__PURE__ */ jsx("div", { "data-testid": testId, children: renderProp(propKey) })
      ] });
    }),
    {
      ...testComponentMeta,
      props: {
        propKey: controlDefinition
      }
    }
  );
  const testElementTree = (component) => /* @__PURE__ */ jsx(Testing.ReactProvider, { runtime, children: component });
  if (!isServer()) {
    const rootElementData = Testing.createRootComponent(
      [elementData, ...rootElements],
      ROOT_ID
    );
    const snapshot = Testing.createMakeswiftPageSnapshot(rootElementData, { locale, cacheData });
    await act(async () => render(testElementTree(/* @__PURE__ */ jsx(Page, { snapshot }))));
    if (action) {
      await act(async () => {
        await action(screen.getByTestId(testId));
      });
    }
    expect(snapshot).toMatchSnapshot("snapshot");
    expect(propSnapshot(screen.getByTestId(testId))).toMatchSnapshot("resolvedValue");
    if (expectedRenders != null) {
      expect(Number(screen.getByTestId(renderCountTestId).textContent)).toBe(expectedRenders);
    }
  } else {
    console.assert(action == null);
    console.assert(rootElements.length === 0);
    const snapshot = Testing.createMakeswiftComponentSnapshot(elementData, { locale, cacheData });
    const elementTree = testElementTree(
      /* @__PURE__ */ jsx(MakeswiftComponent, { snapshot, ...testComponentMeta })
    );
    const document = await serverSideRender(elementTree);
    const getByTestId = (id) => document.querySelector(`[data-testid="${id}"]`);
    expect(propSnapshot(getByTestId(testId))).toMatchSnapshot("resolvedValue");
    expect([...document.querySelectorAll("style")].map((n) => n.textContent)).toMatchSnapshot(
      "component styles"
    );
    expect(Number(getByTestId(renderCountTestId)?.textContent)).toBe(1);
  }
}
export {
  testPageControlPropRendering
};
//# sourceMappingURL=page-control-prop-rendering.js.map