import { useEffect, useState } from "react";
import { Download, X } from "lucide-react";
import { checkUpdate, openExternal, type ReleaseInfo } from "../lib/version";

// 启动时查 GitHub Releases，有新版则在顶部显示一条可关闭的横幅，点击去下载页。
export function UpdateBanner() {
  const [rel, setRel] = useState<ReleaseInfo | null>(null);
  const [dismissed, setDismissed] = useState(false);

  useEffect(() => {
    let alive = true;
    void checkUpdate().then((r) => {
      if (alive) setRel(r);
    });
    return () => {
      alive = false;
    };
  }, []);

  if (!rel || dismissed) return null;
  return (
    <div className="flex shrink-0 items-center gap-3 border-b border-brand/30 bg-brand/10 px-4 py-1.5 text-[12px] text-brand-200">
      <Download className="h-3.5 w-3.5 text-brand-400" />
      <span>
        新版本 <span className="font-semibold">v{rel.version}</span> 可用
      </span>
      <button
        onClick={() => openExternal(rel.url)}
        className="rounded bg-brand/20 px-2 py-0.5 text-brand-200 hover:bg-brand/30"
      >
        前往下载
      </button>
      <button onClick={() => setDismissed(true)} className="ml-auto text-slate-500 hover:text-slate-300" title="忽略">
        <X className="h-3.5 w-3.5" />
      </button>
    </div>
  );
}
