/**
 * @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;
          font-size: 14px;
          line-height: 1.6;
          color: #333;
        }
        
        .placeholder {
          color: #999;
          text-align: center;
          margin-top: 100px;
        }
        
        .word-title {
          font-size: 28px;
          font-weight: bold;
          color: #333;
          margin-bottom: 4px;
        }
        
        .phonetic {
          font-size: 14px;
          color: #666;
          margin-bottom: 16px;
          font-family: 'Times New Roman', serif;
        }
        
        .meanings-section {
          margin-bottom: 16px;
        }
        
        .section-title {
          font-size: 12px;
          font-weight: bold;
          color: #4CAF50;
          margin-bottom: 8px;
          text-transform: uppercase;
        }
        
        .meaning-item {
          margin-bottom: 8px;
        }
        
        .part-of-speech {
          color: #2196F3;
          font-weight: 500;
          margin-right: 8px;
        }
        
        .definition {
          color: #333;
        }
        
        .examples-section {
          margin-top: 16px;
        }
        
        .example-item {
          margin-bottom: 12px;
          padding: 8px;
          background: #f5f5f5;
          border-radius: 4px;
        }
        
        .example-sentence {
          color: #333;
          margin-bottom: 4px;
        }
        
        .example-translation {
          color: #666;
          font-size: 13px;
        }
      </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);
    }
  }

  /**
   * 渲染词典查询结果
   * @param {Object} result - 查询结果
   * @param {string} result.word - 单词
   * @param {string} [result.phonetic] - 音标
   * @param {Array} [result.meanings] - 释义列表
   * @param {Array} [result.examples] - 例句列表
   */
  renderResult(result) {
    const content = this.element.shadowRoot.querySelector('.content');
    
    if (!result) {
      content.innerHTML = '<div class="placeholder">暂无查询结果</div>';
      return;
    }

    const html = `
      <div class="word-title">${this._escapeHtml(result.word)}</div>
      ${result.phonetic ? `<div class="phonetic">${this._escapeHtml(result.phonetic)}</div>` : ''}
      
      ${this._renderMeanings(result.meanings)}
      ${this._renderExamples(result.examples)}
    `;

    content.innerHTML = html;
  }

  /**
   * 渲染释义列表
   * @private
   * @param {Array} meanings - 释义列表
   * @returns {string} HTML 字符串
   */
  _renderMeanings(meanings) {
    if (!meanings || meanings.length === 0) {
      return '';
    }

    const meaningsHtml = meanings.map(m => `
      <div class="meaning-item">
        <span class="part-of-speech">${this._escapeHtml(m.partOfSpeech || '')}</span>
        <span class="definition">${this._escapeHtml(m.definitions?.join('；') || '')}</span>
      </div>
    `).join('');

    return `
      <div class="meanings-section">
        <div class="section-title">释义</div>
        ${meaningsHtml}
      </div>
    `;
  }

  /**
   * 渲染例句列表
   * @private
   * @param {Array} examples - 例句列表
   * @returns {string} HTML 字符串
   */
  _renderExamples(examples) {
    if (!examples || examples.length === 0) {
      return '';
    }

    // 最多显示2个例句
    const displayExamples = examples.slice(0, 2);

    const examplesHtml = displayExamples.map(e => `
      <div class="example-item">
        <div class="example-sentence">${this._escapeHtml(e.sentence || '')}</div>
        ${e.translation ? `<div class="example-translation">${this._escapeHtml(e.translation)}</div>` : ''}
      </div>
    `).join('');

    return `
      <div class="examples-section">
        <div class="section-title">例句</div>
        ${examplesHtml}
      </div>
    `;
  }

  /**
   * HTML 转义，防止 XSS
   * @private
   * @param {string} text - 原始文本
   * @returns {string} 转义后的文本
   */
  _escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  }
}

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