import React, { useEffect, useRef } from 'react';
import type { Drawing } from '../types';

// 도구별 한국어 이름
const DRAWING_LABELS: Record<string, string> = {
  hline:     '수평선',
  vline:     '수직선',
  trendline: '추세선',
  ray:       '레이',
  fib:       '피보나치',
  fibtz:     '피보나치 타임존',
  measure:   '가격 측정',
  rect:      '사각형',
  channel:   '채널',
  pencil:    '자유 드로잉',
  text:      '텍스트',
};

/* ── SVG Icons (IndicatorContextToolbar 와 동일 스타일) ── */
const IcEye = ({ visible }: { visible: boolean }) => visible ? (
  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.5">
    <path d="M1 7 Q4 2.5 7 2.5 Q10 2.5 13 7 Q10 11.5 7 11.5 Q4 11.5 1 7 Z"/>
    <circle cx="7" cy="7" r="2"/>
  </svg>
) : (
  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.5">
    <path d="M1 7 Q4 2.5 7 2.5 Q10 2.5 13 7 Q10 11.5 7 11.5 Q4 11.5 1 7 Z" strokeOpacity="0.35"/>
    <line x1="2" y1="2" x2="12" y2="12"/>
  </svg>
);

const IcGear = () => (
  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.4">
    <circle cx="7" cy="7" r="2.3"/>
    <path d="M7 1 L7.7 2.8 L9.8 2 L9.8 4.2 L11.8 5 L11 7 L11.8 9 L9.8 9.8 L9.8 12 L7.7 11.2 L7 13 L6.3 11.2 L4.2 12 L4.2 9.8 L2.2 9 L3 7 L2.2 5 L4.2 4.2 L4.2 2 L6.3 2.8 Z"/>
  </svg>
);

const IcTrash = () => (
  <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.4">
    <line x1="2" y1="4.5" x2="12" y2="4.5"/>
    <path d="M5 4.5 V3 Q5 2 7 2 Q9 2 9 3 V4.5"/>
    <path d="M3 4.5 L3.5 12 Q3.5 12.5 4 12.5 L10 12.5 Q10.5 12.5 10.5 12 L11 4.5"/>
  </svg>
);

interface DrawingContextToolbarProps {
  drawing:   Drawing;
  screenX:   number;
  screenY:   number;
  onSettings:      () => void;
  onToggleVisible: () => void;
  onRemove:        () => void;
  onClose:         () => void;
}

const DrawingContextToolbar: React.FC<DrawingContextToolbarProps> = ({
  drawing, screenX, screenY,
  onSettings, onToggleVisible, onRemove, onClose,
}) => {
  const ref = useRef<HTMLDivElement>(null);

  // 외부 클릭 시 닫기
  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) {
        onClose();
      }
    };
    const tid = setTimeout(() => document.addEventListener('mousedown', handler), 100);
    return () => { clearTimeout(tid); document.removeEventListener('mousedown', handler); };
  }, [onClose]);

  const W    = 220;
  let left   = screenX + 8;
  let top    = screenY + 8;
  if (left + W > window.innerWidth - 8) left = window.innerWidth - W - 8;
  if (top  + 50 > window.innerHeight - 8) top = screenY - 58;

  const label    = DRAWING_LABELS[drawing.type] ?? drawing.type;
  const isHidden = drawing.visible === false;

  return (
    <div
      ref={ref}
      className="ind-ctx-toolbar"
      style={{ left, top }}
      onMouseDown={e => e.stopPropagation()}
    >
      {/* 색상 닷 + 이름 */}
      <span className="ind-ctx-name" title={label}>
        <span
          style={{
            display:         'inline-block',
            width:           8,
            height:          8,
            borderRadius:    '50%',
            background:      drawing.color,
            marginRight:     5,
            verticalAlign:   'middle',
            flexShrink:      0,
          }}
        />
        {label}
      </span>

      {/* 가시성 토글 */}
      <button
        className="ind-ctx-btn"
        title={isHidden ? '표시' : '숨기기'}
        onClick={onToggleVisible}
      >
        <IcEye visible={!isHidden} />
      </button>

      {/* 설정 */}
      <button
        className="ind-ctx-btn"
        title="설정 (더블클릭)"
        onClick={onSettings}
      >
        <IcGear />
      </button>

      {/* 삭제 */}
      <button
        className="ind-ctx-btn ind-ctx-del"
        title="삭제"
        onClick={onRemove}
      >
        <IcTrash />
      </button>
    </div>
  );
};

export default DrawingContextToolbar;
