import { createContext, useContext } from 'react';
import type { CSSProperties, ReactNode } from 'react';
import { cx } from '../../utils/cx';
import '../../styles/tokens.css';
import '../../styles/base.css';

export type Theme = 'light' | 'dark';

const ThemeContext = createContext<Theme>('light');

/**
 * The theme of the nearest ThemeProvider, or `light` when there is none.
 * Components that portal out of the React tree (Modal) use this to re-apply
 * the theme at the portal root, where the wrapper's attribute cannot reach.
 */
export function useTheme(): Theme {
  return useContext(ThemeContext);
}

export interface ThemeProviderProps {
  /** Which token set applies to this subtree. Defaults to `light`. */
  theme?: Theme;
  children?: ReactNode;
  className?: string;
  style?: CSSProperties;
  /** Renders a different element for the wrapper. Defaults to `div`. */
  as?: 'div' | 'main' | 'section';
}

/**
 * Optional root wrapper. Components are fully styled without it — tokens live
 * on `:root`. Wrap when you want a dark subtree, or want the page background
 * and type ramp to come from the design system.
 */
export function ThemeProvider({
  theme = 'light',
  children,
  className,
  style,
  as: Tag = 'div',
}: ThemeProviderProps) {
  return (
    <ThemeContext.Provider value={theme}>
      <Tag className={cx('ds-root', className)} style={style} data-ds-theme={theme}>
        {children}
      </Tag>
    </ThemeContext.Provider>
  );
}
