/**
 * content.js - 插件入口（平台无关）
 * 职责：获取适配器 → 启动 MutationObserver → 注入 PDF 按钮
 */

(function () {
  'use strict';

  const adapter = getActiveAdapter();
  if (!adapter) return;

  // 预创建面板 DOM
  initPanel(adapter);

  /**
   * 创建 PDF 导出按钮
   */
  function createPdfIconButton() {
    const btn = document.createElement('button');
    btn.className = 'pdf-export-btn';
    btn.setAttribute('title', '导出为 PDF');
    btn.setAttribute('aria-label', '导出为 PDF');
    btn.setAttribute('type', 'button');

    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">
        <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"/>
        <line x1="8" y1="13" x2="16" y2="13"/>
        <line x1="8" y1="17" x2="13" y2="17"/>
        <rect x="8" y="10" width="3" height="2.5" rx="0.5" fill="currentColor" stroke="none"/>
      </svg>
    `;

    return btn;
  }

  /**
   * 向操作栏注入 PDF 按钮
   * 防重复标记打在操作栏元素本身上
   */
  function injectPdfButton(toolbar) {
    if (toolbar.dataset.pdfBtnInjected === 'true') return;
    toolbar.dataset.pdfBtnInjected = 'true';

    const btn = createPdfIconButton();
    btn.addEventListener('click', (e) => {
      e.preventDefault();
      e.stopPropagation();
      openPanel(adapter);
    });

    toolbar.appendChild(btn);
  }

  /**
   * 扫描所有操作栏并注入按钮
   */
  function scanAndInject() {
    const toolbars = adapter.getToolbarAnchors();
    toolbars.forEach((toolbar) => injectPdfButton(toolbar));
  }

  // 初始扫描
  scanAndInject();

  // MutationObserver 监听动态渲染（节流 300ms）
  let _timer = null;
  const observer = new MutationObserver(() => {
    if (_timer) return;
    _timer = setTimeout(() => {
      _timer = null;
      scanAndInject();
    }, 300);
  });

  observer.observe(document.body, { childList: true, subtree: true });

  window.addEventListener('beforeunload', () => observer.disconnect());
})();
