'use client';

import { createContext, useContext, useMemo, type ReactNode } from 'react';
import { type BrandConfig, type ThemeConfig, defaultBrand, defaultTheme, interpolateBrand } from '@/lib/white-label';

interface BrandContextValue {
  brand: BrandConfig;
  theme: ThemeConfig;
  /** Interpolate {productName}, {secondaryName}, etc. into a string */
  t: (template: string) => string;
}

const BrandContext = createContext<BrandContextValue | null>(null);

export function BrandProvider({
  children,
  brand = defaultBrand,
  theme = defaultTheme,
}: {
  children: ReactNode;
  brand?: BrandConfig;
  theme?: ThemeConfig;
}) {
  const value = useMemo(
    () => ({
      brand,
      theme,
      t: (template: string) => interpolateBrand(template, brand),
    }),
    [brand, theme]
  );

  return <BrandContext.Provider value={value}>{children}</BrandContext.Provider>;
}

/**
 * Hook to access brand config, theme, and interpolation helper.
 * 
 * Usage:
 *   const { brand, theme, t } = useBrand();
 *   <h1>{brand.identity.productName}</h1>
 *   <p>{t('Welcome to {productName}')}</p>
 */
export function useBrand(): BrandContextValue {
  const ctx = useContext(BrandContext);
  if (!ctx) {
    // Fallback for components rendered outside provider (SSR, tests, etc.)
    return {
      brand: defaultBrand,
      theme: defaultTheme,
      t: (template: string) => interpolateBrand(template, defaultBrand),
    };
  }
  return ctx;
}
