import { useEffect, useRef } from 'react'
import type { SiteContent } from '../content'

/**
 * Silently saves a draft to /api/admin-content-draft every `interval` ms
 * whenever the content has changed since the last save.
 *
 * Usage:
 *   useAutosave(form, isDirty, handleSaveDraft)
 *
 * The `saveFn` should be stable (useCallback) or a ref-wrapped function.
 */
export function useAutosave(
  content: SiteContent,
  isDirty: boolean,
  saveFn: () => Promise<void>,
  interval = 30_000,
) {
  const saveFnRef = useRef(saveFn)
  saveFnRef.current = saveFn

  const isDirtyRef = useRef(isDirty)
  isDirtyRef.current = isDirty

  useEffect(() => {
    const id = window.setInterval(() => {
      if (!isDirtyRef.current) return
      saveFnRef.current().catch(() => {
        // Autosave failures are silent; the user still sees the "Unsaved" indicator
      })
    }, interval)

    return () => window.clearInterval(id)
  }, [interval])

  // Persist to sessionStorage as an immediate local backup
  useEffect(() => {
    try {
      sessionStorage.setItem('admin-autosave-draft', JSON.stringify(content))
    } catch {
      // sessionStorage quota exceeded — ignore silently
    }
  }, [content])
}
