import React, { useRef, useState, useEffect } from 'react';
import { Box } from '@mui/material';
import { ChartTool } from './ChartToolbar';

export interface DrawingObject {
    id: string;
    type: ChartTool;
    points: { time: number; price: number }[]; // time: unix timestamp, price: value
    style?: {
        color: string;
        lineWidth: number;
        lineStyle: 'solid' | 'dashed' | 'dotted';
        fillColor?: string; // For rectangle/brush
        fillOpacity?: number;
        text?: string; // For text tool
        fontSize?: number;
    };
    extended?: boolean; // ✅ 확장 옵션 (보조지표까지 표시)
    showLabel?: boolean; // ✅ 라벨 표시 옵션 (날짜)
    customText?: string; // ✅ 커스텀 텍스트 (상단 표시)
    fibLevels?: number[]; // ✅ 피보나치 레벨 (Fan/Circle/Wedge용)
}

interface ChartDrawingOverlayProps {
    width: number;
    height: number;
    totalChartHeight?: number; // ✅ 캔들차트 + 모든 보조지표 차트 높이 (확장 옵션용)
    activeTool: ChartTool | null;
    drawings: DrawingObject[];
    onUpdateDrawings: (drawings: DrawingObject[]) => void;
    // Coordinate conversion functions
    timeToCoordinate: (time: number) => number | null;
    coordinateToTime: (x: number) => number | null;
    priceToCoordinate: (price: number) => number | null;
    coordinateToPrice: (y: number) => number | null;
    // Interaction callbacks
    onDrawingComplete?: (drawing: DrawingObject) => void;
    onDrawingClick?: (drawing: DrawingObject) => void; // ✅ Single click handler for settings
    onDrawingDoubleClick?: (drawing: DrawingObject) => void; // ✅ Double click handler
    onDrawingDragStart?: (drawingId: string, startX: number) => void; // ✅ Drag start handler
}

