/**
 * BrandThemeRoot — outer wrapper that scopes the SharedReport surface and,
 * when white-label is on, injects the operator's brand colors as CSS custom
 * properties so KPI tickers, deltas, links, badges and ring focus states all
 * pick them up automatically. Scoped to a wrapper id so the rest of the app
 * (admin, settings, etc.) keeps the default theme.
 *
 * Hex → HSL conversion happens through the safe parser in `lib/branding`,
 * which returns null on invalid input. Invalid colors silently fall through
 * to the default theme rather than emitting a broken CSS variable.
 */
import { type CSSProperties, type PropsWithChildren } from 'react';

import { hexToHslComponents, readableForegroundHsl } from '@/lib/branding';
import { cn } from '@/lib/utils';
import { type Branding } from '@/types';

interface BrandThemeRootProps extends PropsWithChildren {
  branding: Branding | null | undefined;
  className?: string;
}

export function BrandThemeRoot({ branding, className, children }: BrandThemeRootProps) {
  // Cast once so we can write CSS custom properties without TS complaining.
  const cssVars: Record<string, string> = {};

  // Color theming only runs on full white-label. The intent is: when an agency
  // turns on `remove_rankwiz_branding`, they're claiming the surface — so we
  // honor their colors throughout. Default-branded reports stay on RankWizAI
  // theme regardless of whether primary_color is set, to keep our look intact.
  if (branding?.remove_rankwiz_branding) {
    const primaryHsl = hexToHslComponents(branding.primary_color);
    const secondaryHsl = hexToHslComponents(branding.secondary_color);

    if (primaryHsl) {
      const primaryFg = readableForegroundHsl(branding.primary_color);
      cssVars['--primary'] = primaryHsl;
      cssVars['--primary-foreground'] = primaryFg;
      // --accent drives links, hovers, KPI delta arrows; --ring drives focus rings.
      cssVars['--accent'] = primaryHsl;
      cssVars['--accent-foreground'] = primaryFg;
      cssVars['--ring'] = primaryHsl;
      cssVars['--chart-1'] = primaryHsl;
    }
    if (secondaryHsl) {
      // --secondary is shadcn's "subtle button background" token; using it for
      // the operator's secondary_color gives editorial accents (badges,
      // alternate emphasis chips) without changing surface chrome.
      cssVars['--secondary'] = secondaryHsl;
    }
  }

  return (
    <div
      id="shared-report-root"
      className={cn('min-h-screen bg-background text-foreground', className)}
      style={cssVars as CSSProperties}
    >
      {children}
    </div>
  );
}
