/**
 * @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;
    this._collapsedStates = new Map(); // 存储每个词典的折叠状态
  }

  /**
   * 创建面板元素
   * @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;
        }
        
        .loading {
          text-align: center;
          padding: 40px 20px;
          color: #666;
        }
        
        .loading-spinner {
          width: 32px;
          height: 32px;
          border: 3px solid #e0e0e0;
          border-top-color: #4CAF50;
          border-radius: 50%;
          animation: spin 0.8s linear infinite;
          margin: 0 auto 16px;
        }
        
        @keyframes spin {
          to { transform: rotate(360deg); }
        }
        
        .loading-text {
          font-size: 14px;
        }
        
        .dict-section {
          margin-bottom: 16px;
          padding-bottom: 16px;
          border-bottom: 1px solid #eee;
        }
        
        .dict-section:last-child {
          border-bottom: none;
        }
        
        .dict-section {
          margin-bottom: 8px;
          border: 1px solid #e0e0e0;
          border-radius: 6px;
          overflow: hidden;
        }
        
        .dict-header {
          display: flex;
          align-items: center;
          padding: 10px 12px;
          background: #f8f8f8;
          cursor: pointer;
          user-select: none;
          transition: background 0.2s;
        }
        
        .dict-header:hover {
          background: #f0f0f0;
        }
        
        .dict-toggle {
          font-size: 10px;
          margin-right: 6px;
          color: #666;
          width: 12px;
          text-align: center;
        }
        
        .dict-icon {
          width: 16px;
          height: 16px;
          border-radius: 3px;
          margin-right: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 10px;
          font-weight: bold;
          color: white;
          flex-shrink: 0;
        }
        
        .dict-icon.bing {
          background: #00809d;
        }
        
        .dict-icon.youdao {
          background: #e93a2b;
        }
        
        .dict-icon.default {
          background: #999;
        }
        
        .dict-name {
          font-size: 13px;
          font-weight: 600;
          color: #333;
        }
        
        .dict-content {
          padding: 12px;
          display: block;
        }
        
        .dict-content.collapsed {
          display: none;
        }
      </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) {
    if (!result) {
      this._setContent('<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)}
    `;

    this._setContent(html);
  }

  /**
   * 渲染多个词典查询结果
   * @param {Array} results - 多个词典结果 {name, result}[]
   */
  renderMultipleResults(results) {
    if (!results || results.length === 0) {
      this._setContent('<div class="placeholder">暂无查询结果</div>');
      return;
    }

    // 第一个结果作为主结果显示单词标题
    const firstResult = results[0].result;
    let html = `
      <div class="word-title">${this._escapeHtml(firstResult.word)}</div>
    `;

    // 显示每个词典的结果
    for (const { name, result } of results) {
      html += this._renderDictSection(name, result);
    }

    this._setContent(html);
  }

  /**
   * 获取词典图标类名
   * @private
   * @param {string} dictName - 词典名称
   * @returns {string} 图标类名
   */
  _getDictIconClass(dictName) {
    const name = dictName.toLowerCase();
    if (name.includes('必应') || name.includes('bing')) return 'bing';
    if (name.includes('有道') || name.includes('youdao')) return 'youdao';
    return 'default';
  }

  /**
   * 获取词典图标文字
   * @private
   * @param {string} dictName - 词典名称
   * @returns {string} 图标文字
   */
  _getDictIconText(dictName) {
    const name = dictName.toLowerCase();
    if (name.includes('必应') || name.includes('bing')) return 'B';
    if (name.includes('有道') || name.includes('youdao')) return 'Y';
    return dictName.charAt(0).toUpperCase();
  }

  /**
   * 渲染单个词典区块
   * @private
   * @param {string} dictName - 词典名称
   * @param {Object} result - 词典结果
   * @returns {string} HTML 字符串
   */
  _renderDictSection(dictName, result) {
    // 获取保存的折叠状态，默认展开
    const isCollapsed = this._collapsedStates.get(dictName) || false;
    const toggleIcon = isCollapsed ? '▶' : '▼';
    const contentClass = isCollapsed ? 'dict-content collapsed' : 'dict-content';
    
    const iconClass = this._getDictIconClass(dictName);
    const iconText = this._getDictIconText(dictName);
    
    return `
      <div class="dict-section" data-dict="${this._escapeHtml(dictName)}">
        <div class="dict-header">
          <span class="dict-toggle">${toggleIcon}</span>
          <div class="dict-icon ${iconClass}">${iconText}</div>
          <span class="dict-name">${this._escapeHtml(dictName)}</span>
        </div>
        <div class="${contentClass}">
          ${result.phonetic ? `<div class="phonetic" style="margin-bottom: 8px;">${this._escapeHtml(result.phonetic)}</div>` : ''}
          ${this._renderMeanings(result.meanings)}
          ${this._renderExamples(result.examples)}
        </div>
      </div>
    `;
  }

  /**
   * 设置内容区域 HTML
   * @private
   * @param {string} html - HTML 内容
   */
  _setContent(html) {
    const content = this.element.shadowRoot.querySelector('.content');
    content.innerHTML = html;
    
    // 绑定折叠事件
    this._bindCollapseEvents();
  }

  /**
   * 绑定折叠/展开事件
   * @private
   */
  _bindCollapseEvents() {
    const shadow = this.element.shadowRoot;
    const headers = shadow.querySelectorAll('.dict-header');
    
    headers.forEach(header => {
      header.addEventListener('click', (e) => {
        const section = header.closest('.dict-section');
        const content = section.querySelector('.dict-content');
        const toggle = header.querySelector('.dict-toggle');
        const dictName = header.querySelector('.dict-name').textContent;
        
        // 切换折叠状态
        const isCollapsed = content.classList.toggle('collapsed');
        
        // 更新图标
        toggle.textContent = isCollapsed ? '▶' : '▼';
        
        // 保存状态
        this._collapsedStates.set(dictName, isCollapsed);
      });
    });
  }

  /**
   * 显示加载状态
   */
  showLoading() {
    const content = this.element.shadowRoot.querySelector('.content');
    content.innerHTML = `
      <div class="loading">
        <div class="loading-spinner"></div>
        <div class="loading-text">查询中...</div>
      </div>
    `;
  }

  /**
   * 显示超时提示
   */
  showTimeout() {
    const content = this.element.shadowRoot.querySelector('.content');
    content.innerHTML = `
      <div class="loading">
        <div class="loading-text" style="color: #999;">查询超时，请重试</div>
      </div>
    `;
  }

  /**
   * 渲染释义列表
   * @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;
}
