"use client";

import { useEffect, useState, useSyncExternalStore } from "react";
import { getQueuedActions } from "@/lib/offline/queue";

function subscribeOnline(callback: () => void): () => void {
  window.addEventListener("online", callback);
  window.addEventListener("offline", callback);
  return () => {
    window.removeEventListener("online", callback);
    window.removeEventListener("offline", callback);
  };
}

function getOnlineSnapshot(): boolean {
  return navigator.onLine;
}

function getOnlineServerSnapshot(): boolean {
  return true;
}

export function OfflineBanner() {
  const [pendingCount, setPendingCount] = useState(0);
  const online = useSyncExternalStore(subscribeOnline, getOnlineSnapshot, getOnlineServerSnapshot);

  useEffect(() => {
    let cancelled = false;
    const tick = async () => {
      const actions = await getQueuedActions();
      if (cancelled) return;
      setPendingCount(actions.filter((a) => a.status === "pending" || a.status === "in-flight").length);
    };
    void tick();
    const interval = setInterval(tick, 1000);
    return () => {
      cancelled = true;
      clearInterval(interval);
    };
  }, []);

  if (online && pendingCount === 0) return null;

  return (
    <div
     
      aria-live="polite"
      className="sticky top-0 z-40 w-full px-4 py-2 text-sm font-semibold"
      style={{
        backgroundColor: online ? "var(--color-warning-soft)" : "var(--color-danger-soft)",
        color: online ? "var(--color-warning)" : "var(--color-danger)",
      }}
    >
      {online ? (
        <>Syncing {pendingCount} pending action{pendingCount === 1 ? "" : "s"}…</>
      ) : (
        <>You&apos;re offline. Changes will sync when you reconnect.</>
      )}
    </div>
  );
}

export default OfflineBanner;
