"use client";

import { useEffect, useState } from "react";

export type NetworkState = "online" | "offline" | "syncing";

export function useNetworkStatus() {
  const [state, setState] = useState<NetworkState>("online");

  useEffect(() => {
    const update = () =>
      setState(navigator.onLine ? "online" : "offline");
    update();
    window.addEventListener("online", update);
    window.addEventListener("offline", update);
    return () => {
      window.removeEventListener("online", update);
      window.removeEventListener("offline", update);
    };
  }, []);

  const startSync = () => setState("syncing");
  const endSync = () => setState(navigator.onLine ? "online" : "offline");

  return { state, startSync, endSync, isOffline: state === "offline", isSyncing: state === "syncing" };
}
