/**
 * ConfigProvider — 主题对外唯一入口
 *
 * 支持嵌套：内层 Provider 的配置就近覆盖外层。
 * 通过 CSS 变量作用域实现局部主题，不污染外部。
 */
import React from 'react';
import { ThemeContext, AssetsContext } from './context.js';
import { mergeTheme } from './merge-theme.js';
import { resolveTheme } from './resolve-theme.js';
import { getAssets } from './brand-assets.js';
/**
 * 组件资产 URL 字段 → CSS 变量名的静态映射。
 * 只收录通过 CSS `background-image` / `mask` 消费的 URL 字段，
 * 保证业务仅通过 `theme.components` 配置即可生效。
 */
const ASSET_CSS_VAR_MAP = [
    { path: ['filter', 'recordMaskUrl'], varName: '--cnai-filter-record-mask-url' },
    { path: ['table', 'initPageBgUrl'], varName: '--cnai-table-illustration-init-page-url' },
    { path: ['table', 'illustrationGeneralUrl'], varName: '--cnai-table-illustration-general-url' },
    { path: ['table', 'illustrationDigitalUrl'], varName: '--cnai-table-illustration-digital-url' },
];
function normalizeUrlValue(raw) {
    const trimmed = raw.trim();
    if (trimmed.startsWith('url('))
        return trimmed;
    return `url('${trimmed}')`;
}
/**
 * 将品牌资产覆盖映射解析为可直接作为 inline style 使用的 CSS 变量键值对
 *
 * @param components - 品牌资产覆盖映射，undefined/null/'' 值会被跳过
 * @returns 已归一化的 CSS 变量键值对（key 带 `--` 前缀）
 */
function resolveAssetVars(components) {
    var _a;
    if (!components)
        return {};
    const result = {};
    for (const { path, varName } of ASSET_CSS_VAR_MAP) {
        const [comp, field] = path;
        const value = (_a = components[comp]) === null || _a === void 0 ? void 0 : _a[field];
        if (typeof value === 'string' && value) {
            result[varName] = normalizeUrlValue(value);
        }
    }
    return result;
}
/**
 * ConfigProvider 组件
 *
 * @param props - ConfigProvider 组件的 props
 * @param props.theme - 主题配置
 * @param props.children - 子组件
 * @returns ConfigProvider 组件
 */
export const ConfigProvider = ({ theme, children }) => {
    const parentTheme = React.useContext(ThemeContext);
    const mergedTheme = React.useMemo(() => mergeTheme(parentTheme, theme), [parentTheme, theme]);
    const cssVars = React.useMemo(() => {
        const tokenVars = resolveTheme(mergedTheme.token);
        const assetVars = resolveAssetVars(mergedTheme.components);
        return { ...tokenVars, ...assetVars };
    }, [mergedTheme.token, mergedTheme.components]);
    const assets = React.useMemo(() => getAssets(mergedTheme.components), [mergedTheme.components]);
    const hasVars = Object.keys(cssVars).length > 0;
    return (React.createElement(ThemeContext.Provider, { value: mergedTheme },
        React.createElement(AssetsContext.Provider, { value: assets }, hasVars ? (React.createElement("div", { style: { ...cssVars, display: 'contents' } }, children)) : (children))));
};
ConfigProvider.displayName = 'ConfigProvider';
