"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var page_control_prop_rendering_exports = {};
__export(page_control_prop_rendering_exports, {
  testPageControlPropRendering: () => testPageControlPropRendering
});
module.exports = __toCommonJS(page_control_prop_rendering_exports);
var import_jsx_runtime = require("react/jsx-runtime");
var import_react = require("react");
var import_server = require("react-dom/server");
var import_jsdom = require("jsdom");
var import_react2 = require("@testing-library/react");
var import_jest_dom = require("@testing-library/jest-dom");
var import_navigation = require("next/navigation");
var import_react4 = require("../../../../react");
var import_MakeswiftComponent = require("../../../../runtimes/react/components/MakeswiftComponent");
var import_page = require("../../page");
var import_is_server = require("../../../../utils/is-server");
var Testing = __toESM(require("../../../testing"));
const ROOT_ID = "00000000-0000-0000-0000-000000000000";
const ELEMENT_ID = "11111111-1111-1111-1111-111111111111";
const renderProp = (prop) => prop === void 0 ? "undefined" : (0, import_react.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 (0, import_server.renderToReadableStream)(element));
}
async function serverSideRender(children) {
  const serverInsertedCallbacks = [];
  const elementTree = /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_navigation.ServerInsertedHTMLContext.Provider, { value: (handler) => serverInsertedCallbacks.push(handler), children });
  const elementsHTML = await renderToString(elementTree);
  const serverInsertedNodes = serverInsertedCallbacks.map((callback, index) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react.Fragment, { children: callback() }, "__next_server_inserted__" + index));
  const headHTML = await renderToString(serverInsertedNodes);
  const dom = new import_jsdom.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 import_react4.ReactRuntime();
  registerComponents?.(runtime);
  runtime.registerComponent(
    (0, import_react.forwardRef)(({ propKey }, ref) => {
      const renderCount = (0, import_react.useRef)(0);
      ++renderCount.current;
      return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { ref, children: [
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { "data-testid": renderCountTestId, children: renderCount.current }),
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { "data-testid": testId, children: renderProp(propKey) })
      ] });
    }),
    {
      ...testComponentMeta,
      props: {
        propKey: controlDefinition
      }
    }
  );
  const testElementTree = (component) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Testing.ReactProvider, { runtime, children: component });
  if (!(0, import_is_server.isServer)()) {
    const rootElementData = Testing.createRootComponent(
      [elementData, ...rootElements],
      ROOT_ID
    );
    const snapshot = Testing.createMakeswiftPageSnapshot(rootElementData, { locale, cacheData });
    await (0, import_react.act)(async () => (0, import_react2.render)(testElementTree(/* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_page.Page, { snapshot }))));
    if (action) {
      await (0, import_react.act)(async () => {
        await action(import_react2.screen.getByTestId(testId));
      });
    }
    expect(snapshot).toMatchSnapshot("snapshot");
    expect(propSnapshot(import_react2.screen.getByTestId(testId))).toMatchSnapshot("resolvedValue");
    if (expectedRenders != null) {
      expect(Number(import_react2.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__ */ (0, import_jsx_runtime.jsx)(import_MakeswiftComponent.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);
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  testPageControlPropRendering
});
//# sourceMappingURL=page-control-prop-rendering.js.map