import { useState, useEffect, useCallback } from 'react';
import { listPendingOrders, type PendingOrder } from '../offline/order-queue';

export function usePendingOrders() {
  const [orders, setOrders] = useState<PendingOrder[]>([]);

  const refresh = useCallback(async () => {
    const pending = await listPendingOrders();
    setOrders(pending);
  }, []);

  useEffect(() => {
    void refresh();

    const handle = () => void refresh();
    window.addEventListener('sar:sync-complete', handle);
    window.addEventListener('sar:sync-request', handle);
    window.addEventListener('sar:order-queued', handle);
    return () => {
      window.removeEventListener('sar:sync-complete', handle);
      window.removeEventListener('sar:sync-request', handle);
      window.removeEventListener('sar:order-queued', handle);
    };
  }, [refresh]);

  return { orders, refresh };
}
