import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom/client';
import './popup.css';

const Popup: React.FC = () => {
  const [isConnected, setIsConnected] = useState(false);
  const [status, setStatus] = useState('初始化中...');

  useEffect(() => {
    // 检查与后台脚本的连接
    chrome.runtime.sendMessage({ action: 'ping' }, (response) => {
      if (response && response.pong) {
        setIsConnected(true);
        setStatus('已连接到后台服务');
      } else {
        setIsConnected(false);
        setStatus('无法连接到后台服务');
      }
    });
  }, []);

  const handleStartCollection = () => {
    chrome.runtime.sendMessage({ action: 'startCollection' }, (response) => {
      if (response && response.success) {
        setStatus('开始采集数据');
      } else {
        setStatus('采集失败');
      }
    });
  };

  const handleSyncLogistics = () => {
    chrome.runtime.sendMessage({ action: 'syncLogistics' }, (response) => {
      if (response && response.success) {
        setStatus('开始同步物流');
      } else {
        setStatus('同步失败');
      }
    });
  };

  return (
    <div className="popup-container">
      <div className="header">
        <h2>Crawlful</h2>
        <p>全球电商增长助手</p>
      </div>
      
      <div className="status-section">
        <div className={`status-indicator ${isConnected ? 'connected' : 'disconnected'}`}>
          {isConnected ? '已连接' : '未连接'}
        </div>
        <p className="status-message">{status}</p>
      </div>

      <div className="action-buttons">
        <button 
          className="action-button primary" 
          onClick={handleStartCollection}
        >
          开始采集数据
        </button>
        <button 
          className="action-button secondary" 
          onClick={handleSyncLogistics}
        >
          同步物流信息
        </button>
      </div>

      <div className="info-section">
        <h3>功能说明</h3>
        <ul>
          <li>全网采集：自动采集多个平台的商品数据</li>
          <li>AI 语义标准化：智能处理商品信息</li>
          <li>多平台铺货：一键发布到多个电商平台</li>
          <li>物流同步：实时更新物流信息</li>
        </ul>
      </div>

      <div className="footer">
        <p>版本: 1.0.0</p>
      </div>
    </div>
  );
};

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);

root.render(
  <React.StrictMode>
    <Popup />
  </React.StrictMode>
);