import { Q as QInput } from "./QInput-C1k2VUPF.js";
import { Q as QCardSection } from "./QCardSection-BEf1jKxd.js";
import { Q as QSeparator } from "./QSeparator-2SNNJjxi.js";
import { j as createComponent, k as getCurrentInstance, p as computed, q as h, s as hSlot, _ as _export_sfc, a as defineComponent, r as resolveComponent, c as createBlock, o as openBlock, w as withCtx, b as createVNode, g as createBaseVNode, M as createCommentVNode, O as toDisplayString, e as QBtn, i as createTextVNode } from "./index-BRudWVF6.js";
import { u as useDarkProps, a as useDark } from "./use-id-Bga_UBPy.js";
import { Q as QCard } from "./QCard-S3y3u9tH.js";
import { Q as QPage } from "./QPage-y4zftl3-.js";
import { A as AppHeader } from "./AppHeader-DugPHj8B.js";
const QBanner = createComponent({
  name: "QBanner",
  props: {
    ...useDarkProps,
    inlineActions: Boolean,
    dense: Boolean,
    rounded: Boolean
  },
  setup(props, { slots }) {
    const { proxy: { $q } } = getCurrentInstance();
    const isDark = useDark(props, $q);
    const classes = computed(
      () => "q-banner row items-center" + (props.dense === true ? " q-banner--dense" : "") + (isDark.value === true ? " q-banner--dark q-dark" : "") + (props.rounded === true ? " rounded-borders" : "")
    );
    const actionClass = computed(
      () => `q-banner__actions row items-center justify-end col-${props.inlineActions === true ? "auto" : "all"}`
    );
    return () => {
      const child = [
        h("div", {
          class: "q-banner__avatar col-auto row items-center self-start"
        }, hSlot(slots.avatar)),
        h("div", {
          class: "q-banner__content col text-body2"
        }, hSlot(slots.default))
      ];
      const actions = hSlot(slots.action);
      actions !== void 0 && child.push(
        h("div", { class: actionClass.value }, actions)
      );
      return h("div", {
        class: classes.value + (props.inlineActions === false && actions !== void 0 ? " q-banner--top-padding" : ""),
        role: "alert"
      }, child);
    };
  }
});
const _sfc_main = defineComponent({
  name: "DemoPage",
  components: {
    AppHeader
  },
  data() {
    return {
      text: "",
      time: "20:57",
      riqi: "2026-01-20",
      activeTabId: null,
      activeTabTitle: "",
      activeTabUrl: "",
      statusText: ""
    };
  },
  mounted() {
    this.refreshActiveTab();
  },
  methods: {
    getChrome() {
      if (typeof window === "undefined") return null;
      return window.chrome || null;
    },
    async refreshActiveTab() {
      const chrome = this.getChrome();
      if (!chrome || !chrome.tabs || !chrome.tabs.query) {
        this.statusText = "当前不在扩展环境（chrome.tabs 不可用）";
        return;
      }
      this.statusText = "";
      const tabs = await new Promise((resolve) => {
        chrome.tabs.query({ active: true, currentWindow: true }, resolve);
      });
      const tab = tabs && tabs[0];
      this.activeTabId = tab ? tab.id : null;
      this.activeTabTitle = tab ? tab.title || "" : "";
      this.activeTabUrl = tab ? tab.url || "" : "";
      if (!this.activeTabId) {
        this.statusText = "未找到当前标签页";
      }
    },
    async sendToActiveTab(action) {
      const chrome = this.getChrome();
      if (!chrome || !chrome.tabs || !chrome.tabs.sendMessage) {
        this.statusText = "当前不在扩展环境（chrome.tabs.sendMessage 不可用）";
        return null;
      }
      if (!this.activeTabId) {
        await this.refreshActiveTab();
      }
      if (!this.activeTabId) return null;
      const payload = { type: "FBHELPER_DEMO", action };
      try {
        const res = await new Promise((resolve, reject) => {
          chrome.tabs.sendMessage(this.activeTabId, payload, (response) => {
            const err = chrome.runtime && chrome.runtime.lastError;
            if (err) reject(new Error(err.message));
            else resolve(response);
          });
        });
        return res;
      } catch (err) {
        this.statusText = `发送失败：${err && err.message ? err.message : String(err)}`;
        return null;
      }
    },
    async togglePanel() {
      this.statusText = "";
      const res = await this.sendToActiveTab("togglePanel");
      if (res && res.ok) this.statusText = "已切换页面面板";
      else if (res && res.error) this.statusText = `失败：${res.error}`;
    },
    async ping() {
      this.statusText = "";
      const res = await this.sendToActiveTab("ping");
      if (res && res.ok) {
        this.statusText = `后台时间：${new Date(res.time).toLocaleString()}`;
      } else if (res && res.error) {
        this.statusText = `失败：${res.error}`;
      }
    },
    async runSnippet() {
      const chrome = this.getChrome();
      if (!chrome || !chrome.scripting) {
        this.statusText = "需要 scripting 权限或不在扩展环境";
        return;
      }
      if (!this.activeTabId) {
        await this.refreshActiveTab();
      }
      if (!this.activeTabId) return;
      this.statusText = "正在执行代码片段...";
      try {
        await chrome.scripting.executeScript({
          target: { tabId: this.activeTabId },
          world: "MAIN",
          func: () => {
            const editors = document.querySelectorAll('div[contenteditable="true"][role="textbox"]')[0];
            [editors].forEach((el, idx) => {
              if (!el) return;
              el.focus();
              let fiber = null;
              for (let k in el) {
                if (k.startsWith("__reactFiber$") || k.startsWith("__reactInternalInstance$")) {
                  fiber = el[k];
                  break;
                }
              }
              if (!fiber) return console.warn("⚠️ 第 " + (idx + 1) + " 个编辑框未找到 Fiber");
              let found = null;
              for (let i = 0; fiber && i < 20; i++, fiber = fiber.return) {
                let p = fiber.memoizedProps || {};
                if (p.editorState && p.onChange) {
                  found = p;
                  break;
                }
              }
              if (!found) return console.warn("第 " + (idx + 1) + " 个编辑框未找到 editorState");
              try {
                let oldState = found.editorState;
                let content = oldState.getCurrentContent?.();
                let randomStr = Math.random().toString(36).substring(2, 6);
                let newContent = content.constructor.createFromText("testtesttest-" + randomStr);
                let newState = oldState.constructor.createWithContent(newContent);
                found.onChange(newState);
              } catch (err) {
                console.error("第 " + (idx + 1) + " 个编辑框更新失败:", err);
              }
            });
          }
        });
        this.statusText = "代码片段执行完成";
      } catch (err) {
        this.statusText = `执行失败：${err.message}`;
      }
    }
  }
});
const _hoisted_1 = { class: "q-pa-sm" };
const _hoisted_2 = { class: "q-gutter-y-sm" };
const _hoisted_3 = { class: "text-body2 ellipsis" };
const _hoisted_4 = { class: "text-caption text-grey-7 ellipsis" };
const _hoisted_5 = { class: "row q-col-gutter-sm q-mt-sm" };
const _hoisted_6 = { class: "col-6" };
const _hoisted_7 = { class: "col-6" };
const _hoisted_8 = { class: "col-12" };
const _hoisted_9 = { class: "col-12" };
function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
  const _component_app_header = resolveComponent("app-header");
  return openBlock(), createBlock(QPage, { class: "popup-page demo-page" }, {
    default: withCtx(() => [
      createVNode(_component_app_header),
      createBaseVNode("div", _hoisted_1, [
        createVNode(QCard, {
          flat: "",
          bordered: ""
        }, {
          default: withCtx(() => [
            createVNode(QCardSection, { class: "q-pb-sm" }, {
              default: withCtx(() => [
                createBaseVNode("div", _hoisted_2, [
                  createVNode(QInput, {
                    modelValue: _ctx.time,
                    "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => _ctx.time = $event),
                    filled: "",
                    type: "time",
                    label: "时间"
                  }, null, 8, ["modelValue"]),
                  createVNode(QInput, {
                    modelValue: _ctx.riqi,
                    "onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => _ctx.riqi = $event),
                    filled: "",
                    type: "date",
                    label: "日期"
                  }, null, 8, ["modelValue"]),
                  createVNode(QInput, {
                    label: "描述",
                    modelValue: _ctx.text,
                    "onUpdate:modelValue": _cache[2] || (_cache[2] = ($event) => _ctx.text = $event),
                    filled: "",
                    type: "textarea"
                  }, null, 8, ["modelValue"])
                ]),
                _cache[3] || (_cache[3] = createBaseVNode("div", { class: "text-subtitle1" }, "BEX Demo", -1)),
                _cache[4] || (_cache[4] = createBaseVNode("div", { class: "text-caption text-grey-7" }, " 从 popup 操作当前标签页的 content script ", -1))
              ]),
              _: 1
            }),
            createVNode(QSeparator),
            createVNode(QCardSection, { class: "q-pt-sm" }, {
              default: withCtx(() => [
                _cache[5] || (_cache[5] = createBaseVNode("div", { class: "text-caption text-grey-7" }, "当前标签页", -1)),
                createBaseVNode("div", _hoisted_3, toDisplayString(_ctx.activeTabTitle || "-"), 1),
                createBaseVNode("div", _hoisted_4, toDisplayString(_ctx.activeTabUrl || "-"), 1),
                createBaseVNode("div", _hoisted_5, [
                  createBaseVNode("div", _hoisted_6, [
                    createVNode(QBtn, {
                      class: "full-width",
                      color: "primary",
                      label: "打开/关闭面板",
                      onClick: _ctx.togglePanel
                    }, null, 8, ["onClick"])
                  ]),
                  createBaseVNode("div", _hoisted_7, [
                    createVNode(QBtn, {
                      class: "full-width",
                      color: "secondary",
                      label: "Ping 后台时间",
                      onClick: _ctx.ping
                    }, null, 8, ["onClick"])
                  ]),
                  createBaseVNode("div", _hoisted_8, [
                    createVNode(QBtn, {
                      class: "full-width",
                      outline: "",
                      color: "grey-8",
                      label: "刷新当前标签页信息",
                      onClick: _ctx.refreshActiveTab
                    }, null, 8, ["onClick"])
                  ]),
                  createBaseVNode("div", _hoisted_9, [
                    createVNode(QBtn, {
                      class: "full-width",
                      color: "deep-orange",
                      label: "执行代码片段",
                      onClick: _ctx.runSnippet
                    }, null, 8, ["onClick"])
                  ])
                ]),
                _ctx.statusText ? (openBlock(), createBlock(QBanner, {
                  key: 0,
                  class: "q-mt-md",
                  dense: ""
                }, {
                  default: withCtx(() => [
                    createTextVNode(toDisplayString(_ctx.statusText), 1)
                  ]),
                  _: 1
                })) : createCommentVNode("", true)
              ]),
              _: 1
            })
          ]),
          _: 1
        })
      ])
    ]),
    _: 1
  });
}
const demo = /* @__PURE__ */ _export_sfc(_sfc_main, [["render", _sfc_render], ["__scopeId", "data-v-409a9804"]]);
export {
  demo as default
};
