/**
 * Terminal 分屏分隔条
 * 可拖动调整两个分屏之间的大小比例
 */
import React, { useRef, useState, useEffect } from 'react';
import type { LayoutOrientation } from './types';
import styles from './index.module.less';

interface TerminalSplitDividerProps {
    orientation: LayoutOrientation;
    onResize: (delta: number, containerSize?: number) => void;
}

/**
 * 分屏分隔条组件
 * - 水平分割：垂直拖动条，左右调整
 * - 垂直分割：水平拖动条，上下调整
 */
export const TerminalSplitDivider: React.FC<TerminalSplitDividerProps> = ({ orientation, onResize }) => {
    const [isDragging, setIsDragging] = useState(false);
    const startPosRef = useRef(0);
    const dividerRef = useRef<HTMLDivElement>(null);
    const lastUpdateRef = useRef(0);
    const lastMousePosRef = useRef(0);  // 记录上一次鼠标位置

    useEffect(() => {
        if (!isDragging) return;

        // 设置拖动时的鼠标样式
        const cursor = orientation === 'horizontal' ? 'col-resize' : 'row-resize';
        document.body.style.cursor = cursor;
        document.body.style.userSelect = 'none';

        const handleMouseMove = (e: MouseEvent) => {
            e.preventDefault();
            
            const currentMousePos = orientation === 'horizontal' ? e.clientX : e.clientY;
            
            // 节流：限制更新频率为16ms（约60fps）
            const now = Date.now();
            if (now - lastUpdateRef.current < 16) {
                return;
            }
            lastUpdateRef.current = now;

            // 计算相对于上一帧的增量
            const delta = currentMousePos - lastMousePosRef.current;
            
            // 如果没有移动，跳过
            if (delta === 0) {
                return;
            }
            
            // 获取父容器的尺寸
            const container = dividerRef.current?.parentElement;
            const containerSize = container 
                ? (orientation === 'horizontal' ? container.clientWidth : container.clientHeight)
                : undefined;
            
            onResize(delta, containerSize);
            lastMousePosRef.current = currentMousePos;
        };

        const handleMouseUp = () => {
            setIsDragging(false);
            document.body.style.cursor = '';
            document.body.style.userSelect = '';
        };

        document.addEventListener('mousemove', handleMouseMove);
        document.addEventListener('mouseup', handleMouseUp);

        return () => {
            document.removeEventListener('mousemove', handleMouseMove);
            document.removeEventListener('mouseup', handleMouseUp);
            document.body.style.cursor = '';
            document.body.style.userSelect = '';
        };
    }, [isDragging, orientation, onResize]);

    const handleMouseDown = (e: React.MouseEvent) => {
        e.preventDefault();
        const initialPos = orientation === 'horizontal' ? e.clientX : e.clientY;
        startPosRef.current = initialPos;
        lastMousePosRef.current = initialPos;
        setIsDragging(true);
    };

    return (
        <div
            ref={dividerRef}
            className={`${styles.divider} ${styles[orientation]} ${isDragging ? styles.dragging : ''}`}
            onMouseDown={handleMouseDown}
        />
    );
};
