export const MINDMAP_DEBUG_CHROME_QUERY_PARAM = "mnoteMindmapDebugChrome";

export type MindmapUiActionId =
  | "undo"
  | "redo"
  | "editNode"
  | "insertSiblingAfter"
  | "insertChild"
  | "deleteNode"
  | "tag"
  | "hyperlink"
  | "note"
  | "image"
  | "icon"
  | "summary"
  | "associativeLine"
  | "formula"
  | "painter"
  | "import"
  | "export"
  | "setTheme"
  | "setLayout"
  | "zoomIn"
  | "zoomOut"
  | "fitView"
  | "centerRoot"
  | "fullscreenCanvas"
  | "fullscreenPage"
  | "exitFullscreen"
  | "search"
  | "showMenu"
  | "expandCollapse"
  | "copyNodeText"
  | "readonly";

export const MINDMAP_TOOLBAR_MORE_ACTION_ID = "more" as const;

export type MindmapToolbarVirtualActionId = typeof MINDMAP_TOOLBAR_MORE_ACTION_ID;

export type MindmapToolbarActionId = MindmapUiActionId | MindmapToolbarVirtualActionId;

export type MindmapToolbarActionCluster = "main" | "file" | "view";

export type MindmapToolbarOverflowGroup = "history" | "node" | "insert" | "file" | "view";

export type MindmapToolbarActionMeta = {
  id: MindmapUiActionId;
  iconKey: string;
  shortLabel: string;
  longLabel: string;
  priority: number;
  overflowGroup: MindmapToolbarOverflowGroup;
  cluster: MindmapToolbarActionCluster;
};

export type MindmapToolbarGroup = {
  id: MindmapToolbarOverflowGroup;
  label: string;
  actions: MindmapUiActionId[];
  collapsePriority: number;
};

export type MindmapSidebarPanel = {
  id: MindmapSidebarPanelId;
  kind: MindmapSidebarPanelId;
  label: string;
  icon: string;
  runtimeCapability: string;
  phase: 1;
  options: MindmapSidebarOption[];
};

export type MindmapSidebarPanelId =
  | "nodeStyle"
  | "baseStyle"
  | "theme"
  | "structure"
  | "outline"
  | "shortcutKey"
  | "settings";

export type MindmapSidebarOptionControlType =
  | "button"
  | "swatch"
  | "segmented"
  | "slider"
  | "numberInput"
  | "select"
  | "layoutCard"
  | "treeItem"
  | "toggle";

export type MindmapSidebarOption = {
  id: string;
  label: string;
  actionId: MindmapUiActionId | null;
  value: unknown;
  controlType: MindmapSidebarOptionControlType;
  preview?: string;
  description?: string;
  readonly?: boolean;
  compatPath?: string;
};

export type MindmapNavigatorItem = {
  id: "stats" | "centerRoot" | "search" | "zoomOut" | "zoom" | "zoomIn" | "fullscreen" | "readonly";
  label: string;
  actionId: MindmapUiActionId | null;
  readOnly: boolean;
  displayMode: "text" | "button" | "input";
};

export type MindmapContextMenuItem = {
  id: string;
  label: string;
  actionId: MindmapUiActionId;
  requiresNode: boolean;
  phase: 1;
};

export type MindmapUiSchema = {
  toolbarGroups: MindmapToolbarGroup[];
  toolbarActionMeta: Record<MindmapUiActionId, MindmapToolbarActionMeta>;
  sidebarPanels: MindmapSidebarPanel[];
  navigatorItems: MindmapNavigatorItem[];
  contextMenuItems: MindmapContextMenuItem[];
};

export const mindmapToolbarPrimaryActionOrder = [
  "undo",
  "redo",
  "editNode",
  "insertSiblingAfter",
  "deleteNode",
  "insertChild",
  "tag",
  "hyperlink",
  "note",
  "image",
  "icon",
  "summary",
  "associativeLine",
  "formula",
] as const satisfies readonly MindmapUiActionId[];

export const mindmapToolbarFileActionOrder = ["import", "export"] as const satisfies readonly MindmapUiActionId[];

const createToolbarActionMeta = (
  id: MindmapUiActionId,
  iconKey: string,
  shortLabel: string,
  longLabel: string,
  priority: number,
  overflowGroup: MindmapToolbarOverflowGroup,
  cluster: MindmapToolbarActionCluster,
): MindmapToolbarActionMeta => ({
  id,
  iconKey,
  shortLabel,
  longLabel,
  priority,
  overflowGroup,
  cluster,
});

