/**
 * 선박 아이템 우클릭 컨텍스트 메뉴 컴포넌트
 */
import React, { useCallback, useEffect } from 'react';
import './VesselContextMenu.scss';

const VesselContextMenu = ({
  vessel,
  position,
  onClose,
  onShowDetail,
}) => {
  // 메뉴 외부 클릭 시 닫기
  useEffect(() => {
    const handleClickOutside = (event) => {
      const target = event.target;
      if (!target.closest('.vessel-context-menu')) {
        onClose();
      }
    };

    const handleEscKey = (event) => {
      if (event.key === 'Escape') {
        onClose();
      }
    };

    // 약간의 지연 후 이벤트 리스너 등록 (우클릭 이벤트와 충돌 방지)
    const timer = setTimeout(() => {
      document.addEventListener('click', handleClickOutside);
      document.addEventListener('keydown', handleEscKey);
    }, 100);

    return () => {
      clearTimeout(timer);
      document.removeEventListener('click', handleClickOutside);
      document.removeEventListener('keydown', handleEscKey);
    };
  }, [onClose]);

  const handleShowDetail = useCallback(() => {
    onShowDetail(vessel.vesselId);
    onClose();
  }, [vessel.vesselId, onShowDetail, onClose]);

  // 화면 경계 체크 및 위치 조정
  const adjustedPosition = {
    x: Math.min(position.x, window.innerWidth - 200), // 메뉴 너비 고려
    y: Math.min(position.y, window.innerHeight - 150), // 메뉴 높이 고려
  };

  return (
    <div
      className="vessel-context-menu"
      style={{
        position: 'fixed',
        top: adjustedPosition.y,
        left: adjustedPosition.x,
        zIndex: 10001, // VesselListManager보다 높게
      }}
    >
      <div className="context-menu-header">
        <span className="vessel-name">{vessel.shipName}</span>
        <span className="vessel-id">ID: {vessel.vesselId}</span>
      </div>

      <div className="context-menu-divider"></div>

      <div className="context-menu-items">
        <button
          className="context-menu-item"
          onClick={handleShowDetail}
        >
          <i className="fas fa-info-circle"></i>
          <span>상세보기</span>
        </button>
      </div>
    </div>
  );
};

export default React.memo(VesselContextMenu);
