import { useEffect, useRef, useState } from 'react';

const POLL_MS = 60_000;

export function VersionWatcher() {
  const [updateAvailable, setUpdateAvailable] = useState(false);
  const initialSha = useRef<string | null>(null);

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

    async function check() {
      try {
        const res = await fetch('/api/version', { cache: 'no-store' });
        if (!res.ok) return;
        const { sha } = await res.json();
        if (!sha) return;
        if (initialSha.current === null) {
          initialSha.current = sha;
        } else if (sha !== initialSha.current && !cancelled) {
          setUpdateAvailable(true);
        }
      } catch {
        /* network blips: ignore */
      }
    }

    check();
    const id = setInterval(check, POLL_MS);
    const onFocus = () => check();
    window.addEventListener('focus', onFocus);

    return () => {
      cancelled = true;
      clearInterval(id);
      window.removeEventListener('focus', onFocus);
    };
  }, []);

  if (!updateAvailable) return null;

  return (
    <div
      role="status"
      aria-live="polite"
      className="fixed bottom-6 right-6 z-[100] max-w-sm bg-neutral-900 text-white rounded-2xl shadow-xl border border-neutral-700 p-4 flex items-start gap-3 animate-fade-in-up"
    >
      <div className="w-2 h-2 mt-2 bg-secondary-400 rounded-full shrink-0 animate-pulse" />
      <div className="flex-1 min-w-0">
        <div className="text-sm font-heading font-semibold mb-0.5">Versiune nouă disponibilă</div>
        <div className="text-xs text-neutral-300 mb-3">
          Reîncarcă pagina pentru ultimele modificări.
        </div>
        <div className="flex gap-2">
          <button
            onClick={() => window.location.reload()}
            className="text-xs font-medium bg-white text-neutral-900 px-3 py-1.5 rounded-lg hover:bg-neutral-100 transition-colors"
          >
            Reîncarcă
          </button>
          <button
            onClick={() => setUpdateAvailable(false)}
            className="text-xs text-neutral-400 px-2 py-1.5 rounded-lg hover:text-white transition-colors"
          >
            Mai târziu
          </button>
        </div>
      </div>
    </div>
  );
}
