function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
function _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
        }
    } catch (err) {
        _d = true;
        _e = err;
    } finally{
        try {
            if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
        }
    }
    return _arr;
}
function _non_iterable_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
import { useSyncExternalStore } from "react";
/**
 * 解析颜色值为 RGB
 */ var parseColorToRgb = function parseColorToRgb(color) {
    var normalizedColor = color.trim().toLowerCase();
    // 短十六进制格式 #rgb
    var shortHexMatch = normalizedColor.match(/^#([0-9a-f]{3})$/i);
    if (shortHexMatch) {
        var _shortHexMatch__split_map = _sliced_to_array(shortHexMatch[1].split('').map(function(char) {
            return Number.parseInt(char + char, 16);
        }), 3), r = _shortHexMatch__split_map[0], g = _shortHexMatch__split_map[1], b = _shortHexMatch__split_map[2];
        return {
            r: r,
            g: g,
            b: b
        };
    }
    // 标准十六进制格式 #rrggbb
    var hexMatch = normalizedColor.match(/^#([0-9a-f]{6})$/i);
    if (hexMatch) {
        return {
            r: Number.parseInt(hexMatch[1].slice(0, 2), 16),
            g: Number.parseInt(hexMatch[1].slice(2, 4), 16),
            b: Number.parseInt(hexMatch[1].slice(4, 6), 16)
        };
    }
    // rgb/rgba 格式
    var rgbMatch = normalizedColor.match(/^rgba?\((\d{1,3})[\s,]+(\d{1,3})[\s,]+(\d{1,3})(?:[\s,]+[\d.]+)?\)$/i);
    if (rgbMatch) {
        return {
            r: Number.parseInt(rgbMatch[1], 10),
            g: Number.parseInt(rgbMatch[2], 10),
            b: Number.parseInt(rgbMatch[3], 10)
        };
    }
    return null;
};
/**
 * 计算颜色的亮度
 * 使用加权公式：Y = 0.299*R + 0.587*G + 0.114*B
 */ var calculateBrightness = function calculateBrightness(color) {
    var rgb = parseColorToRgb(color);
    if (!rgb) return null;
    return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;
};
/**
 * 检测背景色是否为暗色
 */ var isDarkBackground = function isDarkBackground(color) {
    var threshold = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 145;
    var brightness = calculateBrightness(color);
    if (brightness === null) return false;
    return brightness < threshold;
};
/**
 * 检测 HTML 元素的 data-theme 属性是否为 dark
 */ var checkDataTheme = function checkDataTheme() {
    if (typeof document === 'undefined') return false;
    var htmlElement = document.documentElement;
    return htmlElement.getAttribute('data-theme') === 'dark';
};
/**
 * 获取 CSS 变量的计算值
 */ var getCSSVariableValue = function getCSSVariableValue(variableName) {
    if (typeof window === 'undefined') return null;
    var computedStyle = window.getComputedStyle(document.documentElement);
    var value = computedStyle.getPropertyValue(variableName).trim();
    return value || null;
};
/**
 * 根据多种方式检测当前主题
 */ var detectTheme = function detectTheme(cssVariable, darknessThreshold) {
    // 1. 首先检查 html[data-theme='dark']
    if (checkDataTheme()) {
        return 'dark';
    }
    // 2. 检查 CSS 变量的亮度
    var cssValue = getCSSVariableValue(cssVariable);
    if (cssValue && isDarkBackground(cssValue, darknessThreshold)) {
        return 'dark';
    }
    // 3. 检查背景色 CSS 变量
    var bgColor = getCSSVariableValue('--color-gray-bg-page');
    if (bgColor && isDarkBackground(bgColor, darknessThreshold)) {
        return 'dark';
    }
    return 'light';
};
// --- 单例主题检测：所有 hook 实例共享一个 MutationObserver + matchMedia 监听 ---
var listeners = [];
var currentTheme = 'light';
var observerRef = null;
var mediaQueryRef = null;
var refCount = 0;
var DEFAULT_CSS_VARIABLE = '--color-gray-bg-page';
var DEFAULT_DARKNESS_THRESHOLD = 145;
function subscribeTheme(listener) {
    listeners.push(listener);
    refCount++;
    // 第一个订阅者时初始化全局监听器
    if (refCount === 1 && typeof window !== 'undefined') {
        currentTheme = detectTheme(DEFAULT_CSS_VARIABLE, DEFAULT_DARKNESS_THRESHOLD);
        var updateTheme = function updateTheme() {
            var next = detectTheme(DEFAULT_CSS_VARIABLE, DEFAULT_DARKNESS_THRESHOLD);
            if (next !== currentTheme) {
                currentTheme = next;
                listeners.forEach(function(fn) {
                    return fn();
                });
            }
        };
        var htmlElement = document.documentElement;
        observerRef = new MutationObserver(function(mutations) {
            var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
            try {
                for(var _iterator = mutations[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
                    var mutation = _step.value;
                    if (mutation.type === 'attributes' && mutation.attributeName === 'data-theme') {
                        updateTheme();
                        break;
                    }
                }
            } catch (err) {
                _didIteratorError = true;
                _iteratorError = err;
            } finally{
                try {
                    if (!_iteratorNormalCompletion && _iterator.return != null) {
                        _iterator.return();
                    }
                } finally{
                    if (_didIteratorError) {
                        throw _iteratorError;
                    }
                }
            }
        });
        observerRef.observe(htmlElement, {
            attributes: true,
            attributeFilter: [
                'data-theme',
                'class',
                'style'
            ]
        });
        mediaQueryRef = window.matchMedia('(prefers-color-scheme: dark)');
        mediaQueryRef.addEventListener('change', updateTheme);
    }
    return function() {
        listeners = listeners.filter(function(fn) {
            return fn !== listener;
        });
        refCount--;
        // 最后一个订阅者取消时清理全局监听器
        if (refCount === 0) {
            observerRef === null || observerRef === void 0 ? void 0 : observerRef.disconnect();
            observerRef = null;
            if (mediaQueryRef) {
                mediaQueryRef.removeEventListener('change', function() {});
                mediaQueryRef = null;
            }
        }
    };
}
function getSnapshot() {
    return currentTheme;
}
function getServerSnapshot() {
    return 'light';
}
/**
 * 自动检测当前主题的 Hook（单例模式）
 *
 * 所有 hook 实例共享同一个 MutationObserver 和 matchMedia 监听器，
 * 避免页面上多个图表时创建重复的 DOM 监听。
 *
 * 检测策略（按优先级）：
 * 1. 检查 `html[data-theme='dark']` 属性
 * 2. 检查指定 CSS 变量的亮度值
 * 3. 检查 `--color-gray-bg-page` 的亮度值
 *
 * @param options 检测配置选项（observeChanges 为 false 时跳过监听）
 * @returns 检测到的主题 'light' | 'dark'
 *
 * @example
 * ```tsx
 * const theme = useDetectTheme();
 * // theme: 'light' | 'dark'
 *
 * // 禁用监听（仅检测一次）
 * const theme = useDetectTheme({ observeChanges: false });
 * ```
 */ export var useDetectTheme = function useDetectTheme() {
    var options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    var _options_observeChanges = options.observeChanges, observeChanges = _options_observeChanges === void 0 ? true : _options_observeChanges;
    // 当 observeChanges 为 false 时，只做一次性检测，不订阅变更
    var liveTheme = useSyncExternalStore(subscribeTheme, getSnapshot, getServerSnapshot);
    if (!observeChanges) {
        var _options_cssVariable, _options_darknessThreshold;
        return detectTheme((_options_cssVariable = options.cssVariable) !== null && _options_cssVariable !== void 0 ? _options_cssVariable : DEFAULT_CSS_VARIABLE, (_options_darknessThreshold = options.darknessThreshold) !== null && _options_darknessThreshold !== void 0 ? _options_darknessThreshold : DEFAULT_DARKNESS_THRESHOLD);
    }
    return liveTheme;
};
export default useDetectTheme;
