import { onBeforeUnmount, onMounted } from 'vue'

/**
 * 与 Workspace3D iframe（SimpleLite WebTerminal）的 postMessage 双向桥。
 *
 * 当前 SimpleLite WebTerminal 默认会通过 window.postMessage 抛出 `workspace.pick`
 * 与 `workspace.select` 事件给父窗口（Workspace3D.vue 收到后再 emit 给业务页）。
 * 反向的 vue→iframe 通道（设置工具、应用对齐等）走 SimpleLite 反射 API（HTTP/SSE），
 * 这里的桥只承担**坐标 / 选中 / hover** 三类 iframe→vue 数据。
 */

export interface CanvasPickPayload { x: number; y: number; siteId?: number }
export interface CanvasSelectPayload { names: string[] }
export interface CanvasMousePayload { x: number; y: number }

export interface CanvasBridgeOptions {
  onPick?: (p: CanvasPickPayload) => void
  onSelect?: (p: CanvasSelectPayload) => void
  onMouse?: (p: CanvasMousePayload) => void
}

export function useCanvasBridge(opts: CanvasBridgeOptions = {}) {
  function onMessage(ev: MessageEvent) {
    const msg = ev?.data
    if (!msg || typeof msg !== 'object' || typeof (msg as { type?: string }).type !== 'string') return

    const type = (msg as { type: string }).type
    const payload = (msg as { payload?: unknown }).payload

    if (type === 'workspace.pick' && opts.onPick && payload && typeof payload === 'object' && 'x' in payload && 'y' in payload) {
      const p = payload as CanvasPickPayload
      opts.onPick({ x: Number(p.x), y: Number(p.y), siteId: typeof p.siteId === 'number' ? p.siteId : undefined })
    } else if (type === 'workspace.select' && opts.onSelect && Array.isArray(payload)) {
      opts.onSelect({ names: (payload as string[]) })
    } else if (type === 'workspace.mouse' && opts.onMouse && payload && typeof payload === 'object' && 'x' in payload && 'y' in payload) {
      const p = payload as CanvasMousePayload
      opts.onMouse({ x: Number(p.x), y: Number(p.y) })
    }
  }

  onMounted(() => window.addEventListener('message', onMessage))
  onBeforeUnmount(() => window.removeEventListener('message', onMessage))
}
