"use client";
import { createContext, useContext, useMemo, type ReactNode } from "react";

const CspNonceContext = createContext<string>("");

type CspNonceProviderProps = { nonce: string; children: ReactNode };

export function CspNonceProvider({ nonce, children }: CspNonceProviderProps) {
  // NOTE: Do NOT fall back to reading document.querySelector('meta[name="csp-nonce"]').
  // Placing a nonce in a meta tag leaks it to any script on the page, defeating CSP.
  // The nonce must be passed explicitly as a prop from the server component.
  const resolvedNonce = useMemo(() => nonce || "", [nonce]);
  return (
    <CspNonceContext.Provider value={resolvedNonce}>
      {children}
    </CspNonceContext.Provider>
  );
}

export function useCspNonce(): string {
  // Return the nonce from context only. Do NOT read from DOM meta tags.
  return useContext(CspNonceContext);
}
