"use strict";
"use client";
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 detail_panel_exports = {};
__export(detail_panel_exports, {
  default: () => detail_panel_default
});
module.exports = __toCommonJS(detail_panel_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_store = require("./store");
var import_utils = require("../utils");
var import_icons = require("@ant-design/icons");
var import_antd = require("antd");
var import_react = require("react");
var import_blackboard = __toESM(require("./blackboard"));
var import_detail_panel = require("./detail-panel.css");
var import_player = __toESM(require("./player"));
const ScreenshotItem = (props) => {
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "screenshot-item", children: [
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "screenshot-item-title", children: props.time }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("img", { src: props.img, alt: "screenshot" }) })
  ] });
};
const VIEW_TYPE_REPLAY = "replay";
const VIEW_TYPE_BLACKBOARD = "blackboard";
const VIEW_TYPE_SCREENSHOT = "screenshot";
const VIEW_TYPE_JSON = "json";
const DetailPanel = () => {
  var _a;
  const startReplay = (0, import_store.useExecutionDump)((store) => store.startReplay);
  const setStartReplay = (0, import_store.useExecutionDump)((store) => store.setStartReplay);
  const insightDump = (0, import_store.useExecutionDump)((store) => store.insightDump);
  const dumpId = (0, import_store.useExecutionDump)((store) => store._insightDumpLoadId);
  const blackboardViewAvailable = Boolean(insightDump);
  const activeExecution = (0, import_store.useExecutionDump)((store) => store.activeExecution);
  const activeExecutionId = (0, import_store.useExecutionDump)(
    (store) => store._executionDumpLoadId
  );
  const activeTask = (0, import_store.useExecutionDump)((store) => store.activeTask);
  const setActiveTask = (0, import_store.useExecutionDump)((store) => store.setActiveTask);
  const [preferredViewType, setViewType] = (0, import_react.useState)(VIEW_TYPE_REPLAY);
  const animationScripts = (0, import_store.useExecutionDump)(
    (store) => store.activeExecutionAnimation
  );
  const allTasks = (0, import_store.useAllCurrentTasks)();
  let availableViewTypes = [VIEW_TYPE_SCREENSHOT, VIEW_TYPE_JSON];
  if (blackboardViewAvailable) {
    availableViewTypes = [
      VIEW_TYPE_BLACKBOARD,
      VIEW_TYPE_SCREENSHOT,
      VIEW_TYPE_JSON
    ];
  }
  if ((activeTask == null ? void 0 : activeTask.type) === "Planning" && animationScripts && animationScripts.length > 0) {
    availableViewTypes.unshift(VIEW_TYPE_REPLAY);
  }
  const viewType = availableViewTypes.indexOf(preferredViewType) >= 0 ? preferredViewType : availableViewTypes[0];
  let content;
  if (activeExecution && viewType === VIEW_TYPE_REPLAY) {
    content = /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_player.default, {}, `${activeExecutionId}`);
  } else if (!activeTask) {
    content = /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { children: "please select a task" });
  } else if (viewType === VIEW_TYPE_JSON) {
    content = /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "json-content scrollable", children: (0, import_utils.filterBase64Value)(JSON.stringify(activeTask, void 0, 2)) });
  } else if (viewType === VIEW_TYPE_BLACKBOARD) {
    if (blackboardViewAvailable) {
      content = /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
        import_blackboard.default,
        {
          uiContext: insightDump.context,
          highlightElements: insightDump.matchedElement
        },
        `${dumpId}`
      );
    } else {
      content = /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { children: "invalid view" });
    }
  } else if (viewType === VIEW_TYPE_SCREENSHOT) {
    if ((_a = activeTask.recorder) == null ? void 0 : _a.length) {
      content = /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "screenshot-item-wrapper scrollable", children: activeTask.recorder.filter((item) => item.screenshot).map((item, index) => {
        const fullTime = (0, import_utils.timeStr)(item.ts);
        const str = item.timing ? `${fullTime} / ${item.timing}` : fullTime;
        return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ScreenshotItem, { time: str, img: item.screenshot }, index);
      }) });
    } else {
      content = /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { children: "no screenshot" });
    }
  }
  (0, import_react.useEffect)(() => {
    const handleKeyDown = (e) => {
      if (e.key === "Tab") {
        const ifShift = e.shiftKey;
        const index = availableViewTypes.indexOf(viewType);
        const nextIndex = ifShift ? (index - 1 + availableViewTypes.length) % availableViewTypes.length : (index + 1) % availableViewTypes.length;
        setViewType(availableViewTypes[nextIndex]);
        e.preventDefault();
      }
    };
    document.addEventListener("keydown", handleKeyDown);
    return () => {
      document.removeEventListener("keydown", handleKeyDown);
    };
  });
  const validTasks = (0, import_react.useMemo)(() => {
    return allTasks.filter((task) => {
      var _a2;
      return Boolean((_a2 = task == null ? void 0 : task.recorder) == null ? void 0 : _a2.length);
    });
  }, [allTasks]);
  (0, import_react.useEffect)(() => {
    let timeoutId = null;
    const playbackSpeed = 2;
    const playNext = () => {
      var _a2, _b;
      if (!startReplay) {
        return;
      }
      const currentIndex = activeTask ? validTasks.indexOf(activeTask) : -1;
      const nextIndex = currentIndex + 1;
      if (nextIndex >= validTasks.length) {
        setStartReplay(false);
        return;
      }
      const nextTask = validTasks[nextIndex];
      let delay = 0;
      if (((_a2 = activeTask == null ? void 0 : activeTask.timing) == null ? void 0 : _a2.start) && ((_b = nextTask == null ? void 0 : nextTask.timing) == null ? void 0 : _b.start)) {
        delay = (nextTask.timing.start - activeTask.timing.start) / playbackSpeed;
      }
      import_console_browserify.default.log("nextIndex", nextIndex, nextTask);
      timeoutId = setTimeout(() => {
        setActiveTask(nextTask);
      }, delay);
    };
    if (startReplay && validTasks.length > 0) {
      if (!activeTask) {
        setActiveTask(validTasks[0]);
      } else {
        playNext();
      }
    }
    return () => {
      if (timeoutId) {
        clearTimeout(timeoutId);
      }
    };
  }, [startReplay, validTasks, activeTask]);
  const options = availableViewTypes.map((type) => {
    if (type === VIEW_TYPE_REPLAY) {
      return {
        label: "Replay",
        value: type,
        icon: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_icons.VideoCameraOutlined, {})
      };
    }
    if (type === VIEW_TYPE_BLACKBOARD) {
      return {
        label: "Insight",
        value: type,
        icon: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_icons.ScheduleOutlined, {})
      };
    }
    if (type === VIEW_TYPE_SCREENSHOT) {
      return {
        label: "Screenshots",
        value: type,
        icon: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_icons.CameraOutlined, {})
      };
    }
    if (type === VIEW_TYPE_JSON) {
      return {
        label: "JSON View",
        value: type,
        icon: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_icons.FileTextOutlined, {})
      };
    }
    return {
      label: "unknown",
      value: type
    };
  });
  import_console_browserify.default.log("startReplay", startReplay);
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "detail-panel", children: [
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "view-switcher", children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
      import_antd.ConfigProvider,
      {
        theme: {
          components: {
            Segmented: {
              itemSelectedBg: "#bfc4da50",
              itemSelectedColor: "#000000"
            }
          }
        },
        children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
            import_antd.Button,
            {
              type: "text",
              icon: startReplay ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_icons.PauseOutlined, {}) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_icons.CaretRightOutlined, {}),
              color: "default",
              variant: "filled",
              style: {
                background: startReplay ? "#bfc4da80" : void 0
              },
              onClick: () => {
                setStartReplay(!startReplay);
              },
              children: startReplay ? "Pause" : "Start Replay"
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
            import_antd.Segmented,
            {
              options,
              value: viewType,
              onChange: (value) => {
                setViewType(value);
              }
            }
          )
        ]
      }
    ) }),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "detail-content", children: content })
  ] });
};
var detail_panel_default = DetailPanel;
