"use client";

import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { RefreshCw } from "lucide-react";

export function SWRegister() {
  const [updateReady, setUpdateReady] = useState(false);
  const [reg, setReg] = useState<ServiceWorkerRegistration | null>(null);

  useEffect(() => {
    if (!("serviceWorker" in navigator)) return;

    navigator.serviceWorker.register("/sw.js").then((registration) => {
      setReg(registration);

      registration.addEventListener("updatefound", () => {
        const installing = registration.installing;
        if (!installing) return;
        installing.addEventListener("statechange", () => {
          if (installing.state === "installed" && navigator.serviceWorker.controller) {
            setUpdateReady(true);
          }
        });
      });

      // Check for waiting worker immediately (page reload after update)
      if (registration.waiting) setUpdateReady(true);
    });

    // Reload when new SW activates
    navigator.serviceWorker.addEventListener("controllerchange", () => {
      window.location.reload();
    });
  }, []);

  function applyUpdate() {
    if (reg?.waiting) {
      reg.waiting.postMessage("SKIP_WAITING");
    }
  }

  if (!updateReady) return null;

  return (
    <div className="fixed bottom-4 left-4 right-4 z-50 flex items-center justify-between gap-3 bg-slate-900 text-white px-4 py-3 rounded-xl shadow-xl max-w-sm mx-auto">
      <p className="text-sm font-medium">A new version is available.</p>
      <Button size="sm" variant="secondary" onClick={applyUpdate} className="gap-1.5 flex-shrink-0">
        <RefreshCw className="h-3.5 w-3.5" />
        Update
      </Button>
    </div>
  );
}
