"use client";

import * as React from "react";

import { syncCustomerCsrfToken } from "@/lib/customer-csrf.sync";

const CustomerCsrfContext = React.createContext<string | null>(null);

/** Server-provided CSRF token so mutations do not depend solely on document.cookie. */
export function CustomerCsrfProvider({
  token,
  children,
}: {
  token: string | null;
  children: React.ReactNode;
}) {
  return (
    <CustomerCsrfContext.Provider value={token}>{children}</CustomerCsrfContext.Provider>
  );
}

export function useCustomerCsrfToken(): string | null {
  return React.useContext(CustomerCsrfContext);
}

export function CustomerCsrfSync({ token }: { token: string | null }) {
  // Sync during render so the first mutation after navigation already has the token.
  syncCustomerCsrfToken(token);
  React.useEffect(() => {
    syncCustomerCsrfToken(token);
    return () => {
      syncCustomerCsrfToken(null);
    };
  }, [token]);
  return null;
}
