"use client";

import { useEffect } from "react";
import { toast } from "sonner";
import { flushOfflineQueue } from "@/lib/offline-queue";

/** Drains any offline-queued actions (lib/offline-queue.ts) once the browser
 * regains connectivity. Background Sync (public/sw.js) already covers this
 * on Chromium, but Safari/Firefox never fire that API at all, so this is
 * the only path that works there — safe to run alongside it since both
 * read/delete from the same IndexedDB queue and a queue drained by one has
 * nothing left for the other to redo. */
export function OfflineSyncManager() {
  useEffect(() => {
    async function flush() {
      const synced = await flushOfflineQueue();
      if (synced > 0) toast.success(`Synced ${synced} offline action${synced === 1 ? "" : "s"}`);
    }

    if (navigator.onLine) void flush();
    window.addEventListener("online", flush);

    function onSwMessage(e: MessageEvent) {
      if (e.data?.type === "epicure:offline-synced" && e.data.count > 0) {
        toast.success(`Synced ${e.data.count} offline action${e.data.count === 1 ? "" : "s"}`);
      }
    }
    navigator.serviceWorker?.addEventListener("message", onSwMessage);

    return () => {
      window.removeEventListener("online", flush);
      navigator.serviceWorker?.removeEventListener("message", onSwMessage);
    };
  }, []);

  return null;
}
