'use client';

import React, {
  createContext,
  useContext,
  useEffect,
  useMemo,
  useRef,
  useState,
  useCallback,
} from 'react';
import { useRouter } from 'next/navigation';
import type {
  AddToCartInput,
  Cart,
  CartIncludeOption,
  CartStore,
  CartStoreStatus,
  CartWithIncludes,
  CustomerProfile,
  PublicRegion,
  WishlistKey,
} from 'brainerce';
import { createCartStore, getCartTotals } from 'brainerce';
import { CartProvider, useCart as useCartSnapshot, useCartStore } from 'brainerce/react';
import { SALES_CHANNEL_ID, getClient, initClient } from '@/core/lib/brainerce';
import { pickRegion, readRegionCookie, writeRegionCookie } from '@/core/lib/region';
import { pickPublicStoreInfo, type PublicStoreInfo } from '@/core/lib/store-info';
import {
  pickPublicCapabilities,
  type PublicStoreCapabilities,
} from '@/core/lib/capabilities';
import { checkAuthStatus, proxyLogout } from '@/core/lib/auth';
import { WishlistProvider } from '@/core/providers/wishlist-provider';
<% if (i18nEnabled) { %>
import { MessagesContext } from '@/core/lib/translations';
import { getMessages, defaultLocale, supportedLocales } from '@/i18n';
<% } %>

// ---- Store Info Context ----
interface StoreInfoContextValue {
  storeInfo: PublicStoreInfo | null;
  loading: boolean;
}

const StoreInfoContext = createContext<StoreInfoContextValue>({
  storeInfo: null,
  loading: true,
});

export function useStoreInfo() {
  return useContext(StoreInfoContext);
}

// ---- Store Capabilities Context ----
// What the merchant configured on this sales channel: low-stock warning and
// threshold, back-in-stock alerts, reservation timeout, and which optional
// features are switched on. Fetched ONCE for the whole app — it is per sales
// channel, not per product, so a page-level fetch would be repeated work.
interface StoreCapabilitiesContextValue {
  capabilities: PublicStoreCapabilities | null;
  capabilitiesLoading: boolean;
}

// The default is a real value, not a throw: a component rendered during SSR or
// outside <StoreProvider> reads `null` and falls back to its own default rather
// than crashing the tree.
const StoreCapabilitiesContext = createContext<StoreCapabilitiesContextValue>({
  capabilities: null,
  capabilitiesLoading: true,
});

export function useStoreCapabilities() {
  return useContext(StoreCapabilitiesContext);
}

// ---- Region Context ----
// Which region prices this session. Seeded from the server (see RootLayout,
// which calls resolveRegion()) so SSR and the client agree from frame 0
// instead of the client flipping the currency after hydration.
//
// ⛔ A single-region store is a NO-OP by design. `regions.length <= 1` means
// the switcher renders nothing and `regionId` is the default the backend
// would have picked anyway. Nothing about this is conditional on a capability
// flag: there ISN'T one for regions, and a storefront that skips `regionId`
// does not hide a feature, it shows every shopper the default region's prices.
interface RegionContextValue {
  /** Active regions, default first. Empty when the store has none. */
  regions: PublicRegion[];
  /** The region in force, or null when the store has no regions. */
  region: PublicRegion | null;
  /** Spread into SDK reads: `...(regionId ? { regionId } : {})`. */
  regionId: string | undefined;
  /** Buyer country from the edge, or null. Reused by the tax estimate. */
  buyerCountry: string | null;
  /** Switch region: persists the choice and re-fetches server + client data. */
  setRegion: (regionId: string) => void;
}

const RegionContext = createContext<RegionContextValue>({
  regions: [],
  region: null,
  regionId: undefined,
  buyerCountry: null,
  setRegion: () => {},
});

export function useRegion() {
  return useContext(RegionContext);
}

// ---- Auth Context ----
interface AuthContextValue {
  isLoggedIn: boolean;
  authLoading: boolean;
  customer: CustomerProfile | null;
  login: () => Promise<void>;
  logout: () => Promise<void>;
}

const AuthContext = createContext<AuthContextValue>({
  isLoggedIn: false,
  authLoading: true,
  customer: null,
  login: async () => {},
  logout: async () => {},
});

export function useAuth() {
  return useContext(AuthContext);
}

