"use client";

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

export function UpdateChecker() {
  const [hasUpdate, setHasUpdate] = useState(false);
  const currentVersionRef = useRef(null);

  useEffect(() => {
    if (process.env.NODE_ENV !== "production") return;

    let intervalId;

    const fetchVersion = async () => {
      const res = await fetch(`/version.json?t=${Date.now()}`, {
        cache: "no-store",
      });

      if (!res.ok) {
        throw new Error(`Failed to fetch version: ${res.status}`);
      }

      const data = await res.json();
      return String(data.version);
    };

    const init = async () => {
      try {
        currentVersionRef.current = await fetchVersion();

        intervalId = setInterval(async () => {
          try {
            const latestVersion = await fetchVersion();

            if (
              currentVersionRef.current &&
              latestVersion !== currentVersionRef.current
            ) {
              setHasUpdate(true);
              clearInterval(intervalId);
            }
          } catch (err) {
            console.error("Update check failed:", err);
          }
        }, 30000);
      } catch (err) {
        console.error("Initial version fetch failed:", err);
      }
    };

    init();

    return () => {
      if (intervalId) clearInterval(intervalId);
    };
  }, []);

  if (!hasUpdate) return null;

  return (
    <div
      style={{
        position: "fixed",
        bottom: "16px",
        right: "16px",
        background: "#111",
        color: "#fff",
        padding: "12px 16px",
        borderRadius: "8px",
        zIndex: 9999,
        cursor: "pointer",
      }}
      onClick={() => window.location.reload()}
    >
      نسخه جدید سامانه در دسترس است
    </div>
  );
}
