"use client"; import { useEffect, useRef, useState } from "react"; function newKey(): string { return crypto.randomUUID(); } /** * Remembered keys survive an unmount so the split panel can retry the same allocation after * the payment dialog is closed and reopened (redesign-pos-sale-flow, BABYBOO-38). * The map is keyed by the caller's `cartSignature` and cleared (to a fresh key) when `onOrderPlaced` * fires — the next attempt is a different order. */ // Keys remembered per signature for `remember` callers (redesign-pos-sale-flow): the split panel lives in // the payment dialog, which unmounts when it closes, so reopening it and retrying the same allocation must // reuse the key the counter already dedups on. `onOrderPlaced` replaces the remembered key. const remembered = new Map(); function keyFor(signature: string, remember: boolean): string { if (!remember) return newKey(); const key = remembered.get(signature) ?? newKey(); remembered.set(signature, key); return key; } export function usePosClientKey( cartSignature: string, options?: { remember?: boolean }, ): { clientKey: string; onOrderPlaced: () => void; } { const remember = options?.remember ?? false; const [clientKey, setClientKey] = useState(() => keyFor(cartSignature, remember)); const prevSignature = useRef(cartSignature); useEffect(() => { if (prevSignature.current !== cartSignature) { prevSignature.current = cartSignature; setClientKey(keyFor(cartSignature, remember)); } }, [cartSignature, remember]); const onOrderPlaced = () => { const k = newKey(); if (remember) { remembered.set(cartSignature, k); } setClientKey(k); }; return { clientKey, onOrderPlaced }; }