import { useEffect } from "react"
import { smokeEnabled } from "../../lib/desktop-api"

type ViewMode = "chat" | "experts" | "tasks" | "plugins" | "settings" | "knowledge"

export async function waitForSmokeUiReady(targetView: ViewMode, timeoutMs = 10000) {
  const started = Date.now()
  while (Date.now() - started < timeoutMs) {
    const state = window.__QJC_SMOKE__
    if (state?.viewMode === targetView && !state.ui?.saving) {
      return
    }
    await new Promise<void>((resolve) => {
      window.setTimeout(resolve, 50)
    })
  }

  throw new Error(`Smoke UI did not become ready for ${targetView}.`)
}

export function useSmokeActions(actions: NonNullable<typeof window.__QJC_SMOKE_ACTIONS__>) {
  useEffect(() => {
    if (!smokeEnabled) {
      delete window.__QJC_SMOKE_ACTIONS__
      return
    }

    window.__QJC_SMOKE_ACTIONS__ = actions
    return () => {
      delete window.__QJC_SMOKE_ACTIONS__
    }
  }, [actions])
}
