"use client"; import { withBase } from "@/lib/base-path"; import { useState } from "react"; import { useRouter } from "next/navigation"; import { Icon } from "./Icon"; import { useToast } from "./Toast"; export function RefreshInsightsButton({ pageId, variant = "on-band" }: { pageId: string | null; variant?: "on-band" | "primary" }) { const router = useRouter(); const toast = useToast(); const [busy, setBusy] = useState(false); async function refresh() { setBusy(true); const res = await fetch(withBase("/api/insights/refresh"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ pageId }), }); const body = await res.json().catch(() => ({})); setBusy(false); if (!res.ok || !body.ok) { toast.show(body.error ?? body.errors?.join(" · ") ?? "ดึงข้อมูลไม่สำเร็จ", "error"); return; } toast.show(body.errors?.length ? `ดึงได้ ${body.refreshed} เพจ · ${body.errors.join(" · ")}` : "อัปเดตข้อมูลล่าสุดแล้ว", body.errors?.length ? "warn" : "ok"); router.refresh(); } return ( ); }