/**
 * @file 词典结果展示面板
 * @description 显示词典查询结果的基础面板组件
 */

const PANEL_WIDTH = 400;
const PANEL_HEIGHT = 300;
const VIEWPORT_MARGIN = 10;

/**
 * 词典结果面板类
 */
export class DictPanel {
  constructor() {
    this.element = this.createElement();
    this.isDragging = false;
    this.dragOffset = { x: 0, y: 0 };
    this._dragHandlers = null;
    this._isVisible = false;
  }

  /**
   * 创建面板元素
   * @returns {HTMLElement} 面板元素
   */
  createElement() {
    // 创建容器
    const container = document.createElement('div');
    container.style.cssText = `
      position: fixed;
      z-index: 2147483646;
      display: none;
      width: ${PANEL_WIDTH}px;
      height: ${PANEL_HEIGHT}px;
    `;

    // 创建 Shadow DOM
    const shadow = container.attachShadow({ mode: 'open' });

    // Shadow DOM 内容
    shadow.innerHTML = `
      <style>
        .panel {
          width: 100%;
          height: 100%;
          background-color: #ffffff;
          border-radius: 8px;
          box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
          display: flex;
          flex-direction: column;
          overflow: hidden;
          font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        }
        
        .header {
          padding: 12px 16px;
          background-color: #4CAF50;
          color: white;
          font-size: 16px;
          font-weight: 500;
          border-radius: 8px 8px 0 0;
          cursor: move;
          user-select: none;
        }
        
        .header:hover {
          background-color: #45a049;
        }
        
        .content {
          flex: 1;
          padding: 16px;
          overflow-y: auto;
        }
        
        .placeholder {
          color: #999;
          text-align: center;
          margin-top: 100px;
        }
      </style>
      <div class="panel">
        <div class="header">词典结果</div>
        <div class="content">
          <div class="placeholder">查询结果将显示在这里</div>
        </div>
      </div>
    `;

    // 阻止点击事件冒泡
    container.addEventListener('click', (e) => {
      e.stopPropagation();
    });

    // 添加到页面
    document.body.appendChild(container);

    return container;
  }

  /**
   * 绑定拖拽事件
   */
  bindDragEvents() {
    if (this._dragHandlers) return; // 已绑定则跳过

    const header = this.element.shadowRoot.querySelector('.header');
    
    // 鼠标按下开始拖拽
    const handleMouseDown = (e) => {
      this.isDragging = true;
      this.dragOffset.x = e.clientX - this.element.offsetLeft;
      this.dragOffset.y = e.clientY - this.element.offsetTop;
      
      e.preventDefault();
      e.stopPropagation();

      document.addEventListener('mousemove', handleMouseMove);
      document.addEventListener('mouseup', handleMouseUp);
    };
    
    // 鼠标移动时更新位置
    const handleMouseMove = (e) => {
      if (!this.isDragging) return;
      
      let newX = e.clientX - this.dragOffset.x;
      let newY = e.clientY - this.dragOffset.y;
      
      const viewportWidth = window.innerWidth;
      const viewportHeight = window.innerHeight;
      
      newX = Math.max(VIEWPORT_MARGIN, Math.min(newX, viewportWidth - PANEL_WIDTH - VIEWPORT_MARGIN));
      newY = Math.max(VIEWPORT_MARGIN, Math.min(newY, viewportHeight - PANEL_HEIGHT - VIEWPORT_MARGIN));
      
      this.element.style.left = `${newX}px`;
      this.element.style.top = `${newY}px`;
    };
    
    // 鼠标抬起结束拖拽
    const handleMouseUp = () => {
      this.isDragging = false;
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
    };
    
    header.addEventListener('mousedown', handleMouseDown);
    
    this._dragHandlers = { handleMouseDown, header };
  }

  /**
   * 解绑拖拽事件
   */
  unbindDragEvents() {
    if (!this._dragHandlers) return;
    
    const { handleMouseDown, header } = this._dragHandlers;
    header.removeEventListener('mousedown', handleMouseDown);
    
    this._dragHandlers = null;
  }

  /**
   * 计算面板位置，确保不超出视口
   */
  calculatePosition(x, y) {
    const viewportWidth = window.innerWidth;
    const viewportHeight = window.innerHeight;
    
    let panelX = x;
    let panelY = y;
    
    if (panelX + PANEL_WIDTH + VIEWPORT_MARGIN > viewportWidth) {
      panelX = x - PANEL_WIDTH;
    }
    
    if (panelY + PANEL_HEIGHT + VIEWPORT_MARGIN > viewportHeight) {
      panelY = y - PANEL_HEIGHT;
    }
    
    panelX = Math.max(VIEWPORT_MARGIN, panelX);
    panelY = Math.max(VIEWPORT_MARGIN, panelY);
    
    if (panelX + PANEL_WIDTH > viewportWidth - VIEWPORT_MARGIN) {
      panelX = viewportWidth - PANEL_WIDTH - VIEWPORT_MARGIN;
    }
    
    if (panelY + PANEL_HEIGHT > viewportHeight - VIEWPORT_MARGIN) {
      panelY = viewportHeight - PANEL_HEIGHT - VIEWPORT_MARGIN;
    }
    
    return { x: panelX, y: panelY };
  }

  /**
   * 显示面板
   */
  show(x, y) {
    if (this._isVisible) return;
    
    const position = this.calculatePosition(x, y);
    this.element.style.left = `${position.x}px`;
    this.element.style.top = `${position.y}px`;
    this.element.style.display = 'block';
    this._isVisible = true;
    
    // 绑定拖拽事件
    this.bindDragEvents();
  }

  /**
   * 隐藏面板
   */
  hide() {
    if (!this._isVisible) return;
    
    this.element.style.display = 'none';
    this._isVisible = false;
    
    // 解绑拖拽事件
    this.unbindDragEvents();
  }

  /**
   * 销毁组件
   */
  destroy() {
    this.hide();
    this.unbindDragEvents();
    
    if (this.element.parentNode) {
      this.element.parentNode.removeChild(this.element);
    }
  }
}

/**
 * 创建并显示词典面板
 */
export function createDictPanel(x, y) {
  const panel = new DictPanel();
  panel.show(x, y);
  return panel;
}
