/**
 * Background preload for Monaco editor core + generic editor.worker.
 * Trigger after the user selects a server and a directory listing succeeds,
 * so the first double-click to open a file does not wait on ~3.9MB of JS.
 */
import { warmGenericEditorWorker } from '@/monaco/setupMonacoEnv'

let warmed = false

function runPreload(): void {
  void import('@/monaco/initMonaco').then(({ initMonaco }) => {
    initMonaco()
    warmGenericEditorWorker()
  })
}

/**
 * Schedule Monaco core preload once per browser session (idle time).
 * Safe to call on every successful browse; guarded by module-level `warmed`.
 */
export function preloadMonacoCore(): void {
  if (warmed) return
  warmed = true

  if (typeof requestIdleCallback === 'function') {
    requestIdleCallback(runPreload, { timeout: 3000 })
  } else {
    setTimeout(runPreload, 300)
  }
}
