import { useState, useEffect } from 'react'
import db from '../db/posdb'

// Polls offline_ops every 3 s and returns the count of unsynced ops.
// Returns 0 when everything is flushed (hides the badge).
export default function useOfflineQueueCount() {
  const [count, setCount] = useState(0)

  useEffect(() => {
    let cancelled = false

    async function refresh() {
      try {
        const ops = await db.offline_ops.toArray()
        if (!cancelled) setCount(ops.filter(o => !o.synced).length)
      } catch {
        // IDB unavailable — leave count as-is
      }
    }

    refresh()
    const id = setInterval(refresh, 3000)
    return () => {
      cancelled = true
      clearInterval(id)
    }
  }, [])

  return count
}
