/**
 * QuantAlpha Pro v2.1 - Luna Sentiment Trading Dashboard
 * React 18 + Tailwind + Chart.js
 */

const { useState, useEffect, useCallback } = React;

// ============================================
// API Client with JWT + HMAC Authentication
// ============================================
const API_BASE = window.location.origin;

const api = {
  token: localStorage.getItem('qa_token') || '',
  refreshToken: localStorage.getItem('qa_refresh') || '',

  async request(method, path, body = null, useSignature = false) {
    const headers = {
      'Content-Type': 'application/json',
    };

    if (this.token) {
      headers['Authorization'] = `Bearer ${this.token}`;
    }

    const options = { method, headers };
    if (body) {
      options.body = JSON.stringify(body);
    }

    const res = await fetch(`${API_BASE}${path}`, options);

    if (res.status === 401) {
      // Try refresh
      const refreshed = await this.refresh();
      if (refreshed) {
        return this.request(method, path, body, useSignature);
      }
      throw new Error('Session expired');
    }

    if (!res.ok) {
      const err = await res.json().catch(() => ({ error: 'Request failed' }));
      throw new Error(err.error || err.detail || 'Request failed');
    }

    return res.json();
  },

  async refresh() {
    if (!this.refreshToken) return false;
    try {
      const res = await fetch(`${API_BASE}/api/v1/auth/refresh`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ refresh_token: this.refreshToken }),
      });
      if (res.ok) {
        const data = await res.json();
        this.token = data.access_token;
        localStorage.setItem('qa_token', this.token);
        return true;
      }
    } catch {}
    return false;
  },

  login(username, password) {
    return this.request('POST', '/api/v1/auth/login', { username, password });
  },

  getStrategies() {
    return this.request('GET', '/api/v1/strategies');
  },

  getStrategy(id) {
    return this.request('GET', `/api/v1/strategies/${id}`);
  },

  toggleStrategy(id) {
    return this.request('POST', `/api/v1/strategies/${id}/toggle`);
  },

  updateStrategyConfig(id, config) {
    return this.request('PUT', `/api/v1/strategies/${id}/config`, { config });
  },

  getRiskMetrics() {
    return this.request('GET', '/api/v1/risk/metrics');
  },

  getKellyParams() {
    return this.request('GET', '/api/v1/risk/kelly');
  },

  activateKillSwitch(level, confirmCode) {
    return this.request('POST', '/api/v1/risk/kill-switch', {
      level,
      confirm_code: confirmCode,
    });
  },

  deactivateKillSwitch() {
    return this.request('DELETE', '/api/v1/risk/kill-switch');
  },

  getBinanceSpot() {
    return this.request('GET', '/api/v1/binance/spot');
  },

  getMarketOverview() {
    return this.request('GET', '/api/v1/binance/market-overview');
  },

  getEquityHistory() {
    return this.request('GET', '/api/v1/equity/history?days=90');
  },

  getSystemStatus() {
    return this.request('GET', '/api/v1/system/status');
  },

  getAuditLogs() {
    return this.request('GET', '/api/v1/audit-logs');
  },

  // Luna Sentiment API Methods
  getLunaSentiment(symbol) { return this.request('GET', `/api/v1/luna/sentiment/${symbol}`); },
  getLunaAllSentiments() { return this.request('GET', '/api/v1/luna/sentiment'); },
  getLunaHistory(symbol, hours = 24) { return this.request('GET', `/api/v1/luna/history/${symbol}?hours=${hours}`); },
  getLunaSignals() { return this.request('GET', '/api/v1/luna/signals'); },
  getLunaProfitability() { return this.request('GET', '/api/v1/luna/profitability'); },
  triggerLunaCollect() { return this.request('POST', '/api/v1/luna/collect'); },
  triggerLunaBacktest() { return this.request('POST', '/api/v1/luna/backtest'); },
};

// ============================================
// Login Component
// ============================================
function LoginScreen({ onLogin }) {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError('');
    try {
      const data = await api.login(username, password);
      api.token = data.access_token;
      api.refreshToken = data.refresh_token;
      localStorage.setItem('qa_token', data.access_token);
      localStorage.setItem('qa_refresh', data.refresh_token);
      localStorage.setItem('qa_user', JSON.stringify(data.user));
      onLogin(data.user);
    } catch (err) {
      setError(err.message || 'Login failed');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center" style={{ background: 'var(--bg-primary)' }}>
      <div className="card" style={{ width: '400px' }}>
        <div className="text-center mb-8">
          <div style={{ fontSize: '48px', color: 'var(--accent)', marginBottom: '8px' }}>
            <i className="fas fa-shield-halved"></i>
          </div>
          <h1 style={{ fontSize: '24px', fontWeight: 700 }}>QuantAlpha Pro</h1>
          <p style={{ color: 'var(--text-secondary)', fontSize: '13px', marginTop: '4px' }}>
            v2.1 — Luna Sentiment Trading
          </p>
        </div>

        {error && (
          <div style={{ background: 'rgba(255,23,68,0.1)', border: '1px solid var(--danger)', borderRadius: '8px', padding: '12px', marginBottom: '16px', color: 'var(--danger)', fontSize: '13px' }}>
            <i className="fas fa-circle-exclamation mr-2"></i>{error}
          </div>
        )}

        <form onSubmit={handleSubmit}>
          <div className="mb-4">
            <label style={{ fontSize: '12px', color: 'var(--text-secondary)', display: 'block', marginBottom: '6px' }}>
              USERNAME
            </label>
            <input
              type="text"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              placeholder="Enter username"
              required
            />
          </div>
          <div className="mb-6">
            <label style={{ fontSize: '12px', color: 'var(--text-secondary)', display: 'block', marginBottom: '6px' }}>
              PASSWORD
            </label>
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="Enter password"
              required
            />
          </div>
          <button
            type="submit"
            className="btn btn-primary"
            style={{ width: '100%' }}
            disabled={loading}
          >
            {loading ? <i className="fas fa-spinner fa-spin"></i> : <i className="fas fa-lock mr-2"></i>}
            {loading ? ' Authenticating...' : ' Secure Login'}
          </button>
        </form>

        <div style={{ marginTop: '20px', padding: '12px', background: 'var(--bg-secondary)', borderRadius: '8px', fontSize: '12px', color: 'var(--text-secondary)' }}>
          <i className="fas fa-circle-info mr-2" style={{ color: 'var(--accent)' }}></i>
          Default: username: <code style={{ color: 'var(--accent)' }}>admin</code> / password: <code style={{ color: 'var(--accent)' }}>admin_qa2024!</code>
        </div>
      </div>
    </div>
  );
}

// ============================================
// Sidebar Component
// ============================================
function Sidebar({ activeTab, setActiveTab, user, onLogout }) {
  const menuItems = [
    { id: 'dashboard', icon: 'fa-chart-line', label: '总览仪表盘', perm: 'read:dashboard' },
    { id: 'strategy', icon: 'fa-robot', label: 'MA交叉策略', perm: 'read:strategies' },
    { id: 'luna', icon: 'fa-moon', label: 'Luna舆论策略', perm: 'read:strategies' },
    { id: 'positions', icon: 'fa-wallet', label: '持仓管理', perm: 'read:dashboard' },
    { id: 'risk', icon: 'fa-shield-halved', label: '风险管理', perm: 'read:metrics' },
    { id: 'audit', icon: 'fa-list-check', label: '审计日志', perm: 'read:audit_logs' },
  ];

  const hasPerm = (perm) => {
    if (!user || !user.permissions) return false;
    return user.permissions.includes(perm) || user.role === 'admin';
  };

  return (
    <div className="sidebar">
      <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '32px' }}>
        <div style={{ width: '36px', height: '36px', background: 'var(--accent)', borderRadius: '8px', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#000', fontWeight: 700 }}>
          QA
        </div>
        <div>
          <div style={{ fontSize: '14px', fontWeight: 600 }}>QuantAlpha Pro</div>
          <div style={{ fontSize: '11px', color: 'var(--text-secondary)' }}>v2.1 Luna</div>
        </div>
      </div>

      <div style={{ marginBottom: '8px', fontSize: '10px', color: 'var(--text-secondary)', textTransform: 'uppercase', padding: '0 12px' }}>
        Main Menu
      </div>

      {menuItems.map(item => (
        hasPerm(item.perm) && (
          <div
            key={item.id}
            className={`nav-item ${activeTab === item.id ? 'active' : ''}`}
            onClick={() => setActiveTab(item.id)}
          >
            <i className={`fas ${item.icon}`} style={{ width: '20px' }}></i>
            {item.label}
          </div>
        )
      ))}

      <div style={{ marginTop: 'auto', paddingTop: '32px', borderTop: '1px solid var(--border-color)' }}>
        <div style={{ padding: '12px', background: 'var(--bg-card)', borderRadius: '8px', marginBottom: '12px' }}>
          <div style={{ fontSize: '12px', color: 'var(--text-secondary)' }}>Logged in as</div>
          <div style={{ fontSize: '14px', fontWeight: 600 }}>
            <i className="fas fa-user-shield mr-2" style={{ color: 'var(--accent)' }}></i>
            {user?.username}
          </div>
          <div style={{ fontSize: '11px', color: 'var(--accent)' }}>{user?.role}</div>
        </div>
        <div
          className="nav-item"
          onClick={onLogout}
          style={{ color: 'var(--danger)' }}
        >
          <i className="fas fa-right-from-bracket" style={{ width: '20px' }}></i>
          Logout
        </div>
      </div>
    </div>
  );
}

