/**
 * 차트 우클릭 컨텍스트 메뉴 (매수 / 매도)
 */
import React, { useEffect, useRef } from 'react';
import { createPortal } from 'react-dom';

export interface ChartContextMenuProps {
  x: number;
  y: number;
  marketLabel: string;
  priceLabel: string;
  onBuy: () => void;
  onSell: () => void;
  onClose: () => void;
}

const ChartContextMenu: React.FC<ChartContextMenuProps> = ({
  x, y, marketLabel, priceLabel, onBuy, onSell, onClose,
}) => {
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const onDown = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) onClose();
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    document.addEventListener('mousedown', onDown);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onDown);
      document.removeEventListener('keydown', onKey);
    };
  }, [onClose]);

  const menuW = 168;
  const menuH = 88;
  const left = Math.min(x, window.innerWidth - menuW - 8);
  const top  = Math.min(y, window.innerHeight - menuH - 8);

  return createPortal(
    <div
      ref={ref}
      className="chart-ctx-menu"
      style={{ left, top }}
      role="menu"
    >
      <div className="chart-ctx-menu-hint">
        <span>{marketLabel}</span>
        <span className="chart-ctx-menu-price">{priceLabel}</span>
      </div>
      <button type="button" className="chart-ctx-menu-item chart-ctx-menu-item--buy" onClick={onBuy}>
        매수
      </button>
      <button type="button" className="chart-ctx-menu-item chart-ctx-menu-item--sell" onClick={onSell}>
        매도
      </button>
    </div>,
    document.body,
  );
};

export default ChartContextMenu;
