"use client";
import Buffer from "buffer";
import processBrowser from "process/browser";
import console from "console-browserify";
var buffer = {
  Buffer
};
import { jsx, jsxs } from "react/jsx-runtime";
import { useAllCurrentTasks, useExecutionDump } from "./store";
import { filterBase64Value, timeStr } from "../utils";
import {
  CameraOutlined,
  CaretRightOutlined,
  FileTextOutlined,
  PauseOutlined,
  ScheduleOutlined,
  VideoCameraOutlined
} from "@ant-design/icons";
import { Button, ConfigProvider, Segmented } from "antd";
import { useEffect, useMemo, useState } from "react";
import Blackboard from "./blackboard";
import "./detail-panel.css";
import Player from "./player";
const ScreenshotItem = (props) => {
  return /* @__PURE__ */ jsxs("div", { className: "screenshot-item", children: [
    /* @__PURE__ */ jsx("div", { className: "screenshot-item-title", children: props.time }),
    /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ 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 = useExecutionDump((store) => store.startReplay);
  const setStartReplay = useExecutionDump((store) => store.setStartReplay);
  const insightDump = useExecutionDump((store) => store.insightDump);
  const dumpId = useExecutionDump((store) => store._insightDumpLoadId);
  const blackboardViewAvailable = Boolean(insightDump);
  const activeExecution = useExecutionDump((store) => store.activeExecution);
  const activeExecutionId = useExecutionDump(
    (store) => store._executionDumpLoadId
  );
  const activeTask = useExecutionDump((store) => store.activeTask);
  const setActiveTask = useExecutionDump((store) => store.setActiveTask);
  const [preferredViewType, setViewType] = useState(VIEW_TYPE_REPLAY);
  const animationScripts = useExecutionDump(
    (store) => store.activeExecutionAnimation
  );
  const allTasks = 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__ */ jsx(Player, {}, `${activeExecutionId}`);
  } else if (!activeTask) {
    content = /* @__PURE__ */ jsx("div", { children: "please select a task" });
  } else if (viewType === VIEW_TYPE_JSON) {
    content = /* @__PURE__ */ jsx("div", { className: "json-content scrollable", children: filterBase64Value(JSON.stringify(activeTask, void 0, 2)) });
  } else if (viewType === VIEW_TYPE_BLACKBOARD) {
    if (blackboardViewAvailable) {
      content = /* @__PURE__ */ jsx(
        Blackboard,
        {
          uiContext: insightDump.context,
          highlightElements: insightDump.matchedElement
        },
        `${dumpId}`
      );
    } else {
      content = /* @__PURE__ */ jsx("div", { children: "invalid view" });
    }
  } else if (viewType === VIEW_TYPE_SCREENSHOT) {
    if ((_a = activeTask.recorder) == null ? void 0 : _a.length) {
      content = /* @__PURE__ */ jsx("div", { className: "screenshot-item-wrapper scrollable", children: activeTask.recorder.filter((item) => item.screenshot).map((item, index) => {
        const fullTime = timeStr(item.ts);
        const str = item.timing ? `${fullTime} / ${item.timing}` : fullTime;
        return /* @__PURE__ */ jsx(ScreenshotItem, { time: str, img: item.screenshot }, index);
      }) });
    } else {
      content = /* @__PURE__ */ jsx("div", { children: "no screenshot" });
    }
  }
  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 = useMemo(() => {
    return allTasks.filter((task) => {
      var _a2;
      return Boolean((_a2 = task == null ? void 0 : task.recorder) == null ? void 0 : _a2.length);
    });
  }, [allTasks]);
  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;
      }
      console.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__ */ jsx(VideoCameraOutlined, {})
      };
    }
    if (type === VIEW_TYPE_BLACKBOARD) {
      return {
        label: "Insight",
        value: type,
        icon: /* @__PURE__ */ jsx(ScheduleOutlined, {})
      };
    }
    if (type === VIEW_TYPE_SCREENSHOT) {
      return {
        label: "Screenshots",
        value: type,
        icon: /* @__PURE__ */ jsx(CameraOutlined, {})
      };
    }
    if (type === VIEW_TYPE_JSON) {
      return {
        label: "JSON View",
        value: type,
        icon: /* @__PURE__ */ jsx(FileTextOutlined, {})
      };
    }
    return {
      label: "unknown",
      value: type
    };
  });
  console.log("startReplay", startReplay);
  return /* @__PURE__ */ jsxs("div", { className: "detail-panel", children: [
    /* @__PURE__ */ jsx("div", { className: "view-switcher", children: /* @__PURE__ */ jsxs(
      ConfigProvider,
      {
        theme: {
          components: {
            Segmented: {
              itemSelectedBg: "#bfc4da50",
              itemSelectedColor: "#000000"
            }
          }
        },
        children: [
          /* @__PURE__ */ jsx(
            Button,
            {
              type: "text",
              icon: startReplay ? /* @__PURE__ */ jsx(PauseOutlined, {}) : /* @__PURE__ */ jsx(CaretRightOutlined, {}),
              color: "default",
              variant: "filled",
              style: {
                background: startReplay ? "#bfc4da80" : void 0
              },
              onClick: () => {
                setStartReplay(!startReplay);
              },
              children: startReplay ? "Pause" : "Start Replay"
            }
          ),
          /* @__PURE__ */ jsx(
            Segmented,
            {
              options,
              value: viewType,
              onChange: (value) => {
                setViewType(value);
              }
            }
          )
        ]
      }
    ) }),
    /* @__PURE__ */ jsx("div", { className: "detail-content", children: content })
  ] });
};
var detail_panel_default = DetailPanel;
export {
  detail_panel_default as default
};
