const API_URL = "https://bot.ecommclaw.com/api/skills";
let globalSkills = [];

function showToast() {
  const t = document.getElementById('toast');
  t.classList.add('show');
  setTimeout(() => t.classList.remove('show'), 3000);
}

function dispatchCommand(text) {
  if (typeof chrome !== 'undefined' && chrome.runtime) {
    chrome.runtime.sendMessage({
      target: "background",
      action: "send_message",
      text: text
    }, (response) => {
      showToast();
      closeModal();
    });
  } else {
    alert("无法发送指令：请在插件环境中运行。\n指令内容：" + text);
  }
}

function renderList(skills) {
  const grid = document.getElementById('skillsGrid');
  grid.innerHTML = '';
  if (skills.length === 0) {
    grid.innerHTML = `<div class="loading-state">没有找到匹配的技能</div>`;
    return;
  }
  
  const nameMap = {
    "ozon-daily-blockbuster-for-rich-browser": "🔥 Ozon 爆款一键挖掘",
    "customer-1688-image-search": "🖼️ 手动 1688 图搜",
    "ozon-seller-shopcheck-homepage": "🏪 巡店",
    "1688-image-search": "1688 以图搜款 (旧版)",
    "ozon-seller": "Ozon 卖家API调用",
    "ozon-bestsellers-query": "Ozon 商品数据库查询",
    "ozon-scraper": "Ozon 商品数据从页面抓取",
    "render_generic_report": "输出 HTML报表"
  };

  skills.forEach((skill, index) => {
    const row = document.createElement('div');
    row.className = 'skill-row';
    if (skill.is_atomic) row.style.borderColor = '#533483';

    let tagsHtml = '';
    if (skill.tags && Array.isArray(skill.tags)) {
      skill.tags.forEach(t => { tagsHtml += `<span class="tag">${t}</span>`; });
    }
    if (skill.is_atomic) tagsHtml += `<span class="tag tag-atomic">Atomic Skill</span>`;
    
    const displayName = nameMap[skill.name] || skill.name;

    row.innerHTML = `
      <div style="display: flex; gap: 16px; align-items: center; width: 100%;">
        <div class="skill-icon" style="margin-bottom: 0; width: 40px; height: 40px; font-size: 20px; ${skill.is_atomic ? 'background: rgba(83, 52, 131, 0.4);' : ''}">${skill.emoji || '🔧'}</div>
        <div class="skill-content">
          <h3 class="skill-title" style="font-size: 15px;">${displayName}</h3>
          <div class="skill-tags" style="margin-top: 0;">${tagsHtml}</div>
        </div>
      </div>
      <p class="skill-desc" title="${skill.description}" style="margin-top: 4px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; white-space: normal;">${skill.description}</p>
    `;
    
    row.addEventListener('click', () => openModal(index));
    grid.appendChild(row);
  });
}

