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 _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_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 _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 _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 { isString } from "lodash-es";
import React, { memo, useContext, useEffect, useMemo, useRef, useState } from "react";
import { resolveSegments } from "../TextAnimate";
import { useTypingAnimationStyle } from "./style";
/**
 * 等价 framer-motion 的 useInView({ amount: 0.3, once: true })。
 *
 * 使用原生 IntersectionObserver 实现：
 * - threshold: 0.3 → 元素至少 30% 可见时触发
 * - once: true → 触发后立即断开 observer，不再回退为 false
 * - SSR/无 IntersectionObserver 环境下默认返回 true（与原行为兼容，
 *   避免在测试或老旧环境中动画永不开始）
 */ function useInViewOnce(ref, amount) {
    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') {
            // 环境不支持时直接置为 true，等价 framer-motion 的 fallback 行为
            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);
                        observer.disconnect();
                        break;
                    }
                }
            } catch (err) {
                _didIteratorError = true;
                _iteratorError = err;
            } finally{
                try {
                    if (!_iteratorNormalCompletion && _iterator.return != null) {
                        _iterator.return();
                    }
                } finally{
                    if (_didIteratorError) {
                        throw _iteratorError;
                    }
                }
            }
        }, {
            threshold: amount
        });
        observer.observe(target);
        return function() {
            observer.disconnect();
        };
    }, [
        ref,
        amount
    ]);
    return inView;
}
var TypingAnimationBase = function TypingAnimationBase(_0) {
    var children = _0.children, words = _0.words, className = _0.className, _0_duration = _0.duration, duration = _0_duration === void 0 ? 100 : _0_duration, typeSpeed = _0.typeSpeed, deleteSpeed = _0.deleteSpeed, _0_delay = _0.delay, delay = _0_delay === void 0 ? 0 : _0_delay, _0_pauseDelay = _0.pauseDelay, pauseDelay = _0_pauseDelay === void 0 ? 1000 : _0_pauseDelay, _0_loop = _0.loop, loop = _0_loop === void 0 ? false : _0_loop, tmp = _0.as, Component = tmp === void 0 ? 'span' : tmp, _0_startOnView = _0.startOnView, startOnView = _0_startOnView === void 0 ? true : _0_startOnView, _0_showCursor = _0.showCursor, showCursor = _0_showCursor === void 0 ? true : _0_showCursor, _0_blinkCursor = _0.blinkCursor, blinkCursor = _0_blinkCursor === void 0 ? true : _0_blinkCursor, _0_cursorStyle = _0.cursorStyle, cursorStyle = _0_cursorStyle === void 0 ? 'line' : _0_cursorStyle, props = _object_without_properties(_0, [
        "children",
        "words",
        "className",
        "duration",
        "typeSpeed",
        "deleteSpeed",
        "delay",
        "pauseDelay",
        "loop",
        "as",
        "startOnView",
        "showCursor",
        "blinkCursor",
        "cursorStyle"
    ]);
    var getPrefixCls = useContext(ConfigProvider.ConfigContext).getPrefixCls;
    var prefixCls = getPrefixCls('typing-animation');
    var _useTypingAnimationStyle = useTypingAnimationStyle(prefixCls), wrapSSR = _useTypingAnimationStyle.wrapSSR, hashId = _useTypingAnimationStyle.hashId;
    var _useState = _sliced_to_array(useState([]), 2), displayedText = _useState[0], setDisplayedText = _useState[1];
    var _useState1 = _sliced_to_array(useState(0), 2), currentWordIndex = _useState1[0], setCurrentWordIndex = _useState1[1];
    var _useState2 = _sliced_to_array(useState(0), 2), currentCharIndex = _useState2[0], setCurrentCharIndex = _useState2[1];
    var _useState3 = _sliced_to_array(useState('typing'), 2), phase = _useState3[0], setPhase = _useState3[1];
    var elementRef = useRef(null);
    // 等价 framer-motion 的 useInView({ amount: 0.3, once: true })
    var isInView = useInViewOnce(elementRef, 0.3);
    var wordsToAnimate = useMemo(function() {
        return words || [
            resolveSegments(children, 'character')
        ];
    }, [
        words,
        children
    ]);
    var hasMultipleWords = wordsToAnimate.length > 1;
    var typingSpeed = typeSpeed || duration;
    var deletingSpeed = deleteSpeed || typingSpeed / 2;
    var shouldStart = startOnView ? isInView : true;
    useEffect(function() {
        if (!shouldStart || wordsToAnimate.length === 0) return;
        var timeoutDelay = delay > 0 && displayedText.length === 0 ? delay : phase === 'typing' ? typingSpeed : phase === 'deleting' ? deletingSpeed : pauseDelay;
        var timeout = setTimeout(function() {
            var currentWord = wordsToAnimate[currentWordIndex] || '';
            var graphemes = isString(currentWord) ? Array.from(currentWord) : currentWord;
            switch(phase){
                case 'typing':
                    if (currentCharIndex < graphemes.length) {
                        setDisplayedText(graphemes.slice(0, currentCharIndex + 1));
                        setCurrentCharIndex(currentCharIndex + 1);
                    } else {
                        if (hasMultipleWords || loop) {
                            var isLastWord = currentWordIndex === wordsToAnimate.length - 1;
                            if (!isLastWord || loop) {
                                setPhase('pause');
                            }
                        }
                    }
                    break;
                case 'pause':
                    setPhase('deleting');
                    break;
                case 'deleting':
                    if (currentCharIndex > 0) {
                        setDisplayedText(graphemes.slice(0, currentCharIndex - 1));
                        setCurrentCharIndex(currentCharIndex - 1);
                    } else {
                        var nextIndex = (currentWordIndex + 1) % wordsToAnimate.length;
                        setCurrentWordIndex(nextIndex);
                        setPhase('typing');
                    }
                    break;
            }
        }, timeoutDelay);
        return function() {
            return clearTimeout(timeout);
        };
    }, [
        shouldStart,
        phase,
        currentCharIndex,
        currentWordIndex,
        displayedText,
        wordsToAnimate,
        hasMultipleWords,
        loop,
        typingSpeed,
        deletingSpeed,
        pauseDelay,
        delay
    ]);
    var currentWordGraphemes = isString(wordsToAnimate[currentWordIndex]) ? Array.from(wordsToAnimate[currentWordIndex]) : [
        wordsToAnimate[currentWordIndex]
    ];
    var isComplete = !loop && currentWordIndex === wordsToAnimate.length - 1 && currentCharIndex >= currentWordGraphemes.length && phase !== 'deleting';
    var shouldShowCursor = showCursor && !isComplete && (hasMultipleWords || loop || currentCharIndex < currentWordGraphemes.length);
    var getCursorChar = function getCursorChar() {
        switch(cursorStyle){
            case 'block':
                return '▌';
            case 'underscore':
                return '_';
            case 'line':
            default:
                return '|';
        }
    };
    // 替代 framer-motion 的 motion(Component) HOC：
    // 由于 TypingAnimation 仅用 motion 作为 ref 容器（无 variants/animate 等动画属性），
    // 直接 createElement(Component) 即可，行为完全等价。
    return wrapSSR(/*#__PURE__*/ React.createElement(Component, _object_spread({
        ref: elementRef,
        className: classNames(prefixCls, hashId, className),
        'data-testid': prefixCls
    }, props), displayedText, shouldShowCursor && /*#__PURE__*/ React.createElement("span", {
        key: "__typing-cursor__",
        className: classNames("".concat(prefixCls, "-cursor"), hashId, blinkCursor && "".concat(prefixCls, "-cursor-blinking"))
    }, getCursorChar())));
};
TypingAnimationBase.displayName = 'TypingAnimation';
export var TypingAnimation = /*#__PURE__*/ memo(TypingAnimationBase);