const ChartDrawingOverlay: React.FC<ChartDrawingOverlayProps> = ({
    width,
    height,
    totalChartHeight,
    activeTool,
    drawings,
    onUpdateDrawings,
    timeToCoordinate,
    coordinateToTime,
    priceToCoordinate,
    coordinateToPrice,
    onDrawingComplete,
    onDrawingClick,
    onDrawingDoubleClick,
    onDrawingDragStart,
}) => {
    const svgRef = useRef<SVGSVGElement>(null);
    const containerRef = useRef<HTMLDivElement>(null);
    const [currentDrawing, setCurrentDrawing] = useState<DrawingObject | null>(null);
    const [isDrawing, setIsDrawing] = useState(false);
    const [actualWidth, setActualWidth] = useState(width);

    // ✅ 실제 컨테이너 너비 측정
    useEffect(() => {
        const measureWidth = () => {
            if (containerRef.current) {
                const measured = containerRef.current.clientWidth;
                setActualWidth(measured);
                console.log(`📏 [ChartDrawingOverlay] 실제 너비 측정: ${measured}px (prop: ${width}px)`);
            }
        };
        
        measureWidth();
        window.addEventListener('resize', measureWidth);
        
        // 약간의 지연 후 재측정 (DOM 업데이트 대기)
        const timer = setTimeout(measureWidth, 100);
        
        return () => {
            window.removeEventListener('resize', measureWidth);
            clearTimeout(timer);
        };
    }, [width]);

    // ✅ 디버깅: width 값 확인
    useEffect(() => {
        console.log(`📏 [ChartDrawingOverlay] width 업데이트: ${width}px, actualWidth: ${actualWidth}px, height: ${height}px`);
    }, [width, height, actualWidth]);

    // Helper to get SVG dash array
    const getStrokeDasharray = (style: string) => {
        switch (style) {
            case 'dashed': return '5,5';
            case 'dotted': return '2,2';
            default: return '0';
        }
    };

    const handleMouseDown = (e: React.MouseEvent) => {
        // ✅ crosshair 모드일 때는 이벤트를 처리하지 않음 (차트 기본 동작 허용)
        if (!activeTool || activeTool === 'crosshair') {
            return;
        }

        const rect = svgRef.current?.getBoundingClientRect();
        if (!rect) return;

        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;

        const time = coordinateToTime(x);
        const price = coordinateToPrice(y);

        if (time === null || price === null) return;

        e.stopPropagation(); // Stop propagation to chart

        const newPoint = { time, price };

        // Handle Text Tool (Immediate creation)
        if (activeTool === 'text') {
            const text = window.prompt("텍스트를 입력하세요:", "Text");
            if (text) {
                const newDrawing: DrawingObject = {
                    id: `drawing-${Date.now()}`,
                    type: 'text',
                    points: [newPoint],
                    style: {
                        color: '#ffffff',
                        lineWidth: 0,
                        lineStyle: 'solid',
                        text: text,
                        fontSize: 14
                    }
                };
                onUpdateDrawings([...drawings, newDrawing]);
                if (onDrawingComplete) onDrawingComplete(newDrawing);
            }
            return;
        }

        // ✅ Handle Horizontal/Vertical Line (Immediate creation - One click)
        if (activeTool === 'horizontalLine' || activeTool === 'verticalLine') {
            const newDrawing: DrawingObject = {
                id: `drawing-${Date.now()}`,
                type: activeTool,
                points: [newPoint], // Only need one point for H/V lines
                style: {
                    color: '#2962ff',
                    lineWidth: 2,
                    lineStyle: 'solid',
                },
                extended: true, // ✅ 수평선, 세로줄 모두 기본적으로 확장 (전체 영역)
                showLabel: true, // ✅ 날짜 라벨 기본 표시
            };
            onUpdateDrawings([...drawings, newDrawing]);
            if (onDrawingComplete) {
                onDrawingComplete(newDrawing);
            }
            return;
        }

        if (!isDrawing) {
            // Start new drawing
            setIsDrawing(true);
            const newId = `drawing-${Date.now()}`;
            setCurrentDrawing({
                id: newId,
                type: activeTool,
                points: [newPoint], // Start point
                style: {
                    color: '#2962ff',
                    lineWidth: 2,
                    lineStyle: 'solid',
                    fillColor: activeTool === 'brush' ? 'none' : 'rgba(41, 98, 255, 0.2)',
                    fillOpacity: 0.2,
                }
            });
        } else {
            // Finish drawing for 2-point tools (Click-Click)
            // Brush/Freehand is handled in MouseUp/MouseMove, but we don't finish purely on Click for Brush (Drag only)
            if (activeTool !== 'brush' && currentDrawing) {
                const finalPoints = [...currentDrawing.points, newPoint];
                const completedDrawing = { ...currentDrawing, points: finalPoints };

                const newDrawings = [...drawings, completedDrawing];
                onUpdateDrawings(newDrawings);
                if (onDrawingComplete) {
                    onDrawingComplete(completedDrawing);
                }

                setCurrentDrawing(null);
                setIsDrawing(false);
            }
        }
    };

    const handleMouseMove = (e: React.MouseEvent) => {
        if (!isDrawing || !currentDrawing) return;

        const rect = svgRef.current?.getBoundingClientRect();
        if (!rect) return;

        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;

        const time = coordinateToTime(x);
        const price = coordinateToPrice(y);

        if (time === null || price === null) return;

        // Update the drawing
        const activePoints = [...currentDrawing.points];

        if (currentDrawing.type === 'brush') {
            // For brush, append points (Freehand)
            activePoints.push({ time, price });
        } else {
            // For 2-point tools (TrendLine, Rect, Measure), replace the second point
            if (activePoints.length === 1) {
                activePoints.push({ time, price });
            } else {
                activePoints[activePoints.length - 1] = { time, price };
            }
        }

        setCurrentDrawing({
            ...currentDrawing,
            points: activePoints
        });
    };

    const handleMouseUp = () => {
        // Only finish drawing on MouseUp for Brush tool (Drag interaction)
        if (isDrawing && currentDrawing && currentDrawing.type === 'brush') {
            const newDrawings = [...drawings, currentDrawing];
            onUpdateDrawings(newDrawings);
            if (onDrawingComplete) onDrawingComplete(currentDrawing);

            setCurrentDrawing(null);
            setIsDrawing(false);
        }
    };

    // Render a single drawing object
    const renderDrawing = (drawing: DrawingObject, isPreview: boolean = false) => {
        const { type, points, style } = drawing;
        if (!points || points.length < 1) return null;

        const p1 = points[0];
        const x1 = timeToCoordinate(p1.time);
        const y1 = priceToCoordinate(p1.price);

        if (x1 === null || y1 === null) return null;

        // Single point rendering (preview start) - except Text/Brush/HorizontalLine/VerticalLine
        // ✅ HorizontalLine and VerticalLine only need 1 point and should render immediately
        if (points.length === 1 && isPreview && type !== 'brush' && type !== 'horizontalLine' && type !== 'verticalLine' && type !== 'text') {
            return <circle cx={x1} cy={y1} r={3} fill={style?.color || 'blue'} />;
        }

        const p2 = points[points.length - 1];
        const x2 = timeToCoordinate(p2.time);
        const y2 = priceToCoordinate(p2.price);

        // For brush, we need all points
        // For others, if we have only 1 point (and not previewing), we usually prefer not to render or render dot
        // But for preview of 2nd point, p2 is valid.

        const commonProps = {
            stroke: style?.color || '#2962ff',
            strokeWidth: style?.lineWidth || 2,
            strokeDasharray: getStrokeDasharray(style?.lineStyle || 'solid'),
            opacity: isPreview ? 0.7 : 1,
        };

        // ✅ Interaction props for existing drawings
        const interactionProps = !isPreview ? {
            onDoubleClick: (e: React.MouseEvent) => {
                e.stopPropagation(); // Stop zoom/other events
                if (onDrawingDoubleClick) onDrawingDoubleClick(drawing);
            },
            cursor: 'pointer',
            pointerEvents: 'stroke', // Allow clicking on stroke
        } : {};

        // Helper to add transparent wide stroke for easier clicking and dragging
        const renderClickableLine = (x1: number, y1: number, x2: number, y2: number, enableDrag: boolean = false) => {
            if (isPreview) return null;
            
            let isDragging = false;
            
            return (
                <line
                    x1={x1} y1={y1} x2={x2} y2={y2}
                    stroke="transparent"
                    strokeWidth={10}
                    style={{ pointerEvents: 'stroke', cursor: enableDrag ? 'move' : 'pointer' }}
                    onClick={(e: React.MouseEvent) => {
                        e.stopPropagation();
                        if (!isDragging && onDrawingClick) {
                            onDrawingClick(drawing);
                        }
                    }}
                    onDoubleClick={(e: React.MouseEvent) => {
                        e.stopPropagation();
                        if (onDrawingDoubleClick) onDrawingDoubleClick(drawing);
                    }}
                    onMouseDown={enableDrag ? (e: React.MouseEvent) => {
                        e.stopPropagation();
                        e.preventDefault();
                        
                        const rect = svgRef.current?.getBoundingClientRect();
                        if (!rect) return;
                        
                        isDragging = false;
                        const startX = e.clientX;
                        const startY = e.clientY;
                        const startPoints = [...drawing.points];
                        
                        const handleMouseMove = (moveEvent: MouseEvent) => {
                            const deltaX = moveEvent.clientX - startX;
                            const deltaY = moveEvent.clientY - startY;
                            
                            if (Math.abs(deltaX) > 5 || Math.abs(deltaY) > 5) {
                                isDragging = true;
                            }
                            
                            const newPoints = startPoints.map(pt => {
                                const ptX = timeToCoordinate(pt.time);
                                const ptY = priceToCoordinate(pt.price);
                                if (ptX === null || ptY === null) return pt;
                                
                                const newX = ptX + deltaX;
                                const newY = ptY + deltaY;
                                const newTime = coordinateToTime(newX);
                                const newPrice = coordinateToPrice(newY);
                                
                                if (newTime === null || newPrice === null) return pt;
                                return { time: newTime, price: newPrice };
                            });
                            
                            const updatedDrawing: DrawingObject = {
                                ...drawing,
                                points: newPoints
                            };
                            
                            const updatedDrawings = drawings.map(d =>
                                d.id === drawing.id ? updatedDrawing : d
                            );
                            onUpdateDrawings(updatedDrawings);
                        };
                        
                        const handleMouseUp = () => {
                            document.removeEventListener('mousemove', handleMouseMove);
                            document.removeEventListener('mouseup', handleMouseUp);
                            setTimeout(() => { isDragging = false; }, 50);
                        };
                        
                        document.addEventListener('mousemove', handleMouseMove);
                        document.addEventListener('mouseup', handleMouseUp);
                    } : undefined}
                />
            );
        };

        switch (type) {
            case 'trendLine':
                if (x2 === null || y2 === null) return null;
                return (
                    <g>
                        {renderClickableLine(x1, y1, x2, y2, true)}
                        <line x1={x1} y1={y1} x2={x2} y2={y2} {...commonProps} style={{ pointerEvents: 'none' }} />
                    </g>
                );
            case 'horizontalLine':
                // Horizontal line at Y1
                // ✅ Y축 라벨 영역을 제외한 순수 차트 영역까지만 그리기
                // Y축 라벨 영역은 약 100px이므로 actualWidth - 100으로 설정
                const horizontalLineEndX = actualWidth - 100;
                
                // ✅ 가격 라벨 포맷
                const priceLabel = p1.price.toFixed(2);
                
                console.log(`🔍 [HorizontalLine 렌더링] actualWidth=${actualWidth}, endX=${horizontalLineEndX}, y1=${y1}, isPreview=${isPreview}`);
                return (
                    <g>
                        {/* ✅ 드래그 가능한 투명 클릭 영역 (Y축 방향 이동) */}
                        {!isPreview && (
                            <line
                                x1={0} y1={y1} x2={horizontalLineEndX} y2={y1}
                                stroke="transparent"
                                strokeWidth={20}
                                style={{ pointerEvents: 'stroke', cursor: 'ns-resize' }}
                                onDoubleClick={(e: React.MouseEvent) => {
                                    e.stopPropagation();
                                    if (onDrawingDoubleClick) onDrawingDoubleClick(drawing);
                                }}
                                onMouseDown={(e: React.MouseEvent) => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    
                                    const startY = e.clientY;
                                    const startPrice = p1.price;
                                    
                                    const handleMouseMove = (moveEvent: MouseEvent) => {
                                        const deltaY = moveEvent.clientY - startY;
                                        const newY = y1 + deltaY;
                                        const newPrice = coordinateToPrice(newY);
                                        
                                        if (newPrice !== null) {
                                            // ✅ 수평선은 price만 변경 (time은 유지)
                                            const updatedDrawing: DrawingObject = {
                                                ...drawing,
                                                points: [{ time: p1.time, price: newPrice }]
                                            };
                                            
                                            const updatedDrawings = drawings.map(d =>
                                                d.id === drawing.id ? updatedDrawing : d
                                            );
                                            onUpdateDrawings(updatedDrawings);
                                        }
                                    };
                                    
                                    const handleMouseUp = () => {
                                        document.removeEventListener('mousemove', handleMouseMove);
                                        document.removeEventListener('mouseup', handleMouseUp);
                                    };
                                    
                                    document.addEventListener('mousemove', handleMouseMove);
                                    document.addEventListener('mouseup', handleMouseUp);
                                }}
                            />
                        )}
                        <line x1={0} y1={y1} x2={horizontalLineEndX} y2={y1} {...commonProps} style={{ pointerEvents: 'none' }} />
                        
                        {/* ✅ 가격 라벨 표시 안 함 (Y축 라벨과 중복 방지) */}
                    </g>
                );
            case 'verticalLine':
                // Vertical Line at X1
                // ✅ extended 옵션에 따라 높이 결정
                const effectiveHeight = drawing.extended && totalChartHeight ? totalChartHeight : height;
                
                // ✅ 날짜 라벨 포맷 (Unix timestamp를 날짜로 변환)
                const verticalLineDate = new Date(p1.time * 1000);
                const dateLabel = `${verticalLineDate.getFullYear()}-${String(verticalLineDate.getMonth() + 1).padStart(2, '0')}-${String(verticalLineDate.getDate()).padStart(2, '0')}`;
                
                return (
                    <g>
                        {/* ✅ 드래그 가능한 투명 클릭 영역 */}
                        {!isPreview && (
                            <line
                                x1={x1} y1={0} x2={x1} y2={effectiveHeight}
                                stroke="transparent"
                                strokeWidth={40}
                                style={{ pointerEvents: 'stroke', cursor: 'move' }}
                                onDoubleClick={(e: React.MouseEvent) => {
                                    e.stopPropagation();
                                    if (onDrawingDoubleClick) onDrawingDoubleClick(drawing);
                                }}
                                onMouseDown={(e: React.MouseEvent) => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    if (onDrawingDragStart) {
                                        onDrawingDragStart(drawing.id, e.clientX);
                                    }
                                }}
                            />
                        )}
                        <line x1={x1} y1={0} x2={x1} y2={effectiveHeight} {...commonProps} style={{ pointerEvents: 'none' }} />
                        
                        {/* ✅ 커스텀 텍스트 표시 (상단) */}
                        {drawing.customText && (
                            <g>
                                {/* 배경 박스 */}
                                <rect
                                    x={x1 - 40}
                                    y={5}
                                    width={80}
                                    height={20}
                                    fill={style?.color || '#2962ff'}
                                    opacity={0.9}
                                    rx={3}
                                    style={{ pointerEvents: 'none' }}
                                />
                                {/* 텍스트 */}
                                <text
                                    x={x1}
                                    y={19}
                                    fill="white"
                                    fontSize="11px"
                                    fontWeight="bold"
                                    textAnchor="middle"
                                    style={{ pointerEvents: 'none' }}
                                >
                                    {drawing.customText}
                                </text>
                            </g>
                        )}
                        
                        {/* ✅ 날짜 라벨 표시 (하단) */}
                        {drawing.showLabel !== false && (
                            <g>
                                {/* 배경 박스 */}
                                <rect
                                    x={x1 - 45}
                                    y={height - 25}
                                    width={90}
                                    height={20}
                                    fill={style?.color || '#2962ff'}
                                    opacity={0.9}
                                    rx={3}
                                    style={{ pointerEvents: 'none' }}
                                />
                                {/* 날짜 텍스트 */}
                                <text
                                    x={x1}
                                    y={height - 11}
                                    fill="white"
                                    fontSize="11px"
                                    fontWeight="bold"
                                    textAnchor="middle"
                                    style={{ pointerEvents: 'none' }}
                                >
                                    {dateLabel}
                                </text>
                            </g>
                        )}
                    </g>
                );
            case 'rectangle':
                if (x2 === null || y2 === null) return null;
                const rectX = Math.min(x1, x2);
                const rectY = Math.min(y1, y2);
                const rectW = Math.abs(x2 - x1);
                const rectH = Math.abs(y2 - y1);
                return (() => {
                    let isDragging = false;
                    return (
                        <rect
                            x={rectX} y={rectY} width={rectW} height={rectH}
                            {...commonProps}
                            fill={style?.fillColor || 'rgba(41, 98, 255, 0.2)'}
                            fillOpacity={style?.fillOpacity || 0.2}
                            style={{ pointerEvents: 'all', cursor: 'move' }}
                            onClick={(e: React.MouseEvent) => {
                                e.stopPropagation();
                                if (!isDragging && onDrawingClick) {
                                    onDrawingClick(drawing);
                                }
                            }}
                            onDoubleClick={(e: React.MouseEvent) => {
                                e.stopPropagation();
                                if (onDrawingDoubleClick) onDrawingDoubleClick(drawing);
                            }}
                            onMouseDown={!isPreview ? (e: React.MouseEvent) => {
                                e.stopPropagation();
                                e.preventDefault();
                                
                                const rect = svgRef.current?.getBoundingClientRect();
                                if (!rect) return;
                                
                                isDragging = false;
                                const startX = e.clientX;
                                const startY = e.clientY;
                                const startPoints = [...drawing.points];
                                
                                const handleMouseMove = (moveEvent: MouseEvent) => {
                                    const deltaX = moveEvent.clientX - startX;
                                    const deltaY = moveEvent.clientY - startY;
                                    
                                    if (Math.abs(deltaX) > 5 || Math.abs(deltaY) > 5) {
                                        isDragging = true;
                                    }
                                    
                                    const newPoints = startPoints.map(pt => {
                                        const ptX = timeToCoordinate(pt.time);
                                        const ptY = priceToCoordinate(pt.price);
                                        if (ptX === null || ptY === null) return pt;
                                        
                                        const newX = ptX + deltaX;
                                        const newY = ptY + deltaY;
                                        const newTime = coordinateToTime(newX);
                                        const newPrice = coordinateToPrice(newY);
                                        
                                        if (newTime === null || newPrice === null) return pt;
                                        return { time: newTime, price: newPrice };
                                    });
                                    
                                    const updatedDrawing: DrawingObject = {
                                        ...drawing,
                                        points: newPoints
                                    };
                                    
                                    const updatedDrawings = drawings.map(d =>
                                        d.id === drawing.id ? updatedDrawing : d
                                    );
                                    onUpdateDrawings(updatedDrawings);
                                };
                                
                                const handleMouseUp = () => {
                                    document.removeEventListener('mousemove', handleMouseMove);
                                    document.removeEventListener('mouseup', handleMouseUp);
                                    setTimeout(() => { isDragging = false; }, 50);
                                };
                                
                                document.addEventListener('mousemove', handleMouseMove);
                                document.addEventListener('mouseup', handleMouseUp);
                            } : undefined}
                        />
                    );
                })();
            case 'measure':
                if (x2 === null || y2 === null) return null;
                const priceDiff = p2.price - p1.price;
                const pricePercent = (priceDiff / p1.price) * 100;
                const timeDiffSeconds = p2.time - p1.time;
                const isDays = Math.abs(timeDiffSeconds) > 86400;
                const timeLabel = isDays
                    ? `${(Math.abs(timeDiffSeconds) / 86400).toFixed(1)} Days`
                    : `${(Math.abs(timeDiffSeconds) / 3600).toFixed(1)} Hours`;

                return (
                    <g>
                        {renderClickableLine(x1, y1, x2, y2, true)}
                        <line x1={x1} y1={y1} x2={x2} y2={y2} {...commonProps} strokeDasharray="5,5" style={{ pointerEvents: 'none' }} />
                        <rect
                            x={x2 + 10} y={y2 - 30} width={140} height={50}
                            fill="rgba(0,0,0,0.7)" rx={4}
                            style={{ pointerEvents: 'none' }}
                        />
                        <text x={x2 + 15} y={y2 - 10} fill="white" fontSize="12px" fontWeight="bold" style={{ pointerEvents: 'none' }}>
                            {priceDiff > 0 ? '+' : ''}{priceDiff.toLocaleString()} ({pricePercent.toFixed(2)}%)
                        </text>
                        <text x={x2 + 15} y={y2 + 10} fill="#cccccc" fontSize="11px" style={{ pointerEvents: 'none' }}>
                            {timeLabel}
                        </text>
                    </g>
                );
            case 'brush':
                const pathData = points.map(p => {
                    const px = timeToCoordinate(p.time);
                    const py = priceToCoordinate(p.price);
                    if (px === null || py === null) return '';
                    return `${px},${py}`;
                }).filter(s => s).join(' ');
                if (!pathData) return null;
                return (
                    <g>
                        {!isPreview && (() => {
                            let isDragging = false;
                            return (
                                <polyline 
                                    points={pathData} 
                                    fill="none" 
                                    stroke="transparent" 
                                    strokeWidth={10} 
                                    strokeLinecap="round" 
                                    strokeLinejoin="round" 
                                    style={{ pointerEvents: 'stroke', cursor: 'move' }}
                                    onClick={(e: React.MouseEvent) => {
                                        e.stopPropagation();
                                        if (!isDragging && onDrawingClick) {
                                            onDrawingClick(drawing);
                                        }
                                    }}
                                    onDoubleClick={(e: React.MouseEvent) => {
                                        e.stopPropagation();
                                        if (onDrawingDoubleClick) onDrawingDoubleClick(drawing);
                                    }}
                                    onMouseDown={(e: React.MouseEvent) => {
                                        e.stopPropagation();
                                        e.preventDefault();
                                        
                                        const rect = svgRef.current?.getBoundingClientRect();
                                        if (!rect) return;
                                        
                                        isDragging = false;
                                        const startX = e.clientX;
                                        const startY = e.clientY;
                                        const startPoints = [...drawing.points];
                                        
                                        const handleMouseMove = (moveEvent: MouseEvent) => {
                                            const deltaX = moveEvent.clientX - startX;
                                            const deltaY = moveEvent.clientY - startY;
                                            
                                            if (Math.abs(deltaX) > 5 || Math.abs(deltaY) > 5) {
                                                isDragging = true;
                                            }
                                            
                                            const newPoints = startPoints.map(pt => {
                                                const ptX = timeToCoordinate(pt.time);
                                                const ptY = priceToCoordinate(pt.price);
                                                if (ptX === null || ptY === null) return pt;
                                                
                                                const newX = ptX + deltaX;
                                                const newY = ptY + deltaY;
                                                const newTime = coordinateToTime(newX);
                                                const newPrice = coordinateToPrice(newY);
                                                
                                                if (newTime === null || newPrice === null) return pt;
                                                return { time: newTime, price: newPrice };
                                            });
                                            
                                            const updatedDrawing: DrawingObject = {
                                                ...drawing,
                                                points: newPoints
                                            };
                                            
                                            const updatedDrawings = drawings.map(d =>
                                                d.id === drawing.id ? updatedDrawing : d
                                            );
                                            onUpdateDrawings(updatedDrawings);
                                        };
                                        
                                        const handleMouseUp = () => {
                                            document.removeEventListener('mousemove', handleMouseMove);
                                            document.removeEventListener('mouseup', handleMouseUp);
                                            setTimeout(() => { isDragging = false; }, 50);
                                        };
                                        
                                        document.addEventListener('mousemove', handleMouseMove);
                                        document.addEventListener('mouseup', handleMouseUp);
                                    }}
                                />
                            );
                        })()}
                        <polyline points={pathData} fill="none" {...commonProps} strokeLinecap="round" strokeLinejoin="round" style={{ pointerEvents: 'none' }} />
                    </g>
                );

            case 'text':
                return (() => {
                    let isDragging = false;
                    return (
                        <text 
                            x={x1} 
                            y={y1} 
                            fill={style?.color || 'white'} 
                            fontSize={style?.fontSize || 14} 
                            fontWeight="bold" 
                            style={{ pointerEvents: 'all', cursor: 'move' }}
                            onClick={(e: React.MouseEvent) => {
                                e.stopPropagation();
                                if (!isDragging && onDrawingClick) {
                                    onDrawingClick(drawing);
                                }
                            }}
                            onDoubleClick={(e: React.MouseEvent) => {
                                e.stopPropagation();
                                if (onDrawingDoubleClick) onDrawingDoubleClick(drawing);
                            }}
                            onMouseDown={!isPreview ? (e: React.MouseEvent) => {
                                e.stopPropagation();
                                e.preventDefault();
                                
                                const rect = svgRef.current?.getBoundingClientRect();
                                if (!rect) return;
                                
                                isDragging = false;
                                const startX = e.clientX;
                                const startY = e.clientY;
                                const startPoint = drawing.points[0];
                                
                                const handleMouseMove = (moveEvent: MouseEvent) => {
                                    const deltaX = moveEvent.clientX - startX;
                                    const deltaY = moveEvent.clientY - startY;
                                    
                                    if (Math.abs(deltaX) > 5 || Math.abs(deltaY) > 5) {
                                        isDragging = true;
                                    }
                                    
                                    const ptX = timeToCoordinate(startPoint.time);
                                    const ptY = priceToCoordinate(startPoint.price);
                                    if (ptX === null || ptY === null) return;
                                    
                                    const newX = ptX + deltaX;
                                    const newY = ptY + deltaY;
                                    const newTime = coordinateToTime(newX);
                                    const newPrice = coordinateToPrice(newY);
                                    
                                    if (newTime === null || newPrice === null) return;
                                    
                                    const updatedDrawing: DrawingObject = {
                                        ...drawing,
                                        points: [{ time: newTime, price: newPrice }]
                                    };
                                    
                                    const updatedDrawings = drawings.map(d =>
                                        d.id === drawing.id ? updatedDrawing : d
                                    );
                                    onUpdateDrawings(updatedDrawings);
                                };
                                
                                const handleMouseUp = () => {
                                    document.removeEventListener('mousemove', handleMouseMove);
                                    document.removeEventListener('mouseup', handleMouseUp);
                                    setTimeout(() => { isDragging = false; }, 50);
                                };
                                
                                document.addEventListener('mousemove', handleMouseMove);
                                document.addEventListener('mouseup', handleMouseUp);
                            } : undefined}
                        >
                            {style?.text || 'Text'}
                        </text>
                    );
                })();

            case 'fibonacci':
                if (x2 === null || y2 === null) return null;
                
                // 피보나치 되돌림 레벨 (0%, 23.6%, 38.2%, 50%, 61.8%, 100%)
                const fibLevels = [
                    { level: 0, label: '0%', color: '#787B86' },
                    { level: 0.236, label: '23.6%', color: '#F23645' },
                    { level: 0.382, label: '38.2%', color: '#FF9800' },
                    { level: 0.5, label: '50%', color: '#4CAF50' },
                    { level: 0.618, label: '61.8%', color: '#2962FF' },
                    { level: 1, label: '100%', color: '#787B86' }
                ];
                
                const priceRange = p2.price - p1.price;
                // ✅ 수평선: Y축 라벨 영역 제외한 차트 영역까지만 (트레이딩뷰 스타일)
                const fibStartX = 0;
                const fibEndX = actualWidth - 100;
                
                return (
                    <g {...interactionProps} pointerEvents="all">
                        {/* 투명한 클릭 영역 - 두 점 사이의 세로 영역 */}
                        {!isPreview && (
                            <rect
                                x={0}
                                y={Math.min(y1, y2)}
                                width={width}
                                height={Math.abs(y2 - y1)}
                                fill="transparent"
                                stroke="transparent"
                                strokeWidth={10}
                            />
                        )}
                        
                        {/* 피보나치 레벨 라인들 - 전체 차트 범위에 걸쳐 수평선 */}
                        {fibLevels.map(({ level, label, color }) => {
                            const levelPrice = p1.price + (priceRange * level);
                            const levelY = priceToCoordinate(levelPrice);
                            
                            if (levelY === null) return null;
                            
                            return (
                                <g key={level}>
                                    {/* 레벨 라인 - 차트 전체 너비 */}
                                    <line
                                        x1={fibStartX}
                                        y1={levelY}
                                        x2={fibEndX}
                                        y2={levelY}
                                        stroke={color}
                                        strokeWidth={1}
                                        strokeDasharray={level === 0 || level === 1 ? '0' : '3,3'}
                                        opacity={isPreview ? 0.7 : 1}
                                        style={{ pointerEvents: 'none' }}
                                    />
                                    {/* 레벨 라벨 - 오른쪽 끝에 표시 */}
                                    <text
                                        x={fibEndX - 80}
                                        y={levelY - 3}
                                        fill={color}
                                        fontSize="11px"
                                        fontWeight="bold"
                                        opacity={isPreview ? 0.7 : 1}
                                        style={{ pointerEvents: 'none' }}
                                    >
                                        {label} ({levelPrice.toFixed(2)})
                                    </text>
                                </g>
                            );
                        })}
                        
                        {/* 시작점과 끝점 표시 */}
                        <circle cx={x1} cy={y1} r={4} fill={style?.color || '#2962ff'} opacity={isPreview ? 0.7 : 1} style={{ pointerEvents: 'none' }} />
                        <circle cx={x2} cy={y2} r={4} fill={style?.color || '#2962ff'} opacity={isPreview ? 0.7 : 1} style={{ pointerEvents: 'none' }} />
                    </g>
                );

            case 'diagonalLine':
                if (x2 === null || y2 === null) return null;
                return (
                    <g>
                        {renderClickableLine(x1, y1, x2, y2, true)}
                        <line x1={x1} y1={y1} x2={x2} y2={y2} {...commonProps} style={{ pointerEvents: 'none' }} />
                    </g>
                );

            case 'angleLine':
                if (x2 === null || y2 === null) return null;
                const angle = Math.atan2(y2 - y1, x2 - x1) * (180 / Math.PI);
                const angleLabel = `${angle.toFixed(1)}°`;
                return (
                    <g>
                        {renderClickableLine(x1, y1, x2, y2, true)}
                        <line x1={x1} y1={y1} x2={x2} y2={y2} {...commonProps} style={{ pointerEvents: 'none' }} />
                        <rect
                            x={x2 + 10} y={y2 - 15} width={60} height={20}
                            fill="rgba(0,0,0,0.7)" rx={3}
                            style={{ pointerEvents: 'none' }}
                        />
                        <text x={x2 + 15} y={y2} fill="white" fontSize="11px" fontWeight="bold" style={{ pointerEvents: 'none' }}>
                            {angleLabel}
                        </text>
                    </g>
                );

            case 'parallelChannel':
                if (points.length < 2 || x2 === null || y2 === null) return null;
                const channelWidth = points.length >= 3 ? points[2].price - p1.price : (p2.price - p1.price) * 0.5;
                const y1Parallel = priceToCoordinate(p1.price + channelWidth);
                const y2Parallel = priceToCoordinate(p2.price + channelWidth);
                
                if (y1Parallel === null || y2Parallel === null) return null;
                
                return (
                    <g>
                        {renderClickableLine(x1, y1, x2, y2, true)}
                        <line x1={x1} y1={y1} x2={x2} y2={y2} {...commonProps} style={{ pointerEvents: 'none' }} />
                        <line x1={x1} y1={y1Parallel} x2={x2} y2={y2Parallel} {...commonProps} style={{ pointerEvents: 'none' }} />
                        <line x1={x1} y1={y1} x2={x1} y2={y1Parallel} {...commonProps} strokeDasharray="2,2" style={{ pointerEvents: 'none' }} />
                    </g>
                );

            case 'fibonacciFan':
                if (x2 === null || y2 === null) return null;
                const fanLevels = drawing.fibLevels || [0.382, 0.5, 0.618];
                const fanPriceRange = p2.price - p1.price;
                
                return (
                    <g>
                        {renderClickableLine(x1, y1, x2, y2, true)}
                        {fanLevels.map((level, idx) => {
                            const levelPrice = p1.price + (fanPriceRange * level);
                            const levelY = priceToCoordinate(levelPrice);
                            if (levelY === null) return null;
                            
                            return (
                                <g key={idx}>
                                    <line x1={x1} y1={y1} x2={x2} y2={levelY} {...commonProps} style={{ pointerEvents: 'none' }} />
                                    <text x={x2 + 5} y={levelY} fill={style?.color || '#2962ff'} fontSize="10px" style={{ pointerEvents: 'none' }}>
                                        {`${(level * 100).toFixed(1)}%`}
                                    </text>
                                </g>
                            );
                        })}
                    </g>
                );

            case 'fibonacciCircle':
                if (x2 === null || y2 === null) return null;
                const circleLevels = drawing.fibLevels || [0.382, 0.5, 0.618, 1.0];
                const centerX = (x1 + x2) / 2;
                const centerY = (y1 + y2) / 2;
                const baseRadius = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)) / 2;
                
                return (
                    <g>
                        {renderClickableLine(x1, y1, x2, y2, true)}
                        {circleLevels.map((level, idx) => {
                            const radius = baseRadius * level;
                            return (
                                <circle
                                    key={idx}
                                    cx={centerX}
                                    cy={centerY}
                                    r={radius}
                                    {...commonProps}
                                    fill={style?.fillColor || 'transparent'}
                                    fillOpacity={style?.fillOpacity || 0.1}
                                    style={{ pointerEvents: 'none' }}
                                />
                            );
                        })}
                    </g>
                );

            case 'fibonacciWedge':
                if (x2 === null || y2 === null) return null;
                const wedgeLevels = drawing.fibLevels || [0.382, 0.5, 0.618];
                const wedgePriceRange = p2.price - p1.price;
                
                return (
                    <g>
                        {renderClickableLine(x1, y1, x2, y2, true)}
                        {wedgeLevels.map((level, idx) => {
                            const wedgeLevelPrice = p1.price + (wedgePriceRange * level);
                            const wedgeLevelY = priceToCoordinate(wedgeLevelPrice);
                            if (wedgeLevelY === null) return null;
                            
                            const wedgePoints = `${x1},${y1} ${x2},${wedgeLevelY} ${x2},${y2}`;
                            return (
                                <g key={idx}>
                                    <polyline
                                        points={wedgePoints}
                                        {...commonProps}
                                        fill={style?.fillColor || 'rgba(41, 98, 255, 0.1)'}
                                        fillOpacity={style?.fillOpacity || 0.1}
                                        style={{ pointerEvents: 'none' }}
                                    />
                                    <text x={x2 + 5} y={wedgeLevelY} fill={style?.color || '#2962ff'} fontSize="10px" style={{ pointerEvents: 'none' }}>
                                        {`${(level * 100).toFixed(1)}%`}
                                    </text>
                                </g>
                            );
                        })}
                    </g>
                );

            default:
                return null;
        }
    };

    // ✅ extended 옵션이 있는 drawing이 있으면 totalChartHeight 사용
    const hasExtendedDrawing = drawings.some(d => d.extended);
    const effectiveContainerHeight = hasExtendedDrawing && totalChartHeight ? totalChartHeight : height;
    
    // ✅ SVG width는 실제 측정된 너비 사용
    const effectiveSvgWidth = actualWidth;

    return (
        <Box
            ref={containerRef}
            sx={{
                position: 'absolute',
                top: 0,
                left: 0,
                width: '100%',
                height: effectiveContainerHeight,
                zIndex: 20, // Above chart
                // ✅ crosshair/magnifier 모드일 때는 pointer events 비활성화 (차트 기본 동작 허용)
                pointerEvents: activeTool && activeTool !== 'crosshair' && activeTool !== 'magnifier' ? 'auto' : 'none',
                cursor: isDrawing ? 'crosshair' : 'default',
                overflow: 'visible',
            }}
            onMouseDown={handleMouseDown}
            onMouseMove={handleMouseMove}
            onMouseUp={handleMouseUp}
        // Logic for click to finish is now in handleMouseDown
        >
            <svg
                ref={svgRef}
                width={effectiveSvgWidth}
                height={effectiveContainerHeight}
                style={{ overflow: 'visible' }}
            >
                {drawings.map(d => (
                    <g key={d.id}>{renderDrawing(d)}</g>
                ))}
                {currentDrawing && (
                    <g key="current-drawing">{renderDrawing(currentDrawing, true)}</g>
                )}
            </svg>
        </Box>
    );
};

export default ChartDrawingOverlay;
