import { create } from 'zustand'
import db from '../db/posdb'

const useKdsReadyStore = create((set) => ({
  readyCount: 0,

  // Recompute by scanning IndexedDB orders snapshot
  async refresh() {
    try {
      const orders = await db.pos_orders.toArray()
      let count = 0
      for (const o of orders) {
        if (o.status === 'open' || o.status === 'partially_paid') {
          for (const item of o.items || []) {
            if (item.status !== 'cancelled' && item.kds_status === 'done') {
              count++
            }
          }
        }
      }
      set({ readyCount: count })
    } catch {
      // IndexedDB unavailable — leave as-is
    }
  },
}))

export default useKdsReadyStore
