import { BrainerceClient } from 'brainerce';

/**
 * CLIENT-SAFE half of the SDK wiring — imported by ~30 `'use client'`
 * components. Nothing here may reach `next/headers` or any server-only API,
 * or the client bundle fails to build. The server half lives in
 * `brainerce.server.ts`.
 */

// Read either env var name. The new one is preferred; the old one is a soft
// alias kept for backwards compatibility — both are accepted by the SDK.
export const SALES_CHANNEL_ID =
  process.env.NEXT_PUBLIC_BRAINERCE_SALES_CHANNEL_ID ||
  process.env.NEXT_PUBLIC_BRAINERCE_CONNECTION_ID ||
  '<%= connectionId %>';

// Singleton SDK client — routes through same-origin BFF proxy for httpOnly cookie auth
let clientInstance: BrainerceClient | null = null;

export function getClient(): BrainerceClient {
  if (!clientInstance) {
    clientInstance = new BrainerceClient({
      salesChannelId: SALES_CHANNEL_ID,
      baseUrl: '/api/store', // same-origin proxy handles auth via httpOnly cookie
      proxyMode: true, // skip client-side token checks; proxy adds Authorization header
    });
  }
  return clientInstance;
}
<% if (i18nEnabled) { %>

/** Initialize client with a specific locale for translated content */
export function initClientWithLocale(locale: string): BrainerceClient {
  const client = getClient();
  client.setLocale(locale);
  return client;
}
<% } %>

// Cart identity belongs to the SDK. It owns the guest cart id, the session
// cart and the logged-in cart cache, and `smartGetCart()` resolves the right
// one. Do not mirror a cart id into localStorage here: a second copy drifts
// out of step on login, cart merge and post-payment clear, and the SDK will
// not read it back.

// Initialize client (no token hydration — auth handled by httpOnly cookie)
export function initClient(): BrainerceClient {
  return getClient();
}
