var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
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));
import Buffer2 from "buffer";
import processBrowser from "process/browser";
import console from "console-browserify";
var buffer = {
  Buffer: Buffer2
};
import { jsx, jsxs } from "react/jsx-runtime";
import DetailSide from "./component/detail-side";
import { useExecutionDump } from "./component/store";
import { Alert, ConfigProvider, Empty, Upload, message } from "antd";
import { useEffect, useRef, useState } from "react";
import ReactDOM from "react-dom/client";
import { Panel, PanelGroup, PanelResizeHandle } from "react-resizable-panels";
import { globalThemeConfig } from "./component/color";
import DetailPanel from "./component/detail-panel";
import GlobalHoverPreview from "./component/global-hover-preview";
import Player from "./component/player";
import Sidebar from "./component/sidebar";
import Timeline from "./component/timeline";
import "./index.css";
import { transformComputerUseDataToDump } from "./transform";
const { Dragger } = Upload;
let globalRenderCount = 1;
function Visualizer(props) {
  const { onActiveTaskChange, dumps } = props;
  const executionDump = useExecutionDump((store) => store.dump);
  const executionDumpLoadId = useExecutionDump(
    (store) => store._executionDumpLoadId
  );
  const replayAllMode = useExecutionDump((store) => store.replayAllMode);
  const setReplayAllMode = useExecutionDump((store) => store.setReplayAllMode);
  const replayAllScripts = useExecutionDump(
    (store) => store.allExecutionAnimation
  );
  const insightWidth = useExecutionDump((store) => store.insightWidth);
  const insightHeight = useExecutionDump((store) => store.insightHeight);
  const setGroupedDump = useExecutionDump((store) => store.setGroupedDump);
  const reset = useExecutionDump((store) => store.reset);
  const [mainLayoutChangeFlag, setMainLayoutChangeFlag] = useState(0);
  const mainLayoutChangedRef = useRef(false);
  const dump = useExecutionDump((store) => store.dump);
  const setOnActiveTaskChange = useExecutionDump(
    (store) => store.setOnActiveTaskChange
  );
  useEffect(() => {
    if (dumps) {
      setGroupedDump(dumps[0]);
    }
    return () => {
      reset();
    };
  }, []);
  useEffect(() => {
    if (onActiveTaskChange) {
      setOnActiveTaskChange(onActiveTaskChange);
    }
    return () => {
      setOnActiveTaskChange(void 0);
    };
  }, [onActiveTaskChange]);
  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) {
        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) {
            console.error(e2);
            message.error("failed to parse dump data", e2.message);
          }
        } else {
          message.error("Invalid dump file");
        }
      };
      return false;
    }
  };
  let mainContent;
  if (dump && dump.executions.length === 0) {
    mainContent = /* @__PURE__ */ jsx("div", { className: "main-right", children: /* @__PURE__ */ jsx(
      Empty,
      {
        image: Empty.PRESENTED_IMAGE_SIMPLE,
        description: "There is no task info in this dump file."
      }
    ) });
  } else if (!executionDump) {
    mainContent = /* @__PURE__ */ jsx("div", { className: "main-right uploader-wrapper", children: /* @__PURE__ */ jsxs(Dragger, __spreadProps(__spreadValues({ className: "uploader" }, uploadProps), { children: [
      /* @__PURE__ */ jsxs("p", { className: "ant-upload-text", children: [
        "Click or drag the",
        " ",
        /* @__PURE__ */ jsx("b", { children: /* @__PURE__ */ jsx("i", { children: ".web-dump.json" }) }),
        " ",
        "file into this area."
      ] }),
      /* @__PURE__ */ jsxs("p", { className: "ant-upload-text", children: [
        "The latest dump file is usually placed in",
        " ",
        /* @__PURE__ */ jsx("b", { children: /* @__PURE__ */ jsx("i", { children: "./midscene_run/report" }) })
      ] }),
      /* @__PURE__ */ 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__ */ jsx("div", { className: "replay-all-mode-wrapper", children: /* @__PURE__ */ jsx(
      Player,
      {
        replayScripts: replayAllScripts,
        imageWidth: insightWidth,
        imageHeight: insightHeight
      },
      `${executionDumpLoadId}`
    ) }) : /* @__PURE__ */ jsxs(PanelGroup, { autoSaveId: "page-detail-layout-v2", direction: "horizontal", children: [
      /* @__PURE__ */ jsx(Panel, { defaultSize: 75, maxSize: 95, children: /* @__PURE__ */ jsx("div", { className: "main-content-container", children: /* @__PURE__ */ jsx(DetailPanel, {}) }) }),
      /* @__PURE__ */ jsx(PanelResizeHandle, {}),
      /* @__PURE__ */ jsx(Panel, { maxSize: 95, children: /* @__PURE__ */ jsx("div", { className: "main-side", children: /* @__PURE__ */ jsx(DetailSide, {}) }) })
    ] });
    mainContent = /* @__PURE__ */ jsxs(
      PanelGroup,
      {
        autoSaveId: "main-page-layout",
        direction: "horizontal",
        onLayout: () => {
          if (!mainLayoutChangedRef.current) {
            setMainLayoutChangeFlag((prev) => prev + 1);
          }
        },
        children: [
          /* @__PURE__ */ jsx(Panel, { maxSize: 95, defaultSize: 20, children: /* @__PURE__ */ jsx("div", { className: "page-side", children: /* @__PURE__ */ jsx(Sidebar, {}) }) }),
          /* @__PURE__ */ jsx(
            PanelResizeHandle,
            {
              onDragging: (isChanging) => {
                if (mainLayoutChangedRef.current && !isChanging) {
                  setMainLayoutChangeFlag((prev) => prev + 1);
                }
                mainLayoutChangedRef.current = isChanging;
              }
            }
          ),
          /* @__PURE__ */ jsx(Panel, { defaultSize: 80, maxSize: 95, children: /* @__PURE__ */ jsxs("div", { className: "main-right", children: [
            /* @__PURE__ */ jsx(Timeline, {}, mainLayoutChangeFlag),
            /* @__PURE__ */ jsx("div", { className: "main-content", children: content })
          ] }) })
        ]
      }
    );
  }
  const [containerHeight, setContainerHeight] = useState("100%");
  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
        );
      }
    };
  }, []);
  useEffect(() => {
    return () => {
      globalRenderCount += 1;
    };
  }, []);
  return /* @__PURE__ */ jsxs(ConfigProvider, { theme: globalThemeConfig(), children: [
    /* @__PURE__ */ jsx(
      "div",
      {
        className: "page-container",
        style: { height: containerHeight },
        children: mainContent
      },
      `render-${globalRenderCount}`
    ),
    /* @__PURE__ */ jsx(GlobalHoverPreview, {})
  ] });
}
function mount(id) {
  var _a;
  const element = document.getElementById(id);
  if (!element) {
    throw new Error(`failed to get element for id: ${id}`);
  }
  const root = ReactDOM.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__ */ jsx(
      "div",
      {
        style: {
          width: "100%",
          height: "100%",
          padding: "100px",
          boxSizing: "border-box"
        },
        children: /* @__PURE__ */ jsx(
          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) {
      console.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);
      console.log("contentObj", contentObj);
      console.log("Array.isArray(contentObj)", Array.isArray(contentObj));
      if (Array.isArray(contentObj)) {
        contentObj.forEach((c) => {
          jsonContent = transformComputerUseDataToDump(c);
          jsonContent.attributes = attributes;
          reportDump.push(jsonContent);
        });
      } else {
        jsonContent = transformComputerUseDataToDump(contentObj);
        jsonContent.attributes = attributes;
        reportDump.push(jsonContent);
      }
    } catch (e) {
      console.error(el);
      console.error("failed to parse json content", e);
    }
  });
  root.render(/* @__PURE__ */ jsx(Visualizer, { dumps: reportDump }));
}
var src_default = {
  mount,
  Visualizer
};
export {
  Visualizer,
  src_default as default
};
