// 直接在页面注入控制面板
function injectOrderControlPanel() {
  try {
    // 检查当前URL是否为目标网站，排除seller.ozon.ru
  const currentUrl = window.location.href;
  const isTargetSite =
    (currentUrl.includes('ozon.ru') && !currentUrl.includes('seller.ozon.ru') && !currentUrl.includes('/product/')) ||
    (currentUrl.includes('ozon.kz') && !currentUrl.includes('seller.ozon.kz') && !currentUrl.includes('/product/')) ||
    (currentUrl.includes('ozon.by') && !currentUrl.includes('seller.ozon.by') && !currentUrl.includes('/product/')) ||
	currentUrl.includes('1688.com') ||
    currentUrl.includes('pinduoduo.com') ||
    currentUrl.includes('yangkeduo.com')||
    currentUrl.includes('taobao.com');
  
  if (!isTargetSite) {
    console.log('当前网站不是目标网站，不注入控制面板');
    return;
  }

    // 确保 document.body 存在
    if (!document.body) {
      setTimeout(injectOrderControlPanel, 100);
      return;
    }

    // 直接注入控制面板HTML
    const controlPanel = document.createElement('div');
    controlPanel.className = 'order-control-panel';
    controlPanel.innerHTML = `
      <div class="login-main" id="xq-login-main">
        <div class="login-main-title">
			<h3>熊猫</h3>
			<div class="fold-btn">折叠</div>
		</div>
      </div>
    `;
    document.body.appendChild(controlPanel);
	
	// 拖拽功能
	const titleBar = controlPanel.querySelector('.login-main-title');
	let isDragging = false;
	let startX, startY, initialLeft, initialTop;
	
	if (titleBar) {
	  titleBar.addEventListener('mousedown', function(e) {
	    // 如果点击的是折叠按钮，不触发拖拽
	    if (e.target.closest('.fold-btn')) return;
	    
	    isDragging = true;
	    startX = e.clientX;
	    startY = e.clientY;
	    
	    const rect = controlPanel.getBoundingClientRect();
	    initialLeft = rect.left;
	    initialTop = rect.top;
	    
	    // 从 right 定位切换到 left 定位
	    controlPanel.style.right = 'auto';
	    controlPanel.style.left = initialLeft + 'px';
	    controlPanel.style.top = initialTop + 'px';
	    
	    document.body.style.userSelect = 'none';
	  });
	}
	
	document.addEventListener('mousemove', function(e) {
	  if (!isDragging) return;
	  const dx = e.clientX - startX;
	  const dy = e.clientY - startY;
	  controlPanel.style.left = (initialLeft + dx) + 'px';
	  controlPanel.style.top = (initialTop + dy) + 'px';
	});
	
	document.addEventListener('mouseup', function() {
	  if (isDragging) {
	    isDragging = false;
	    document.body.style.userSelect = '';
	  }
	});
	
	// 找到折叠按钮和 login-main 容器
	const foldBtn = controlPanel.querySelector('.fold-btn');
	const loginMain = controlPanel.querySelector('.login-main');
	const titleH3 = controlPanel.querySelector('.login-main-title h3');
	
	if (foldBtn && loginMain) {
	  foldBtn.addEventListener('click', function() {
	    // 获取 login-main 下的所有直接子 div（不包括按钮自身所在的 .login-main-title）
	    const allChildDivs = loginMain.querySelectorAll(':scope > div');
	    
	    // 遍历所有子 div，隐藏除了 .login-main-title 以外的其他 div
	    allChildDivs.forEach(div => {
	      // 如果当前 div 不是标题栏（.login-main-title），则切换其隐藏状态
	      if (!div.classList.contains('login-main-title')) {
	        if (div.style.display === 'none') {
	          div.style.display = ''; // 恢复显示
			  titleH3.style.display = '';
			  foldBtn.textContent = '折叠';
	        } else {
	          div.style.display = 'none'; // 隐藏
			  titleH3.style.display = 'none';
			  foldBtn.textContent = '展开';
	        }
	      }
	    });
	    
	    // 为 login-main 添加或移除 'login-main-small' 样式类
	    loginMain.classList.toggle('login-main-small');
		controlPanel.classList.toggle('order-control-panel-small');
	  });
	}
	
	
    // 注入orderScript.js
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.charset = 'UTF-8';
    script.src = chrome.runtime.getURL('js/orderScript.js');
    document.documentElement.appendChild(script);

    // 发送当前URL给控制面板
    const currentUrlInfo = {
      type: 'SET_CURRENT_URL',
      url: currentUrl
    };
    window.postMessage(currentUrlInfo, '*');

    console.log('控制面板已注入到页面');
  } catch (e) {
    console.error('注入控制面板失败:', e);
  }
}

// 添加CSS样式
function addOrderButtonStyles() {
  const style = document.createElement('style');
    style.textContent = `
        .order-control-panel {
            position: fixed;
            right: 20px;
            top: 20px;
            z-index: 999999;
            width: 160px;
        }
        .order-control-panel-small {
        	right: 0;
        	top: 20px;
        	z-index: 999999;
        	width: 40px
        }
        .login-main {
            background: #ffffff;
            border-top: 3px solid rgb(38, 154, 241);
            border-radius: 8px;
            color: #151515;
            padding: 10px;
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
            display: flex;
            flex-direction: column;
            gap: 6px;
        }
        .login-main-title {
        	display: flex;
        	justify-content: space-between;
        	align-items: center;
        	border-bottom: 1px solid #eaeaea;
        	padding-bottom: 8px;
        	cursor: move;
        	user-select: none;
        	white-space: nowrap;
        }
        .login-main-title h3 {
            margin: 0;
            color: #151515;
            font-size: 12px;
            font-weight: 600;
        }
        .login-main-title div{
        	
        }
		.login-main-title .fold-btn {
			cursor:pointer;
			font-size: 11px;
			
		}
        .login-main #xq-move-web a {
            color: #151515;
            text-decoration: none;
            font-size: 12px;
            font-weight: 500;
            transition: color 0.2s;
        }
        .login-main #xq-move-web a:hover {
            color: #151515;
        }
        .login-main #xq-move-web {
            margin: 0;
        }
        .login-main p {
            margin: 0;
            padding: 6px 8px;
            border-radius: 4px;
            background-color: rgba(255, 107, 107, 0.1);
            border: 1px solid rgba(255, 107, 107, 0.5);
            color: #FFCBCB;
            font-size: 12px;
        }
        .btn-main {
            display: flex;
            flex-direction: column;
            gap: 6px;
            margin-top: 8px;
            border-top: 1px solid #3A5A8A;
            padding-top: 6px;
        }
        .btn-main button {
            border-radius: 4px;
            color: rgb(33, 57, 92);
            border: none;
            background: #A7FFEA;
            height: 28px;
            padding: 0 8px;
            width: 100%;
            font-size: 12px;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.2s ease;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .btn-main button:hover {
            filter: brightness(1.1);
        }
    `;
    document.head.appendChild(style);
}

// 确保在DOM加载完成后调用，增加容错处理
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', function() {
    addOrderButtonStyles();
    injectOrderControlPanel();
  });
} else {
  // 如果DOM已经加载完成，直接调用
  addOrderButtonStyles();
  setTimeout(injectOrderControlPanel, 0);
}

