"use client"; // components/ClientToggle.tsx // Toggles `is_client` on a director or company row. // // Optimistic: flips UI immediately, reverts and shows an inline // error banner if the API call fails. Used both inline (row hover) // and on the detail page (full button + label). import { useState } from "react"; import { pbToggleClient } from "@/lib/api"; type Collection = "ysterbaard_directors" | "ysterbaard_companies"; interface Props { collection: Collection; id: string; isClient: boolean; /** "pill" hides the text label so it can sit inline in a row; * "button" shows the label + on/off state. */ variant?: "pill" | "button"; /** Optional className passthrough. */ className?: string; /** Called after a successful server-side toggle. Use to invalidate * the surrounding query so PB truth is reflected. */ onAfterToggle?: () => void; } export default function ClientToggle({ collection, id, isClient, variant = "pill", className = "", onAfterToggle }: Props) { const [optimistic, setOptimistic] = useState(isClient); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); // When the upstream `isClient` prop changes (e.g. after a refetch), // keep optimistic in sync. if (!busy && optimistic !== isClient) { setOptimistic(isClient); } async function toggle() { const next = !optimistic; // Confirm before making the change const confirmed = window.confirm( next ? "Mark this as a client?\n\nClick OK to confirm, Cancel to abort." : "Remove client status?\n\nClick OK to confirm, Cancel to abort." ); if (!confirmed) return; setOptimistic(next); setBusy(true); setError(null); try { await pbToggleClient({ collection, id, is_client: next }); onAfterToggle?.(); } catch (e) { // Revert and surface. setOptimistic(!next); setError(e instanceof Error ? e.message : "Toggle failed"); // Auto-clear the inline error after a beat. setTimeout(() => setError(null), 5000); } finally { setBusy(false); } } if (variant === "button") { return (
{error ? (

{error}

) : null}
); } // pill (row-inline) variant return ( {error ? ( ⚠ {error} ) : null} ); }