// Keep the device screen on while a mobile warehouse workflow is active — scanning sessions otherwise
// dim and lock between picks, forcing staff to re-wake the device constantly.
//
// Native-only + fail-soft: @capacitor-community/keep-awake is dynamically imported behind a
// native-platform check, so the web build never loads it and activate()/deactivate() are no-ops on web.
// Any plugin error is swallowed (the screen just behaves normally).
//
// Usage — one line at the top of a work page's <script setup>:
//   useKeepAwake()                 // auto: keeps awake while the page is mounted/active, releases on leave
//   const { activate, deactivate } = useKeepAwake(false)   // manual control
//
// Auto-mode wires onMounted/onActivated to acquire and onDeactivated/onBeforeUnmount to release, so it
// also behaves correctly for the keepalive'd <NuxtPage> the app uses (a cached-but-hidden page sleeps).

const isNative = () => typeof window !== 'undefined'
  && !!(window as any).Capacitor
  && typeof (window as any).Capacitor.isNativePlatform === 'function'
  && (window as any).Capacitor.isNativePlatform() === true

export const useKeepAwake = (auto = true) => {
  let active = false

  const activate = async () => {
    if (!isNative() || active) return
    active = true
    try {
      const { KeepAwake } = await import('@capacitor-community/keep-awake')
      await KeepAwake.keepAwake()
    } catch {
      active = false // let a later call retry
    }
  }

  const deactivate = async () => {
    if (!isNative() || !active) return
    active = false
    try {
      const { KeepAwake } = await import('@capacitor-community/keep-awake')
      await KeepAwake.allowSleep()
    } catch { /* non-fatal */ }
  }

  if (auto && getCurrentInstance()) {
    onMounted(activate)
    onActivated(activate)     // re-acquire when a keepalive'd page is shown again
    onDeactivated(deactivate) // release when a keepalive'd page is hidden
    onBeforeUnmount(deactivate)
  }

  return { activate, deactivate }
}