function openModal(index) {
  const skill = globalSkills[index];
  if (!skill) return;

  const nameMap = {
    "ozon-daily-blockbuster-for-rich-browser": "🔥 Ozon 爆款一键挖掘",
    "customer-1688-image-search": "🖼️ 手动 1688 图搜",
    "ozon-seller-shopcheck-homepage": "🏪 巡店",
    "1688-image-search": "1688 以图搜款 (旧版)",
    "ozon-seller": "Ozon 卖家API调用",
    "ozon-bestsellers-query": "Ozon 商品数据库查询",
    "ozon-scraper": "Ozon 商品数据从页面抓取",
    "render_generic_report": "输出 HTML报表"
  };
  const displayName = nameMap[skill.name] || skill.name;
  
  document.getElementById('modalTitle').innerText = displayName;
  document.getElementById('modalIcon').innerText = skill.emoji || '🔧';
  if (skill.is_atomic) document.getElementById('modalIcon').style.background = 'rgba(83, 52, 131, 0.4)';
  else document.getElementById('modalIcon').style.background = '#0f3460';
  
  let tagsHtml = '';
  if (skill.tags && Array.isArray(skill.tags)) {
    skill.tags.forEach(t => { tagsHtml += `<span class="tag">${t}</span>`; });
  }
  if (skill.is_atomic) tagsHtml += `<span class="tag tag-atomic">Atomic Skill</span>`;
  document.getElementById('modalTags').innerHTML = tagsHtml;
  
  // Parse and render Markdown (if available, otherwise use description)
  const mdContent = skill.markdown ? marked.parse(skill.markdown) : `<p>${skill.description}</p>`;
  document.getElementById('modalMarkdown').innerHTML = mdContent;
  
  // Render Inputs
  const inputsContainer = document.getElementById('modalInputs');
  inputsContainer.innerHTML = '';
  if (skill.inputs && Array.isArray(skill.inputs)) {
    skill.inputs.forEach(input => {
      inputsContainer.innerHTML += `
        <div class="form-group">
          <label>${input.label}</label>
          <input type="${input.type || 'text'}" id="input_${skill.id}_${input.id}" placeholder="${input.placeholder || ''}" value="${input.default || ''}">
        </div>
      `;
    });
  }
  
  // Setup Execute Button
  const execBtn = document.getElementById('modalExecBtn');
  const btnLabel = skill.is_atomic ? '✨ 生成原子化 Demo' : '🚀 立即执行';
  execBtn.innerText = btnLabel;
  execBtn.className = skill.is_atomic ? 'btn-exec demo' : 'btn-exec';
  
  // Remove old event listeners
  const newExecBtn = execBtn.cloneNode(true);
  execBtn.parentNode.replaceChild(newExecBtn, execBtn);
  
  newExecBtn.addEventListener('click', () => {
    let finalCommand = skill.action_command;
    if (skill.inputs && Array.isArray(skill.inputs)) {
      skill.inputs.forEach(input => {
        const val = document.getElementById(`input_${skill.id}_${input.id}`).value;
        finalCommand = finalCommand.replace(`{${input.id}}`, val);
      });
    }
    dispatchCommand(finalCommand);
  });
  
  document.getElementById('skillModal').classList.add('active');
}

function closeModal() {
  document.getElementById('skillModal').classList.remove('active');
}

// Close modal when clicking outside content
document.getElementById('skillModal').addEventListener('click', (e) => {
  if (e.target === document.getElementById('skillModal')) closeModal();
});

// Search filter
document.getElementById('searchInput').addEventListener('input', (e) => {
  const query = e.target.value.toLowerCase();
  const filtered = globalSkills.filter(s => 
    s.name.toLowerCase().includes(query) || 
    s.description.toLowerCase().includes(query) ||
    (s.tags && s.tags.some(t => t.toLowerCase().includes(query)))
  );
  renderList(filtered);
});

async function loadSkills() {
  const grid = document.getElementById('skillsGrid');
  try {
    if (typeof chrome !== 'undefined' && chrome.storage) {
      chrome.storage.local.get(["tenantId"], async (res) => {
        const tenantId = res.tenantId || "main";
        const fetchUrl = `${API_URL}?tenantId=${tenantId}`;
        
        const response = await fetch(fetchUrl);
        if (!response.ok) throw new Error("Network response was not ok");
        const json = await response.json();
        
        if (json.status === "success" && Array.isArray(json.data)) {
          globalSkills = json.data;
          renderList(globalSkills);
        }
      });
    } else {
      // Local testing fallback
      grid.innerHTML = `<div class="loading-state">请在 Chrome 插件环境中运行。</div>`;
    }
  } catch (e) {
    console.error("Failed to load skills:", e);
    grid.innerHTML = `<div class="loading-state" style="color: #f5222d;">❌ 无法连接到服务端 API (${API_URL})</div>`;
  }
}

document.addEventListener('DOMContentLoaded', loadSkills);


// Close Modal Button
document.getElementById('modalCloseBtn').addEventListener('click', closeModal);