// ---- Cart ----
//
// ⛔ The cart is NOT React state in this file. It lives in one cart store (from
// the SDK) that owns everything cart behaviour needs: the optimistic view, a
// serial queue of writes, explicit loading/empty/ready/error statuses, the item
// count remembered from the last visit, and the epoch that discards answers from
// a previous login. A hand-written copy of that logic in a storefront is where
// every "the cart shows 0", "my quantity jumped back" and "double fetch on
// login" bug used to come from.
//
// The rules that follow from it, for every component and hook:
//   1. Change the cart with the actions from `useCart()` (`add`, `setQuantity`,
//      `remove`, `applyCoupon`, `removeCoupon`, `clear`). NEVER call a mutating
//      SDK method and then re-read the cart: the action already did both, in
//      order, and shows the change instantly.
//   2. Render `status`, not `cart === null`. `loading` is "no answer yet", `empty`
//      is "the server said so", `error` is "could not load" (offer `retry`).
//   3. Before leaving for /checkout, `await flush()` and continue only when `ok`.
//
// Created at MODULE level, not inside a component, so that its first request is
// sent while the bundle is still loading, before React hydrates. On the server
// this is inert: `start()` does nothing without a `window`, and the server
// renders the `loading` snapshot, so nothing is shared between requests.
const cartStore: CartStore = createCartStore(getClient(), { scope: SALES_CHANNEL_ID });
<% if (i18nEnabled) { %>
// The cart's lines carry translated product names, taken from the client's
// locale. That locale is normally set in an effect, which runs AFTER this first
// request. Read it from the URL instead, so the very first answer is already in
// the shopper's language.
let cartLocale: string | undefined;
<% } %>
if (typeof window !== 'undefined') {
<% if (i18nEnabled) { %>
  const firstSegment = window.location.pathname.split('/')[1];
  cartLocale = (supportedLocales as readonly string[]).includes(firstSegment)
    ? firstSegment
    : defaultLocale;
  getClient().setLocale(cartLocale);
<% } %>
  cartStore.start();
}

/** The outcome of ONE write, for the caller that made it. Writes never throw. */
export type CartWriteResult =
  | { ok: true; error: null }
  /** `error` is the original error: a `BrainerceError` carries `details.code`. */
  | { ok: false; error: Error };

/**
 * Run one store action and report whether THAT write failed.
 *
 * Store actions always resolve, and `mutationError` is a single shared slot, so
 * "await add(...) then read mutationError" is easy to get wrong. This does it
 * once: the action is queued synchronously, so nothing can slip in between the
 * call and the read, and a write that was a quiet no-op (a quantity that did not
 * change) is not blamed for an older, unrelated failure.
 */
async function trackWrite(
  store: CartStore,
  action: () => Promise<void>
): Promise<CartWriteResult> {
  const before = store.getSnapshot();
  await action();
  const after = store.getSnapshot();
  if (after.epoch !== before.epoch) {
    // A login, logout or order completion landed mid-write: the write was discarded.
    return { ok: false, error: new Error('The cart changed before this update was saved.') };
  }
  if (after.mutationError && after.mutationError !== before.mutationError) {
    return { ok: false, error: after.mutationError };
  }
  return { ok: true, error: null };
}

/**
 * What `useCart()` returns.
 *
 * Additive over the original `{ cart, cartLoading, refreshCart, itemCount,
 * totals }`: every legacy field keeps its meaning, so code written against the
 * old shape still compiles and works.
 */
export interface UseCartResult {
  // ---- legacy fields ----
  /** The optimistic view: the last server answer with pending quantity changes and removals applied. */
  cart: Cart | null;
  /** True only before the FIRST answer (and again right after a login/logout). Prefer `status`. */
  cartLoading: boolean;
  /**
   * Force a re-read from the server. Only for changes the store did not make
   * itself (an order bump, a checkout-scoped coupon, an expired reservation).
   * After a store action it is never needed.
   */
  refreshCart: () => Promise<void>;
  /** Units in the cart. Before the first answer: the count remembered from the last visit, so the header badge never flashes 0. */
  itemCount: number;
  /** From the last CONFIRMED cart. Never computed from the optimistic lines. */
  totals: { subtotal: number; discount: number; shipping: number; total: number };

