'use client'; import { useEffect, useRef } from 'react'; import { useCart } from '@/core/providers/store-provider'; import { useIsCartOrCheckoutRoute } from '@/core/hooks/use-route-chrome'; import { getClient } from '@/core/lib/brainerce'; /** * Mounts the Brainerce AI chat widget (the store's shopping assistant). * * Everything about the bot — name, avatar, colors, greeting, starter * questions, capabilities, guardrails — is configured by the merchant in the * Brainerce dashboard (Customers → Storefront Bot). This component renders * nothing until the bot is switched Live there, so it is always safe to keep * mounted. * * It is destroyed on `/cart` and `/checkout` (`/he/cart` too) and created again * when the shopper leaves them: a floating bubble over the order summary, the * coupon field or the pay button is the thing that covers the controls a * shopper is trying to reach at the moment that matters most. * * The widget's product cards call `onAddToCart`, which goes through the same * cart store `add` as the storefront's own product cards, so the header cart * count stays in sync. * * When the platform switched the bot's cart tools on for this store, the bot * changes the cart on the SERVER. `getCartProof` tells it which cart this * shopper holds (asked before every turn, so it follows a login or an account * switch) and `onCartUpdated` re-reads the cart from the server afterwards. * Both are harmless while the cart tools are off. */ export function BrainerceBotWidget() { const { add, cart, refreshCart } = useCart(); const addRef = useRef(add); addRef.current = add; // The widget is mounted once, so these are read through refs: a closure // would keep answering with the cart (or refresh) of the render it was made in. const cartIdRef = useRef(null); cartIdRef.current = cart?.id ?? null; const refreshCartRef = useRef(refreshCart); refreshCartRef.current = refreshCart; // A boolean, not the pathname: the effect below must re-run when the answer // flips, not on every navigation, or the widget would be torn down and // rebuilt (and re-fetch its settings) on each page change. const hidden = useIsCartOrCheckoutRoute(); useEffect(() => { if (hidden) return; const connectionId = process.env.NEXT_PUBLIC_BRAINERCE_SALES_CHANNEL_ID || process.env.NEXT_PUBLIC_BRAINERCE_CONNECTION_ID; if (!connectionId) return; let bot: { destroy(): void } | null = null; let cancelled = false; // CF-082: `mount` fetches the bot's settings, so a run that was cleaned up before the import // resolved (React StrictMode in development, a quick route flip) must not call it at all. It used to // check `cancelled` only AFTER mounting, which made a second `/settings` request per page. void import('brainerce/bot').then(({ BrainerceBot }) => cancelled ? null : BrainerceBot.mount({ connectionId, baseUrl: process.env.NEXT_PUBLIC_BRAINERCE_API_URL || undefined, // Order-lookup login gating: this template's own same-origin BFF proxy // (see src/app/api/store/[...path]/route.ts) already forwards the // shopper's httpOnly session cookie as a Bearer header — the same // mechanism @/core/lib/brainerce's own client uses. Opting the bot in // here lets it detect login state without the widget ever touching the // cookie itself. customerSessionProxyPath: '/api/store', onAddToCart: async ({ productId, variantId, quantity }) => { // The store queues the add and adopts the server's answer; nothing to // re-read afterwards. `false` makes the widget fall back to the // product page. const result = await addRef.current({ productId, variantId: variantId ?? undefined, quantity, }); return result.ok; }, getCartProof: () => { // The SDK client holds a GUEST cart's token in memory and drops it once // the cart is linked to an account. A signed-in shopper's cart is proven // by the bot session instead, so only the cart id goes for that one. const held = getClient().getHeldCartProof(); const cartId = cartIdRef.current ?? held?.cartId ?? null; if (!cartId) return null; return held && held.cartId === cartId ? { cartId, cartToken: held.cartToken } : { cartId }; }, // The server already changed the cart: re-read it, never apply numbers locally. onCartUpdated: async () => { await refreshCartRef.current(); }, }).then((mounted) => { if (cancelled) mounted?.destroy(); else bot = mounted; }) ); return () => { cancelled = true; bot?.destroy(); }; }, [hidden]); return null; }