'use client'; import { useCallback, useEffect, useState } from 'react'; import type { StateSnapshot } from '@/lib/game/state'; import { sessionHeaders } from './authClient'; // ISS-021 (v0.20.0) — shared action runner for the side panes (extracted verbatim from // RightPane.runAction when the On board section moved to LeftPane). POSTs an action endpoint; // every success returns the FULL post-action snapshot (v0.8.0 convention), pushed into the // shared shell state immediately via applySnapshot so the UI updates without waiting for the // next poll tick. A non-2xx {error} body becomes the pane's inline error AND is mirrored to // the shell as a bottom-right toast via onError (ISS-008 — both surfaces by design). Buttons // are disabled while a request is in flight, so at most one action runs per pane at a time. export function useGameAction( state: StateSnapshot | null, applySnapshot: (snapshot: StateSnapshot) => void, onError?: (message: string) => void, ): { runAction: (path: string, body?: unknown) => Promise; busy: boolean; actionError: string | null } { const [busy, setBusy] = useState(false); // Inline error from a failed action — auto-clears on the next successful poll (the shell's // snapshot prop changes every tick) or the next successful action. const [actionError, setActionError] = useState(null); useEffect(() => { if (state !== null) setActionError(null); }, [state]); const runAction = useCallback( async (path: string, body?: unknown) => { if (busy) return; setBusy(true); try { const res = await fetch(path, { method: 'POST', // v1.1.0 (ISS-107): action endpoints are session-guarded — echo the stored id. headers: { 'Content-Type': 'application/json', ...sessionHeaders() }, body: body === undefined ? undefined : JSON.stringify(body), cache: 'no-store', }); const data = (await res.json()) as StateSnapshot & { error?: string }; if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`); setActionError(null); applySnapshot(data); } catch (err) { const message = err instanceof Error ? err.message : String(err); setActionError(message); // inline pane error stays… onError?.(message); // …and the shell mirrors it as a bottom-right toast (ISS-008) } finally { setBusy(false); } }, [applySnapshot, busy, onError], ); return { runAction, busy, actionError }; }