"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 __async = (__this, __arguments, generator) => {
  return new Promise((resolve, reject) => {
    var fulfilled = (value) => {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    };
    var rejected = (value) => {
      try {
        step(generator.throw(value));
      } catch (e) {
        reject(e);
      }
    };
    var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
    step((generator = generator.apply(__this, __arguments)).next());
  });
};
var blackboard_exports = {};
__export(blackboard_exports, {
  default: () => blackboard_default,
  rectMarkForItem: () => rectMarkForItem
});
module.exports = __toCommonJS(blackboard_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_antd = require("antd");
var import_pixi_filters = require("pixi-filters");
var PIXI = __toESM(require("pixi.js"));
var import_unsafe_eval = require("pixi.js/unsafe-eval");
var import_react = require("react");
var import_blackboard = require("./blackboard.css");
var import_color = require("./color");
var import_store = require("./store");
const itemFillAlpha = 0.4;
const highlightAlpha = 0.4;
const noop = () => {
};
const rectMarkForItem = (rect, name, ifHighlight, onPointOver, onPointerOut) => {
  const { left, top, width, height } = rect;
  const themeColor = ifHighlight ? (0, import_color.highlightColorForType)("element") : (0, import_color.colorForName)(name);
  const alpha = ifHighlight ? highlightAlpha : itemFillAlpha;
  const graphics = new PIXI.Graphics();
  graphics.beginFill(themeColor, alpha);
  graphics.lineStyle(1, themeColor, 1);
  graphics.drawRect(left, top, width, height);
  graphics.endFill();
  if (onPointOver && onPointerOut) {
    graphics.interactive = true;
    graphics.on("pointerover", onPointOver);
    graphics.on("pointerout", onPointerOut);
  }
  const dropShadowFilter = new import_pixi_filters.DropShadowFilter({
    blur: 2,
    quality: 3,
    alpha: 0.4,
    offset: { x: 4, y: 4 },
    color: 3355443
  });
  graphics.filters = [dropShadowFilter];
  const nameFontSize = 18;
  const texts = new PIXI.Text(name, {
    fontSize: nameFontSize,
    fill: 0
  });
  texts.x = left;
  texts.y = Math.max(top - (nameFontSize + 4), 0);
  return [graphics, texts];
};
const Blackboard = (props) => {
  const highlightElements = props.highlightElements || [];
  const highlightIds = highlightElements.map((e) => e.id);
  const context = props.uiContext;
  const { size, screenshotBase64, screenshotBase64WithElementMarker } = context;
  const screenWidth = size.width;
  const screenHeight = size.height;
  const domRef = (0, import_react.useRef)(null);
  const app = (0, import_react.useMemo)(() => new PIXI.Application(), []);
  const [appInitialed, setAppInitialed] = (0, import_react.useState)(false);
  const highlightContainer = (0, import_react.useMemo)(() => new PIXI.Container(), []);
  const elementMarkContainer = (0, import_react.useMemo)(() => new PIXI.Container(), []);
  const [hoverElement, setHoverElement] = (0, import_react.useState)(null);
  const pixiBgRef = (0, import_react.useRef)();
  const { markerVisible, setMarkerVisible, elementsVisible, setTextsVisible } = (0, import_store.useBlackboardPreference)();
  const ifMarkerAvailable = !!screenshotBase64WithElementMarker;
  (0, import_react.useEffect)(() => {
    Promise.resolve(
      (() => __async(void 0, null, function* () {
        if (!domRef.current || !screenWidth) {
          return;
        }
        yield app.init({
          width: screenWidth,
          height: screenHeight,
          background: 16777215
        });
        const canvasEl = domRef.current;
        domRef.current.appendChild(app.canvas);
        const { clientWidth } = domRef.current.parentElement;
        const targetHeight = window.innerHeight * 0.5;
        const viewportRatio = clientWidth / targetHeight;
        if (screenWidth / screenHeight <= viewportRatio) {
          const ratio = targetHeight / screenHeight;
          canvasEl.style.width = `${Math.floor(screenWidth * ratio)}px`;
          canvasEl.style.height = `${Math.floor(screenHeight * ratio)}px`;
        }
        app.stage.addChild(highlightContainer);
        app.stage.addChild(elementMarkContainer);
        setAppInitialed(true);
      }))()
    );
    return () => {
      import_console_browserify.default.log("will destroy");
      try {
        app.destroy(true, { children: true, texture: true });
      } catch (e) {
        import_console_browserify.default.warn("destroy failed", e);
      }
    };
  }, [app, screenWidth, screenHeight]);
  (0, import_react.useEffect)(() => {
    if (!appInitialed) {
      return;
    }
    const img = new Image();
    img.onload = () => {
      if (!app.stage)
        return;
      const screenshotTexture = PIXI.Texture.from(img);
      const backgroundSprite = new PIXI.Sprite(screenshotTexture);
      backgroundSprite.x = 0;
      backgroundSprite.y = 0;
      backgroundSprite.width = screenWidth;
      backgroundSprite.height = screenHeight;
      app.stage.addChildAt(backgroundSprite, 0);
      if (ifMarkerAvailable) {
        const markerImg = new Image();
        markerImg.onload = () => {
          const markerTexture = PIXI.Texture.from(markerImg);
          const markerSprite = new PIXI.Sprite(markerTexture);
          markerSprite.x = 0;
          markerSprite.y = 0;
          markerSprite.width = screenWidth;
          markerSprite.height = screenHeight;
          app.stage.addChildAt(markerSprite, 1);
          pixiBgRef.current = markerSprite;
          markerSprite.visible = markerVisible;
        };
        markerImg.onerror = (e) => {
          import_console_browserify.default.error("load marker failed", e);
        };
        markerImg.src = screenshotBase64WithElementMarker;
      }
    };
    img.onerror = (e) => {
      import_console_browserify.default.error("load screenshot failed", e);
    };
    img.src = screenshotBase64;
  }, [app.stage, appInitialed]);
  const { highlightElementRects } = (0, import_react.useMemo)(() => {
    const highlightElementRects2 = [];
    highlightContainer.removeChildren();
    elementMarkContainer.removeChildren();
    context.content.forEach((element) => {
      const { rect, content, id } = element;
      const ifHighlight = highlightIds.includes(id) || (hoverElement == null ? void 0 : hoverElement.id) === id;
      if (ifHighlight) {
        const [graphics2] = rectMarkForItem(
          rect,
          content,
          ifHighlight,
          noop,
          noop
        );
        highlightContainer.addChild(graphics2);
      }
      const removeHover = () => {
        setHoverElement(null);
      };
      const [graphics] = rectMarkForItem(
        rect,
        content,
        ifHighlight,
        (props == null ? void 0 : props.disableInteraction) ? void 0 : () => {
          setHoverElement(element);
        },
        (props == null ? void 0 : props.disableInteraction) ? void 0 : removeHover
      );
      elementMarkContainer.addChild(graphics);
    });
    elementMarkContainer.visible = elementsVisible;
    return {
      highlightElementRects: highlightElementRects2
    };
  }, [
    app,
    appInitialed,
    highlightElements,
    context.content,
    hoverElement
    // bgVisible,
    // elementsVisible,
  ]);
  const onSetMarkerVisible = (e) => {
    setMarkerVisible(e.target.checked);
    if (pixiBgRef.current) {
      pixiBgRef.current.visible = e.target.checked;
    }
  };
  const onSetElementsVisible = (e) => {
    setTextsVisible(e.target.checked);
    elementMarkContainer.visible = e.target.checked;
  };
  let bottomTipA = null;
  if (highlightElementRects.length === 1) {
    bottomTipA = /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "bottom-tip", children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "bottom-tip-item", children: [
      "Element: ",
      JSON.stringify(highlightElementRects[0])
    ] }) });
  } else if (highlightElementRects.length > 1) {
    bottomTipA = /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "bottom-tip", children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "bottom-tip-item", children: [
      "Element: ",
      JSON.stringify(highlightElementRects)
    ] }) });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "blackboard", children: [
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      "div",
      {
        className: "blackboard-main-content",
        style: { width: "100%" },
        ref: domRef
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      "div",
      {
        className: "blackboard-filter",
        style: { display: props.hideController ? "none" : "block" },
        children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "overlay-control", children: [
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
            import_antd.Checkbox,
            {
              checked: markerVisible,
              onChange: onSetMarkerVisible,
              disabled: !ifMarkerAvailable,
              children: "Marker"
            }
          ),
          /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_antd.Checkbox, { checked: elementsVisible, onChange: onSetElementsVisible, children: "Elements" })
        ] })
      }
    ),
    /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      "div",
      {
        className: "bottom-tip",
        style: { display: props.hideController ? "none" : "block" },
        children: bottomTipA
      }
    )
  ] });
};
var blackboard_default = Blackboard;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  rectMarkForItem
});
