(function () {
  // 防止重复注入
  if (window.__vdSelectorActive) return;
  window.__vdSelectorActive = true;

  /* ── 注入选取模式样式 ── */
  const STYLE_ID = 'vd-selector-style';
  if (!document.getElementById(STYLE_ID)) {
    const style = document.createElement('style');
    style.id = STYLE_ID;
    style.textContent = `
      /* 遮罩提示条 */
      #vd-select-banner {
        position: fixed;
        top: 0; left: 0; right: 0;
        z-index: 2147483647;
        background: linear-gradient(135deg, rgba(74,111,255,0.95), rgba(128,64,221,0.95));
        color: #fff;
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
        font-size: 13px;
        padding: 10px 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        box-shadow: 0 2px 16px rgba(0,0,0,0.4);
        backdrop-filter: blur(8px);
      }
      #vd-select-banner span { opacity: 0.9; }
      #vd-select-cancel {
        background: rgba(255,255,255,0.18);
        border: 1px solid rgba(255,255,255,0.3);
        color: #fff;
        font-size: 12px;
        padding: 5px 14px;
        border-radius: 16px;
        cursor: pointer;
        transition: background 0.15s;
      }
      #vd-select-cancel:hover { background: rgba(255,255,255,0.28); }

      /* 高亮悬停元素 */
      .vd-hover-highlight {
        outline: 2px solid #4a6fff !important;
        outline-offset: 2px !important;
        background-color: rgba(74,111,255,0.08) !important;
        cursor: crosshair !important;
      }

      /* 已选中确认框 */
      #vd-confirm-box {
        position: fixed;
        z-index: 2147483647;
        background: rgba(15,15,26,0.96);
        border: 1px solid rgba(74,111,255,0.5);
        border-radius: 12px;
        padding: 14px 16px;
        min-width: 240px;
        max-width: 320px;
        box-shadow: 0 8px 32px rgba(0,0,0,0.5);
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
        color: #e8e8f0;
        backdrop-filter: blur(12px);
      }
      #vd-confirm-box .vd-cb-title {
        font-size: 12px; color: #888; margin-bottom: 6px;
      }
      #vd-confirm-box .vd-cb-text {
        font-size: 13px; font-weight: 500;
        color: #c8d0ff;
        word-break: break-all;
        margin-bottom: 10px;
        max-height: 60px;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      #vd-confirm-box .vd-cb-sel {
        font-size: 11px; color: #555;
        font-family: monospace;
        margin-bottom: 12px;
        word-break: break-all;
      }
      #vd-confirm-box .vd-cb-btns {
        display: flex; gap: 8px;
      }
      #vd-confirm-box .vd-cb-save {
        flex: 1;
        padding: 8px;
        background: linear-gradient(135deg, #4a6fff, #8040dd);
        color: #fff; font-size: 12px; font-weight: 500;
        border: none; border-radius: 8px; cursor: pointer;
        transition: opacity 0.15s;
      }
      #vd-confirm-box .vd-cb-save:hover { opacity: 0.85; }
      #vd-confirm-box .vd-cb-cancel {
        flex: 1;
        padding: 8px;
        background: rgba(255,255,255,0.06);
        color: #888; font-size: 12px;
        border: 1px solid rgba(255,255,255,0.1);
        border-radius: 8px; cursor: pointer;
        transition: background 0.15s;
      }
      #vd-confirm-box .vd-cb-cancel:hover { background: rgba(255,255,255,0.1); }
    `;
    document.head.appendChild(style);
  }

  /* ── 顶部提示横幅 ── */
  const banner = document.createElement('div');
  banner.id = 'vd-select-banner';
  banner.innerHTML = `
    <span>🎯 选取标题区域：将鼠标移到包含视频标题的元素上，单击选中</span>
    <button id="vd-select-cancel">取消</button>
  `;
  document.body.appendChild(banner);

  document.getElementById('vd-select-cancel').addEventListener('click', exitSelectMode);

  /* ── 状态变量 ── */
  let hoveredEl = null;
  let confirmBox = null;

  /* ── 生成 CSS Selector ── */
  function getSelector(el) {
    if (el.id) return '#' + CSS.escape(el.id);

    const parts = [];
    let cur = el;
    while (cur && cur !== document.body) {
      let part = cur.tagName.toLowerCase();
      if (cur.id) {
        part = '#' + CSS.escape(cur.id);
        parts.unshift(part);
        break;
      }
      // 加 nth-of-type 保证唯一性
      const siblings = Array.from(cur.parentElement?.children || [])
        .filter(c => c.tagName === cur.tagName);
      if (siblings.length > 1) {
        const idx = siblings.indexOf(cur) + 1;
        part += `:nth-of-type(${idx})`;
      }
      parts.unshift(part);
      cur = cur.parentElement;
    }
    return parts.join(' > ');
  }

  /* ── 鼠标移动：高亮悬停元素 ── */
  function onMouseMove(e) {
    if (confirmBox) return; // 确认框显示期间停止高亮更新
    const el = e.target;
    if (el === hoveredEl) return;
    if (hoveredEl) hoveredEl.classList.remove('vd-hover-highlight');
    // 跳过扩展自己的 UI 元素
    if (el.closest('#vd-select-banner') || el.closest('#vd-confirm-box')) return;
    hoveredEl = el;
    hoveredEl.classList.add('vd-hover-highlight');
  }

  /* ── 点击：显示确认框 ── */
  function onClick(e) {
    if (e.target.closest('#vd-select-banner') || e.target.closest('#vd-confirm-box')) return;
    e.preventDefault();
    e.stopPropagation();

    const el = e.target;
    const text = el.innerText?.trim() || el.textContent?.trim() || '（无文字内容）';
    const selector = getSelector(el);

    showConfirmBox(e.clientX, e.clientY, text, selector, el);
  }

  /* ── 确认框 ── */
  function showConfirmBox(x, y, text, selector, el) {
    removeConfirmBox();
    confirmBox = document.createElement('div');
    confirmBox.id = 'vd-confirm-box';
    confirmBox.innerHTML = `
      <div class="vd-cb-title">选中元素的文字内容</div>
      <div class="vd-cb-text">${text.slice(0, 80)}${text.length > 80 ? '…' : ''}</div>
      <div class="vd-cb-sel">${selector}</div>
      <div class="vd-cb-btns">
        <button class="vd-cb-save">保存此规则</button>
        <button class="vd-cb-cancel">重新选取</button>
      </div>
    `;

    // 定位：尽量在点击位置右下，避免超出视口
    const margin = 12;
    confirmBox.style.left = Math.min(x + margin, window.innerWidth - 340) + 'px';
    confirmBox.style.top  = Math.min(y + margin, window.innerHeight - 180) + 'px';
    document.body.appendChild(confirmBox);

    confirmBox.querySelector('.vd-cb-save').addEventListener('click', () => {
      saveRule(selector, el);
    });
    confirmBox.querySelector('.vd-cb-cancel').addEventListener('click', () => {
      removeConfirmBox();
      if (hoveredEl) hoveredEl.classList.add('vd-hover-highlight');
    });
  }

  function removeConfirmBox() {
    if (confirmBox) { confirmBox.remove(); confirmBox = null; }
  }

  /* ── 保存规则到 chrome.storage ── */
  function saveRule(selector, el) {
    const domain = location.hostname;
    // 弹出命名输入框
    const name = window.prompt(
      '请为这条规则起个名字（方便识别）：',
      domain + ' 视频标题'
    );
    if (name === null) return; // 用户点了取消

    chrome.storage.local.get('titleRules', function (data) {
      const titleRules = data.titleRules || [];
      const exists = titleRules.some(
        function (r) { return r.domain === domain && r.selector === selector; }
      );
      if (!exists) {
        titleRules.push({
          id: 'rule_' + Date.now(),
          name: name.trim() || domain + ' 视频标题',
          domain: domain,
          selector: selector,
          builtin: false
        });
        chrome.storage.local.set({ titleRules: titleRules });
      }
    });

    exitSelectMode();

    el.style.outline = '2px solid #4caf50';
    el.style.outlineOffset = '2px';
    setTimeout(function () {
      el.style.outline = '';
      el.style.outlineOffset = '';
    }, 1500);

    if (typeof window.__vdShowToast === 'function') {
      window.__vdShowToast('✅ 标题规则已保存！');
    }
  }


  /* ── 退出选取模式 ── */
  function exitSelectMode() {
    document.removeEventListener('mousemove', onMouseMove, true);
    document.removeEventListener('click', onClick, true);
    document.removeEventListener('keydown', onKeyDown, true);
    if (hoveredEl) hoveredEl.classList.remove('vd-hover-highlight');
    removeConfirmBox();
    banner.remove();
    window.__vdSelectorActive = false;
  }

  /* ── ESC 退出 ── */
  function onKeyDown(e) {
    if (e.key === 'Escape') exitSelectMode();
  }

  document.addEventListener('mousemove', onMouseMove, true);
  document.addEventListener('click', onClick, true);
  document.addEventListener('keydown', onKeyDown, true);

  // 监听 popup 发来的启动消息（selector.js 被动态注入时已自动启动，此处兼容处理）
  chrome.runtime.onMessage.addListener((msg) => {
    if (msg.type === 'VD_START_SELECT' && !window.__vdSelectorActive) {
      window.__vdSelectorActive = true;
    }
  });

})();
