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 _array_without_holes(arr) {
    if (Array.isArray(arr)) return _array_like_to_array(arr);
}
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _iterable_to_array(iter) {
    if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
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 _non_iterable_spread() {
    throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            }));
        }
        ownKeys.forEach(function(key) {
            _define_property(target, key, source[key]);
        });
    }
    return target;
}
function _object_without_properties(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys, key, i;
    if (typeof Reflect !== "undefined" && Reflect.ownKeys) {
        sourceKeys = Reflect.ownKeys(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
        return target;
    }
    target = _object_without_properties_loose(source, excluded);
    if (Object.getOwnPropertySymbols) {
        sourceKeys = Object.getOwnPropertySymbols(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
    }
    return target;
}
function _object_without_properties_loose(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys = Object.getOwnPropertyNames(source), key, i;
    for(i = 0; i < sourceKeys.length; i++){
        key = sourceKeys[i];
        if (excluded.indexOf(key) >= 0) continue;
        if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
        target[key] = source[key];
    }
    return target;
}
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 _to_consumable_array(arr) {
    return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
}
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 { ConfigProvider } from "antd";
import classNames from "clsx";
import { isNumber, isObject, isString } from "lodash-es";
import toArray from "rc-util/lib/Children/toArray";
import React, { memo, useContext, useEffect, useMemo, useRef, useState } from "react";
import { useTextAnimateStyle } from "./style";
/**
 * 各拆分模式下相邻 segment 的 stagger 增量（秒/项）。
 *
 * 与历史 framer-motion 实现保持一致：每个 item 的 framer-motion `custom={i * staggerTimings[by]}`
 * 由这里的常量推导。新实现中 stagger 通过 inline `--text-animate-delay` 实现。
 */ var staggerTimings = {
    text: 0.06,
    word: 0.05,
    character: 0.03,
    line: 0.06,
    mix: 0.06
};
/**
 * 等价 framer-motion useInView({ amount, once }) 的原生 IntersectionObserver Hook。
 *
 * - amount: threshold（0~1）
 * - once: 触发后是否断开 observer 不再回退为 false
 * - SSR / 无 IntersectionObserver 环境直接返回 true，与 framer-motion fallback 行为一致
 */ function useInViewObserver(ref, amount, once) {
    var _useState = _sliced_to_array(useState(function() {
        if (typeof window === 'undefined') return true;
        if (typeof IntersectionObserver === 'undefined') return true;
        return false;
    }), 2), inView = _useState[0], setInView = _useState[1];
    useEffect(function() {
        if (typeof IntersectionObserver === 'undefined') {
            setInView(true);
            return;
        }
        var target = ref.current;
        if (!target) return;
        var observer = new IntersectionObserver(function(entries) {
            var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
            try {
                for(var _iterator = entries[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
                    var entry = _step.value;
                    if (entry.isIntersecting) {
                        setInView(true);
                        if (once) {
                            observer.disconnect();
                        }
                        return;
                    }
                }
            } catch (err) {
                _didIteratorError = true;
                _iteratorError = err;
            } finally{
                try {
                    if (!_iteratorNormalCompletion && _iterator.return != null) {
                        _iterator.return();
                    }
                } finally{
                    if (_didIteratorError) {
                        throw _iteratorError;
                    }
                }
            }
            if (!once) {
                setInView(false);
            }
        }, {
            threshold: amount
        });
        observer.observe(target);
        return function() {
            observer.disconnect();
        };
    }, [
        ref,
        amount,
        once
    ]);
    return inView;
}
export var resolveSegments = function resolveSegments(children, by) {
    var result = [];
    toArray(children).forEach(function(item) {
        if (isString(item) || isNumber(item)) {
            var itemString = item.toString();
            if (itemString === '') return;
            switch(by){
                case 'word':
                    var _result;
                    (_result = result).push.apply(_result, _to_consumable_array(itemString.split(/(\s+)/)));
                    break;
                case 'character':
                    var _result1;
                    (_result1 = result).push.apply(_result1, _to_consumable_array(itemString.split('')));
                    break;
                case 'line':
                    var _result2;
                    (_result2 = result).push.apply(_result2, _to_consumable_array(itemString.split('\n')));
                    break;
                case 'text':
                default:
                    result.push(itemString);
            }
        } else {
            result.push(item);
        }
    });
    return result;
};
var TextAnimateBase = function TextAnimateBase(_0) {
    var children = _0.children, _0_delay = _0.delay, delay = _0_delay === void 0 ? 0 : _0_delay, _0_duration = _0.duration, duration = _0_duration === void 0 ? 0.3 : _0_duration, variants = _0.variants, className = _0.className, segmentClassName = _0.segmentClassName, tmp = _0.as, Component = tmp === void 0 ? 'p' : tmp, _0_startOnView = _0.startOnView, startOnView = _0_startOnView === void 0 ? true : _0_startOnView, _0_once = _0.once, once = _0_once === void 0 ? false : _0_once, _0_by = _0.by, by = _0_by === void 0 ? 'word' : _0_by, _0_animation = _0.animation, animation = _0_animation === void 0 ? 'fadeIn' : _0_animation, _0_accessible = _0.accessible, accessible = _0_accessible === void 0 ? true : _0_accessible, props = _object_without_properties(_0, [
        "children",
        "delay",
        "duration",
        "variants",
        "className",
        "segmentClassName",
        "as",
        "startOnView",
        "once",
        "by",
        "animation",
        "accessible"
    ]);
    var getPrefixCls = useContext(ConfigProvider.ConfigContext).getPrefixCls;
    var prefixCls = getPrefixCls('text-animate');
    var _useTextAnimateStyle = useTextAnimateStyle(prefixCls), wrapSSR = _useTextAnimateStyle.wrapSSR, hashId = _useTextAnimateStyle.hashId;
    var segments = useMemo(function() {
        return resolveSegments(children, by);
    }, [
        children,
        by
    ]);
    // 等价历史 framer-motion `staggerChildren = duration / segments.length`
    var staggerChildrenSec = useMemo(function() {
        return segments.length > 0 ? duration / segments.length : 0;
    }, [
        duration,
        segments.length
    ]);
    // 等价 framer-motion useInView({ once, amount: 0.5 })
    // - startOnView=false 时立即播放（始终视为 in view）
    // - startOnView=true 时配合 IntersectionObserver 决定是否触发动画
    var containerRef = useRef(null);
    var isInView = useInViewObserver(containerRef, 0.5, once);
    var shouldPlay = startOnView ? isInView : true;
    // 自定义 variants 与预设 animation 的解析：
    // - 自定义 variants → data-animation="custom"（CSS 退化为 fadeIn 视觉效果，
    //   见 style.ts 中 `data-animation="custom"` 选择器与文档说明）
    // - 否则使用 animation preset；animation 为 null/undefined 时 fallback 到 fadeIn
    //   （与原默认参数 animation='fadeIn' 一致）
    var itemAnimationName = variants ? 'custom' : animation || 'fadeIn';
    // 单项 stagger 延迟基数（秒）：
    // 历史 framer-motion 实现存在两套 stagger 系数：
    //   1) 父级 staggerChildren = duration / segments.length（影响默认入场节奏）
    //   2) item 的 custom = i * staggerTimings[by]（仅在自定义 variants 中作为参数被消费）
    // 为保留语义：
    //   - 预设 animation 路径使用 staggerChildrenSec
    //   - 自定义 variants 路径使用 staggerTimings[by]，与 framer-motion `custom` 入参对齐
    var customStaggerDelaySec = staggerTimings[by];
    // 容器 props：保留 framer-motion 时代的 className/data-testid/aria-label 行为
    var containerProps = _object_spread({
        ref: containerRef,
        className: classNames(prefixCls, hashId, className),
        'data-testid': prefixCls,
        'data-in-view': shouldPlay ? 'true' : 'false',
        'aria-label': accessible && isString(children) ? children : undefined
    }, props);
    return wrapSSR(/*#__PURE__*/ React.createElement(Component, containerProps, segments.map(function(segment, i) {
        var itemKey = "".concat(by, "-").concat(isObject(segment) ? segment.key : segment, "-").concat(i);
        var itemDelaySec = delay + i * (variants ? customStaggerDelaySec : staggerChildrenSec);
        return /*#__PURE__*/ React.createElement("span", {
            key: itemKey,
            "data-animation": shouldPlay ? itemAnimationName : 'none',
            className: classNames("".concat(prefixCls, "-item"), "".concat(prefixCls, "-item-").concat(by), hashId, segmentClassName),
            "aria-hidden": accessible ? true : undefined,
            style: {
                animationDuration: "".concat(duration, "s"),
                '--text-animate-delay': "".concat(itemDelaySec, "s")
            }
        }, segment);
    })));
};
// Export the memoized version
export var TextAnimate = /*#__PURE__*/ memo(TextAnimateBase);
