(()=>{
  if(window.__productWorkbenchShopeeCapture)return;
  window.__productWorkbenchShopeeCapture=true;
  const cleanUrl=value=>{
    try{const u=new URL(value,location.href);if(!/^https?:$/.test(u.protocol))return'';u.hash='';return u.href}catch{return''}
  };
  const imageUrl=el=>{
    const direct=el.currentSrc||el.src||el.getAttribute('data-src')||'';
    if(direct)return cleanUrl(direct);
    const bg=getComputedStyle(el).backgroundImage.match(/url\(["']?(.*?)["']?\)/i);
    return bg?cleanUrl(bg[1]):'';
  };
  function extract(){
    const all=[...document.querySelectorAll('img,[style*="background-image"]')];
    const isSku=el=>!!el.closest('[class*="variation" i],[class*="model" i],[class*="tier" i],[class*="option" i]');
    const acceptable=el=>{
      const r=el.getBoundingClientRect(),u=imageUrl(el);
      return u&&/shopee|shp|cf\.shopee/i.test(u)&&r.width>=36&&r.height>=36&&!/avatar|logo|icon|rating|voucher/i.test(u);
    };
    const unique=list=>[...new Map(list.filter(acceptable).map(el=>[imageUrl(el).replace(/\?.*$/,''),{url:imageUrl(el),width:Math.round(el.getBoundingClientRect().width),height:Math.round(el.getBoundingClientRect().height)}])).values()];
    const sku=unique(all.filter(isSku));
    const gallery=unique(all.filter(el=>!isSku(el)&&Math.max(el.getBoundingClientRect().width,el.getBoundingClientRect().height)>=180));
    return {pageUrl:location.href,title:document.title,keyword:'',skuImages:sku.slice(0,24),galleryImages:gallery.slice(0,12),capturedAt:new Date().toISOString()};
  }
  function panel(text,button=true){
    let box=document.querySelector('#pw-shopee-capture');
    if(!box){box=document.createElement('div');box.id='pw-shopee-capture';box.style='position:fixed;right:18px;bottom:18px;z-index:2147483647;width:310px;padding:15px;border-radius:14px;background:#101828;color:white;box-shadow:0 12px 38px #0005;font:14px/1.5 system-ui';document.body.appendChild(box)}
    box.innerHTML=`<b style="display:block;font-size:16px;margin-bottom:6px">SKU 参考抓取</b><div style="color:#d0d5dd">${text}</div>${button?'<button id="pw-shopee-send" style="width:100%;margin-top:12px;padding:10px;border:0;border-radius:9px;background:#ee4d2d;color:#fff;font-weight:700;cursor:pointer">抓取当前商品 SKU 图并回到工作台</button>':''}`;
    box.querySelector('#pw-shopee-send')?.addEventListener('click',send);
  }
  function send(){
    const result=extract(),images=result.skuImages.length?result.skuImages:result.galleryImages;
    if(!images.length){panel('当前页面尚未识别到商品图片。请等商品页加载完成后再点一次。');return}
    panel(`已识别 ${images.length} 张候选图，正在回传…`,false);
    chrome.runtime.sendMessage({type:'SHOPEE_SKU_CAPTURED',result},r=>panel(r?.ok?'已回传工作台，可关闭本页。':'回传失败：'+(r?.error||'未知错误'),false));
  }
  chrome.runtime.sendMessage({type:'GET_SHOPEE_JOB'},r=>{
    if(!r?.job)return;
    const login=/\/buyer\/login/i.test(location.pathname),search=/\/search(?:\?|$)/i.test(location.pathname);
    panel(login?'请先完成 Shopee 登录；登录成功返回搜索结果后，再选择一个公开商品。':search?'请从搜索结果中打开一个合适的公开竞品；进入商品详情页后点击回传按钮。':'确认这是要参考的商品后，点击下方按钮。',!search&&!login);
  });
})();