  // ---- state ----
  /** `loading`: no answer yet · `empty`: the server says no lines · `ready` · `error`: the load failed, call `retry()`. */
  status: CartStoreStatus;
  /** Item count from the previous visit (0 when unknown). Size a skeleton with it, never print it as data. */
  hintCount: number;
  /** A write is queued or in flight, or a refresh is running. */
  isSyncing: boolean;
  /** Writes are pending, so `totals` do not include them yet. Dim the amounts, do not hide them. */
  totalsStale: boolean;
  /** The store's own gate: ready, nothing pending, no unavailable line, reservation alive. */
  canCheckout: boolean;
  /** The last failed load (shown with `retry`). */
  loadError: Error | null;
  /** The last failed write, already rolled back. Cleared by `dismissMutationError()` or the next good write. */
  mutationError: Error | null;
  /** The cart store itself, for the rare imperative call (`store.getSnapshot()`). */
  store: CartStore;

  // ---- actions (each resolves with the outcome of its own write) ----
  add(input: AddToCartInput): Promise<CartWriteResult>;
  /** Absolute quantity. Rapid taps are merged: a burst sends at most two requests. `<= 0` removes the line. */
  setQuantity(itemId: string, quantity: number): Promise<CartWriteResult>;
  remove(itemId: string): Promise<CartWriteResult>;
  applyCoupon(code: string): Promise<CartWriteResult>;
  removeCoupon(): Promise<CartWriteResult>;
  clear(): Promise<CartWriteResult>;
  /** Leave `status === 'error'`: loads the cart again. */
  retry(): Promise<void>;
  /** Wait for queued writes to land. Call before navigating to /checkout and continue only when `ok`. */
  flush(): Promise<{ ok: boolean }>;
  dismissMutationError(): void;
  /** One request for the cart page's extras (`recommendations`, `upgrades`, `bundles`). Null when it failed. */
  loadEnrichment(include: CartIncludeOption[]): Promise<CartWithIncludes | null>;
}

const ZERO_TOTALS = { subtotal: 0, discount: 0, shipping: 0, total: 0 };

export function useCart(): UseCartResult {
  const snapshot = useCartSnapshot();
  const { store } = snapshot;

  const refreshCart = useCallback(() => store.refresh({ force: true }), [store]);

  // Bound once per store, so the identities below are stable and safe in effect deps.
  const writes = useMemo(
    () => ({
      add: (input: AddToCartInput) => trackWrite(store, () => store.add(input)),
      setQuantity: (itemId: string, quantity: number) =>
        trackWrite(store, () => store.setQuantity(itemId, quantity)),
      remove: (itemId: string) => trackWrite(store, () => store.remove(itemId)),
      applyCoupon: (code: string) => trackWrite(store, () => store.applyCoupon(code)),
      removeCoupon: () => trackWrite(store, () => store.removeCoupon()),
      clear: () => trackWrite(store, () => store.clear()),
    }),
    [store]
  );

  const totals = useMemo(
    () => (snapshot.cart ? getCartTotals(snapshot.cart) : ZERO_TOTALS),
    [snapshot.cart]
  );

  return useMemo<UseCartResult>(
    () => ({
      cart: snapshot.cart,
      cartLoading: snapshot.status === 'loading',
      refreshCart,
      itemCount: snapshot.itemCount,
      totals,
      status: snapshot.status,
      hintCount: snapshot.hintCount,
      isSyncing: snapshot.isSyncing,
      totalsStale: snapshot.totalsStale,
      canCheckout: snapshot.canCheckout,
      loadError: snapshot.loadError,
      mutationError: snapshot.mutationError,
      store,
      ...writes,
      retry: snapshot.retry,
      flush: snapshot.flush,
      dismissMutationError: snapshot.dismissMutationError,
      loadEnrichment: snapshot.loadEnrichment,
    }),
    [snapshot, store, refreshCart, totals, writes]
  );
}

/**
 * The cart store, for code that needs a STABLE handle in an effect dependency
 * list (`useCart()` returns a new object whenever the cart changes). Typical
 * use: `useCartStore().reset('order-complete')` after a paid order.
 */
export { useCartStore };

