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

export default function UpdatePrompt() {
  const [show, setShow] = useState(false);
  const [active, setActive] = useState(false);

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

    const handleMessage = (event) => {
      if (event.data?.type === "SW_UPDATED") {
        setShow(true);
        requestAnimationFrame(() => setActive(true));
      }
    };

    navigator.serviceWorker.addEventListener("message", handleMessage);
    return () => navigator.serviceWorker.removeEventListener("message", handleMessage);
  }, []);

  if (!show) return null;

  const handleUpdate = () => {
    setActive(false);
    setTimeout(() => {
      window.location.reload();
    }, 250);
  };

  const handleDismiss = () => {
    setActive(false);
    setTimeout(() => setShow(false), 200);
  };

  return (
    <div
      className={`fixed inset-x-0 bottom-28 z-[150] flex justify-center px-4 transition-all duration-300 ease-out ${active ? "opacity-100 translate-y-0" : "opacity-0 translate-y-4"}`}
    >
      <div className="bg-[#2C1810] text-[#FAF6F1] rounded-full shadow-[0_8px_32px_rgba(44,24,16,0.35)] flex items-center gap-3 pl-3 pr-4 py-2.5 max-w-[420px] w-full border border-white/5">
        {/* Icon */}
        <div className="w-9 h-9 rounded-full bg-white/10 flex items-center justify-center flex-shrink-0">
          <RefreshCw size={16} strokeWidth={2.5} className="text-white" />
        </div>

        {/* Text */}
        <div className="flex-1 min-w-0">
          <div className="text-sm font-semibold text-white leading-tight">Update available</div>
          <div className="text-xs text-white/60 mt-0.5">A new version of Brew is ready.</div>
        </div>

        {/* Actions */}
        <div className="flex items-center gap-2 flex-shrink-0">
          <button
            onClick={handleDismiss}
            className="text-xs text-white/50 hover:text-white/80 transition-colors cursor-pointer px-2 py-2"
          >
            Later
          </button>
          <button
            onClick={handleUpdate}
            className="text-xs font-semibold bg-white text-[#2C1810] px-4 py-2 rounded-full hover:bg-white/90 transition-colors cursor-pointer"
          >
            Update
          </button>
        </div>
      </div>
    </div>
  );
}
