import { ref, onMounted, onUnmounted } from 'vue'

/**
 * Reactive document visibility state.
 * Returns { isVisible: Ref<boolean> } that tracks Document.hidden.
 */
export function useVisibility() {
  const isVisible = ref(!document.hidden)

  onMounted(() => {
    const onChange = () => {
      isVisible.value = !document.hidden
    }
    document.addEventListener('visibilitychange', onChange)
    onUnmounted(() => {
      document.removeEventListener('visibilitychange', onChange)
    })
  })

  return { isVisible }
}

/**
 * Synchronous check for document visibility (non-reactive).
 */
export function isDocumentVisible() {
  return !document.hidden
}

/**
 * Detect if the current device is likely mobile (touch + narrow viewport).
 */
export function isMobileDevice() {
  if (typeof window === 'undefined') return false
  return (
    ('ontouchstart' in window) &&
    window.matchMedia('(max-width: 768px)').matches
  )
}

/**
 * Get the recommended debounce for AI completion based on device.
 */
export function getRecommendedDebounce(baseMs) {
  if (isMobileDevice()) return Math.max(baseMs, 2000)
  return baseMs
}

/**
 * Get the recommended markdown sync interval based on device.
 */
export function getRecommendedSyncInterval(baseMs) {
  if (isMobileDevice()) return Math.max(baseMs, 300)
  return baseMs
}

/**
 * Initialize global visibility listener that adds/removes 'hidden-tab' class on <html>.
 * This allows CSS rules to pause animations and reduce GPU work when the tab is hidden.
 */
export function initVisibilityListener() {
  if (typeof document === 'undefined') return

  const updateClass = () => {
    document.documentElement.classList.toggle('hidden-tab', document.hidden)
  }

  updateClass() // Initial state
  document.addEventListener('visibilitychange', updateClass)
}

