import React, { useMemo } from 'react';

interface HighlightLayerProps {
    value: string;
    className?: string;
}

/**
 * 变量高亮层
 * 将文本中的变量表达式高亮显示
 */
const HighlightLayer: React.FC<HighlightLayerProps> = ({ value, className }) => {
    // 正则匹配 ${xxx.yyy} 格式的变量
    const VARIABLE_PATTERN = /\$\{([^}]+)\}/g;
    
    // 解析文本，分离普通文本和变量
    const highlightedContent = useMemo(() => {
        if (!value) return null;
        
        const parts: React.ReactNode[] = [];
        let lastIndex = 0;
        let match: RegExpExecArray | null;
        
        // 重置正则表达式的 lastIndex
        VARIABLE_PATTERN.lastIndex = 0;
        
        while ((match = VARIABLE_PATTERN.exec(value)) !== null) {
            const matchStart = match.index;
            const matchEnd = matchStart + match[0].length;
            
            // 添加变量前的普通文本
            if (matchStart > lastIndex) {
                parts.push(
                    <span key={`text-${lastIndex}`}>
                        {value.substring(lastIndex, matchStart)}
                    </span>
                );
            }
            
            // 添加高亮的变量
            // 关键：不使用 padding/margin/border，只使用背景色和下划线
            // 不改变字体、字重，保持和输入框完全一致
            parts.push(
                <span
                    key={`var-${matchStart}`}
                    className="variable-highlight"
                    style={{
                        backgroundColor: 'hsl(199 89% 55% / 0.25)',
                        color: 'hsl(199 89% 25%)',
                        textDecoration: 'underline',
                        textDecorationColor: 'hsl(199 89% 48% / 0.6)',
                        textDecorationThickness: '2px',
                        textUnderlineOffset: '2px',
                        // 确保垂直对齐
                        display: 'inline',
                        verticalAlign: 'baseline',
                    }}
                >
                    {match[0]}
                </span>
            );
            
            lastIndex = matchEnd;
        }
        
        // 添加最后一段普通文本
        if (lastIndex < value.length) {
            parts.push(
                <span key={`text-${lastIndex}`}>
                    {value.substring(lastIndex)}
                </span>
            );
        }
        
        return parts.length > 0 ? parts : value;
    }, [value]);
    
    return (
        <div
            className={className}
            style={{
                pointerEvents: 'none',
                userSelect: 'none',
            }}
        >
            {highlightedContent}
        </div>
    );
};

export default HighlightLayer;