export const mindmapDefaultUiSchema: MindmapUiSchema = {
  toolbarGroups: [
    {
      id: "history",
      label: "历史",
      actions: ["undo", "redo"],
      collapsePriority: 4,
    },
    {
      id: "node",
      label: "节点",
      actions: ["editNode", "insertSiblingAfter", "deleteNode", "insertChild"],
      collapsePriority: 1,
    },
    {
      id: "insert",
      label: "插入",
      actions: ["tag", "hyperlink", "note", "image", "icon", "summary", "associativeLine", "formula"],
      collapsePriority: 2,
    },
    {
      id: "file",
      label: "文件",
      actions: ["import", "export"],
      collapsePriority: 5,
    },
    {
      id: "view",
      label: "视图",
      actions: ["painter", "centerRoot", "zoomOut", "zoomIn", "search", "readonly"],
      collapsePriority: 3,
    },
  ],
  toolbarActionMeta: {
    undo: createToolbarActionMeta("undo", "undo", "撤销", "撤销", 10, "history", "main"),
    redo: createToolbarActionMeta("redo", "redo", "重做", "重做", 20, "history", "main"),
    editNode: createToolbarActionMeta("editNode", "type", "编辑", "编辑节点", 30, "node", "main"),
    insertSiblingAfter: createToolbarActionMeta("insertSiblingAfter", "sibling", "同级", "插入同级节点", 40, "node", "main"),
    deleteNode: createToolbarActionMeta("deleteNode", "trash", "删除", "删除节点", 50, "node", "main"),
    insertChild: createToolbarActionMeta("insertChild", "child", "子级", "插入子节点", 60, "node", "main"),
    tag: createToolbarActionMeta("tag", "tag", "标签", "标签", 70, "insert", "main"),
    hyperlink: createToolbarActionMeta("hyperlink", "link", "链接", "超链接", 80, "insert", "main"),
    note: createToolbarActionMeta("note", "note", "备注", "备注", 90, "insert", "main"),
    image: createToolbarActionMeta("image", "image", "图片", "图片", 100, "insert", "main"),
    icon: createToolbarActionMeta("icon", "smile", "图标", "图标", 110, "insert", "main"),
    summary: createToolbarActionMeta("summary", "summary", "概要", "概要", 120, "insert", "main"),
    associativeLine: createToolbarActionMeta("associativeLine", "route", "关联", "关联线", 130, "insert", "main"),
    formula: createToolbarActionMeta("formula", "formula", "公式", "公式", 140, "insert", "main"),
    painter: createToolbarActionMeta("painter", "paintbrush", "格式", "格式刷", 210, "view", "view"),
    import: createToolbarActionMeta("import", "import", "导入", "导入", 310, "file", "file"),
    export: createToolbarActionMeta("export", "export", "导出", "导出", 320, "file", "file"),
    setTheme: createToolbarActionMeta("setTheme", "palette", "主题", "主题", 410, "view", "view"),
    setLayout: createToolbarActionMeta("setLayout", "layout", "结构", "结构", 420, "view", "view"),
    zoomIn: createToolbarActionMeta("zoomIn", "zoom-in", "放大", "放大", 510, "view", "view"),
    zoomOut: createToolbarActionMeta("zoomOut", "zoom-out", "缩小", "缩小", 500, "view", "view"),
    fitView: createToolbarActionMeta("fitView", "fit", "适应", "适应画布", 520, "view", "view"),
    centerRoot: createToolbarActionMeta("centerRoot", "target", "回根", "回到根节点", 490, "view", "view"),
    fullscreenCanvas: createToolbarActionMeta("fullscreenCanvas", "fullscreen", "全屏", "全屏查看", 550, "view", "view"),
    fullscreenPage: createToolbarActionMeta("fullscreenPage", "fullscreen-page", "全页", "全屏编辑", 560, "view", "view"),
    exitFullscreen: createToolbarActionMeta("exitFullscreen", "exit-fullscreen", "退出", "退出全屏", 570, "view", "view"),
    search: createToolbarActionMeta("search", "search", "搜索", "搜索", 530, "view", "view"),
    showMenu: createToolbarActionMeta("showMenu", "menu", "菜单", "显示菜单", 580, "view", "view"),
    expandCollapse: createToolbarActionMeta("expandCollapse", "expand", "展开", "展开/收起", 610, "view", "view"),
    copyNodeText: createToolbarActionMeta("copyNodeText", "copy", "复制", "复制文本", 620, "view", "view"),
    readonly: createToolbarActionMeta("readonly", "lock", "只读", "只读", 540, "view", "view"),
  },
  sidebarPanels: [
    {
      id: "nodeStyle",
      kind: "nodeStyle",
      label: "节点样式",
      icon: "palette",
      runtimeCapability: "node-style",
      phase: 1,
      options: [
        { id: "node-fill-blue", label: "海蓝", actionId: "painter", value: "#dbeafe", controlType: "swatch", preview: "#dbeafe", compatPath: "nodes.$active.data.fillColor" },
        { id: "node-fill-green", label: "薄荷", actionId: "painter", value: "#dcfce7", controlType: "swatch", preview: "#dcfce7", compatPath: "nodes.$active.data.fillColor" },
        { id: "node-fill-amber", label: "暖黄", actionId: "painter", value: "#fef3c7", controlType: "swatch", preview: "#fef3c7", compatPath: "nodes.$active.data.fillColor" },
        { id: "node-text-dark", label: "深色文字", actionId: "painter", value: "#0f172a", controlType: "swatch", preview: "#0f172a", compatPath: "nodes.$active.data.color" },
        { id: "node-text-blue", label: "蓝色文字", actionId: "painter", value: "#1d4ed8", controlType: "swatch", preview: "#1d4ed8", compatPath: "nodes.$active.data.color" },
        { id: "node-font-14", label: "14 px", actionId: "painter", value: 14, controlType: "segmented", compatPath: "nodes.$active.data.fontSize" },
        { id: "node-font-18", label: "18 px", actionId: "painter", value: 18, controlType: "segmented", compatPath: "nodes.$active.data.fontSize" },
        { id: "node-font-bold", label: "加粗", actionId: "painter", value: true, controlType: "toggle", compatPath: "nodes.$active.data.fontWeight" },
        { id: "node-font-italic", label: "斜体", actionId: "painter", value: true, controlType: "toggle", compatPath: "nodes.$active.data.fontStyle" },
        { id: "node-shape-round", label: "圆角矩形", actionId: "painter", value: "roundedRectangle", controlType: "button", compatPath: "nodes.$active.data.shape" },
        { id: "node-shape-rect", label: "矩形", actionId: "painter", value: "rectangle", controlType: "button", compatPath: "nodes.$active.data.shape" },
        { id: "node-border-blue", label: "蓝色边框", actionId: "painter", value: "#60a5fa", controlType: "swatch", preview: "#60a5fa", compatPath: "nodes.$active.data.borderColor" },
        { id: "node-line-teal", label: "青色分支线", actionId: "painter", value: "#14b8a6", controlType: "swatch", preview: "#14b8a6", compatPath: "nodes.$active.data.lineColor" },
        { id: "node-line-width-2", label: "边线 2", actionId: "painter", value: 2, controlType: "segmented", compatPath: "nodes.$active.data.lineWidth" },
      ],
    },
    {
      id: "baseStyle",
      kind: "baseStyle",
      label: "导图样式",
      icon: "sliders",
      runtimeCapability: "base-style",
      phase: 1,
      options: [
        { id: "base-curve-line", label: "曲线", actionId: "painter", value: "curve", controlType: "segmented", compatPath: "style.map.lineStyle" },
        { id: "base-direct-line", label: "直线", actionId: "painter", value: "straight", controlType: "segmented", compatPath: "style.map.lineStyle" },
        { id: "base-rainbow-lines", label: "彩虹线条", actionId: "painter", value: { enabled: true }, controlType: "toggle", compatPath: "style.map.rainbowLines" },
        { id: "base-line-width-2", label: "线宽 2", actionId: "painter", value: 2, controlType: "segmented", compatPath: "style.map.lineWidth" },
        { id: "base-line-width-4", label: "线宽 4", actionId: "painter", value: 4, controlType: "segmented", compatPath: "style.map.lineWidth" },
        { id: "base-background-light", label: "浅色背景", actionId: "painter", value: "#f8fafc", controlType: "swatch", preview: "#f8fafc", compatPath: "style.map.backgroundColor" },
        { id: "base-node-spacing-36", label: "节点间距 36", actionId: "painter", value: 36, controlType: "numberInput", compatPath: "style.map.nodeSpacing" },
        { id: "base-summary-bracket", label: "括号概要", actionId: "painter", value: "bracket", controlType: "select", compatPath: "style.map.summaryStyle" },
      ],
    },
    {
      id: "theme",
      kind: "theme",
      label: "主题",
      icon: "swatch",
      runtimeCapability: "theme",
      phase: 1,
      options: [
        { id: "theme-classic", label: "Classic", actionId: "setTheme", value: "classic", controlType: "swatch", preview: "#60a5fa", description: "默认主题" },
        { id: "theme-classic4", label: "KMind", actionId: "setTheme", value: "classic4", controlType: "swatch", preview: "#22c55e", description: "KMind-like" },
        { id: "theme-simple", label: "Simple", actionId: "setTheme", value: "simple", controlType: "swatch", preview: "#f59e0b", description: "轻量主题" },
        { id: "theme-dark", label: "Dark", actionId: "setTheme", value: "dark", controlType: "swatch", preview: "#334155", description: "深色主题" },
      ],
    },
    {
      id: "structure",
      kind: "structure",
      label: "结构",
      icon: "layout",
      runtimeCapability: "layout",
      phase: 1,
      options: [
        { id: "layout-logical", label: "逻辑结构图", actionId: "setLayout", value: "logicalStructure", controlType: "layoutCard", preview: "logicalStructure" },
        { id: "layout-mind-map", label: "思维导图", actionId: "setLayout", value: "mindMap", controlType: "layoutCard", preview: "mindMap" },
        { id: "layout-organization", label: "组织结构图", actionId: "setLayout", value: "organizationStructure", controlType: "layoutCard", preview: "organizationStructure" },
        { id: "layout-catalog", label: "目录组织图", actionId: "setLayout", value: "catalogOrganization", controlType: "layoutCard", preview: "catalogOrganization" },
        { id: "layout-timeline", label: "时间轴", actionId: "setLayout", value: "timeline", controlType: "layoutCard", preview: "timeline" },
        { id: "layout-fishbone", label: "鱼骨图", actionId: "setLayout", value: "fishbone", controlType: "layoutCard", preview: "fishbone" },
      ],
    },
    {
      id: "outline",
      kind: "outline",
      label: "大纲",
      icon: "list-tree",
      runtimeCapability: "outline",
      phase: 1,
      options: [],
    },
    {
      id: "shortcutKey",
      kind: "shortcutKey",
      label: "快捷键",
      icon: "sparkles",
      runtimeCapability: "shortcut-key",
      phase: 1,
      options: [
        { id: "shortcut-insert-child", label: "Tab", description: "插入子节点", actionId: null, value: null, controlType: "treeItem", readonly: true },
        { id: "shortcut-insert-sibling", label: "Enter", description: "插入同级节点", actionId: null, value: null, controlType: "treeItem", readonly: true },
        { id: "shortcut-delete", label: "Delete", description: "删除节点", actionId: null, value: null, controlType: "treeItem", readonly: true },
      ],
    },
    {
      id: "settings",
      kind: "settings",
      label: "设置",
      icon: "hexagon",
      runtimeCapability: "settings",
      phase: 1,
      options: [
        { id: "settings-readonly-hint", label: "只读模式", description: "导航栏切换", actionId: null, value: null, controlType: "toggle", readonly: true },
        { id: "settings-mouse", label: "鼠标行为", description: "左键选中，右键拖拽", actionId: null, value: "leftSelectRightDrag", controlType: "select", readonly: true },
      ],
    },
  ],
  navigatorItems: [
    { id: "stats", label: "统计", actionId: null, readOnly: true, displayMode: "text" },
    { id: "centerRoot", label: "回根节点", actionId: "centerRoot", readOnly: true, displayMode: "button" },
    { id: "search", label: "搜索", actionId: "search", readOnly: true, displayMode: "button" },
    { id: "zoomOut", label: "缩小", actionId: "zoomOut", readOnly: true, displayMode: "button" },
    { id: "zoom", label: "缩放", actionId: null, readOnly: true, displayMode: "input" },
    { id: "zoomIn", label: "放大", actionId: "zoomIn", readOnly: true, displayMode: "button" },
    { id: "fullscreen", label: "全屏", actionId: "fullscreenCanvas", readOnly: true, displayMode: "button" },
    { id: "readonly", label: "只读", actionId: "readonly", readOnly: true, displayMode: "button" },
  ],
  contextMenuItems: [
    { id: "insertChild", label: "插入子节点", actionId: "insertChild", requiresNode: true, phase: 1 },
    { id: "insertSiblingAfter", label: "插入同级节点", actionId: "insertSiblingAfter", requiresNode: true, phase: 1 },
    { id: "deleteNode", label: "删除节点", actionId: "deleteNode", requiresNode: true, phase: 1 },
    { id: "summary", label: "概要", actionId: "summary", requiresNode: true, phase: 1 },
    { id: "associativeLine", label: "关联线", actionId: "associativeLine", requiresNode: true, phase: 1 },
    { id: "expandCollapse", label: "展开/收起", actionId: "expandCollapse", requiresNode: true, phase: 1 },
    { id: "copyNodeText", label: "复制文本", actionId: "copyNodeText", requiresNode: true, phase: 1 },
    { id: "centerRoot", label: "回根节点", actionId: "centerRoot", requiresNode: false, phase: 1 },
    { id: "fitView", label: "适应画布", actionId: "fitView", requiresNode: false, phase: 1 },
    { id: "search", label: "搜索", actionId: "search", requiresNode: false, phase: 1 },
    { id: "readonly", label: "只读切换", actionId: "readonly", requiresNode: false, phase: 1 },
    { id: "showMenu", label: "显示菜单", actionId: "showMenu", requiresNode: false, phase: 1 },
  ],
};

export const isMindmapDebugChromeEnabled = (href: string): boolean => {
  try {
    const value = new URL(href).searchParams.get(MINDMAP_DEBUG_CHROME_QUERY_PARAM);
    return value === "1" || value === "true";
  } catch {
    return false;
  }
};
