/**
 * panel.js - 内容选择面板（平台无关）
 * 负责渲染右侧抽屉面板、管理勾选状态、触发 PDF 生成和在线分享
 */

(function () {
  'use strict';

  let _adapter = null;
  let _panelEl = null;
  let _overlayEl = null;
  let _selectedIds = new Set();
  let _allMessages = [];
  let _isOpen = false;

  /**
   * 初始化面板（只创建一次 DOM）
   * @param {BaseAdapter} adapter
   */
  function initPanel(adapter) {
    _adapter = adapter;

    if (document.getElementById('pdf-export-panel')) return;

    // 创建遮罩
    _overlayEl = document.createElement('div');
    _overlayEl.id = 'pdf-panel-overlay';
    document.body.appendChild(_overlayEl);

    // 创建面板
    _panelEl = document.createElement('div');
    _panelEl.id = 'pdf-export-panel';
    _panelEl.setAttribute('role', 'dialog');
    _panelEl.setAttribute('aria-modal', 'true');
    _panelEl.setAttribute('aria-label', '导出对话');
    _panelEl.innerHTML = _buildPanelHTML();
    document.body.appendChild(_panelEl);

    _bindEvents();
  }

  function _buildPanelHTML() {
    return `
      <div class="pdf-panel-header">
        <h2 class="pdf-panel-title">导出对话</h2>
        <div class="pdf-panel-header-actions">
          <button class="pdf-token-btn" id="pdf-token-btn" title="配置 API Token">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
                 stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
              <circle cx="12" cy="12" r="3"/>
              <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/>
            </svg>
          </button>
          <button class="pdf-panel-close" id="pdf-panel-close-btn" aria-label="关闭面板">×</button>
        </div>
      </div>

      <!-- Token 配置区（默认隐藏） -->
      <div class="pdf-token-section" id="pdf-token-section" style="display:none;">
        <div class="pdf-token-label">ChatView API Token</div>
        <div class="pdf-token-input-row">
          <input type="password" class="pdf-token-input" id="pdf-token-input"
                 placeholder="输入 Bearer Token..." autocomplete="off" />
          <button class="pdf-token-save-btn" id="pdf-token-save-btn">保存</button>
        </div>
        <div class="pdf-token-hint">Token 安全存储在本地，不会上传到任何服务器</div>
        <div class="pdf-token-status" id="pdf-token-status"></div>
      </div>

      <div class="pdf-select-all-bar">
        <label class="pdf-select-all-label">
          <input type="checkbox" id="pdf-select-all-cb" checked />
          全选
        </label>
        <span class="pdf-select-count" id="pdf-select-count">已选 0 / 共 0 条</span>
      </div>

      <div class="pdf-message-list" id="pdf-message-list">
        <div class="pdf-empty-state">正在加载消息...</div>
      </div>

      <div class="pdf-panel-footer">
        <div class="pdf-export-hint" id="pdf-export-hint">约 0 条消息将导出</div>

        <!-- 操作按钮行 -->
        <div class="pdf-btn-row">
          <button class="pdf-btn-generate" id="pdf-btn-generate">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
                 stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
              <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
              <polyline points="14 2 14 8 20 8"/>
            </svg>
            导出 PDF
          </button>
          <button class="pdf-btn-share" id="pdf-btn-share">
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
                 stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
              <circle cx="18" cy="5" r="3"/>
              <circle cx="6" cy="12" r="3"/>
              <circle cx="18" cy="19" r="3"/>
              <line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/>
              <line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/>
            </svg>
            在线分享
          </button>
          <button class="pdf-btn-cancel" id="pdf-btn-cancel">取消</button>
        </div>

        <!-- 分享结果区（成功后显示） -->
        <div class="pdf-share-result" id="pdf-share-result" style="display:none;">
          <div class="pdf-share-result-label">分享链接已生成</div>
          <div class="pdf-share-link-row">
            <input type="text" class="pdf-share-link-input" id="pdf-share-link-input" readonly />
            <button class="pdf-share-copy-btn" id="pdf-share-copy-btn">复制</button>
          </div>
          <a class="pdf-share-open-link" id="pdf-share-open-link" target="_blank" rel="noopener">在新标签页打开 →</a>
        </div>

        <div class="pdf-error-msg" id="pdf-error-msg"></div>
      </div>
    `;
  }

  function _bindEvents() {
    // 关闭按钮
    document.getElementById('pdf-panel-close-btn').addEventListener('click', closePanel);

    // 取消按钮
    document.getElementById('pdf-btn-cancel').addEventListener('click', closePanel);

    // 全选复选框
    document.getElementById('pdf-select-all-cb').addEventListener('change', (e) => {
      if (e.target.checked) {
        _allMessages.forEach((m) => _selectedIds.add(m.id));
      } else {
        _selectedIds.clear();
      }
      _renderMessageList();
      _updateFooter();
    });

    // 生成 PDF 按钮
    document.getElementById('pdf-btn-generate').addEventListener('click', _onGeneratePDF);

    // 在线分享按钮
    document.getElementById('pdf-btn-share').addEventListener('click', _onShare);

    // Token 配置按钮（齿轮图标）
    document.getElementById('pdf-token-btn').addEventListener('click', _toggleTokenSection);

    // Token 保存按钮
    document.getElementById('pdf-token-save-btn').addEventListener('click', _onSaveToken);

    // Token 输入框回车保存
    document.getElementById('pdf-token-input').addEventListener('keydown', (e) => {
      if (e.key === 'Enter') _onSaveToken();
    });

    // 复制链接按钮
    document.getElementById('pdf-share-copy-btn').addEventListener('click', _onCopyShareLink);

    // Esc 关闭
    document.addEventListener('keydown', _onKeyDown);
  }

  function _onKeyDown(e) {
    if (e.key === 'Escape' && _isOpen) {
      closePanel();
    }
  }

  // ── Token 配置 ────────────────────────────────────────────

  async function _toggleTokenSection() {
    const section = document.getElementById('pdf-token-section');
    if (!section) return;

    const isVisible = section.style.display !== 'none';
    if (isVisible) {
      section.style.display = 'none';
      return;
    }

    // 展开时，读取已有 Token 并显示（遮掩显示）
    section.style.display = 'block';
    const token = await window.ShareAPI.getToken();
    const input = document.getElementById('pdf-token-input');
    if (input) {
      input.value = token || '';
      input.placeholder = token ? '已配置（输入新值可更新）' : '输入 Bearer Token...';
    }

    // 更新状态显示
    const statusEl = document.getElementById('pdf-token-status');
    if (statusEl) {
      statusEl.textContent = token ? '✓ Token 已配置' : '未配置 Token';
      statusEl.className = 'pdf-token-status ' + (token ? 'ok' : 'empty');
    }
  }

  async function _onSaveToken() {
    const input = document.getElementById('pdf-token-input');
    const statusEl = document.getElementById('pdf-token-status');
    if (!input) return;

    const val = input.value.trim();
    if (!val) {
      await window.ShareAPI.clearToken();
      if (statusEl) {
        statusEl.textContent = '已清除 Token';
        statusEl.className = 'pdf-token-status empty';
      }
      return;
    }

    await window.ShareAPI.saveToken(val);
    if (statusEl) {
      statusEl.textContent = '✓ Token 已保存';
      statusEl.className = 'pdf-token-status ok';
    }

    // 保存后 1.5s 自动收起
    setTimeout(() => {
      const section = document.getElementById('pdf-token-section');
      if (section) section.style.display = 'none';
    }, 1500);
  }

  // ── 面板开关 ──────────────────────────────────────────────

  /**
   * 打开面板
   * 注意顺序：先显示加载提示（不锁定滚动）→ ensureAllRendered → 提取消息 → 锁定滚动
   */
  async function openPanel(adapter) {
    if (!_panelEl) initPanel(adapter);
    _adapter = adapter;
    _hideError();
    _hideShareResult();

    // 显示面板（不锁定滚动，以便 ensureAllRendered 可以正常滚动页面）
    _panelEl.classList.add('open');
    _overlayEl.classList.add('visible');
    _isOpen = true;

    // 显示加载提示
    const listEl = document.getElementById('pdf-message-list');
    if (listEl) {
      listEl.innerHTML = '<div class="pdf-empty-state">正在加载全部消息，请稍候...</div>';
    }

    // 执行虚拟滚动渲染（此时 body overflow 未锁定，滚动可正常工作）
    if (_adapter.ensureAllRendered) {
      try {
        await _adapter.ensureAllRendered();
      } catch (e) {
        console.warn('[AI PDF Exporter] ensureAllRendered 失败:', e);
      }
    }

    // 立即提取消息（不给 ChatGPT 时间再次卸载消息）
    _allMessages = _adapter.extractAllMessages();
    _selectedIds = new Set(_allMessages.map((m) => m.id));

    // 提取完成后再锁定背景滚动
    document.body.style.overflow = 'hidden';

    _renderMessageList();
    _updateFooter();
    _updateSelectAllState();
  }

  function closePanel() {
    if (!_panelEl) return;
    _panelEl.classList.remove('open');
    _overlayEl.classList.remove('visible');
    _isOpen = false;
    document.body.style.overflow = '';
  }

  // ── 消息列表渲染 ──────────────────────────────────────────

  function _renderMessageList() {
    const listEl = document.getElementById('pdf-message-list');
    if (!listEl) return;

    if (_allMessages.length === 0) {
      listEl.innerHTML = '<div class="pdf-empty-state">未找到消息，请确认页面已加载完成。</div>';
      return;
    }

    listEl.innerHTML = _allMessages.map((msg) => _buildMessageCardHTML(msg)).join('');

    listEl.querySelectorAll('.pdf-msg-card').forEach((card) => {
      card.addEventListener('click', (e) => {
        if (e.target.classList.contains('pdf-msg-checkbox')) return;
        const id = card.dataset.msgId;
        _toggleMessage(id);
      });

      const cb = card.querySelector('.pdf-msg-checkbox');
      if (cb) {
        cb.addEventListener('change', (e) => {
          const id = card.dataset.msgId;
          if (e.target.checked) {
            _selectedIds.add(id);
          } else {
            _selectedIds.delete(id);
          }
          _updateCardState(card, e.target.checked);
          _updateFooter();
          _updateSelectAllState();
        });
      }
    });
  }

  function _buildMessageCardHTML(msg) {
    const isSelected = _selectedIds.has(msg.id);
    const roleLabel = msg.role === 'user' ? 'You' : 'AI';
    const roleClass = msg.role === 'user' ? 'user' : 'assistant';
    const selectedClass = isSelected ? 'selected' : 'unselected';
    const preview = (msg.content || '').replace(/\s+/g, ' ').trim().slice(0, 200);
    const codeTag = msg.hasCode ? '<span class="pdf-msg-tag code">[含代码]</span>' : '';

    return `
      <div class="pdf-msg-card ${selectedClass}" data-msg-id="${_escapeAttr(msg.id)}">
        <input type="checkbox" class="pdf-msg-checkbox" ${isSelected ? 'checked' : ''} aria-label="选择此消息" />
        <div class="pdf-msg-avatar ${roleClass}">${roleLabel}</div>
        <div class="pdf-msg-body">
          <div class="pdf-msg-preview">${_escapeHtml(preview)}</div>
          <div class="pdf-msg-tags">${codeTag}</div>
        </div>
      </div>
    `;
  }

  function _toggleMessage(id) {
    if (_selectedIds.has(id)) {
      _selectedIds.delete(id);
    } else {
      _selectedIds.add(id);
    }
    const card = document.querySelector(`[data-msg-id="${CSS.escape(id)}"]`);
    if (card) _updateCardState(card, _selectedIds.has(id));
    _updateFooter();
    _updateSelectAllState();
  }

  function _updateCardState(card, isSelected) {
    card.classList.toggle('selected', isSelected);
    card.classList.toggle('unselected', !isSelected);
    const cb = card.querySelector('.pdf-msg-checkbox');
    if (cb) cb.checked = isSelected;
  }

  function _updateFooter() {
    const count = _selectedIds.size;
    const total = _allMessages.length;
    const countEl = document.getElementById('pdf-select-count');
    if (countEl) countEl.textContent = `已选 ${count} / 共 ${total} 条`;
    const hintEl = document.getElementById('pdf-export-hint');
    if (hintEl) hintEl.textContent = `约 ${count} 条消息将导出`;
  }

  function _updateSelectAllState() {
    const cb = document.getElementById('pdf-select-all-cb');
    if (!cb) return;
    const total = _allMessages.length;
    const selected = _selectedIds.size;
    cb.checked = selected === total && total > 0;
    cb.indeterminate = selected > 0 && selected < total;
  }

  // ── PDF 生成 ──────────────────────────────────────────────

  async function _onGeneratePDF() {
    const selectedMessages = _allMessages.filter((m) => _selectedIds.has(m.id));
    if (selectedMessages.length === 0) {
      _showError('请至少选择一条消息');
      return;
    }

    const btn = document.getElementById('pdf-btn-generate');
    _setButtonLoading(btn, true, '生成中...');
    _hideError();
    _hideShareResult();

    try {
      const title = _adapter.getConversationTitle();
      await generatePDF({ title, messages: selectedMessages });
      closePanel();
    } catch (err) {
      console.error('[AI PDF Exporter] PDF 生成失败:', err);
      _showError('PDF 生成失败，请重试。' + (err.message ? `（${err.message}）` : ''));
    } finally {
      _setButtonLoading(btn, false, '导出 PDF');
    }
  }

  // ── 在线分享 ──────────────────────────────────────────────

  async function _onShare() {
    const selectedMessages = _allMessages.filter((m) => _selectedIds.has(m.id));
    if (selectedMessages.length === 0) {
      _showError('请至少选择一条消息');
      return;
    }

    _hideError();
    _hideShareResult();

    // 检查 Token
    const token = await window.ShareAPI.getToken();
    if (!token) {
      // 没有 Token，展开配置区并提示
      const section = document.getElementById('pdf-token-section');
      if (section) section.style.display = 'block';
      const input = document.getElementById('pdf-token-input');
      if (input) input.focus();
      _showError('请先配置 API Token，然后再点击在线分享');
      return;
    }

    const btn = document.getElementById('pdf-btn-share');
    _setButtonLoading(btn, true, '分享中...');

    try {
      const title = _adapter.getConversationTitle();
      const result = await window.ShareAPI.shareContent({
        messages: selectedMessages,
        title,
      });

      // 显示分享结果
      _showShareResult(result.url);
    } catch (err) {
      console.error('[AI PDF Exporter] 分享失败:', err);

      if (err.code === 'NO_TOKEN' || err.code === 'INVALID_TOKEN') {
        // Token 问题，展开配置区
        const section = document.getElementById('pdf-token-section');
        if (section) section.style.display = 'block';
        const input = document.getElementById('pdf-token-input');
        if (input) {
          input.value = '';
          input.focus();
        }
      }

      _showError(err.message || '分享失败，请重试');
    } finally {
      _setButtonLoading(btn, false, '在线分享');
    }
  }

  function _showShareResult(url) {
    const resultEl = document.getElementById('pdf-share-result');
    const linkInput = document.getElementById('pdf-share-link-input');
    const openLink = document.getElementById('pdf-share-open-link');

    if (!resultEl || !linkInput) return;

    linkInput.value = url;
    if (openLink) {
      openLink.href = url;
    }

    resultEl.style.display = 'block';

    // 自动选中链接文字
    setTimeout(() => linkInput.select(), 50);
  }

  function _hideShareResult() {
    const resultEl = document.getElementById('pdf-share-result');
    if (resultEl) resultEl.style.display = 'none';
  }

  async function _onCopyShareLink() {
    const linkInput = document.getElementById('pdf-share-link-input');
    const copyBtn = document.getElementById('pdf-share-copy-btn');
    if (!linkInput) return;

    try {
      await navigator.clipboard.writeText(linkInput.value);
      if (copyBtn) {
        copyBtn.textContent = '已复制 ✓';
        copyBtn.classList.add('copied');
        setTimeout(() => {
          copyBtn.textContent = '复制';
          copyBtn.classList.remove('copied');
        }, 2000);
      }
    } catch (e) {
      // 降级：选中文字
      linkInput.select();
      document.execCommand('copy');
    }
  }

  // ── 通用 UI 工具 ──────────────────────────────────────────

  function _setButtonLoading(btn, isLoading, label) {
    if (!btn) return;
    btn.disabled = isLoading;
    if (isLoading) {
      btn.innerHTML = `<div class="pdf-spinner"></div>${label}`;
    } else {
      // 恢复原始内容（带图标）
      const isPDF = label.includes('PDF');
      const isShare = label.includes('分享');
      if (isPDF) {
        btn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
             stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
          <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
          <polyline points="14 2 14 8 20 8"/>
        </svg>导出 PDF`;
      } else if (isShare) {
        btn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none"
             stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
          <circle cx="18" cy="5" r="3"/>
          <circle cx="6" cy="12" r="3"/>
          <circle cx="18" cy="19" r="3"/>
          <line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/>
          <line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/>
        </svg>在线分享`;
      } else {
        btn.textContent = label;
      }
    }
  }

  function _showError(msg) {
    const el = document.getElementById('pdf-error-msg');
    if (!el) return;
    el.textContent = msg;
    el.classList.add('visible');
  }

  function _hideError() {
    const el = document.getElementById('pdf-error-msg');
    if (el) el.classList.remove('visible');
  }

  function _escapeHtml(str) {
    return String(str)
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#39;');
  }

  function _escapeAttr(str) {
    return String(str).replace(/"/g, '&quot;');
  }

  // 暴露到全局
  window.initPanel = initPanel;
  window.openPanel = openPanel;
  window.closePanel = closePanel;
})();