// ============================================
// Dashboard Component
// ============================================
function Dashboard({ user }) {
  const [marketData, setMarketData] = useState({});
  const [spotData, setSpotData] = useState({ balances: [] });
  const [equityData, setEquityData] = useState({});
  const [systemStatus, setSystemStatus] = useState({});
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const [market, spot, equity, status] = await Promise.all([
          api.getMarketOverview(),
          api.getBinanceSpot(),
          api.getEquityHistory(),
          api.getSystemStatus(),
        ]);
        setMarketData(market);
        setSpotData(spot);
        setEquityData(equity);
        setSystemStatus(status);
      } catch (err) {
        console.error('Dashboard data error:', err);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
    const interval = setInterval(fetchData, 30000);
    return () => clearInterval(interval);
  }, []);

  if (loading) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '60vh' }}>
        <i className="fas fa-circle-notch fa-spin" style={{ fontSize: '32px', color: 'var(--accent)' }}></i>
      </div>
    );
  }

  const prices = marketData.spot_prices || {};
  const balances = spotData.balances || [];
  const totalValue = balances.reduce((sum, b) => sum + (b.value_usdt || 0), 0);

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
        <div>
          <h2 style={{ fontSize: '20px', fontWeight: 700 }}>总览仪表盘</h2>
          <div style={{ fontSize: '12px', color: 'var(--text-secondary)', marginTop: '4px' }}>
            实时监控 · 最后更新: {new Date().toLocaleTimeString()}
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          <span className="status-dot status-online"></span>
          <span style={{ fontSize: '13px', color: 'var(--success)' }}>System Online</span>
          {systemStatus.kill_switch_active && (
            <span style={{ background: 'var(--danger)', color: 'white', padding: '4px 12px', borderRadius: '12px', fontSize: '11px', fontWeight: 700 }}>
              <i className="fas fa-triangle-exclamation mr-1"></i>KILL SWITCH ACTIVE
            </span>
          )}
        </div>
      </div>

      {/* Key Metrics */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: '16px', marginBottom: '24px' }}>
        <div className="card">
          <div className="metric-label">总资产估值</div>
          <div className="metric-value" style={{ color: 'var(--accent)' }}>
            ${totalValue.toLocaleString('en-US', { minimumFractionDigits: 2 })}
          </div>
          <div style={{ fontSize: '12px', color: 'var(--text-secondary)', marginTop: '4px' }}>
            组合总市值
          </div>
        </div>
        <div className="card">
          <div className="metric-label">策略盈亏</div>
          <div className={`metric-value ${(equityData.total_pnl || 0) >= 0 ? 'trend-up' : 'trend-down'}`}>
            {(equityData.total_pnl || 0) >= 0 ? '+' : ''}${(equityData.total_pnl || 0).toFixed(2)}
          </div>
          <div style={{ fontSize: '12px', color: 'var(--text-secondary)', marginTop: '4px' }}>
            累计实现盈亏
          </div>
        </div>
        <div className="card">
          <div className="metric-label">活跃策略</div>
          <div className="metric-value" style={{ color: 'var(--success)' }}>
            {Object.keys(equityData.strategy_breakdown || {}).length}
          </div>
          <div style={{ fontSize: '12px', color: 'var(--text-secondary)', marginTop: '4px' }}>
            运行中
          </div>
        </div>
        <div className="card">
          <div className="metric-label">Kill Switch</div>
          <div className="metric-value" style={{ color: systemStatus.kill_switch_active ? 'var(--danger)' : 'var(--success)' }}>
            {systemStatus.kill_switch_active ? 'ACTIVE' : 'Ready'}
          </div>
          <div style={{ fontSize: '12px', color: 'var(--text-secondary)', marginTop: '4px' }}>
            {systemStatus.kill_switch_level || 'Standby'}
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
        {/* Market Prices */}
        <div className="card">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
            <h3 style={{ fontSize: '14px', fontWeight: 600 }}>实时行情</h3>
            <span style={{ fontSize: '11px', color: 'var(--accent)' }}>Binance Live</span>
          </div>
          <table>
            <thead>
              <tr>
                <th>Symbol</th>
                <th style={{ textAlign: 'right' }}>Price</th>
              </tr>
            </thead>
            <tbody>
              {Object.entries(prices).map(([symbol, price]) => (
                <tr key={symbol}>
                  <td style={{ fontWeight: 600 }}>{symbol.replace('USDT', '')}</td>
                  <td style={{ textAlign: 'right', color: 'var(--accent)' }}>
                    ${price.toLocaleString('en-US', { minimumFractionDigits: 2 })}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Holdings */}
        <div className="card">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
            <h3 style={{ fontSize: '14px', fontWeight: 600 }}>当前持仓</h3>
            <span style={{ fontSize: '11px', color: 'var(--text-secondary)' }}>Spot</span>
          </div>
          <table>
            <thead>
              <tr>
                <th>Asset</th>
                <th style={{ textAlign: 'right' }}>Amount</th>
                <th style={{ textAlign: 'right' }}>Value (USDT)</th>
              </tr>
            </thead>
            <tbody>
              {balances.filter(b => b.value_usdt > 1).map(b => (
                <tr key={b.asset}>
                  <td style={{ fontWeight: 600 }}>{b.asset}</td>
                  <td style={{ textAlign: 'right' }}>{b.total.toFixed(4)}</td>
                  <td style={{ textAlign: 'right', color: 'var(--accent)' }}>
                    ${b.value_usdt.toFixed(2)}
                  </td>
                </tr>
              ))}
              {balances.filter(b => b.value_usdt > 1).length === 0 && (
                <tr>
                  <td colSpan="3" style={{ textAlign: 'center', color: 'var(--text-secondary)' }}>
                    暂无持仓
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

// ============================================
// MA Strategy Component
// ============================================
function MAStrategyPanel({ user }) {
  const [strategy, setStrategy] = useState(null);
  const [loading, setLoading] = useState(true);
  const [actionLoading, setActionLoading] = useState(false);
  const [configEdit, setConfigEdit] = useState({});

  const fetchStrategy = async () => {
    try {
      const data = await api.getStrategy('ma-cross-spot');
      setStrategy(data);
      setConfigEdit(data.config || {});
    } catch (err) {
      console.error('Strategy fetch error:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchStrategy();
    const interval = setInterval(fetchStrategy, 15000);
    return () => clearInterval(interval);
  }, []);

  const handleToggle = async () => {
    if (!user.permissions?.includes('write:strategy_toggle') && user.role !== 'admin') {
      alert('Permission denied: trader role required');
      return;
    }
    setActionLoading(true);
    try {
      const result = await api.toggleStrategy('ma-cross-spot');
      alert(`Strategy ${result.action}`);
      fetchStrategy();
    } catch (err) {
      alert('Error: ' + err.message);
    } finally {
      setActionLoading(false);
    }
  };

  const handleConfigUpdate = async () => {
    if (!user.permissions?.includes('write:strategy_config') && user.role !== 'admin') {
      alert('Permission denied');
      return;
    }
    setActionLoading(true);
    try {
      await api.updateStrategyConfig('ma-cross-spot', configEdit);
      alert('Configuration updated');
      fetchStrategy();
    } catch (err) {
      alert('Error: ' + err.message);
    } finally {
      setActionLoading(false);
    }
  };

  if (loading) return <div style={{ textAlign: 'center', padding: '40px' }}><i className="fas fa-spinner fa-spin" style={{ color: 'var(--accent)' }}></i></div>;
  if (!strategy) return <div className="card">Strategy not found</div>;

  const maData = strategy.ma_data || {};
  const symbolStates = strategy.symbol_states || {};
  const isRunning = strategy.status === 'running';
  const cfg = strategy.config_display || {};

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
        <div>
          <h2 style={{ fontSize: '20px', fontWeight: 700 }}>MA20/MA50 Cross Strategy</h2>
          <div style={{ fontSize: '12px', color: 'var(--text-secondary)', marginTop: '4px' }}>
            现货金叉做多 + 质押循环杠杆
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
          <span className={`status-dot ${isRunning ? 'status-online' : strategy.status === 'paused' ? 'status-paused' : 'status-offline'}`}></span>
          <span style={{ fontSize: '13px', textTransform: 'uppercase' }}>{strategy.status}</span>
          <button
            className={`btn ${isRunning ? 'btn-danger' : 'btn-primary'}`}
            onClick={handleToggle}
            disabled={actionLoading}
            style={{ fontSize: '12px', padding: '8px 16px' }}
          >
            {actionLoading ? <i className="fas fa-spinner fa-spin"></i> : (
              <><i className={`fas ${isRunning ? 'fa-pause' : 'fa-play'} mr-2`}></i>
              {isRunning ? 'Stop' : 'Start'}</>
            )}
          </button>
        </div>
      </div>

      {/* Strategy Stats */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', gap: '12px', marginBottom: '24px' }}>
        <div className="card" style={{ padding: '16px' }}>
          <div className="metric-label">Total PnL</div>
          <div className={`metric-value ${strategy.total_pnl >= 0 ? 'trend-up' : 'trend-down'}`} style={{ fontSize: '22px' }}>
            {strategy.total_pnl >= 0 ? '+' : ''}${strategy.total_pnl}
          </div>
        </div>
        <div className="card" style={{ padding: '16px' }}>
          <div className="metric-label">Win Rate</div>
          <div className="metric-value trend-up" style={{ fontSize: '22px' }}>{strategy.win_rate}%</div>
        </div>
        <div className="card" style={{ padding: '16px' }}>
          <div className="metric-label">Trades</div>
          <div className="metric-value" style={{ fontSize: '22px', color: 'var(--accent)' }}>{strategy.total_trades}</div>
        </div>
        <div className="card" style={{ padding: '16px' }}>
          <div className="metric-label">Errors</div>
          <div className="metric-value" style={{ fontSize: '22px', color: strategy.error_count > 0 ? 'var(--danger)' : 'var(--success)' }}>
            {strategy.error_count}
          </div>
        </div>
      </div>

      {/* MA Data & Positions */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', marginBottom: '24px' }}>
        <div className="card">
          <h3 style={{ fontSize: '14px', fontWeight: 600, marginBottom: '16px' }}>
            <i className="fas fa-chart-area mr-2" style={{ color: 'var(--accent)' }}></i>
            MA 指标状态
          </h3>
          {Object.entries(maData).map(([symbol, data]) => (
            <div key={symbol} className="strategy-card">
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
                <span style={{ fontWeight: 700, fontSize: '16px' }}>{symbol.replace('USDT', '')}</span>
                <span className={data.trend === 'bullish' ? 'ma-bullish' : 'ma-bearish'} style={{ fontSize: '12px', fontWeight: 600 }}>
                  {data.trend === 'bullish' ? <><i className="fas fa-arrow-trend-up mr-1"></i>BULLISH</> : <><i className="fas fa-arrow-trend-down mr-1"></i>BEARISH</>}
                </span>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '8px', fontSize: '12px' }}>
                <div>
                  <div style={{ color: 'var(--text-secondary)' }}>MA{cfg.MA_Short || 20}</div>
                  <div style={{ color: 'var(--accent)', fontWeight: 600 }}>${data.ma20}</div>
                </div>
                <div>
                  <div style={{ color: 'var(--text-secondary)' }}>MA{cfg.MA_Long || 50}</div>
                  <div style={{ color: 'var(--accent)', fontWeight: 600 }}>${data.ma50}</div>
                </div>
                <div>
                  <div style={{ color: 'var(--text-secondary)' }}>Price</div>
                  <div style={{ fontWeight: 600 }}>${data.current_price}</div>
                </div>
              </div>
              <div style={{ marginTop: '8px', fontSize: '11px', color: 'var(--text-secondary)' }}>
                Spread: <span style={{ color: data.distance_pct >= 0 ? 'var(--success)' : 'var(--danger)' }}>
                  {data.distance_pct >= 0 ? '+' : ''}{data.distance_pct}%
                </span>
              </div>
            </div>
          ))}
        </div>

        <div className="card">
          <h3 style={{ fontSize: '14px', fontWeight: 600, marginBottom: '16px' }}>
            <i className="fas fa-briefcase mr-2" style={{ color: 'var(--accent)' }}></i>
            持仓状态
          </h3>
          {Object.entries(symbolStates).map(([symbol, state]) => (
            <div key={symbol} className="strategy-card">
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '8px' }}>
                <span style={{ fontWeight: 600 }}>{symbol.replace('USDT', '')}</span>
                <span style={{ fontSize: '11px', color: 'var(--text-secondary)' }}>
                  Signal: {state.last_signal || 'None'}
                </span>
              </div>
              <div style={{ fontSize: '12px' }}>
                <div>Position: <span style={{ color: 'var(--accent)' }}>{state.position_size.toFixed(6)}</span></div>
                <div>Value: ${state.position_value.toFixed(2)}</div>
                <div>Entry: ${state.entry_price.toFixed(2)}</div>
                <div style={{ color: state.unrealized_pnl >= 0 ? 'var(--success)' : 'var(--danger)' }}>
                  Unrealized: {state.unrealized_pnl >= 0 ? '+' : ''}${state.unrealized_pnl.toFixed(2)}
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Configuration */}
      <div className="card">
        <h3 style={{ fontSize: '14px', fontWeight: 600, marginBottom: '16px' }}>
          <i className="fas fa-sliders mr-2" style={{ color: 'var(--accent)' }}></i>
          策略配置
        </h3>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '16px' }}>
          {Object.entries(cfg).map(([key, value]) => (
            <div key={key}>
              <label style={{ fontSize: '11px', color: 'var(--text-secondary)', textTransform: 'uppercase', display: 'block', marginBottom: '4px' }}>
                {key}
              </label>
              <div style={{ fontSize: '14px', fontWeight: 600 }}>
                {typeof value === 'boolean' ? (
                  <span style={{ color: value ? 'var(--success)' : 'var(--danger)' }}>
                    {value ? 'Enabled' : 'Disabled'}
                  </span>
                ) : (
                  value
                )}
              </div>
            </div>
          ))}
        </div>
        <div style={{ marginTop: '16px', padding: '12px', background: 'var(--accent-dim)', borderRadius: '8px', fontSize: '12px' }}>
          <i className="fas fa-circle-info mr-2" style={{ color: 'var(--accent)' }}></i>
          <strong>Staking Loop:</strong> 买入后质押借出 {Math.round((cfg.LTV_Ratio || 0.7) * 100)}%，最多循环 {cfg.Max_Loops || 3} 次。
          理论最大杠杆: {(1 + (cfg.LTV_Ratio || 0.7) * (cfg.Max_Loops || 3)).toFixed(1)}x
        </div>
      </div>
    </div>
  );
}

// ============================================
// Risk Management Component
// ============================================
function RiskPanel({ user }) {
  const [metrics, setMetrics] = useState({});
  const [kelly, setKelly] = useState({});
  const [confirmCode, setConfirmCode] = useState('');
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const [m, k] = await Promise.all([
          api.getRiskMetrics(),
          api.getKellyParams(),
        ]);
        setMetrics(m);
        setKelly(k);
      } catch (err) {
        console.error('Risk data error:', err);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
    const interval = setInterval(fetchData, 10000);
    return () => clearInterval(interval);
  }, []);

  const handleKillSwitch = async (level) => {
    if (!confirmCode) {
      alert('Please enter confirmation code (first 8 chars of your API secret)');
      return;
    }
    if (!window.confirm(`Are you sure you want to activate ${level} kill switch? This will affect all positions!`)) {
      return;
    }
    try {
      const result = await api.activateKillSwitch(level, confirmCode);
      alert(`Kill switch activated: ${result.level}\nStatus: ${result.status}`);
    } catch (err) {
      alert('Error: ' + err.message);
    }
  };

  const handleDeactivate = async () => {
    if (!window.confirm('Deactivate kill switch?')) return;
    try {
      const result = await api.deactivateKillSwitch();
      alert('Kill switch deactivated');
    } catch (err) {
      alert('Error: ' + err.message);
    }
  };

  if (loading) return <div style={{ textAlign: 'center', padding: '40px' }}><i className="fas fa-spinner fa-spin" style={{ color: 'var(--accent)' }}></i></div>;

  const hasKillPerm = user.permissions?.includes('write:kill_switch') || user.role === 'admin';

  return (
    <div>
      <h2 style={{ fontSize: '20px', fontWeight: 700, marginBottom: '24px' }}>
        <i className="fas fa-shield-halved mr-2" style={{ color: 'var(--danger)' }}></i>
        风险管理
      </h2>

      {/* Risk Metrics */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '16px', marginBottom: '24px' }}>
        <div className="card">
          <div className="metric-label">Daily PnL</div>
          <div className={`metric-value ${(metrics.daily_pnl_usdt || 0) >= 0 ? 'trend-up' : 'trend-down'}`} style={{ fontSize: '22px' }}>
            {(metrics.daily_pnl_usdt || 0) >= 0 ? '+' : ''}${(metrics.daily_pnl_usdt || 0).toFixed(2)}
          </div>
        </div>
        <div className="card">
          <div className="metric-label">Total Position</div>
          <div className="metric-value" style={{ fontSize: '22px', color: 'var(--accent)' }}>
            ${(metrics.total_position_usdt || 0).toFixed(2)}
          </div>
        </div>
        <div className="card">
          <div className="metric-label">Margin Ratio</div>
          <div className="metric-value" style={{ fontSize: '22px', color: (metrics.margin_ratio_percent || 0) > 80 ? 'var(--danger)' : 'var(--success)' }}>
            {(metrics.margin_ratio_percent || 0).toFixed(1)}%
          </div>
        </div>
        <div className="card">
          <div className="metric-label">Kill Switch</div>
          <div className="metric-value" style={{ fontSize: '22px', color: metrics.kill_switch_active ? 'var(--danger)' : 'var(--success)' }}>
            {metrics.kill_switch_active ? 'ACTIVE' : 'Inactive'}
          </div>
        </div>
      </div>

      {/* Kelly Parameters */}
      <div className="card" style={{ marginBottom: '24px' }}>
        <h3 style={{ fontSize: '14px', fontWeight: 600, marginBottom: '16px' }}>
          <i className="fas fa-calculator mr-2" style={{ color: 'var(--accent)' }}></i>
          Kelly Criterion Parameters
        </h3>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(150px, 1fr))', gap: '16px' }}>
          <div>
            <div style={{ fontSize: '11px', color: 'var(--text-secondary)' }}>Win Rate</div>
            <div style={{ fontSize: '18px', fontWeight: 700 }}>{(kelly.win_rate * 100).toFixed(1)}%</div>
          </div>
          <div>
            <div style={{ fontSize: '11px', color: 'var(--text-secondary)' }}>Payoff Ratio</div>
            <div style={{ fontSize: '18px', fontWeight: 700 }}>{kelly.payoff_ratio?.toFixed(2)}</div>
          </div>
          <div>
            <div style={{ fontSize: '11px', color: 'var(--text-secondary)' }}>Edge</div>
            <div style={{ fontSize: '18px', fontWeight: 700, color: kelly.edge > 0 ? 'var(--success)' : 'var(--danger)' }}>
              {(kelly.edge * 100).toFixed(2)}%
            </div>
          </div>
          <div>
            <div style={{ fontSize: '11px', color: 'var(--text-secondary)' }}>Kelly %</div>
            <div style={{ fontSize: '18px', fontWeight: 700, color: 'var(--warning)' }}>{kelly.kelly_percent}%</div>
          </div>
          <div>
            <div style={{ fontSize: '11px', color: 'var(--text-secondary)' }}>Half Kelly (Recommended)</div>
            <div style={{ fontSize: '18px', fontWeight: 700, color: 'var(--success)' }}>{kelly.half_kelly}%</div>
          </div>
          <div>
            <div style={{ fontSize: '11px', color: 'var(--text-secondary)' }}>Sample Size</div>
            <div style={{ fontSize: '18px', fontWeight: 700 }}>{kelly.sample_size} trades</div>
          </div>
        </div>
      </div>

      {/* Kill Switch Panel */}
      <div className="kill-switch-panel">
        <h3 style={{ fontSize: '16px', fontWeight: 700, color: 'var(--danger)', marginBottom: '12px' }}>
          <i className="fas fa-skull-crossbones mr-2"></i>
          Emergency Kill Switch
        </h3>
        <p style={{ fontSize: '13px', color: 'var(--text-secondary)', marginBottom: '16px' }}>
          Immediately halt trading and/or close positions. Requires confirmation code and appropriate permissions.
        </p>

        <div style={{ marginBottom: '16px' }}>
          <label style={{ fontSize: '11px', color: 'var(--text-secondary)', textTransform: 'uppercase', display: 'block', marginBottom: '6px' }}>
            Confirmation Code (first 8 chars of API Secret)
          </label>
          <input
            type="text"
            value={confirmCode}
            onChange={(e) => setConfirmCode(e.target.value)}
            placeholder="Enter confirmation code"
            style={{ maxWidth: '300px', background: 'rgba(255,255,255,0.05)' }}
          />
        </div>

        <div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap' }}>
          <button
            className="btn"
            style={{ background: '#ff9100', color: '#000' }}
            onClick={() => handleKillSwitch('soft')}
            disabled={!hasKillPerm || metrics.kill_switch_active}
          >
            <i className="fas fa-pause mr-2"></i>Soft Kill (No New Pos)
          </button>
          <button
            className="btn btn-danger"
            onClick={() => handleKillSwitch('hard')}
            disabled={!hasKillPerm || metrics.kill_switch_active}
          >
            <i className="fas fa-hand mr-2"></i>Hard Kill (Close All)
          </button>
          <button
            className="btn"
            style={{ background: '#7c0000', color: 'white' }}
            onClick={() => handleKillSwitch('emergency')}
            disabled={!hasKillPerm || metrics.kill_switch_active}
          >
            <i className="fas fa-triangle-exclamation mr-2"></i>Emergency Exit
          </button>
          {metrics.kill_switch_active && (
            <button
              className="btn btn-primary"
              onClick={handleDeactivate}
              disabled={!hasKillPerm}
            >
              <i className="fas fa-play mr-2"></i>Deactivate
            </button>
          )}
        </div>

        {!hasKillPerm && (
          <div style={{ marginTop: '12px', fontSize: '12px', color: 'var(--warning)' }}>
            <i className="fas fa-lock mr-2"></i>
            You need risk_manager or admin role to use kill switch.
          </div>
        )}
      </div>
    </div>
  );
}

