"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp.call(b, prop))
      __defNormalProp(a, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    }
  return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
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 src_exports = {};
__export(src_exports, {
  Visualizer: () => Visualizer,
  default: () => src_default
});
module.exports = __toCommonJS(src_exports);
var import_buffer = __toESM(require("buffer"));
var import_browser = __toESM(require("process/browser"));
var import_console_browserify = __toESM(require("console-browserify"));
var buffer = {
  Buffer: import_buffer.default
};
var import_jsx_runtime = require("react/jsx-runtime");
var import_detail_side = __toESM(require("./component/detail-side"));
var import_store = require("./component/store");
var import_antd = require("antd");
var import_react = require("react");
var import_client = __toESM(require("react-dom/client"));
var import_react_resizable_panels = require("react-resizable-panels");
var import_color = require("./component/color");
var import_detail_panel = __toESM(require("./component/detail-panel"));
var import_global_hover_preview = __toESM(require("./component/global-hover-preview"));
var import_player = __toESM(require("./component/player"));
var import_sidebar = __toESM(require("./component/sidebar"));
var import_timeline = __toESM(require("./component/timeline"));
var import_index = require("./index.css");
var import_transform = require("./transform");
const { Dragger } = import_antd.Upload;
let globalRenderCount = 1;
function Visualizer(props) {
  const { onActiveTaskChange, dumps } = props;
  const executionDump = (0, import_store.useExecutionDump)((store) => store.dump);
  const executionDumpLoadId = (0, import_store.useExecutionDump)(
    (store) => store._executionDumpLoadId
  );
  const replayAllMode = (0, import_store.useExecutionDump)((store) => store.replayAllMode);
  const setReplayAllMode = (0, import_store.useExecutionDump)((store) => store.setReplayAllMode);
  const replayAllScripts = (0, import_store.useExecutionDump)(
    (store) => store.allExecutionAnimation
  );
  const insightWidth = (0, import_store.useExecutionDump)((store) => store.insightWidth);
  const insightHeight = (0, import_store.useExecutionDump)((store) => store.insightHeight);
  const setGroupedDump = (0, import_store.useExecutionDump)((store) => store.setGroupedDump);
  const reset = (0, import_store.useExecutionDump)((store) => store.reset);
  const [mainLayoutChangeFlag, setMainLayoutChangeFlag] = (0, import_react.useState)(0);
  const mainLayoutChangedRef = (0, import_react.useRef)(false);
  const dump = (0, import_store.useExecutionDump)((store) => store.dump);
  const setOnActiveTaskChange = (0, import_store.useExecutionDump)(
    (store) => store.setOnActiveTaskChange
  );
  (0, import_react.useEffect)(() => {
    if (dumps) {
      setGroupedDump(dumps[0]);
    }
    return () => {
      reset();
    };
  }, []);
  (0, import_react.useEffect)(() => {
    if (onActiveTaskChange) {
      setOnActiveTaskChange(onActiveTaskChange);
    }
    return () => {
      setOnActiveTaskChange(void 0);
    };
  }, [onActiveTaskChange]);
  (0, import_react.useEffect)(() => {
    let resizeThrottler = false;
    const onResize = () => {
      if (resizeThrottler) {
        return;
      }
      resizeThrottler = true;
      setTimeout(() => {
        resizeThrottler = false;
        setMainLayoutChangeFlag((prev) => prev + 1);
      }, 300);
    };
    window.addEventListener("resize", onResize);
    return () => {
      window.removeEventListener("resize", onResize);
    };
  }, []);
  const uploadProps = {
    name: "file",
    multiple: false,
    capture: false,
    customRequest: () => {
    },
    beforeUpload(file) {
      const ifValidFile = file.name.endsWith("web-dump.json");
      if (!ifValidFile) {
        import_antd.message.error("invalid file extension");
        return false;
      }
      const reader = new FileReader();
      reader.readAsText(file);
      reader.onload = (e) => {
        var _a;
        const result = (_a = e.target) == null ? void 0 : _a.result;
        if (typeof result === "string") {
          try {
            const data = JSON.parse(result);
            setGroupedDump(data[0]);
          } catch (e2) {
            import_console_browserify.default.error(e2);
            import_antd.message.error("failed to parse dump data", e2.message);
          }
        } else {
          import_antd.message.error("Invalid dump file");
        }
      };
      return false;
    }
  };
  let mainContent;
  if (dump && dump.executions.length === 0) {
    mainContent = /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "main-right", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      import_antd.Empty,
      {
        image: import_antd.Empty.PRESENTED_IMAGE_SIMPLE,
        description: "There is no task info in this dump file."
      }
    ) });
  } else if (!executionDump) {
    mainContent = /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "main-right uploader-wrapper", children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Dragger, __spreadProps(__spreadValues({ className: "uploader" }, uploadProps), { children: [
      /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", { className: "ant-upload-text", children: [
        "Click or drag the",
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)("b", { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("i", { children: ".web-dump.json" }) }),
        " ",
        "file into this area."
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("p", { className: "ant-upload-text", children: [
        "The latest dump file is usually placed in",
        " ",
        /* @__PURE__ */ (0, import_jsx_runtime.jsx)("b", { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("i", { children: "./midscene_run/report" }) })
      ] }),
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "ant-upload-text", children: "All data will be processed locally by the browser. No data will be sent to the server." })
    ] })) });
  } else {
    const content = replayAllMode ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "replay-all-mode-wrapper", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      import_player.default,
      {
        replayScripts: replayAllScripts,
        imageWidth: insightWidth,
        imageHeight: insightHeight
      },
      `${executionDumpLoadId}`
    ) }) : /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_react_resizable_panels.PanelGroup, { autoSaveId: "page-detail-layout-v2", direction: "horizontal", children: [
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_resizable_panels.Panel, { defaultSize: 75, maxSize: 95, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "main-content-container", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_detail_panel.default, {}) }) }),
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_resizable_panels.PanelResizeHandle, {}),
      /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_resizable_panels.Panel, { maxSize: 95, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "main-side", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_detail_side.default, {}) }) })
    ] });
    mainContent = /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
      import_react_resizable_panels.PanelGroup,
      {
        autoSaveId: "main-page-layout",
        direction: "horizontal",
        onLayout: () => {
          if (!mainLayoutChangedRef.current) {
            setMainLayoutChangeFlag((prev) => prev + 1);
          }
        },
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_resizable_panels.Panel, { maxSize: 95, defaultSize: 20, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "page-side", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_sidebar.default, {}) }) }),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
            import_react_resizable_panels.PanelResizeHandle,
            {
              onDragging: (isChanging) => {
                if (mainLayoutChangedRef.current && !isChanging) {
                  setMainLayoutChangeFlag((prev) => prev + 1);
                }
                mainLayoutChangedRef.current = isChanging;
              }
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_resizable_panels.Panel, { defaultSize: 80, maxSize: 95, children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "main-right", children: [
            /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_timeline.default, {}, mainLayoutChangeFlag),
            /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "main-content", children: content })
          ] }) })
        ]
      }
    );
  }
  const [containerHeight, setContainerHeight] = (0, import_react.useState)("100%");
  (0, import_react.useEffect)(() => {
    const ifInRspressPage = document.querySelector(".rspress-nav");
    const navHeightKey = "--rp-nav-height";
    const originalNavHeight = getComputedStyle(
      document.documentElement
    ).getPropertyValue(navHeightKey);
    if (ifInRspressPage) {
      const newNavHeight = "42px";
      setContainerHeight(`calc(100vh - ${newNavHeight})`);
      document.documentElement.style.setProperty(navHeightKey, newNavHeight);
    }
    return () => {
      if (ifInRspressPage) {
        document.documentElement.style.setProperty(
          navHeightKey,
          originalNavHeight
        );
      }
    };
  }, []);
  (0, import_react.useEffect)(() => {
    return () => {
      globalRenderCount += 1;
    };
  }, []);
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_antd.ConfigProvider, { theme: (0, import_color.globalThemeConfig)(), children: [
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      "div",
      {
        className: "page-container",
        style: { height: containerHeight },
        children: mainContent
      },
      `render-${globalRenderCount}`
    ),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_global_hover_preview.default, {})
  ] });
}
function mount(id) {
  var _a;
  const element = document.getElementById(id);
  if (!element) {
    throw new Error(`failed to get element for id: ${id}`);
  }
  const root = import_client.default.createRoot(element);
  const dumpElements = document.querySelectorAll(
    'script[type="ui_tars_web_dump"]'
  );
  if (dumpElements.length === 1 && ((_a = dumpElements[0].textContent) == null ? void 0 : _a.trim()) === "") {
    const errorPanel = /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      "div",
      {
        style: {
          width: "100%",
          height: "100%",
          padding: "100px",
          boxSizing: "border-box"
        },
        children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
          import_antd.Alert,
          {
            message: "Midscene.js - Error",
            description: "There is no dump data to display.",
            type: "error",
            showIcon: true
          }
        )
      }
    );
    return root.render(errorPanel);
  }
  const reportDump = [];
  Array.from(dumpElements).filter((el) => {
    const textContent = el.textContent;
    if (!textContent) {
      import_console_browserify.default.warn("empty content in script tag", el);
    }
    return !!textContent;
  }).forEach((el) => {
    const attributes = {};
    Array.from(el.attributes).forEach((attr) => {
      const { name, value } = attr;
      const valueDecoded = decodeURIComponent(value);
      if (name.startsWith("playwright_")) {
        attributes[attr.name] = valueDecoded;
      }
    });
    const content = el.textContent;
    let jsonContent;
    try {
      const contentObj = JSON.parse(content);
      import_console_browserify.default.log("contentObj", contentObj);
      import_console_browserify.default.log("Array.isArray(contentObj)", Array.isArray(contentObj));
      if (Array.isArray(contentObj)) {
        contentObj.forEach((c) => {
          jsonContent = (0, import_transform.transformComputerUseDataToDump)(c);
          jsonContent.attributes = attributes;
          reportDump.push(jsonContent);
        });
      } else {
        jsonContent = (0, import_transform.transformComputerUseDataToDump)(contentObj);
        jsonContent.attributes = attributes;
        reportDump.push(jsonContent);
      }
    } catch (e) {
      import_console_browserify.default.error(el);
      import_console_browserify.default.error("failed to parse json content", e);
    }
  });
  root.render(/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Visualizer, { dumps: reportDump }));
}
var src_default = {
  mount,
  Visualizer
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  Visualizer
});
