// ===== 统一销毁逻辑（关键优化）=====
function destroy(menu, handleClose) {
  if (menu && menu.parentNode) {
    menu.parentNode.removeChild(menu);
  }
  document.removeEventListener('mousedown', handleClose);
}

// ===== 按钮工厂（核心优化点）=====
function createBtn(text, isSplit, onClick, menu, handleClose) {
  const btn = document.createElement('button');
  btn.innerHTML = text;

  Object.assign(btn.style, {
    width: '100%',
    border: 'none',
    background: 'transparent',
    padding: '6px 10px',
    textAlign: 'left',
    cursor: 'pointer',
    fontSize: '13px',
    color: '#333',
  });

  if (isSplit) {
    btn.style.borderBottom = '1px solid #ddd';
  }

  btn.onmouseenter = () => (btn.style.background = '#e6e6e6');
  btn.onmouseleave = () => (btn.style.background = 'transparent');

  btn.onclick = () => {
    onClick && onClick();
    destroy(menu, handleClose);
  };

  return btn;
}

function createTitle(text) {
  const title = document.createElement('div');
  title.innerHTML = text;
  Object.assign(title.style, {
    background: '#e9e9e9',
    borderRadius: '4px',
    padding: '6px 8px',
    marginBottom: '4px',
    fontSize: '12px',
    color: '#666',
    display: 'flex',
    alignItems: 'center',
    gap: '6px',
  });
  return title;
}

function createMenu(event) {
  const menu = document.createElement('div');
  menu.id = 'fl-context-menu';

  Object.assign(menu.style, {
    position: 'fixed',
    left: event.clientX + 'px',
    top: event.clientY + 'px',
    background: '#f3f3f3',
    border: '1px solid #dcdcdc',
    borderRadius: '6px',
    boxShadow: '0 2px 6px rgba(0,0,0,0.1)',
    padding: '4px',
    minWidth: '150px',
    zIndex: 99999,
    fontFamily: 'system-ui, -apple-system, sans-serif',
  });
  return menu;
}

export function onContextHandle(event, domId, hideText, isolateText, hideFn, isolateFn) {
  event.preventDefault();

  const model = document.getElementById(domId);
  if (!model) return;

  const parent = model.parentElement;
  if (!parent) return;

  // 清理旧菜单
  const oldMenu = document.getElementById('fl-context-menu');
  if (oldMenu) oldMenu.remove();

  // ===== 创建菜单 =====
  const menu = createMenu(event);

  menu.addEventListener('mousedown', e => e.stopPropagation());

  // ===== 标题 =====
  const title = createTitle('☰ 显示控制');

  // ===== 按钮容器 =====
  const btnWrap = document.createElement('div');
  btnWrap.style.display = 'flex';
  btnWrap.style.flexDirection = 'column';

  // ===== 创建按钮 =====
  const hideBtn = createBtn(hideText || '隐藏', true, hideFn, menu, handleClose);
  const isolateBtn = createBtn(isolateText || '隔离', false, isolateFn, menu, handleClose);

  btnWrap.appendChild(hideBtn);
  btnWrap.appendChild(isolateBtn);

  menu.appendChild(title);
  menu.appendChild(btnWrap);

  parent.appendChild(menu);

  function handleClose() {
    destroy(menu, handleClose);
  }

  // 延迟绑定，避免立即关闭
  setTimeout(() => {
    document.addEventListener('mousedown', handleClose);
  }, 0);
}
