'use client'

import { useEffect, useRef } from 'react'
import { usePathname, useRouter } from 'next/navigation'
import { isCaptureBusy } from '@/lib/capture-busy'

/**
 * After IDLE_MS of no interaction, return to the home page and scroll to the
 * top — so the app is always sitting at a clean starting state with the record
 * button in reach. Mounted once in the root layout.
 *
 * Guards:
 * Applies everywhere, /trades included. It used to exempt pages you leave open
 * and watch, because at one minute the reset fought you for simply reading —
 * at half an hour it no longer competes with use, so the exemption would only
 * leave one page stranded wherever it was last session.
 *
 * Guards:
 *  - A capture in progress (recording / uploading / unsaved note) suppresses
 *    the reset so we never discard the user's work — we check again next cycle.
 */

/**
 * Half an hour: long enough to read a trades ladder or a long list without
 * being interrupted, short enough that the phone you pick up tomorrow is
 * showing the record button rather than where you left off.
 */
const IDLE_MS = 30 * 60_000

export function IdleReset() {
  const router = useRouter()
  const pathname = usePathname()
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null)
  // Seeded in the effect, not here: reading a clock during render is impure
  // and can differ between renders of the same component.
  const lastActivity = useRef<number>(0)

  useEffect(() => {
    lastActivity.current = Date.now()

    const schedule = () => {
      lastActivity.current = Date.now()
      if (timer.current) clearTimeout(timer.current)
      timer.current = setTimeout(onIdle, IDLE_MS)
    }

    const onIdle = () => {
      // Don't interrupt an in-progress capture — wait another cycle.
      if (isCaptureBusy()) {
        schedule()
        return
      }
      if (pathname !== '/') {
        router.push('/')
        // Let the home page mount before scrolling to the top.
        setTimeout(() => window.scrollTo({ top: 0, behavior: 'smooth' }), 120)
      } else {
        window.scrollTo({ top: 0, behavior: 'smooth' })
      }
    }

    const events: (keyof DocumentEventMap)[] = [
      'pointerdown',
      'keydown',
      'touchstart',
      'scroll',
      'wheel',
    ]
    // A timer alone is not enough at this length. Browsers throttle and
    // eventually suspend setTimeout in a backgrounded PWA, so the half hour
    // may simply never elapse — and the phone picked up tomorrow is exactly
    // the case this exists for. Checking the clock on the way back in covers
    // what the timer slept through.
    const onVisible = () => {
      if (document.visibilityState !== 'visible') return
      if (Date.now() - lastActivity.current >= IDLE_MS) onIdle()
      else schedule()
    }

    for (const e of events) document.addEventListener(e, schedule, { passive: true })
    document.addEventListener('visibilitychange', onVisible)
    schedule()

    return () => {
      if (timer.current) clearTimeout(timer.current)
      for (const e of events) document.removeEventListener(e, schedule)
      document.removeEventListener('visibilitychange', onVisible)
    }
  }, [pathname, router])

  return null
}
