"use client";

import { useEffect, useRef, useState } from "react";
import { RefreshCw, X } from "lucide-react";

const POLL_INTERVAL_MS = 60_000;
const ENDPOINT = "/api/version";

type VersionPayload = { commit: string; commitShort: string; buildTime: string };

export function VersionWatcher() {
  const initialRef = useRef<string | null>(null);
  const [latest, setLatest] = useState<VersionPayload | null>(null);
  const [dismissed, setDismissed] = useState(false);

  useEffect(() => {
    let cancelled = false;

    const fetchVersion = async () => {
      try {
        const res = await fetch(ENDPOINT, { cache: "no-store" });
        if (!res.ok || cancelled) return;
        const data = (await res.json()) as VersionPayload;
        if (!data?.commit) return;
        if (initialRef.current === null) {
          initialRef.current = data.commit;
          return;
        }
        if (data.commit !== initialRef.current) {
          setLatest(data);
        }
      } catch {
        // network noise — ignore
      }
    };

    fetchVersion();
    const interval = setInterval(fetchVersion, POLL_INTERVAL_MS);
    return () => {
      cancelled = true;
      clearInterval(interval);
    };
  }, []);

  if (!latest || dismissed) return null;

  return (
    <div
      role="status"
      className="fixed bottom-4 right-4 z-[60] flex items-center gap-2 rounded-lg border bg-background/95 px-3 py-2 shadow-lg backdrop-blur animate-in fade-in slide-in-from-bottom-2"
    >
      <RefreshCw className="h-4 w-4 text-primary" />
      <div className="flex flex-col text-xs">
        <span className="font-medium">Versiune nouă disponibilă</span>
        <span className="text-muted-foreground">
          <code className="font-mono">{latest.commitShort}</code> · apasă pentru reîncărcare
        </span>
      </div>
      <button
        type="button"
        onClick={() => window.location.reload()}
        className="ml-2 rounded bg-primary px-2 py-1 text-xs font-medium text-primary-foreground hover:bg-primary/90"
      >
        Reîncarcă
      </button>
      <button
        type="button"
        onClick={() => setDismissed(true)}
        className="rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground"
        aria-label="Închide"
      >
        <X className="h-3.5 w-3.5" />
      </button>
    </div>
  );
}