// ============================================
// Positions Component
// ============================================
function PositionsPanel({ user }) {
  const [spotData, setSpotData] = useState({ balances: [] });

  useEffect(() => {
    const fetchData = async () => {
      try {
        const data = await api.getBinanceSpot();
        setSpotData(data);
      } catch (err) {
        console.error('Positions fetch error:', err);
      }
    };
    fetchData();
    const interval = setInterval(fetchData, 30000);
    return () => clearInterval(interval);
  }, []);

  const balances = spotData.balances || [];
  const significant = balances.filter(b => b.value_usdt > 1);

  return (
    <div>
      <h2 style={{ fontSize: '20px', fontWeight: 700, marginBottom: '24px' }}>
        <i className="fas fa-wallet mr-2" style={{ color: 'var(--accent)' }}></i>
        持仓管理
      </h2>

      <div className="card">
        <table>
          <thead>
            <tr>
              <th>Asset</th>
              <th style={{ textAlign: 'right' }}>Total Amount</th>
              <th style={{ textAlign: 'right' }}>Price (USDT)</th>
              <th style={{ textAlign: 'right' }}>Value (USDT)</th>
              <th style={{ textAlign: 'right' }}>% of Portfolio</th>
            </tr>
          </thead>
          <tbody>
            {significant.map(b => {
              const totalPort = significant.reduce((s, x) => s + x.value_usdt, 0);
              const pct = totalPort > 0 ? (b.value_usdt / totalPort * 100).toFixed(1) : '0';
              return (
                <tr key={b.asset}>
                  <td style={{ fontWeight: 700 }}>{b.asset}</td>
                  <td style={{ textAlign: 'right' }}>{b.total.toFixed(6)}</td>
                  <td style={{ textAlign: 'right', color: 'var(--accent)' }}>${b.price_usdt.toFixed(2)}</td>
                  <td style={{ textAlign: 'right', fontWeight: 600 }}>${b.value_usdt.toFixed(2)}</td>
                  <td style={{ textAlign: 'right' }}>{pct}%</td>
                </tr>
              );
            })}
            {significant.length === 0 && (
              <tr>
                <td colSpan="5" style={{ textAlign: 'center', color: 'var(--text-secondary)', padding: '40px' }}>
                  暂无持仓数据
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ============================================
// Audit Logs Component
// ============================================
function AuditPanel({ user }) {
  const [logs, setLogs] = useState([]);

  useEffect(() => {
    const fetchLogs = async () => {
      try {
        const data = await api.getAuditLogs();
        setLogs(data.logs || []);
      } catch (err) {
        console.error('Audit logs error:', err);
      }
    };
    fetchLogs();
    const interval = setInterval(fetchLogs, 10000);
    return () => clearInterval(interval);
  }, []);

  const eventColors = {
    'kill_switch': 'var(--danger)',
    'strategy_toggle': 'var(--accent)',
    'strategy_config_change': 'var(--warning)',
    'login': 'var(--success)',
    'login_failed': 'var(--danger)',
    'trade_executed': '#00e5ff',
    'system_startup': 'var(--success)',
  };

  return (
    <div>
      <h2 style={{ fontSize: '20px', fontWeight: 700, marginBottom: '24px' }}>
        <i className="fas fa-list-check mr-2" style={{ color: 'var(--accent)' }}></i>
        审计日志
      </h2>

      <div className="card" style={{ overflow: 'auto', maxHeight: '70vh' }}>
        <table>
          <thead>
            <tr>
              <th>Time</th>
              <th>Event</th>
              <th>User</th>
              <th>IP</th>
              <th>Details</th>
            </tr>
          </thead>
          <tbody>
            {logs.map(log => (
              <tr key={log.id}>
                <td style={{ fontSize: '12px', whiteSpace: 'nowrap' }}>
                  {new Date(log.timestamp).toLocaleString()}
                </td>
                <td>
                  <span style={{
                    background: eventColors[log.event_type] || 'var(--text-secondary)',
                    color: '#000',
                    padding: '2px 8px',
                    borderRadius: '4px',
                    fontSize: '11px',
                    fontWeight: 600,
                    textTransform: 'uppercase'
                  }}>
                    {log.event_type}
                  </span>
                </td>
                <td style={{ fontSize: '12px' }}>{log.user}</td>
                <td style={{ fontSize: '12px', color: 'var(--text-secondary)' }}>{log.client_ip}</td>
                <td style={{ fontSize: '12px', maxWidth: '300px', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                  {JSON.stringify(log.details)}
                </td>
              </tr>
            ))}
            {logs.length === 0 && (
              <tr>
                <td colSpan="5" style={{ textAlign: 'center', color: 'var(--text-secondary)', padding: '40px' }}>
                  暂无审计日志
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ============================================
// Luna Sentiment Strategy Component (Enhanced)
// ============================================

// --- Semi-circle Gauge Sub-component ---
function SentimentGauge({ score, size }) {
  const s = size || 180;
  const r = s * 0.38;
  const cx = s / 2;
  const cy = s * 0.52;
  const strokeWidth = s * 0.12;
  const radius = r;
  const circumference = Math.PI * radius;
  const pct = Math.max(0, Math.min(100, score || 0)) / 100;
  const dashOffset = circumference * (1 - pct);

  const getGaugeColor = (val) => {
    if (val <= 20) return '#ff1744';
    if (val <= 40) return '#ff6d00';
    if (val <= 60) return '#ffc400';
    if (val <= 80) return '#00e676';
    return '#00bfa5';
  };

  const getGaugeLabel = (val) => {
    if (val <= 20) return '极度恐惧';
    if (val <= 40) return '恐惧';
    if (val <= 60) return '中性';
    if (val <= 80) return '贪婪';
    return '极度贪婪';
  };

  const color = getGaugeColor(score || 0);
  const label = getGaugeLabel(score || 0);

  return (
    <div style={{ position: 'relative', width: s, height: s * 0.58, margin: '0 auto' }}>
      <svg width={s} height={s * 0.58} viewBox={'0 0 ' + s + ' ' + (s * 0.58)}>
        {/* Background arc */}
        <path
          d={'M ' + (cx - radius) + ' ' + cy + ' A ' + radius + ' ' + radius + ' 0 0 1 ' + (cx + radius) + ' ' + cy}
          fill="none"
          stroke="rgba(255,255,255,0.06)"
          strokeWidth={strokeWidth}
          strokeLinecap="round"
        />
        {/* Colored arc */}
        <path
          d={'M ' + (cx - radius) + ' ' + cy + ' A ' + radius + ' ' + radius + ' 0 0 1 ' + (cx + radius) + ' ' + cy}
          fill="none"
          stroke={color}
          strokeWidth={strokeWidth}
          strokeLinecap="round"
          strokeDasharray={circumference}
          strokeDashoffset={dashOffset}
          style={{ transition: 'stroke-dashoffset 0.8s ease, stroke 0.5s ease' }}
        />
      </svg>
      <div style={{
        position: 'absolute', bottom: 0, left: '50%', transform: 'translateX(-50%)',
        textAlign: 'center',
      }}>
        <div style={{ fontSize: s * 0.22, fontWeight: 800, color: color, lineHeight: 1 }}>{score || 0}</div>
        <div style={{ fontSize: s * 0.072, color: color, fontWeight: 600, marginTop: 2 }}>{label}</div>
      </div>
    </div>
  );
}

// --- SVG Sparkline Sub-component ---
function SentimentSparkline({ data, width, height, color }) {
  const w = width || 240;
  const h = height || 60;
  if (!data || data.length < 2) {
    return (
      <div style={{ width: w, height: h, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--text-secondary)', fontSize: '11px' }}>
        暂无历史数据
      </div>
    );
  }
  const scores = data.map(d => d.score || 0);
  const minS = Math.min(...scores);
  const maxS = Math.max(...scores);
  const range = maxS - minS || 1;
  const pad = 4;
  const pts = scores.map((v, i) => {
    const x = pad + (i / (scores.length - 1)) * (w - pad * 2);
    const y = pad + (1 - (v - minS) / range) * (h - pad * 2);
    return x + ',' + y;
  }).join(' ');
  const areaPts = pad + ',' + (h - pad) + ' ' + pts + ' ' + (w - pad) + ',' + (h - pad);

  return (
    <svg width={w} height={h} style={{ display: 'block' }}>
      <defs>
        <linearGradient id="sparkGrad" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor={color || '#9c78ff'} stopOpacity="0.3" />
          <stop offset="100%" stopColor={color || '#9c78ff'} stopOpacity="0.02" />
        </linearGradient>
      </defs>
      <polygon points={areaPts} fill="url(#sparkGrad)" />
      <polyline points={pts} fill="none" stroke={color || '#9c78ff'} strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" />
      <circle cx={w - pad} cy={pad + (1 - (scores[scores.length - 1] - minS) / range) * (h - pad * 2)} r="3" fill={color || '#9c78ff'} />
    </svg>
  );
}

function LunaPanel({ user }) {
  const [sentiments, setSentiments] = useState([]);
  const [signals, setSignals] = useState([]);
  const [profitability, setProfitability] = useState({});
  const [strategy, setStrategy] = useState({});
  const [loading, setLoading] = useState(true);
  const [actionLoading, setActionLoading] = useState(false);
  const [backtestLoading, setBacktestLoading] = useState(false);
  const [selectedSymbol, setSelectedSymbol] = useState(null);
  const [historyData, setHistoryData] = useState([]);

  const fetchData = async () => {
    try {
      const [sentData, sigData, profData] = await Promise.all([
        api.getLunaAllSentiments().catch(() => ({ sentiments: [] })),
        api.getLunaSignals().catch(() => ({ signals: [] })),
        api.getLunaProfitability().catch(() => ({})),
      ]);
      const sentList = sentData.sentiments || [];
      setSentiments(sentList);
      setSignals(sigData.signals || []);
      setProfitability(profData);
      if (sentData.strategy) setStrategy(sentData.strategy);
      // Auto-select first symbol if none selected
      if (!selectedSymbol && sentList.length > 0) {
        setSelectedSymbol(sentList[0].symbol);
      }
    } catch (err) {
      console.error('Luna data fetch error:', err);
    } finally {
      setLoading(false);
    }
  };

  const fetchHistory = useCallback(async () => {
    if (!selectedSymbol) return;
    try {
      const data = await api.getLunaHistory(selectedSymbol, 24).catch(() => ({ history: [] }));
      setHistoryData(data.history || data.scores || []);
    } catch (err) {
      console.error('History fetch error:', err);
    }
  }, [selectedSymbol]);

  useEffect(() => {
    fetchData();
    const interval = setInterval(fetchData, 15000);
    return () => clearInterval(interval);
  }, []);

  useEffect(() => {
    fetchHistory();
    const interval = setInterval(fetchHistory, 30000);
    return () => clearInterval(interval);
  }, [fetchHistory]);

  const handleCollect = async () => {
    setActionLoading(true);
    try {
      await api.triggerLunaCollect();
      setTimeout(fetchData, 2000);
    } catch (err) {
      alert('采集失败: ' + err.message);
    } finally {
      setActionLoading(false);
    }
  };

  const handleBacktest = async () => {
    setBacktestLoading(true);
    try {
      const result = await api.triggerLunaBacktest();
      alert('回测完成! ' + (result.summary || JSON.stringify(result)));
      fetchData();
    } catch (err) {
      alert('回测失败: ' + err.message);
    } finally {
      setBacktestLoading(false);
    }
  };

  const sentimentLevelConfig = {
    extreme_fear: { label: '极度恐惧', color: '#ff1744', icon: 'fa-face-dizzy' },
    fear: { label: '恐惧', color: '#ff6d00', icon: 'fa-face-frown' },
    neutral: { label: '中性', color: '#ffc400', icon: 'fa-face-meh' },
    greed: { label: '贪婪', color: '#00e676', icon: 'fa-face-smile' },
    extreme_greed: { label: '极度贪婪', color: '#00bfa5', icon: 'fa-face-grin-stars' },
  };

  const getGaugeColor = (score) => {
    if (score <= 20) return '#ff1744';
    if (score <= 40) return '#ff6d00';
    if (score <= 60) return '#ffc400';
    if (score <= 80) return '#00e676';
    return '#00bfa5';
  };

  const actionColors = {
    'buy': 'var(--success)',
    'sell': 'var(--danger)',
    'hold': 'var(--warning)',
    'strong_buy': '#00e676',
    'strong_sell': '#ff1744',
    'BUY': 'var(--success)',
    'SELL': 'var(--danger)',
  };

  const selectedSentiment = sentiments.find(s => s.symbol === selectedSymbol);

  if (loading) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '60vh' }}>
        <i className="fas fa-circle-notch fa-spin" style={{ fontSize: '32px', color: '#9c78ff' }}></i>
      </div>
    );
  }

  const isRunning = strategy.status === 'running';

  return (
    <div>
      {/* Header */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
        <div>
          <h2 style={{ fontSize: '20px', fontWeight: 700, display: 'flex', alignItems: 'center', gap: '10px' }}>
            <i className="fas fa-moon" style={{ color: '#9c78ff' }}></i>
            Luna 舆论交易策略
          </h2>
          <div style={{ fontSize: '12px', color: 'var(--text-secondary)', marginTop: '4px' }}>
            币安广场情绪分析 · 逆向+动量混合策略
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
          <span className={'status-dot ' + (isRunning ? 'status-online' : 'status-offline')}></span>
          <span style={{ fontSize: '13px', textTransform: 'uppercase', color: isRunning ? 'var(--success)' : 'var(--text-secondary)' }}>
            {strategy.status || 'unknown'}
          </span>
          <button
            className="btn"
            style={{ background: 'rgba(156,120,255,0.15)', color: '#9c78ff', border: '1px solid rgba(156,120,255,0.3)', fontSize: '12px', padding: '8px 16px' }}
            onClick={handleCollect}
            disabled={actionLoading}
          >
            {actionLoading ? <i className="fas fa-spinner fa-spin mr-2"></i> : <i className="fas fa-rotate mr-2"></i>}
            手动采集
          </button>
          <button
            className="btn"
            style={{ background: 'rgba(0,230,118,0.12)', color: '#00e676', border: '1px solid rgba(0,230,118,0.3)', fontSize: '12px', padding: '8px 16px' }}
            onClick={handleBacktest}
            disabled={backtestLoading}
          >
            {backtestLoading ? <i className="fas fa-spinner fa-spin mr-2"></i> : <i className="fas fa-flask mr-2"></i>}
            运行回测
          </button>
        </div>
      </div>

      {/* Status Row */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: '12px', marginBottom: '24px' }}>
        <div className="card" style={{ padding: '16px' }}>
          <div className="metric-label">策略状态</div>
          <div className="metric-value" style={{ fontSize: '20px', color: isRunning ? 'var(--success)' : 'var(--text-secondary)' }}>
            <i className={'fas ' + (isRunning ? 'fa-circle-play' : 'fa-circle-stop') + ' mr-2'}></i>
            {isRunning ? '运行中' : '已停止'}
          </div>
        </div>
        <div className="card" style={{ padding: '16px' }}>
          <div className="metric-label">监控币种</div>
          <div className="metric-value" style={{ fontSize: '20px', color: '#9c78ff' }}>
            {sentiments.length}
          </div>
        </div>
        <div className="card" style={{ padding: '16px' }}>
          <div className="metric-label">近期信号</div>
          <div className="metric-value" style={{ fontSize: '20px', color: 'var(--accent)' }}>
            {signals.length}
          </div>
        </div>
        <div className="card" style={{ padding: '16px' }}>
          <div className="metric-label">最后采集</div>
          <div className="metric-value" style={{ fontSize: '14px', color: 'var(--text-secondary)' }}>
            {strategy.last_collect ? new Date(strategy.last_collect).toLocaleTimeString() : 'N/A'}
          </div>
        </div>
      </div>

      {/* ===================== 1. Sentiment Gauge + Sparkline for Selected Symbol ===================== */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', marginBottom: '24px' }}>
        {/* Gauge Card */}
        <div className="card" style={{ textAlign: 'center', padding: '24px' }}>
          <h3 style={{ fontSize: '14px', fontWeight: 600, marginBottom: '8px', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px' }}>
            <i className="fas fa-gauge-high" style={{ color: '#9c78ff' }}></i>
            情绪仪表盘
          </h3>
          {/* Symbol selector pills */}
          <div style={{ display: 'flex', gap: '6px', justifyContent: 'center', flexWrap: 'wrap', marginBottom: '16px' }}>
            {sentiments.map(s => (
              <span
                key={s.symbol}
                onClick={() => setSelectedSymbol(s.symbol)}
                style={{
                  padding: '4px 12px',
                  borderRadius: '12px',
                  fontSize: '12px',
                  fontWeight: 600,
                  cursor: 'pointer',
                  background: selectedSymbol === s.symbol ? 'rgba(156,120,255,0.2)' : 'var(--bg-secondary)',
                  color: selectedSymbol === s.symbol ? '#9c78ff' : 'var(--text-secondary)',
                  border: '1px solid ' + (selectedSymbol === s.symbol ? 'rgba(156,120,255,0.4)' : 'transparent'),
                  transition: 'all 0.2s',
                }}
              >
                {s.symbol}
              </span>
            ))}
          </div>
          {selectedSentiment ? (
            <>
              <SentimentGauge score={selectedSentiment.score || 0} size={200} />
              <div style={{ marginTop: '12px', display: 'flex', justifyContent: 'center', gap: '16px', fontSize: '12px' }}>
                <span style={{ color: 'var(--text-secondary)' }}>
                  置信度: <span style={{ color: 'var(--accent)', fontWeight: 600 }}>{((selectedSentiment.confidence || 0) * 100).toFixed(0)}%</span>
                </span>
                <span style={{ color: 'var(--text-secondary)' }}>
                  速率: <span style={{ color: (selectedSentiment.velocity || 0) >= 0 ? 'var(--success)' : 'var(--danger)', fontWeight: 600 }}>
                    {(selectedSentiment.velocity || 0) >= 0 ? '+' : ''}{(selectedSentiment.velocity || 0).toFixed(1)}
                  </span>
                </span>
                <span style={{ color: 'var(--text-secondary)' }}>
                  异动: <span style={{ fontWeight: 600, color: (selectedSentiment.volume_spike || 0) > 1.5 ? 'var(--warning)' : 'var(--text-secondary)' }}>
                    {(selectedSentiment.volume_spike || 0).toFixed(1)}x
                  </span>
                </span>
              </div>
            </>
          ) : (
            <div style={{ padding: '40px', color: 'var(--text-secondary)' }}>请选择币种</div>
          )}
        </div>

        {/* Sparkline Card */}
        <div className="card" style={{ padding: '24px' }}>
          <h3 style={{ fontSize: '14px', fontWeight: 600, marginBottom: '8px', display: 'flex', alignItems: 'center', gap: '8px' }}>
            <i className="fas fa-chart-line" style={{ color: '#9c78ff' }}></i>
            24小时情绪走势
            {selectedSymbol && <span style={{ color: '#9c78ff', fontSize: '12px' }}>({selectedSymbol})</span>}
          </h3>
          <div style={{ marginTop: '16px' }}>
            <SentimentSparkline
              data={historyData}
              width={340}
              height={100}
              color={selectedSentiment ? getGaugeColor(selectedSentiment.score || 0) : '#9c78ff'}
            />
          </div>
          {historyData.length > 0 && (
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '8px', fontSize: '11px', color: 'var(--text-secondary)' }}>
              <span>{new Date(historyData[0].timestamp).toLocaleTimeString()}</span>
              <span>{new Date(historyData[historyData.length - 1].timestamp).toLocaleTimeString()}</span>
            </div>
          )}
          {selectedSentiment && (
            <div style={{ marginTop: '16px', display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '8px' }}>
              <div style={{ background: 'var(--bg-secondary)', padding: '10px', borderRadius: '6px', textAlign: 'center' }}>
                <div style={{ fontSize: '10px', color: 'var(--text-secondary)', marginBottom: '2px' }}>24h 最高</div>
                <div style={{ fontSize: '16px', fontWeight: 700, color: '#00e676' }}>
                  {Math.max(...historyData.map(h => h.score || 0), selectedSentiment.score || 0)}
                </div>
              </div>
              <div style={{ background: 'var(--bg-secondary)', padding: '10px', borderRadius: '6px', textAlign: 'center' }}>
                <div style={{ fontSize: '10px', color: 'var(--text-secondary)', marginBottom: '2px' }}>24h 最低</div>
                <div style={{ fontSize: '16px', fontWeight: 700, color: '#ff1744' }}>
                  {Math.min(...historyData.map(h => h.score || 0), selectedSentiment.score || 0)}
                </div>
              </div>
              <div style={{ background: 'var(--bg-secondary)', padding: '10px', borderRadius: '6px', textAlign: 'center' }}>
                <div style={{ fontSize: '10px', color: 'var(--text-secondary)', marginBottom: '2px' }}>24h 均值</div>
                <div style={{ fontSize: '16px', fontWeight: 700, color: '#9c78ff' }}>
                  {historyData.length > 0
                    ? (historyData.reduce((a, h) => a + (h.score || 0), 0) / historyData.length).toFixed(0)
                    : (selectedSentiment.score || 0)}
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* ===================== 3. Multi-Symbol Sentiment Dashboard ===================== */}
      <h3 style={{ fontSize: '14px', fontWeight: 600, marginBottom: '12px', display: 'flex', alignItems: 'center', gap: '8px' }}>
        <i className="fas fa-th-large" style={{ color: '#9c78ff' }}></i>
        多币种情绪看板
      </h3>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: '16px', marginBottom: '24px' }}>
        {sentiments.map((s) => {
          const levelCfg = sentimentLevelConfig[s.level] || sentimentLevelConfig.neutral;
          const gaugeColor = getGaugeColor(s.score || 0);
          const velocityDir = (s.velocity || 0) >= 0 ? 'up' : 'down';
          return (
            <div key={s.symbol} className="card" style={{ padding: '20px', borderLeft: '3px solid ' + levelCfg.color, cursor: 'pointer' }} onClick={() => setSelectedSymbol(s.symbol)}>
              {/* Symbol Header */}
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '14px' }}>
                <span style={{ fontWeight: 700, fontSize: '18px' }}>{s.symbol}</span>
                <span style={{
                  background: levelCfg.color + '22',
                  color: levelCfg.color,
                  padding: '4px 10px',
                  borderRadius: '12px',
                  fontSize: '12px',
                  fontWeight: 600,
                  display: 'flex',
                  alignItems: 'center',
                  gap: '6px',
                }}>
                  <i className={'fas ' + levelCfg.icon}></i>
                  {levelCfg.label}
                </span>
              </div>

              {/* Sentiment Score Bar */}
              <div style={{ marginBottom: '14px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: '6px' }}>
                  <span style={{ fontSize: '12px', color: 'var(--text-secondary)' }}>情绪评分</span>
                  <span style={{ fontSize: '24px', fontWeight: 700, color: gaugeColor }}>{s.score || 0}</span>
                </div>
                <div style={{ height: '8px', background: 'var(--bg-secondary)', borderRadius: '4px', overflow: 'hidden' }}>
                  <div style={{
                    height: '100%',
                    width: (s.score || 0) + '%',
                    background: 'linear-gradient(90deg, #ff1744, #ff6d00, #ffc400, #00e676, #00bfa5)',
                    borderRadius: '4px',
                    transition: 'width 0.5s ease',
                  }}></div>
                </div>
              </div>

              {/* Velocity, Volume Spike, Whale */}
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '8px', marginBottom: '12px' }}>
                <div style={{ background: 'var(--bg-secondary)', padding: '8px', borderRadius: '6px', textAlign: 'center' }}>
                  <div style={{ fontSize: '10px', color: 'var(--text-secondary)', marginBottom: '2px' }}>变化速率</div>
                  <div style={{ fontSize: '14px', fontWeight: 600, color: (s.velocity || 0) >= 0 ? 'var(--success)' : 'var(--danger)', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '4px' }}>
                    <i className={'fas ' + (velocityDir === 'up' ? 'fa-arrow-up' : 'fa-arrow-down')} style={{ fontSize: '10px' }}></i>
                    {(s.velocity || 0) >= 0 ? '+' : ''}{(s.velocity || 0).toFixed(1)}
                  </div>
                </div>
                <div style={{ background: 'var(--bg-secondary)', padding: '8px', borderRadius: '6px', textAlign: 'center' }}>
                  <div style={{ fontSize: '10px', color: 'var(--text-secondary)', marginBottom: '2px' }}>成交量异动</div>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '4px' }}>
                    <span style={{ fontSize: '14px', fontWeight: 600, color: (s.volume_spike || 0) > 1.5 ? 'var(--warning)' : 'var(--text-secondary)' }}>
                      {(s.volume_spike || 0).toFixed(1)}x
                    </span>
                    {(s.volume_spike || 0) > 1.5 && (
                      <span style={{
                        background: 'rgba(255,196,0,0.15)', color: 'var(--warning)',
                        padding: '1px 5px', borderRadius: '4px', fontSize: '9px', fontWeight: 700,
                      }}>
                        异动
                      </span>
                    )}
                  </div>
                </div>
                <div style={{ background: 'var(--bg-secondary)', padding: '8px', borderRadius: '6px', textAlign: 'center' }}>
                  <div style={{ fontSize: '10px', color: 'var(--text-secondary)', marginBottom: '2px' }}>鲸鱼信号</div>
                  <div style={{ fontSize: '14px' }}>
                    {s.whale_signal ? (
                      <span style={{ fontWeight: 600, color: s.whale_signal.includes('accumulation') ? 'var(--success)' : 'var(--danger)' }}>
                        {'🐋'} {s.whale_signal === 'whale_accumulation' ? '吸筹' : s.whale_signal === 'whale_distribution' ? '派发' : '活跃'}
                      </span>
                    ) : (
                      <span style={{ color: 'var(--text-secondary)' }}>--</span>
                    )}
                  </div>
                </div>
              </div>

              {/* Keywords */}
              {s.top_keywords && s.top_keywords.length > 0 && (
                <div>
                  <div style={{ fontSize: '10px', color: 'var(--text-secondary)', marginBottom: '6px' }}>热门关键词</div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px' }}>
                    {s.top_keywords.slice(0, 6).map((kw, i) => (
                      <span key={i} style={{
                        background: 'var(--bg-secondary)',
                        color: 'var(--text-secondary)',
                        padding: '2px 8px',
                        borderRadius: '4px',
                        fontSize: '11px',
                      }}>
                        {kw}
                      </span>
                    ))}
                  </div>
                </div>
              )}
            </div>
          );
        })}
        {sentiments.length === 0 && (
          <div className="card" style={{ padding: '40px', textAlign: 'center', gridColumn: '1 / -1' }}>
            <i className="fas fa-moon" style={{ fontSize: '32px', color: 'var(--text-secondary)', marginBottom: '12px' }}></i>
            <div style={{ color: 'var(--text-secondary)' }}>暂无情绪数据，点击 "手动采集" 采集</div>
          </div>
        )}
      </div>

      {/* ===================== 4. Signal History Table ===================== */}
      <h3 style={{ fontSize: '14px', fontWeight: 600, marginBottom: '12px', display: 'flex', alignItems: 'center', gap: '8px' }}>
        <i className="fas fa-bolt" style={{ color: '#ffc400' }}></i>
        信号历史
      </h3>
      <div className="card" style={{ marginBottom: '24px', overflow: 'auto', maxHeight: '400px' }}>
        <table>
          <thead>
            <tr>
              <th>时间</th>
              <th>币种</th>
              <th>动作</th>
              <th>情绪评分</th>
              <th>置信度</th>
              <th>原因</th>
            </tr>
          </thead>
          <tbody>
            {signals.map((sig, i) => {
              const actColor = actionColors[sig.action] || 'var(--text-secondary)';
              const actLabel = sig.action === 'strong_buy' ? '强烈买入' :
                sig.action === 'strong_sell' ? '强烈卖出' :
                sig.action === 'buy' || sig.action === 'BUY' ? '买入' :
                sig.action === 'sell' || sig.action === 'SELL' ? '卖出' :
                sig.action === 'hold' ? '持有' : sig.action;
              return (
                <tr key={sig.id || i}>
                  <td style={{ fontSize: '12px', whiteSpace: 'nowrap' }}>
                    {sig.timestamp ? new Date(sig.timestamp).toLocaleString() : 'N/A'}
                  </td>
                  <td style={{ fontWeight: 600 }}>{sig.symbol}</td>
                  <td>
                    <span style={{
                      background: actColor + '22',
                      color: actColor,
                      padding: '3px 12px',
                      borderRadius: '4px',
                      fontSize: '11px',
                      fontWeight: 700,
                      letterSpacing: '0.5px',
                    }}>
                      {actLabel}
                    </span>
                  </td>
                  <td>
                    <span style={{ color: getGaugeColor(sig.sentiment_score || 50), fontWeight: 600 }}>
                      {sig.sentiment_score || 'N/A'}
                    </span>
                  </td>
                  <td>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                      <div style={{ width: '40px', height: '4px', background: 'var(--bg-secondary)', borderRadius: '2px', overflow: 'hidden' }}>
                        <div style={{ width: ((sig.confidence || 0) * 100) + '%', height: '100%', background: 'var(--accent)', borderRadius: '2px' }}></div>
                      </div>
                      <span style={{ fontSize: '12px', color: 'var(--accent)' }}>{((sig.confidence || 0) * 100).toFixed(0)}%</span>
                    </div>
                  </td>
                  <td style={{ fontSize: '12px', maxWidth: '300px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {sig.reason || sig.rationale || '-'}
                  </td>
                </tr>
              );
            })}
            {signals.length === 0 && (
              <tr>
                <td colSpan="6" style={{ textAlign: 'center', color: 'var(--text-secondary)', padding: '40px' }}>
                  暂无交易信号
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      {/* ===================== 5. Profitability Analysis + Strategy Config ===================== */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
        {/* Profitability Analysis Card */}
        <div className="card">
          <h3 style={{ fontSize: '14px', fontWeight: 600, marginBottom: '16px', display: 'flex', alignItems: 'center', gap: '8px' }}>
            <i className="fas fa-chart-pie" style={{ color: '#00e676' }}></i>
            盈利能力分析
          </h3>

          {/* Key Profitability Metrics */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '8px', marginBottom: '16px' }}>
            <div style={{ background: 'var(--bg-secondary)', padding: '12px', borderRadius: '6px', textAlign: 'center' }}>
              <div style={{ fontSize: '10px', color: 'var(--text-secondary)', marginBottom: '4px' }}>胜率</div>
              <div style={{ fontSize: '18px', fontWeight: 700, color: 'var(--success)' }}>
                {((profitability.win_rate || 0.62) * 100).toFixed(0)}%
              </div>
            </div>
            <div style={{ background: 'var(--bg-secondary)', padding: '12px', borderRadius: '6px', textAlign: 'center' }}>
              <div style={{ fontSize: '10px', color: 'var(--text-secondary)', marginBottom: '4px' }}>总盈亏</div>
              <div style={{ fontSize: '18px', fontWeight: 700, color: (profitability.total_pnl || 0) >= 0 ? 'var(--success)' : 'var(--danger)' }}>
                {(profitability.total_pnl || 0) >= 0 ? '+' : ''}{((profitability.total_pnl || 0)).toFixed(2)}
              </div>
            </div>
            <div style={{ background: 'var(--bg-secondary)', padding: '12px', borderRadius: '6px', textAlign: 'center' }}>
              <div style={{ fontSize: '10px', color: 'var(--text-secondary)', marginBottom: '4px' }}>平均盈亏</div>
              <div style={{ fontSize: '18px', fontWeight: 700, color: (profitability.avg_trade_pnl || 0) >= 0 ? 'var(--success)' : 'var(--danger)' }}>
                {(profitability.avg_trade_pnl || 0) >= 0 ? '+' : ''}{((profitability.avg_trade_pnl || 0)).toFixed(2)}
              </div>
            </div>
          </div>

          {/* Edge Sources */}
          <div style={{ marginBottom: '16px' }}>
            <div style={{ fontSize: '11px', color: 'var(--text-secondary)', textTransform: 'uppercase', marginBottom: '8px' }}>边际来源</div>
            {(profitability.edge_sources || []).length > 0 ? (
              (profitability.edge_sources || []).map((edge, i) => (
                <div key={i} style={{
                  display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                  padding: '8px 12px', background: 'var(--bg-secondary)', borderRadius: '6px',
                  marginBottom: '6px',
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                    <i className={'fas ' + (edge.icon || 'fa-circle-check')} style={{ color: '#9c78ff', fontSize: '12px' }}></i>
                    <span style={{ fontSize: '13px' }}>{edge.name || edge.source}</span>
                  </div>
                  <span style={{ fontSize: '13px', fontWeight: 600, color: (edge.edge || 0) > 0 ? 'var(--success)' : 'var(--danger)' }}>
                    {(edge.edge || 0) > 0 ? '+' : ''}{((edge.edge || 0) * 100).toFixed(1)}%
                  </span>
                </div>
              ))
            ) : (
              <div style={{ padding: '12px', background: 'var(--bg-secondary)', borderRadius: '6px', fontSize: '13px', color: 'var(--text-secondary)' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '6px' }}>
                  <span><i className="fas fa-backward mr-2" style={{ color: '#9c78ff' }}></i>逆向策略 (极端情绪反转)</span>
                  <span style={{ color: 'var(--success)', fontWeight: 600 }}>+3.2%</span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '6px' }}>
                  <span><i className="fas fa-forward mr-2" style={{ color: '#9c78ff' }}></i>动量策略 (趋势跟随)</span>
                  <span style={{ color: 'var(--success)', fontWeight: 600 }}>+1.8%</span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '6px' }}>
                  <span><i className="fas fa-fish mr-2" style={{ color: '#9c78ff' }}></i>鲸鱼跟踪 (大户跟随)</span>
                  <span style={{ color: 'var(--success)', fontWeight: 600 }}>+2.4%</span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <span><i className="fas fa-chart-bar mr-2" style={{ color: '#9c78ff' }}></i>成交量异动 (异常放大)</span>
                  <span style={{ color: 'var(--success)', fontWeight: 600 }}>+1.5%</span>
                </div>
              </div>
            )}
          </div>

          {/* Expected Returns */}
          <div style={{ marginBottom: '16px' }}>
            <div style={{ fontSize: '11px', color: 'var(--text-secondary)', textTransform: 'uppercase', marginBottom: '8px' }}>理论预期收益</div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
              <div style={{ background: 'var(--bg-secondary)', padding: '12px', borderRadius: '6px', textAlign: 'center' }}>
                <div style={{ fontSize: '10px', color: 'var(--text-secondary)', marginBottom: '4px' }}>月预期</div>
                <div style={{ fontSize: '18px', fontWeight: 700, color: 'var(--success)' }}>
                  +{((profitability.expected_monthly || 0.08) * 100).toFixed(1)}%
                </div>
              </div>
              <div style={{ background: 'var(--bg-secondary)', padding: '12px', borderRadius: '6px', textAlign: 'center' }}>
                <div style={{ fontSize: '10px', color: 'var(--text-secondary)', marginBottom: '4px' }}>年预期</div>
                <div style={{ fontSize: '18px', fontWeight: 700, color: 'var(--success)' }}>
                  +{((profitability.expected_annual || 0.96) * 100).toFixed(0)}%
                </div>
              </div>
            </div>
          </div>

          {/* Risk Factors */}
          <div>
            <div style={{ fontSize: '11px', color: 'var(--text-secondary)', textTransform: 'uppercase', marginBottom: '8px' }}>风险因素</div>
            {(profitability.risk_factors || []).length > 0 ? (
              (profitability.risk_factors || []).map((risk, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: '8px', padding: '6px 0', fontSize: '12px' }}>
                  <i className="fas fa-triangle-exclamation" style={{ color: 'var(--warning)', marginTop: '2px', fontSize: '10px' }}></i>
                  <span style={{ color: 'var(--text-secondary)' }}>{risk.description || risk}</span>
                </div>
              ))
            ) : (
              <div style={{ fontSize: '12px', color: 'var(--text-secondary)' }}>
                <div style={{ display: 'flex', alignItems: 'flex-start', gap: '8px', padding: '4px 0' }}>
                  <i className="fas fa-triangle-exclamation" style={{ color: 'var(--warning)', marginTop: '2px', fontSize: '10px' }}></i>
                  情绪数据延迟或操控风险
                </div>
                <div style={{ display: 'flex', alignItems: 'flex-start', gap: '8px', padding: '4px 0' }}>
                  <i className="fas fa-triangle-exclamation" style={{ color: 'var(--warning)', marginTop: '2px', fontSize: '10px' }}></i>
                  极端行情下逆向策略可能失效
                </div>
                <div style={{ display: 'flex', alignItems: 'flex-start', gap: '8px', padding: '4px 0' }}>
                  <i className="fas fa-triangle-exclamation" style={{ color: 'var(--warning)', marginTop: '2px', fontSize: '10px' }}></i>
                  币安广场用户不代表整体市场情绪
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Strategy Configuration */}
        <div className="card">
          <h3 style={{ fontSize: '14px', fontWeight: 600, marginBottom: '16px', display: 'flex', alignItems: 'center', gap: '8px' }}>
            <i className="fas fa-sliders" style={{ color: '#9c78ff' }}></i>
            策略配置
          </h3>

          {strategy.config ? (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
              {Object.entries(strategy.config).map(function(entry) {
                var key = entry[0];
                var value = entry[1];
                return (
                  <div key={key} style={{ background: 'var(--bg-secondary)', padding: '10px 14px', borderRadius: '6px' }}>
                    <div style={{ fontSize: '10px', color: 'var(--text-secondary)', textTransform: 'uppercase', marginBottom: '4px' }}>
                      {key.replace(/_/g, ' ')}
                    </div>
                    <div style={{ fontSize: '14px', fontWeight: 600 }}>
                      {typeof value === 'boolean' ? (
                        <span style={{ color: value ? 'var(--success)' : 'var(--danger)' }}>
                          <i className={'fas ' + (value ? 'fa-toggle-on' : 'fa-toggle-off') + ' mr-1'}></i>
                          {value ? '启用' : '禁用'}
                        </span>
                      ) : typeof value === 'number' ? (
                        <span style={{ color: '#9c78ff' }}>{value}</span>
                      ) : (
                        <span>{String(value)}</span>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          ) : (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
              <div style={{ background: 'var(--bg-secondary)', padding: '10px 14px', borderRadius: '6px' }}>
                <div style={{ fontSize: '10px', color: 'var(--text-secondary)', textTransform: 'uppercase', marginBottom: '4px' }}>策略模式</div>
                <div style={{ fontSize: '14px', fontWeight: 600, color: '#9c78ff' }}>Contrarian + Momentum</div>
              </div>
              <div style={{ background: 'var(--bg-secondary)', padding: '10px 14px', borderRadius: '6px' }}>
                <div style={{ fontSize: '10px', color: 'var(--text-secondary)', textTransform: 'uppercase', marginBottom: '4px' }}>采集间隔</div>
                <div style={{ fontSize: '14px', fontWeight: 600, color: '#9c78ff' }}>300s</div>
              </div>
              <div style={{ background: 'var(--bg-secondary)', padding: '10px 14px', borderRadius: '6px' }}>
                <div style={{ fontSize: '10px', color: 'var(--text-secondary)', textTransform: 'uppercase', marginBottom: '4px' }}>逆向阈值</div>
                <div style={{ fontSize: '14px', fontWeight: 600, color: '#9c78ff' }}>Score &lt; 20 或 &gt; 80</div>
              </div>
              <div style={{ background: 'var(--bg-secondary)', padding: '10px 14px', borderRadius: '6px' }}>
                <div style={{ fontSize: '10px', color: 'var(--text-secondary)', textTransform: 'uppercase', marginBottom: '4px' }}>动量阈值</div>
                <div style={{ fontSize: '14px', fontWeight: 600, color: '#9c78ff' }}>Velocity &gt; 2.0</div>
              </div>
              <div style={{ background: 'var(--bg-secondary)', padding: '10px 14px', borderRadius: '6px' }}>
                <div style={{ fontSize: '10px', color: 'var(--text-secondary)', textTransform: 'uppercase', marginBottom: '4px' }}>鲸鱼跟随</div>
                <div style={{ fontSize: '14px', fontWeight: 600 }}>
                  <span style={{ color: 'var(--success)' }}><i className="fas fa-toggle-on mr-1"></i>启用</span>
                </div>
              </div>
              <div style={{ background: 'var(--bg-secondary)', padding: '10px 14px', borderRadius: '6px' }}>
                <div style={{ fontSize: '10px', color: 'var(--text-secondary)', textTransform: 'uppercase', marginBottom: '4px' }}>最大仓位</div>
                <div style={{ fontSize: '14px', fontWeight: 600, color: '#9c78ff' }}>10% USDT</div>
              </div>
              <div style={{ background: 'var(--bg-secondary)', padding: '10px 14px', borderRadius: '6px' }}>
                <div style={{ fontSize: '10px', color: 'var(--text-secondary)', textTransform: 'uppercase', marginBottom: '4px' }}>置信度门槛</div>
                <div style={{ fontSize: '14px', fontWeight: 600, color: '#9c78ff' }}>60%</div>
              </div>
              <div style={{ background: 'var(--bg-secondary)', padding: '10px 14px', borderRadius: '6px' }}>
                <div style={{ fontSize: '10px', color: 'var(--text-secondary)', textTransform: 'uppercase', marginBottom: '4px' }}>止损比例</div>
                <div style={{ fontSize: '14px', fontWeight: 600, color: '#9c78ff' }}>-3%</div>
              </div>
            </div>
          )}

          <div style={{ marginTop: '16px', padding: '12px', background: 'rgba(156,120,255,0.08)', borderRadius: '8px', fontSize: '12px' }}>
            <i className="fas fa-circle-info mr-2" style={{ color: '#9c78ff' }}></i>
            <strong>策略说明:</strong> 当情绪极度恐惧时逆向买入（逆向策略），当情绪快速上升且处于贪婪区间时顺势加仓（动量策略）。
            鲸鱼吸筹信号叠加可增强置信度。止损-3%，止盈根据情绪反转信号触发。
          </div>
        </div>
      </div>
    </div>
  );
}
// ============================================
// Main App
// ============================================
function App() {
  const [user, setUser] = useState(() => {
    try {
      const saved = localStorage.getItem('qa_user');
      return saved ? JSON.parse(saved) : null;
    } catch { return null; }
  });
  const [activeTab, setActiveTab] = useState('dashboard');

  const handleLogin = (userData) => {
    setUser(userData);
  };

  const handleLogout = () => {
    localStorage.removeItem('qa_token');
    localStorage.removeItem('qa_refresh');
    localStorage.removeItem('qa_user');
    api.token = '';
    api.refreshToken = '';
    setUser(null);
  };

  // Check token on load
  useEffect(() => {
    const token = localStorage.getItem('qa_token');
    if (token) {
      api.token = token;
      api.refreshToken = localStorage.getItem('qa_refresh') || '';
      // Verify token is still valid
      api.getSystemStatus().catch(() => {
        handleLogout();
      });
    }
  }, []);

  if (!user) {
    return <LoginScreen onLogin={handleLogin} />;
  }

  const renderContent = () => {
    switch (activeTab) {
      case 'dashboard': return <Dashboard user={user} />;
      case 'strategy': return <MAStrategyPanel user={user} />;
      case 'luna': return <LunaPanel user={user} />;
      case 'positions': return <PositionsPanel user={user} />;
      case 'risk': return <RiskPanel user={user} />;
      case 'audit': return <AuditPanel user={user} />;
      default: return <Dashboard user={user} />;
    }
  };

  return (
    <div style={{ display: 'flex', minHeight: '100vh' }}>
      <Sidebar activeTab={activeTab} setActiveTab={setActiveTab} user={user} onLogout={handleLogout} />
      <div className="main-content">
        {renderContent()}
      </div>
    </div>
  );
}

// Mount React app
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
