/**
 * Rich Browser Extension - Content Script
 * 负责抓取页面上下文（包括用户在输入框填写的内容）
 */

// =============================================================
// 右边小耳朵 + 进度浮层
// - 默认 8×60 px 半透明竖条贴右边（idle）
// - 收到 progress_update → 展开成胶囊显示 "已完成 X/Y"
// - state='done' → 绿色 5s → 自动收回 idle
// - 任何状态点击都发 __rb:'open_sidepanel' 给 background
// 用 ID 唯一保证幂等（content.js 重复注入不会出双耳朵）
// =============================================================
(function injectRbDock() {
  if (window.__rbDockInjected) return;
  window.__rbDockInjected = true;
  const ID = '__rb_dock';
  let doneTimer = null;
  function ensureDock() {
    let el = document.getElementById(ID);
    if (el) return el;
    if (!document.body) return null;
    el = document.createElement('div');
    el.id = ID;
    el.title = '点开 OpenClaw 侧边栏';
    el.style.cssText = [
      'position:fixed', 'top:80px', 'right:0',
      'z-index:2147483646',  // 比 cdp_human_click 的红点 cursor (2147483647) 低 1
      'cursor:pointer',
      'user-select:none', 'pointer-events:auto',
      'font:500 13px/1 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif',
      'color:#fff', 'background:rgba(37,99,235,0.72)',
      'border-radius:6px 0 0 6px',
      'box-shadow:0 2px 8px rgba(0,0,0,0.15)',
      'width:8px', 'height:60px',
      'padding:0',
      'display:flex', 'align-items:center', 'justify-content:center',
      'overflow:hidden', 'white-space:nowrap',
      'transition:width 220ms ease, background-color 220ms ease, padding 220ms ease',
    ].join(';');
    el.addEventListener('mouseenter', () => {
      if (el.dataset.state === 'idle') el.style.background = 'rgba(37,99,235,1.0)';
    });
    el.addEventListener('mouseleave', () => {
      if (el.dataset.state === 'idle') el.style.background = 'rgba(37,99,235,0.72)';
    });
    el.addEventListener('click', () => {
      try { chrome.runtime.sendMessage({ __rb: 'open_sidepanel' }); } catch (e) {}
    });
    el.dataset.state = 'idle';
    document.body.appendChild(el);
    return el;
  }
  function setState(state, text) {
    const el = ensureDock(); if (!el) return;
    if (doneTimer) { clearTimeout(doneTimer); doneTimer = null; }
    el.dataset.state = state;
    if (state === 'idle') {
      el.textContent = '';
      el.style.width = '8px';
      el.style.padding = '0';
      el.style.background = 'rgba(37,99,235,0.72)';
    } else if (state === 'running') {
      el.textContent = text || '执行中...';
      el.style.width = 'auto';
      el.style.minWidth = '120px';
      el.style.maxWidth = '240px';
      el.style.padding = '0 12px';
      el.style.background = 'rgba(37,99,235,0.92)';
    } else if (state === 'done') {
      el.textContent = '✓ ' + (text || '任务完成');
      el.style.width = 'auto';
      el.style.minWidth = '120px';
      el.style.maxWidth = '240px';
      el.style.padding = '0 12px';
      el.style.background = 'rgba(16,185,129,0.95)';
      doneTimer = setTimeout(() => setState('idle', ''), 5000);
    }
  }
  function init() {
    ensureDock();
    chrome.runtime.onMessage.addListener((msg) => {
      if (msg && msg.__rb === 'progress_update') {
        setState(msg.state || 'running', msg.text || '');
      }
    });
  }
  if (document.body) init();
  else document.addEventListener('DOMContentLoaded', init, { once: true });
})();

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  if (msg.action === "extract_context") {
    try {
      // 收集页面中所有的输入框内容
      const inputs = Array.from(document.querySelectorAll('input, textarea, select')).map(el => {
        const idName = el.name || el.id || el.tagName;
        let val = el.value;
        if (el.tagName === 'INPUT' && (el.type === 'checkbox' || el.type === 'radio')) {
          val = el.checked ? 'checked' : 'unchecked';
        } else if (el.tagName === 'SELECT') {
          val = Array.from(el.selectedOptions).map(opt => opt.text).join(',');
        }
        return `${idName}: ${val}`;
      });

      sendResponse({
        url: location.href,
        title: document.title,
        inputs: inputs
      });
    } catch (e) {
      sendResponse({ url: location.href, title: document.title, inputs: [] });
    }
    return true;
  }
});