// ---- Provider Component ----
<% if (i18nEnabled) { %>
export function StoreProvider({
  children,
  locale,
  initialStoreInfo = null,
  initialMessages,
  initialRegions = [],
  initialRegion = null,
  initialCountry = null,
}: {
  children: React.ReactNode;
  locale?: string;
  initialStoreInfo?: PublicStoreInfo | null;
  initialMessages?: Record<string, Record<string, string>>;
  initialRegions?: PublicRegion[];
  initialRegion?: PublicRegion | null;
  initialCountry?: string | null;
}) {
<% } else { %>
export function StoreProvider({
  children,
  initialStoreInfo = null,
  initialRegions = [],
  initialRegion = null,
  initialCountry = null,
}: {
  children: React.ReactNode;
  initialStoreInfo?: PublicStoreInfo | null;
  initialRegions?: PublicRegion[];
  initialRegion?: PublicRegion | null;
  initialCountry?: string | null;
}) {
<% } %>
  // Seed from server-rendered data when available so SSR consumers (PriceDisplay,
  // FreeShippingBar, locale-aware UI, etc.) render with real values from frame 0
  // instead of falling back to USD/defaults until hydration completes.
  const [storeInfo, setStoreInfo] = useState<PublicStoreInfo | null>(initialStoreInfo);
  const [storeLoading, setStoreLoading] = useState(!initialStoreInfo);
  const [capabilities, setCapabilities] = useState<PublicStoreCapabilities | null>(null);
  const [capabilitiesLoading, setCapabilitiesLoading] = useState(true);
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [customer, setCustomer] = useState<CustomerProfile | null>(null);
  const [authLoading, setAuthLoading] = useState(true);
  // The cart store's notion of WHO the shopper is. It is deliberately not
  // `isLoggedIn`: that starts `false` and flips in an effect, so deriving the key
  // from it would reset the cart (and refetch it) on every page load of every
  // logged-in shopper. This starts from the same cookie the SDK reads for the
  // store's first request, so on a normal load it never changes. It is only ever
  // handed to <CartProvider>, never rendered, so reading `document` here cannot
  // cause a hydration mismatch.
  //
  //   null          signed out
  //   customer:<n>  signed in; <n> grows on every login() so that a login which
  //                 happens while the key is already `customer:*` (an OAuth
  //                 redirect lands with the cookie set, before the guest cart is
  //                 merged) still resets the store exactly once.
  const loginSeqRef = useRef(0);
  // The account wishlist `login()` already read while merging the guest list, for the session
  // key it is about to set. <WishlistProvider> reuses it instead of reading the list again.
  const wishlistSeedRef = useRef<{ authKey: string; keys: WishlistKey[] } | null>(null);
  const [cartAuthKey, setCartAuthKey] = useState<string | null>(() =>
    typeof document !== 'undefined' && document.cookie.includes('brainerce_logged_in=1')
      ? 'customer:0'
      : null
  );
  const [regions, setRegions] = useState<PublicRegion[]>(initialRegions);
  const [region, setRegionState] = useState<PublicRegion | null>(initialRegion);
  const router = useRouter();
<% if (i18nEnabled) { %>
  // Seed from server-rendered messages (see RootLayout) so translated text
  // renders at frame 0 instead of a window of raw "namespace.key" strings
  // before the client-only fetch in the effect below resolves — this also
  // closes the same gap on every locale switch, since RootLayout re-runs
  // server-side per locale and StoreProvider remounts with fresh initial data.
  const [messages, setMessages] = useState<Record<string, Record<string, string>>>(
    initialMessages ?? {}
  );
<% } %>

  // Check auth status via httpOnly cookie (server-side validation).
  //   'in'      the server confirmed a session
  //   'out'     the server answered: no session
  //   'unknown' the check itself failed (network). Says nothing about the session.
  const refreshAuth = useCallback(async (): Promise<'in' | 'out' | 'unknown'> => {
    try {
      const status = await checkAuthStatus();
      setIsLoggedIn(status.isLoggedIn);
      setCustomer(status.isLoggedIn ? (status.customer as CustomerProfile) : null);
      return status.isLoggedIn ? 'in' : 'out';
    } catch {
      setIsLoggedIn(false);
      setCustomer(null);
      return 'unknown';
    } finally {
      setAuthLoading(false);
    }
  }, []);

  // Initialize client, check auth, and fetch store info
  useEffect(() => {
    const client = initClient();
<% if (i18nEnabled) { %>

    // Set locale on SDK client for translated product content
    if (locale) {
      client.setLocale(locale);
      // The cart store loaded in the locale the URL named at bundle load. A
      // different one here means the shopper switched language: its lines hold
      // product names in the old language, so read them again.
      if (cartLocale !== locale) {
        cartLocale = locale;
        void cartStore.refresh({ force: true });
      }
    }

    // Load UI message strings for current locale
    getMessages(locale || defaultLocale).then(setMessages);
<% } %>

    // Optimistic check: if brainerce_logged_in cookie exists, assume logged in
    // while we validate the actual token server-side
    if (typeof document !== 'undefined' && document.cookie.includes('brainerce_logged_in=1')) {
      setIsLoggedIn(true);
    }

    // Validate auth token server-side. The cart store already loaded as a
    // signed-in shopper when the cookie said so; only a DEFINITE "no session"
    // answer (a stale cookie) changes that, and a login() that completed while
    // this check was in flight wins over it.
    const loginSeqAtStart = loginSeqRef.current;
    void refreshAuth().then((outcome) => {
      if (outcome === 'out' && loginSeqRef.current === loginSeqAtStart) setCartAuthKey(null);
    });

    // Fetch store info only when the server didn't already provide it. The
    // happy path is that <RootLayout> SSR'd fetchStoreInfo() and seeded us via
    // initialStoreInfo; this branch is the failure fallback (server fetch
    // returned null) so user-facing components don't render forever as 'USD'.
    if (!initialStoreInfo) {
      client
        .getStoreInfo()
        .then((raw) => setStoreInfo(pickPublicStoreInfo(raw)))
        .catch(console.error)
        .finally(() => setStoreLoading(false));
    }
<% if (i18nEnabled) { %>
  }, [refreshAuth, locale, initialStoreInfo]);
<% } else { %>
  }, [refreshAuth, initialStoreInfo]);
<% } %>

  // Fetch the channel's capabilities once, on mount. Deliberately its own
  // effect with no dependencies: the payload carries no translated content, so
  // folding it into the effect above would refetch it on every locale switch
  // for nothing.
  //
  // ⛔ This must never break the store. A brand-new store is empty and this
  // call can fail (offline, a channel not yet live, a backend hiccup). On
  // failure we keep `capabilities` at null and every consumer falls back to its
  // own default, which is the behaviour the storefront had before capabilities
  // existed. Nothing here throws and nothing renders an empty box.
  useEffect(() => {
    let cancelled = false;
    getClient()
      .getStoreCapabilities()
      .then((raw) => {
        if (!cancelled) setCapabilities(pickPublicCapabilities(raw));
      })
      .catch(() => {
        // Swallowed on purpose. See above. Consumers use their defaults.
      })
      .finally(() => {
        if (!cancelled) setCapabilitiesLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, []);

  // Regions. The happy path is that RootLayout resolved them server-side and
  // seeded us, so this effect does nothing at all. It is the fallback for a
  // failed SSR resolve, and it deliberately mirrors the capabilities effect:
  //
  // ⛔ It must never break the store. An empty store, a channel that is not
  // live yet and a backend hiccup all land in the catch, leave `regions` at
  // `[]` and `region` at null, and every consumer then sends no `regionId`,
  // exactly what this storefront did before regions existed. Nothing throws,
  // and the switcher renders nothing rather than an empty dropdown.
  useEffect(() => {
    if (initialRegions.length > 0) return;
    let cancelled = false;
    getClient()
      .getStoreRegions()
      .then((result) => {
        if (cancelled) return;
        const list = Array.isArray(result?.data) ? result.data : [];
        if (list.length === 0) return;
        setRegions(list);
        // The cookie is the shopper's own choice and outranks the country
        // guess. A stale id (region deleted or deactivated) is ignored.
        const chosenId = readRegionCookie();
        const chosen = chosenId ? list.find((r) => r.id === chosenId) : undefined;
        setRegionState(chosen ?? pickRegion(list, initialCountry));
      })
      .catch(() => {
        // Swallowed on purpose. See above.
      });
    return () => {
      cancelled = true;
    };
  }, [initialRegions, initialCountry]);

  // Switching region has to move BOTH halves of the app: the cookie so the
  // next server render prices the same way, `router.refresh()` so the server
  // components already on screen re-fetch, and local state so client hooks
  // (product listing, home grid) refetch immediately instead of waiting.
  const setRegion = useCallback(
    (regionId: string) => {
      const next = regions.find((r) => r.id === regionId);
      if (!next) return;
      writeRegionCookie(regionId);
      setRegionState(next);
      router.refresh();
    },
    [regions, router]
  );

  // Called after successful login (cookie already set by proxy)
  const login = useCallback(async () => {
    // Attach the guest cart to the account, and WAIT for it: the cart store must
    // not read the customer's cart before the merge, or the shopper's guest cart
    // "disappears" on login. The merge is idempotent.
    try {
      await getClient().syncCartOnLogin();
    } catch (err) {
      console.error('Failed to merge the guest cart on login:', err);
    }

    // Same for the guest's saved items (wishlist): move them into the account. Only when
    // there is a guest list. syncOnLogin() ends with a read of the account list, so what it
    // returns is handed to <WishlistProvider> (via `wishlistSeedRef`, tied to the session key
    // set below) and the provider does not read the same list a second time. A failed merge
    // keeps the guest list in the browser, hands over nothing, and the provider merges again
    // (or at least reads the account list) when it loads, so nothing is lost.
    //
    // This runs BEFORE `refreshAuth()` and the key change below, so for a moment a heart can
    // still be tapped in the old session. That is safe, without a second read: a tap in a
    // guest session goes to the browser list, and the provider sees a non-empty browser list
    // at load time and merges it instead of trusting this read; a write queued in a member
    // session (an OAuth landing) is dropped by the session guard when the key changes, and
    // the heart simply goes back, consistent with the list the server holds.
    let wishlistKeys: WishlistKey[] | null = null;
    try {
      if (getClient().wishlist.local.keys().length > 0) {
        wishlistKeys = (await getClient().wishlist.syncOnLogin()).keys;
      }
    } catch (err) {
      console.error('Failed to merge the guest wishlist on login:', err);
    }

    // Refresh auth state from server (reads httpOnly cookie)
    await refreshAuth();

    // The merge is done and the SDK client reflects the session: tell the cart
    // store who the shopper is now. <CartProvider> sees the key change and
    // resets the store ONCE, which is one cart request. The key is bumped on
    // every login (not only on a signed-out → signed-in flip) because an OAuth
    // redirect lands with the cookie already set, so the store loaded before
    // the guest cart was merged and still needs to read it again.
    loginSeqRef.current += 1;
    const nextAuthKey = `customer:${loginSeqRef.current}`;
    wishlistSeedRef.current = wishlistKeys ? { authKey: nextAuthKey, keys: wishlistKeys } : null;
    setCartAuthKey(nextAuthKey);
  }, [refreshAuth]);

  const logout = useCallback(async () => {
    // Clear httpOnly cookie server-side
    await proxyLogout();

    const client = getClient();
    client.onLogout();
    setIsLoggedIn(false);
    setCustomer(null);
    // Signed out: <CartProvider> resets the store as a guest, after onLogout()
    // above has told the client to forget the customer cart.
    setCartAuthKey(null);
  }, []);

<% if (i18nEnabled) { %>
  return (
    <MessagesContext.Provider value={messages}>
      <StoreInfoContext.Provider value={{ storeInfo, loading: storeLoading }}>
        <StoreCapabilitiesContext.Provider value={{ capabilities, capabilitiesLoading }}>
          <RegionContext.Provider
            value={{
              regions,
              region,
              regionId: region?.id,
              buyerCountry: initialCountry,
              setRegion,
            }}
          >
            <AuthContext.Provider value={{ isLoggedIn, authLoading, customer, login, logout }}>
              <CartProvider store={cartStore} authKey={cartAuthKey}>
                <WishlistProvider
                  authKey={cartAuthKey}
                  currency={storeInfo?.currency}
                  seedRef={wishlistSeedRef}
                >
                  {children}
                </WishlistProvider>
              </CartProvider>
            </AuthContext.Provider>
          </RegionContext.Provider>
        </StoreCapabilitiesContext.Provider>
      </StoreInfoContext.Provider>
    </MessagesContext.Provider>
  );
<% } else { %>
  return (
    <StoreInfoContext.Provider value={{ storeInfo, loading: storeLoading }}>
      <StoreCapabilitiesContext.Provider value={{ capabilities, capabilitiesLoading }}>
        <RegionContext.Provider
          value={{
            regions,
            region,
            regionId: region?.id,
            buyerCountry: initialCountry,
            setRegion,
          }}
        >
          <AuthContext.Provider value={{ isLoggedIn, authLoading, customer, login, logout }}>
            <CartProvider store={cartStore} authKey={cartAuthKey}>
              <WishlistProvider
                authKey={cartAuthKey}
                currency={storeInfo?.currency}
                seedRef={wishlistSeedRef}
              >
                {children}
              </WishlistProvider>
            </CartProvider>
          </AuthContext.Provider>
        </RegionContext.Provider>
      </StoreCapabilitiesContext.Provider>
    </StoreInfoContext.Provider>
  );
<% } %>
}
