"use client";

import * as React from "react";
import { useConvex } from "convex/react";
import { AnimatePresence, motion } from "motion/react";
import { CloudOff, RefreshCw, Wifi } from "lucide-react";
import { cn } from "@/lib/utils";

type State = "online" | "reconnecting" | "offline" | "restored";

/**
 * Connection indicator driven by the Convex WebSocket. The reactive client
 * reconnects on its own; this only tells the user what is happening. It
 * drops in from under the top bar and springs away when the link is back.
 */
export function ConnectionStatus() {
  const convex = useConvex();
  const [state, setState] = React.useState<State>("online");
  React.useEffect(() => {
    let wasDown = false;
    let stop = false;
    const tick = () => {
      if (stop) return;
      const cs = convex.connectionState();
      const down = !navigator.onLine || (!cs.isWebSocketConnected && cs.hasEverConnected);
      if (!navigator.onLine) setState("offline");
      else if (down) setState("reconnecting");
      else if (wasDown) {
        setState("restored");
        setTimeout(() => setState((s) => (s === "restored" ? "online" : s)), 2500);
      } else setState((s) => (s === "restored" ? s : "online"));
      wasDown = down;
    };
    const id = setInterval(tick, 2000);
    window.addEventListener("online", tick);
    window.addEventListener("offline", tick);
    return () => {
      stop = true;
      clearInterval(id);
      window.removeEventListener("online", tick);
      window.removeEventListener("offline", tick);
    };
  }, [convex]);
  return (
    <AnimatePresence>
      {state !== "online" ? (
        <motion.div
          key={state}
          role="status"
          aria-live="polite"
          initial={{ opacity: 0, y: -16, scale: 0.9 }}
          animate={{ opacity: 1, y: 0, scale: 1 }}
          exit={{ opacity: 0, y: -10, scale: 0.95 }}
          transition={{ type: "spring", stiffness: 420, damping: 30 }}
          className={cn("pointer-events-none fixed left-1/2 top-16 z-[70] -translate-x-1/2 rounded-full border px-3 py-1.5 text-xs font-medium shadow-lg backdrop-blur", state === "restored" ? "border-positive-500/40 bg-positive-50 text-positive-700 dark:bg-positive-500/15" : state === "offline" ? "border-negative-500/40 bg-negative-50 text-negative-700 dark:bg-negative-500/15" : "border-warning-500/40 bg-warning-50 text-warning-700 dark:bg-warning-500/15")}
        >
          <span className="flex items-center gap-1.5">
            {state === "restored" ? <Wifi className="size-3.5" /> : state === "offline" ? <CloudOff className="size-3.5" /> : <RefreshCw className="size-3.5 animate-spin" />}
            {state === "restored" ? "Synced" : state === "offline" ? "You are offline" : "Reconnecting…"}
          </span>
        </motion.div>
      ) : null}
    </AnimatePresence>
  );
}
