<script setup>
import { ref, onMounted, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  BarElement,
  Title,
  Tooltip,
  Legend,
  Filler
} from 'chart.js'
import { Line, Bar } from 'vue-chartjs'

const { t, locale } = useI18n()

ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  BarElement,
  Title,
  Tooltip,
  Legend,
  Filler
)

const activeTab = ref('dashboard')
const loading = ref(false)
const marketData = ref([])
const signals = ref([])
const backtestResults = ref(null)

const settings = ref({
  rollingWindow: 20,
  gsrUpper: 80,
  gsrLower: 45,
  zscoreThreshold: 1.5,
  initialCapital: 10000
})

const savedProfiles = ref([])
const currentProfileId = ref(null)
const showProfileForm = ref(false)
const newProfile = ref({
  name: '',
  description: ''
})

const loadProfiles = () => {
  const saved = localStorage.getItem('backtestProfiles')
  if (saved) {
    savedProfiles.value = JSON.parse(saved)
  } else {
    savedProfiles.value = [{
      id: 1,
      name: locale.value === 'zh' ? '默认配置' : 'Default',
      description: locale.value === 'zh' ? '系统默认参数' : 'System default parameters',
      settings: { rollingWindow: 20, gsrUpper: 80, gsrLower: 45, zscoreThreshold: 1.5, initialCapital: 10000 }
    }]
    saveProfilesToStorage()
  }
  const currentId = localStorage.getItem('currentProfileId')
  if (currentId) {
    currentProfileId.value = parseInt(currentId)
    const profile = savedProfiles.value.find(p => p.id === currentProfileId.value)
    if (profile) {
      settings.value = { ...profile.settings }
    }
  }
}

const saveProfilesToStorage = () => {
  localStorage.setItem('backtestProfiles', JSON.stringify(savedProfiles.value))
}

const selectProfile = (profile) => {
  currentProfileId.value = profile.id
  settings.value = { ...profile.settings }
  localStorage.setItem('currentProfileId', profile.id)
  loadData()
}

const currentProfileName = computed(() => {
  const profile = savedProfiles.value.find(p => p.id === currentProfileId.value)
  return profile?.name || (locale.value === 'zh' ? '默认配置' : 'Default')
})

const showWelcome = ref(false)
const toast = ref({ show: false, message: '', type: 'success' })

const showToast = (message, type = 'success') => {
  toast.value = { show: true, message, type }
  setTimeout(() => {
    toast.value.show = false
  }, 3000)
}

const confirmModal = ref({ show: false, message: '', onConfirm: null })

const showConfirm = (message, onConfirm) => {
  confirmModal.value = { show: true, message, onConfirm }
}

const createProfile = () => {
  const newId = Math.max(...savedProfiles.value.map(p => p.id), 0) + 1
  savedProfiles.value.push({
    id: newId,
    name: newProfile.value.name || `Profile ${newId}`,
    description: newProfile.value.description || '',
    settings: { ...settings.value }
  })
  currentProfileId.value = newId
  saveProfilesToStorage()
  localStorage.setItem('currentProfileId', newId)
  showProfileForm.value = false
  newProfile.value = { name: '', description: '' }
}

const deleteProfile = (id) => {
  if (savedProfiles.value.length <= 1) return
  savedProfiles.value = savedProfiles.value.filter(p => p.id !== id)
  if (currentProfileId.value === id) {
    currentProfileId.value = savedProfiles.value[0].id
    settings.value = { ...savedProfiles.value[0].settings }
    localStorage.setItem('currentProfileId', currentProfileId.value)
  }
  saveProfilesToStorage()
}

const updateCurrentProfile = () => {
  const idx = savedProfiles.value.findIndex(p => p.id === currentProfileId.value)
  if (idx >= 0) {
    savedProfiles.value[idx].settings = { ...settings.value }
    saveProfilesToStorage()
  }
  loadData()
}

const toggleLanguage = () => {
  locale.value = locale.value === 'en' ? 'zh' : 'en'
}

const getDefaultDates = () => {
  const end = new Date()
  const start = new Date()
  start.setMonth(start.getMonth() - 3)
  return {
    endDate: end.toISOString().split('T')[0],
    startDate: start.toISOString().split('T')[0]
  }
}

const defaultDates = getDefaultDates()

const fetchDataForm = ref({
  startDate: defaultDates.startDate,
  endDate: defaultDates.endDate
})

const priceChartData = computed(() => {
  if (marketData.value.length === 0) {
    return { labels: [], datasets: [] }
  }
  const data = marketData.value.slice(-60)
  return {
    labels: data.map(d => d.date.slice(5)),
    datasets: [
      {
        label: locale.value === 'zh' ? '黄金' : 'Gold',
        borderColor: '#F7B731',
        backgroundColor: 'rgba(247, 183, 49, 0.1)',
        data: data.map(d => d.gold),
        tension: 0.4,
        fill: true,
        pointRadius: 0,
        pointHoverRadius: 6
      },
      {
        label: locale.value === 'zh' ? '白银' : 'Silver',
        borderColor: '#A4B0BE',
        backgroundColor: 'rgba(164, 176, 190, 0.1)',
        data: data.map(d => d.silver),
        tension: 0.4,
        fill: true,
        pointRadius: 0,
        pointHoverRadius: 6
      }
    ]
  }
})

const chartOptions = {
  responsive: true,
  maintainAspectRatio: false,
  interaction: {
    intersect: false,
    mode: 'index'
  },
  plugins: {
    legend: {
      position: 'top',
      labels: {
        color: '#A4B0BE',
        usePointStyle: true,
        padding: 20,
        font: { size: 12 }
      }
    },
    tooltip: {
      backgroundColor: 'rgba(26, 26, 46, 0.9)',
      titleColor: '#F7B731',
      bodyColor: '#fff',
      borderColor: '#333',
      borderWidth: 1,
      padding: 12,
      displayColors: true
    }
  },
  scales: {
    x: {
      grid: { color: 'rgba(255,255,255,0.05)' },
      ticks: { color: '#6C757D', maxTicksLimit: 8 }
    },
    y: {
      grid: { color: 'rgba(255,255,255,0.05)' },
      ticks: { color: '#6C757D' }
    }
  }
}

const gsrChartData = computed(() => {
  if (signals.value.length === 0) {
    return { labels: [], datasets: [] }
  }
  const data = signals.value.slice(-60)
  const gsrValues = data.map(s => s.gsr)
  const colors = gsrValues.map(v => v > 80 ? '#26DE81' : v < 45 ? '#FC5C65' : '#4B7BEC')
  
  return {
    labels: data.map(s => s.date.slice(5)),
    datasets: [{
      label: locale.value === 'zh' ? '金银比' : 'GSR',
      borderColor: '#4B7BEC',
      backgroundColor: 'rgba(75, 123, 236, 0.2)',
      data: gsrValues,
      tension: 0.4,
      fill: true,
      pointRadius: 3,
      pointBackgroundColor: colors,
      pointBorderColor: colors
    }]
  }
})

const equityData = computed(() => {
  if (!backtestResults.value) return { labels: [], datasets: [] }
  return {
    labels: signals.value.slice(-30).map(s => s.date.slice(5)),
    datasets: [{
      label: locale.value === 'zh' ? '策略收益' : 'Strategy Return',
      borderColor: '#26DE81',
      backgroundColor: 'rgba(38, 222, 129, 0.1)',
      data: signals.value.slice(-30).map((_, i) => (i + 1) * (backtestResults.value.totalReturn / 30)),
      tension: 0.4,
      fill: true
    }]
  }
})

const loadData = async () => {
  loading.value = true
  try {
    const [signalsRes, dataRes, btRes] = await Promise.all([
      fetch(`/api/signals?window=${settings.value.rollingWindow}&gsrUpper=${settings.value.gsrUpper}&gsrLower=${settings.value.gsrLower}`),
      fetch(`/api/data`),
      fetch(`/api/backtest?window=${settings.value.rollingWindow}&gsrUpper=${settings.value.gsrUpper}&gsrLower=${settings.value.gsrLower}&capital=${settings.value.initialCapital}`)
    ])
    signals.value = (await signalsRes.json()).signals || []
    marketData.value = (await dataRes.json()).data || []
    backtestResults.value = await btRes.json()
  } catch (e) {
    console.error(e)
  }
  loading.value = false
}

const fetchMarketData = async () => {
  loading.value = true
  try {
    const res = await fetch(`/api/fetch?start=${fetchDataForm.value.startDate}&end=${fetchDataForm.value.endDate}`)
    const data = await res.json()
      showToast(data.message || data.error, data.message ? 'success' : 'error')
      loadData()
    } catch (e) {
      showToast('Error: ' + e.message, 'error')
    }
    loading.value = false
  }

const runBacktest = async () => {
  loading.value = true
  try {
    const res = await fetch(`/api/backtest?window=${settings.value.rollingWindow}&gsrUpper=${settings.value.gsrUpper}&gsrLower=${settings.value.gsrLower}&capital=${settings.value.initialCapital}`)
    backtestResults.value = await res.json()
  } catch (e) {
    console.error(e)
  }
  loading.value = false
}

const saveSettings = () => {
  updateCurrentProfile()
  showToast(locale.value === 'zh' ? '配置已保存,正在重新计算...' : 'Settings saved! Recalculating...')
}

const clearData = async () => {
  showConfirm(locale.value === 'zh' ? '确定要清除所有数据吗?' : 'Are you sure you want to clear all data?', async () => {
    loading.value = true
    try {
      const res = await fetch(`/api/clear`)
      const data = await res.json()
      showToast(data.message || data.error, data.message ? 'success' : 'error')
      marketData.value = []
      signals.value = []
      backtestResults.value = null
    } catch (e) {
      showToast('Error: ' + e.message, 'error')
    }
    loading.value = false
  })
}

onMounted(() => {
  loadProfiles()
  loadData()
  const visited = localStorage.getItem('hasVisited')
  if (!visited) {
    showWelcome.value = true
    localStorage.setItem('hasVisited', 'true')
  }
})
</script>

<template>
  <div class="app-container">
    <div v-if="toast.show" class="toast" :class="toast.type">
      {{ toast.message }}
    </div>

    <div v-if="confirmModal.show" class="confirm-overlay">
      <div class="confirm-modal">
        <p>{{ confirmModal.message }}</p>
        <div class="confirm-actions">
          <button class="btn-secondary" @click="confirmModal.show = false">
            {{ locale === 'zh' ? '取消' : 'Cancel' }}
          </button>
          <button class="btn-primary" @click="confirmModal.onConfirm(); confirmModal.show = false">
            {{ locale === 'zh' ? '确定' : 'Confirm' }}
          </button>
        </div>
      </div>
    </div>

    <aside class="sidebar">
      <div class="logo">
        <div class="logo-icon">💰</div>
        <h2>GoldQuant</h2>
        <span class="tagline">{{ locale === 'zh' ? '量化交易系统' : 'Quant Trading System' }}</span>
      </div>
      
      <nav>
        <a :class="{ active: activeTab === 'dashboard' }" @click="activeTab = 'dashboard'">
          <span class="nav-icon">📊</span>
          <span class="nav-text">{{ t('nav.dashboard') }}</span>
        </a>
        <a :class="{ active: activeTab === 'data' }" @click="activeTab = 'data'">
          <span class="nav-icon">📁</span>
          <span class="nav-text">{{ t('nav.data') }}</span>
        </a>
        <a :class="{ active: activeTab === 'signals' }" @click="activeTab = 'signals'">
          <span class="nav-icon">📈</span>
          <span class="nav-text">{{ t('nav.signals') }}</span>
        </a>
        <a :class="{ active: activeTab === 'backtest' }" @click="activeTab = 'backtest'">
          <span class="nav-icon">🧪</span>
          <span class="nav-text">{{ t('nav.backtest') }}</span>
        </a>
        <a :class="{ active: activeTab === 'settings' }" @click="activeTab = 'settings'">
          <span class="nav-icon">⚙️</span>
          <span class="nav-text">{{ t('nav.settings') }}</span>
        </a>
        <a :class="{ active: activeTab === 'docs' }" @click="activeTab = 'docs'">
          <span class="nav-icon">📖</span>
          <span class="nav-text">{{ locale === 'zh' ? '系统说明' : 'Documentation' }}</span>
        </a>
      </nav>

      <div class="sidebar-footer">
        <button class="lang-btn" @click="toggleLanguage">
          <span class="lang-icon">🌐</span>
          {{ locale === 'en' ? '中文' : 'EN' }}
        </button>
      </div>
    </aside>

    <main class="main-content">
      <div class="license-banner">
        <span>{{ locale === 'zh' ? '授权有效期至 2026年5月5日' : 'License valid until May 5, 2026' }}</span>
        <span class="contact">{{ locale === 'zh' ? '如需续期或功能定制请联系: Geliebte' : 'For renewal or customization: Geliebte' }}</span>
      </div>

      <div v-if="showWelcome" class="welcome-modal">
        <div class="welcome-content">
          <h2>{{ locale === 'zh' ? '欢迎使用黄金量化交易系统' : 'Welcome to Gold Quant Trading System' }}</h2>
          <p>{{ locale === 'zh' ? '在使用前,请先阅读系统说明并配置合适的策略参数' : 'Please read the documentation and configure strategy parameters before use' }}</p>
          <div class="welcome-actions">
            <button class="btn-primary" @click="activeTab = 'docs'; showWelcome = false">
              {{ locale === 'zh' ? '查看系统说明' : 'View Documentation' }}
            </button>
            <button class="btn-secondary" @click="activeTab = 'settings'; showWelcome = false">
              {{ locale === 'zh' ? '配置策略参数' : 'Configure Settings' }}
            </button>
          </div>
        </div>
      </div>

      <div v-if="activeTab === 'dashboard'" class="dashboard">
        <div class="profile-header-bar">
          <span class="profile-label">{{ locale === 'zh' ? '当前策略' : 'Current Strategy' }}:</span>
          <span class="profile-name">{{ currentProfileName }}</span>
          <span class="profile-params">
            GSR: {{ settings.gsrLower }}-{{ settings.gsrUpper }} | 
            Window: {{ settings.rollingWindow }} | 
            Capital: ${{ settings.initialCapital?.toLocaleString() }}
          </span>
        </div>

        <div class="page-header">
          <h1>{{ t('dashboard.title') }}</h1>
          <p class="subtitle">{{ locale === 'zh' ? '黄金/白银交易策略分析' : 'Gold/Silver Trading Strategy Analysis' }}</p>
        </div>

        <div class="stats-grid">
          <div class="stat-card premium">
            <div class="stat-icon">📈</div>
            <div class="stat-content">
              <span class="stat-label">{{ t('dashboard.totalReturn') }}</span>
              <span class="stat-value" :class="{ positive: backtestResults?.totalReturn > 0, negative: backtestResults?.totalReturn < 0 }">
                {{ backtestResults?.totalReturn?.toFixed(2) || '0.00' }}%
              </span>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon">⚡</div>
            <div class="stat-content">
              <span class="stat-label">{{ t('dashboard.sharpeRatio') }}</span>
              <span class="stat-value">{{ backtestResults?.sharpeRatio?.toFixed(2) || '0.00' }}</span>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon">📉</div>
            <div class="stat-content">
              <span class="stat-label">{{ t('dashboard.maxDrawdown') }}</span>
              <span class="stat-value negative">-{{ (backtestResults?.maxDrawdown * 100)?.toFixed(2) || '0.00' }}%</span>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon">🎯</div>
            <div class="stat-content">
              <span class="stat-label">{{ t('dashboard.winRate') }}</span>
              <span class="stat-value">{{ (backtestResults?.winRate * 100)?.toFixed(0) || '0' }}%</span>
            </div>
          </div>
        </div>

        <div class="charts-grid">
          <div class="chart-card">
            <div class="chart-header">
              <h3>{{ t('dashboard.goldSilverPrices') }}</h3>
              <span class="chart-tag">{{ locale === 'zh' ? '美元/盎司' : 'USD/oz' }}</span>
            </div>
            <div class="chart-wrapper">
              <Line :data="priceChartData" :options="chartOptions" />
            </div>
          </div>

          <div class="chart-card">
            <div class="chart-header">
              <h3>{{ t('dashboard.gsr') }}</h3>
              <div class="chart-legend">
                <span class="legend-item"><span class="dot green"></span>>80</span>
                <span class="legend-item"><span class="dot red"></span><45</span>
              </div>
            </div>
            <div class="chart-wrapper">
              <Line :data="gsrChartData" :options="chartOptions" />
            </div>
          </div>
        </div>

        <div class="recent-signals">
          <h3>{{ locale === 'zh' ? '最近信号' : 'Recent Signals' }}</h3>
          <div class="signals-table">
            <div class="table-header">
              <span>{{ t('data.date') }}</span>
              <span>{{ t('data.gsr') }}</span>
              <span>Z-Score</span>
              <span>{{ t('data.regime') }}</span>
              <span>{{ t('data.position') }}</span>
            </div>
            <div class="table-body">
              <div v-for="(sig, i) in signals.slice(-5).reverse()" :key="i" class="table-row">
                <span class="date">{{ sig.date }}</span>
                <span class="gsr">{{ sig.gsr?.toFixed(1) }}</span>
                <span class="zscore" :class="{ high: Math.abs(sig.spreadZScore) > 1 }">{{ sig.spreadZScore?.toFixed(2) }}</span>
                <span class="regime" :class="sig.regime === 0 ? 'low' : 'high'">{{ sig.regime === 0 ? t('data.lowVol') : t('data.highVol') }}</span>
                <span class="position" :class="sig.position">{{ t('positions.' + sig.position) }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div v-if="activeTab === 'data'" class="data-page">
        <div class="profile-header-bar">
          <span class="profile-label">{{ locale === 'zh' ? '当前策略' : 'Current Strategy' }}:</span>
          <span class="profile-name">{{ currentProfileName }}</span>
          <span class="profile-params">
            GSR: {{ settings.gsrLower }}-{{ settings.gsrUpper }} | 
            Window: {{ settings.rollingWindow }} | 
            Capital: ${{ settings.initialCapital?.toLocaleString() }}
          </span>
        </div>

        <div class="page-header">
          <h1>{{ t('data.title') }}</h1>
        </div>

        <div class="fetch-card">
          <h3>{{ locale === 'zh' ? '获取真实市场数据' : 'Fetch Real Market Data' }}</h3>
          <p class="fetch-desc">{{ locale === 'zh' ? '从Yahoo Finance获取黄金(GC=F)和白银(SI=F)的真实历史数据' : 'Fetch real historical data for Gold (GC=F) and Silver (SI=F) from Yahoo Finance' }}</p>
          <div class="form-grid">
            <div class="form-group">
              <label>{{ t('data.startDate') }}</label>
              <input type="date" v-model="fetchDataForm.startDate" />
            </div>
            <div class="form-group">
              <label>{{ t('data.endDate') }}</label>
              <input type="date" v-model="fetchDataForm.endDate" />
            </div>
            <button class="btn-primary" @click="fetchMarketData" :disabled="loading">
              <span v-if="loading" class="spinner"></span>
              {{ loading ? (locale === 'zh' ? '获取中...' : 'Fetching...') : (locale === 'zh' ? '获取数据' : 'Fetch Data') }}
            </button>
            <button class="btn-danger" @click="clearData" :disabled="loading">
              {{ locale === 'zh' ? '清除所有数据' : 'Clear All Data' }}
            </button>
          </div>
        </div>

        <div class="data-table-card">
          <div class="table-header-bar">
            <h3>{{ t('data.availableData') }}</h3>
            <span class="record-count">{{ signals.length }} {{ locale === 'zh' ? '条记录' : 'records' }}</span>
          </div>
          <div class="table-container">
            <table>
              <thead>
                <tr>
                  <th>{{ t('data.date') }}</th>
                  <th>{{ t('data.gold') }}</th>
                  <th>{{ t('data.silver') }}</th>
                  <th>{{ t('data.gsr') }}</th>
                  <th>{{ t('data.regime') }}</th>
                  <th>{{ t('data.position') }}</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(sig, i) in signals.slice(0, 20)" :key="i">
                  <td>{{ sig.date }}</td>
                  <td class="price">${{ marketData[i]?.gold?.toFixed(2) }}</td>
                  <td class="price">${{ marketData[i]?.silver?.toFixed(2) }}</td>
                  <td class="gsr" :class="{ high: sig.gsr > 80, low: sig.gsr < 45 }">{{ sig.gsr?.toFixed(1) }}</td>
                  <td><span class="badge" :class="sig.regime === 0 ? 'low' : 'high'">{{ sig.regime === 0 ? t('data.lowVol') : t('data.highVol') }}</span></td>
                  <td><span class="position-tag" :class="sig.position">{{ t('positions.' + sig.position) }}</span></td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <div v-if="activeTab === 'signals'" class="signals-page">
        <div class="profile-header-bar">
          <span class="profile-label">{{ locale === 'zh' ? '当前策略' : 'Current Strategy' }}:</span>
          <span class="profile-name">{{ currentProfileName }}</span>
          <span class="profile-params">
            GSR: {{ settings.gsrLower }}-{{ settings.gsrUpper }} | 
            Window: {{ settings.rollingWindow }} | 
            Capital: ${{ settings.initialCapital?.toLocaleString() }}
          </span>
        </div>

        <div class="page-header">
          <h1>{{ t('signals.title') }}</h1>
        </div>

        <div class="signals-grid">
          <div v-for="(sig, i) in signals.slice(-15).reverse()" :key="i" class="signal-card" :class="sig.position">
            <div class="signal-header">
              <span class="signal-date">{{ sig.date }}</span>
              <span class="signal-badge" :class="sig.position">{{ t('positions.' + sig.position) }}</span>
            </div>
            <div class="signal-body">
              <div class="signal-metric">
                <span class="metric-label">GSR</span>
                <span class="metric-value">{{ sig.gsr?.toFixed(1) }}</span>
              </div>
              <div class="signal-metric">
                <span class="metric-label">Z-Score</span>
                <span class="metric-value">{{ sig.spreadZScore?.toFixed(2) }}</span>
              </div>
              <div class="signal-metric">
                <span class="metric-label">{{ t('data.regime') }}</span>
                <span class="metric-value">{{ sig.regime === 0 ? t('data.lowVol') : t('data.highVol') }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div v-if="activeTab === 'backtest'" class="backtest-page">
        <div class="profile-header-bar">
          <span class="profile-label">{{ locale === 'zh' ? '当前策略' : 'Current Strategy' }}:</span>
          <span class="profile-name">{{ currentProfileName }}</span>
          <span class="profile-params">
            GSR: {{ settings.gsrLower }}-{{ settings.gsrUpper }} | 
            Window: {{ settings.rollingWindow }} | 
            Capital: ${{ settings.initialCapital?.toLocaleString() }}
          </span>
        </div>

        <div class="page-header">
          <h1>{{ t('backtest.title') }}</h1>
        </div>

        <div class="backtest-actions">
          <button class="btn-primary btn-large" @click="runBacktest" :disabled="loading">
            <span v-if="loading" class="spinner"></span>
            {{ loading ? (locale === 'zh' ? '运行中...' : 'Running...') : t('backtest.run') }}
          </button>
        </div>

        <div v-if="!backtestResults" class="no-results">
          <p>{{ locale === 'zh' ? '点击"运行回测"查看策略表现' : 'Click "Run Backtest" to see strategy performance' }}</p>
        </div>

        <div v-if="backtestResults" class="results-grid">
          <div class="result-card">
            <div class="result-icon">💰</div>
            <div class="result-content">
              <span class="result-label">{{ t('dashboard.totalReturn') }}</span>
              <span class="result-value" :class="{ positive: backtestResults.totalReturn > 0, negative: backtestResults.totalReturn < 0 }">
                {{ backtestResults.totalReturn?.toFixed(2) }}%
              </span>
            </div>
          </div>
          <div class="result-card">
            <div class="result-icon">📊</div>
            <div class="result-content">
              <span class="result-label">{{ t('dashboard.sharpeRatio') }}</span>
              <span class="result-value">{{ backtestResults.sharpeRatio?.toFixed(2) }}</span>
            </div>
          </div>
          <div class="result-card">
            <div class="result-icon">📉</div>
            <div class="result-content">
              <span class="result-label">{{ t('dashboard.maxDrawdown') }}</span>
              <span class="result-value negative">-{{ (backtestResults.maxDrawdown * 100)?.toFixed(2) }}%</span>
            </div>
          </div>
          <div class="result-card">
            <div class="result-icon">🎯</div>
            <div class="result-content">
              <span class="result-label">{{ t('dashboard.winRate') }}</span>
              <span class="result-value">{{ (backtestResults.winRate * 100)?.toFixed(0) }}%</span>
            </div>
          </div>
          <div class="result-card">
            <div class="result-icon">🔢</div>
            <div class="result-content">
              <span class="result-label">{{ t('backtest.numTrades') }}</span>
              <span class="result-value">{{ backtestResults.numTrades }}</span>
            </div>
          </div>
        </div>

        <div v-if="backtestResults" class="result-details">
          <p>{{ locale === 'zh' ? '数据点' : 'Data Points' }}: {{ backtestResults.dataPoints }} | {{ locale === 'zh' ? '信号数' : 'Signals' }}: {{ backtestResults.signals }}</p>
        </div>
      </div>

      <div v-if="activeTab === 'settings'" class="settings-page">
        <div class="page-header">
          <h1>{{ t('settings.title') }}</h1>
        </div>

        <div class="profiles-section">
          <div class="profiles-header">
            <h3>{{ locale === 'zh' ? '参数配置' : 'Parameter Profiles' }}</h3>
            <button class="btn-secondary" @click="showProfileForm = true">
              {{ locale === 'zh' ? '+ 新建配置' : '+ New Profile' }}
            </button>
          </div>

          <div class="profiles-grid">
            <div 
              v-for="profile in savedProfiles" 
              :key="profile.id" 
              class="profile-card"
              :class="{ active: currentProfileId === profile.id }"
              @click="selectProfile(profile)"
            >
              <div class="profile-header">
                <span class="profile-name">{{ profile.name }}</span>
                <span v-if="currentProfileId === profile.id" class="profile-badge">{{ locale === 'zh' ? '已选中' : 'Active' }}</span>
              </div>
              <p class="profile-desc">{{ profile.description || (locale === 'zh' ? '暂无描述' : 'No description') }}</p>
              <div class="profile-params">
                <span>Window: {{ profile.settings.rollingWindow }}</span>
                <span>GSR: {{ profile.settings.gsrLower }}-{{ profile.settings.gsrUpper }}</span>
                <span>Capital: ${{ profile.settings.initialCapital?.toLocaleString() }}</span>
              </div>
              <button 
                v-if="savedProfiles.length > 1" 
                class="delete-btn"
                @click.stop="deleteProfile(profile.id)"
              >{{ locale === 'zh' ? '删除' : 'Delete' }}</button>
            </div>
          </div>

          <div v-if="showProfileForm" class="profile-form-overlay">
            <div class="profile-form">
              <h3>{{ locale === 'zh' ? '新建参数配置' : 'New Profile' }}</h3>
              <div class="form-group">
                <label>{{ locale === 'zh' ? '名称' : 'Name' }}</label>
                <input type="text" v-model="newProfile.name" :placeholder="locale === 'zh' ? '输入配置名称' : 'Enter profile name'" />
              </div>
              <div class="form-group">
                <label>{{ locale === 'zh' ? '描述' : 'Description' }}</label>
                <input type="text" v-model="newProfile.description" :placeholder="locale === 'zh' ? '输入描述(可选)' : 'Enter description (optional)'" />
              </div>
              <div class="form-actions">
                <button class="btn-secondary" @click="showProfileForm = false">{{ locale === 'zh' ? '取消' : 'Cancel' }}</button>
                <button class="btn-primary" @click="createProfile">{{ locale === 'zh' ? '创建' : 'Create' }}</button>
              </div>
            </div>
          </div>
        </div>

        <div class="settings-card">
          <h3>{{ locale === 'zh' ? '当前配置参数' : 'Current Profile Parameters' }}</h3>
          <div class="settings-form">
            <div class="form-group">
              <label>{{ t('settings.rollingWindow') }}</label>
              <input type="number" v-model="settings.rollingWindow" min="5" max="100" />
            </div>
            <div class="form-group">
              <label>{{ t('settings.gsrUpper') }}</label>
              <input type="number" v-model="settings.gsrUpper" min="50" max="120" />
            </div>
            <div class="form-group">
              <label>{{ t('settings.gsrLower') }}</label>
              <input type="number" v-model="settings.gsrLower" min="20" max="60" />
            </div>
            <div class="form-group">
              <label>{{ t('settings.zscoreThreshold') }}</label>
              <input type="number" v-model="settings.zscoreThreshold" min="0.5" max="3" step="0.1" />
            </div>
            <div class="form-group">
              <label>{{ t('settings.initialCapital') }}</label>
              <input type="number" v-model="settings.initialCapital" min="1000" step="1000" />
            </div>
            <button class="btn-primary" @click="saveSettings">
              {{ t('settings.save') }}
            </button>
          </div>
        </div>

        <div class="profiles-section">
          <div class="profiles-header">
            <h3>{{ locale === 'zh' ? '参数配置' : 'Parameter Profiles' }}</h3>
            <button class="btn-secondary" @click="showProfileForm = true">
              {{ locale === 'zh' ? '+ 新建配置' : '+ New Profile' }}
            </button>
          </div>

          <div class="profiles-grid">
            <div 
              v-for="profile in savedProfiles" 
              :key="profile.id" 
              class="profile-card"
              :class="{ active: currentProfileId === profile.id }"
              @click="selectProfile(profile)"
            >
              <div class="profile-header">
                <span class="profile-name">{{ profile.name }}</span>
                <span v-if="currentProfileId === profile.id" class="profile-badge">{{ locale === 'zh' ? '已选中' : 'Active' }}</span>
              </div>
              <p class="profile-desc">{{ profile.description || (locale === 'zh' ? '暂无描述' : 'No description') }}</p>
              <div class="profile-params">
                <span>Window: {{ profile.settings.rollingWindow }}</span>
                <span>GSR: {{ profile.settings.gsrLower }}-{{ profile.settings.gsrUpper }}</span>
                <span>Capital: ${{ profile.settings.initialCapital?.toLocaleString() }}</span>
              </div>
              <button 
                v-if="savedProfiles.length > 1" 
                class="delete-btn"
                @click.stop="deleteProfile(profile.id)"
              >{{ locale === 'zh' ? '删除' : 'Delete' }}</button>
            </div>
          </div>
        </div>
      </div>

      <div v-if="activeTab === 'docs'" class="docs-page">
        <div class="page-header">
          <h1>{{ locale === 'zh' ? '系统说明' : 'Documentation' }}</h1>
          <p class="subtitle">{{ locale === 'zh' ? '了解黄金/白银量化交易系统的工作原理' : 'Understanding the Gold/Silver Quant Trading System' }}</p>
        </div>

        <div class="docs-section">
          <h2>{{ locale === 'zh' ? '系统架构' : 'System Architecture' }}</h2>
          <div class="architecture-diagram">
            <div class="arch-layer">
              <div class="arch-box frontend">
                <div class="arch-title">{{ locale === 'zh' ? '前端 (Vue.js)' : 'Frontend (Vue.js)' }}</div>
                <div class="arch-desc">{{ locale === 'zh' ? '用户界面、图表展示、数据可视化' : 'UI, Charts, Data Visualization' }}</div>
              </div>
            </div>
            <div class="arch-arrow">↓</div>
            <div class="arch-layer">
              <div class="arch-box backend">
                <div class="arch-title">{{ locale === 'zh' ? '后端 (Go)' : 'Backend (Go)' }}</div>
                <div class="arch-desc">{{ locale === 'zh' ? 'API服务、策略计算、数据处理' : 'API, Strategy Calculation, Data Processing' }}</div>
              </div>
            </div>
            <div class="arch-arrow">↓</div>
            <div class="arch-layer">
              <div class="arch-box database">
                <div class="arch-title">{{ locale === 'zh' ? '数据库 (SQLite)' : 'Database (SQLite)' }}</div>
                <div class="arch-desc">{{ locale === 'zh' ? '市场数据存储、策略信号、历史记录' : 'Market Data, Signals, History' }}</div>
              </div>
            </div>
          </div>
        </div>

        <div class="docs-section">
          <h2>{{ locale === 'zh' ? '核心策略逻辑' : 'Core Strategy Logic' }}</h2>
          
          <div class="strategy-card">
            <div class="strategy-header">
              <span class="strategy-num">1</span>
              <h3>{{ locale === 'zh' ? '均值回归 - 价差套利' : 'Mean Reversion - Spread Arbitrage' }}</h3>
            </div>
            <p>{{ locale === 'zh' ? '基于黄金和白银价格的价差进行均值回归交易。当价差偏离均值时，做空高估品种、做多低估品种。' : 'Trade based on the spread between Gold and Silver prices. When spread deviates from mean, short overvalued and long undervalued.' }}</p>
            <div class="formula">
              <code>Z-Score = (Spread - MA{{ settings.rollingWindow }}) / StdDev(Spread, {{ settings.rollingWindow }})</code>
            </div>
            <div class="signal-rule">
              <span class="signal-cond">{{ locale === 'zh' ? '信号规则' : 'Signal Rules' }}:</span>
              <span v-if="locale === 'zh'">Z &lt; -{{ settings.zscoreThreshold }} 买入价差, Z &gt; {{ settings.zscoreThreshold }} 卖出价差</span>
              <span v-else>Z &lt; -{{ settings.zscoreThreshold }} buy spread, Z &gt; {{ settings.zscoreThreshold }} sell spread</span>
            </div>
          </div>

          <div class="strategy-card">
            <div class="strategy-header">
              <span class="strategy-num">2</span>
              <h3>{{ locale === 'zh' ? '金银比 (GSR) 阈值交易' : 'Gold-Silver Ratio (GSR) Threshold' }}</h3>
            </div>
            <p>{{ locale === 'zh' ? `当金银比高于${settings.gsrUpper}时，白银相对黄金被低估买入白银；当金银比低于${settings.gsrLower}时，黄金相对白银被低估买入黄金。` : `When GSR > ${settings.gsrUpper}, Silver is undervalued vs Gold (buy Silver). When GSR < ${settings.gsrLower}, Gold is undervalued vs Silver (buy Gold).` }}</p>
            <div class="formula">
              <code>GSR = Gold Price / Silver Price</code>
            </div>
            <div class="signal-rule">
              <span class="signal-cond">{{ locale === 'zh' ? '信号规则' : 'Signal Rules' }}:</span>
              <span v-if="locale === 'zh'">GSR &gt; {{ settings.gsrUpper }}: 买白银卖黄金, GSR &lt; {{ settings.gsrLower }}: 买黄金卖白银</span>
              <span v-else>GSR &gt; {{ settings.gsrUpper }}: buy Silver/sell Gold, GSR &lt; {{ settings.gsrLower }}: buy Gold/sell Silver</span>
            </div>
          </div>

          <div class="strategy-card">
            <div class="strategy-header">
              <span class="strategy-num">3</span>
              <h3>{{ locale === 'zh' ? '市场状态检测 (隐马尔可夫模型)' : 'Market Regime Detection (HMM)' }}</h3>
            </div>
            <p>{{ locale === 'zh' ? '使用隐马尔可夫模型检测市场波动状态。在高波动状态下减少仓位或保持空仓，降低风险。' : 'Use Hidden Markov Model to detect market volatility regimes. Reduce position or stay flat during high volatility to lower risk.' }}</p>
            <div class="formula">
              <code>2 States: Low Volatility (0) / High Volatility (1)</code>
            </div>
            <div class="signal-rule">
              <span class="signal-cond">{{ locale === 'zh' ? '信号规则' : 'Signal Rules' }}:</span>
              <span v-if="locale === 'zh'">高波动状态: 仓位减半或空仓</span>
              <span v-else>High volatility: 50% position or flat</span>
            </div>
          </div>
        </div>

        <div class="docs-section">
          <h2>{{ locale === 'zh' ? '工作流程' : 'Workflow' }}</h2>
          <div class="workflow-steps">
            <div class="step">
              <div class="step-num">1</div>
              <div class="step-title">{{ locale === 'zh' ? '数据获取' : 'Data Acquisition' }}</div>
              <div class="step-desc">{{ locale === 'zh' ? '从Yahoo Finance获取黄金/白银历史价格数据' : 'Fetch Gold/Silver historical prices from Yahoo Finance' }}</div>
            </div>
            <div class="step">
              <div class="step-num">2</div>
              <div class="step-title">{{ locale === 'zh' ? '特征计算' : 'Feature Calculation' }}</div>
              <div class="step-desc">{{ locale === 'zh' ? '计算GSR、Z-Score、波动率等技术指标' : 'Calculate GSR, Z-Score, volatility and other technical indicators' }}</div>
            </div>
            <div class="step">
              <div class="step-num">3</div>
              <div class="step-title">{{ locale === 'zh' ? '状态检测' : 'Regime Detection' }}</div>
              <div class="step-desc">{{ locale === 'zh' ? 'HMM模型识别当前市场状态' : 'HMM model identifies current market regime' }}</div>
            </div>
            <div class="step">
              <div class="step-num">4</div>
              <div class="step-title">{{ locale === 'zh' ? '信号生成' : 'Signal Generation' }}</div>
              <div class="step-desc">{{ locale === 'zh' ? '结合策略规则生成交易信号' : 'Combine strategy rules to generate trading signals' }}</div>
            </div>
            <div class="step">
              <div class="step-num">5</div>
              <div class="step-title">{{ locale === 'zh' ? '回测验证' : 'Backtesting' }}</div>
              <div class="step-desc">{{ locale === 'zh' ? '使用历史数据验证策略有效性' : 'Validate strategy effectiveness using historical data' }}</div>
            </div>
          </div>
        </div>

        <div class="docs-section">
          <h2>{{ locale === 'zh' ? '回测参数' : 'Backtest Parameters' }}</h2>
          <div class="params-table">
            <div class="param-row">
              <span class="param-name">{{ locale === 'zh' ? '训练期' : 'Training Period' }}</span>
              <span class="param-value">2026-01-05 ~ 2026-04-02</span>
            </div>
            <div class="param-row">
              <span class="param-name">{{ locale === 'zh' ? '初始资金' : 'Initial Capital' }}</span>
              <span class="param-value">${{ settings.initialCapital?.toLocaleString() }}</span>
            </div>
            <div class="param-row">
              <span class="param-name">{{ locale === 'zh' ? '滚动窗口' : 'Rolling Window' }}</span>
              <span class="param-value">{{ settings.rollingWindow }} days</span>
            </div>
            <div class="param-row">
              <span class="param-name">GSR {{ locale === 'zh' ? '阈值上界' : 'Threshold Upper' }}</span>
              <span class="param-value">{{ settings.gsrUpper }}</span>
            </div>
            <div class="param-row">
              <span class="param-name">GSR {{ locale === 'zh' ? '阈值下界' : 'Threshold Lower' }}</span>
              <span class="param-value">{{ settings.gsrLower }}</span>
            </div>
            <div class="param-row">
              <span class="param-name">Z-Score {{ locale === 'zh' ? '阈值' : 'Threshold' }}</span>
              <span class="param-value">±{{ settings.zscoreThreshold }}</span>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

:root {
  --bg-dark: #0D1117;
  --bg-card: #161B22;
  --bg-elevated: #21262D;
  --border-color: #30363D;
  --text-primary: #F0F6FC;
  --text-secondary: #8B949E;
  --text-muted: #6E7681;
  --accent-gold: #F7B731;
  --accent-green: #26DE81;
  --accent-red: #FC5C65;
  --accent-blue: #4B7BEC;
  --accent-purple: #A55EEA;
}

body {
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
  background: var(--bg-dark);
  color: var(--text-primary);
  line-height: 1.6;
}

#app {
  height: 100vh;
}

.spinner {
  display: inline-block;
  width: 16px;
  height: 16px;
  border: 2px solid transparent;
  border-top-color: currentColor;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
  margin-right: 8px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.btn-primary {
  background: linear-gradient(135deg, var(--accent-gold), #E5A720);
  color: #000;
  border: none;
  padding: 0.75rem 1.5rem;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-primary:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(247, 183, 49, 0.4);
}

.btn-primary:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-large {
  padding: 1rem 3rem;
  font-size: 1.1rem;
}

.btn-danger {
  background: linear-gradient(135deg, var(--accent-red), #E5444A);
  color: #fff;
  border: none;
  padding: 0.75rem 1.5rem;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-danger:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(252, 92, 101, 0.4);
}

.btn-danger:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>

<style scoped>
.app-container {
  display: flex;
  height: 100vh;
  background: var(--bg-dark);
}

.sidebar {
  width: 260px;
  background: linear-gradient(180deg, var(--bg-card) 0%, var(--bg-dark) 100%);
  border-right: 1px solid var(--border-color);
  display: flex;
  flex-direction: column;
  padding: 1.5rem;
}

.logo {
  text-align: center;
  padding-bottom: 2rem;
  border-bottom: 1px solid var(--border-color);
  margin-bottom: 2rem;
}

.logo-icon {
  font-size: 3rem;
  margin-bottom: 0.5rem;
}

.logo h2 {
  color: var(--accent-gold);
  font-size: 1.5rem;
  font-weight: 700;
  letter-spacing: 1px;
}

.tagline {
  display: block;
  color: var(--text-muted);
  font-size: 0.75rem;
  margin-top: 0.25rem;
}

.sidebar nav {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.sidebar nav a {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem 1.25rem;
  color: var(--text-secondary);
  text-decoration: none;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-weight: 500;
}

.sidebar nav a:hover {
  background: var(--bg-elevated);
  color: var(--text-primary);
}

.sidebar nav a.active {
  background: linear-gradient(135deg, rgba(247, 183, 49, 0.15), rgba(247, 183, 49, 0.05));
  color: var(--accent-gold);
  border: 1px solid rgba(247, 183, 49, 0.3);
}

.nav-icon {
  font-size: 1.25rem;
}

.sidebar-footer {
  padding-top: 1rem;
  border-top: 1px solid var(--border-color);
}

.lang-btn {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  padding: 0.75rem;
  background: var(--bg-elevated);
  color: var(--text-secondary);
  border: 1px solid var(--border-color);
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.2s;
}

.lang-btn:hover {
  border-color: var(--accent-gold);
  color: var(--accent-gold);
}

.main-content {
  flex: 1;
  overflow-y: auto;
  padding: 2rem;
}

.license-banner {
  background: linear-gradient(135deg, rgba(247, 183, 49, 0.15), rgba(247, 183, 49, 0.05));
  border: 1px solid rgba(247, 183, 49, 0.3);
  border-radius: 8px;
  padding: 0.75rem 1rem;
  margin-bottom: 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 0.85rem;
}

.license-banner span {
  color: var(--text-secondary);
}

.license-banner .contact {
  color: var(--accent-gold);
  font-weight: 500;
}

.page-header {
  margin-bottom: 2rem;
}

.page-header h1 {
  font-size: 1.75rem;
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: 0.5rem;
}

.subtitle {
  color: var(--text-muted);
  font-size: 0.9rem;
}

.profile-header-bar {
  background: linear-gradient(135deg, rgba(247, 183, 49, 0.1), rgba(247, 183, 49, 0.05));
  border: 1px solid rgba(247, 183, 49, 0.3);
  border-radius: 12px;
  padding: 1rem 1.5rem;
  margin-bottom: 1.5rem;
  display: flex;
  align-items: center;
  gap: 1rem;
}

.profile-label {
  color: var(--text-muted);
  font-size: 0.85rem;
}

.profile-name {
  color: var(--accent-gold);
  font-weight: 600;
  font-size: 1rem;
}

.profile-params {
  color: var(--text-secondary);
  font-size: 0.8rem;
  margin-left: auto;
}

.welcome-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.85);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.welcome-content {
  background: var(--bg-card);
  border: 1px solid var(--accent-gold);
  border-radius: 20px;
  padding: 3rem;
  text-align: center;
  max-width: 500px;
}

.welcome-content h2 {
  color: var(--accent-gold);
  font-size: 1.5rem;
  margin-bottom: 1rem;
}

.welcome-content p {
  color: var(--text-secondary);
  margin-bottom: 2rem;
}

.welcome-actions {
  display: flex;
  gap: 1rem;
  justify-content: center;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 1.25rem;
  margin-bottom: 2rem;
}

.stat-card {
  background: var(--bg-card);
  border: 1px solid var(--border-color);
  border-radius: 16px;
  padding: 1.5rem;
  display: flex;
  align-items: center;
  gap: 1rem;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-4px);
  border-color: var(--accent-gold);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.3);
}

.stat-card.premium {
  background: linear-gradient(135deg, rgba(247, 183, 49, 0.1), rgba(247, 183, 49, 0.05));
  border-color: rgba(247, 183, 49, 0.3);
}

.stat-icon {
  font-size: 2rem;
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--bg-elevated);
  border-radius: 12px;
}

.stat-content {
  display: flex;
  flex-direction: column;
}

.stat-label {
  color: var(--text-muted);
  font-size: 0.8rem;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.stat-value {
  font-size: 1.5rem;
  font-weight: 700;
  color: var(--text-primary);
}

.stat-value.positive { color: var(--accent-green); }
.stat-value.negative { color: var(--accent-red); }

.charts-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 1.5rem;
  margin-bottom: 2rem;
}

.chart-card {
  background: var(--bg-card);
  border: 1px solid var(--border-color);
  border-radius: 16px;
  padding: 1.5rem;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.chart-header h3 {
  font-size: 1rem;
  font-weight: 600;
}

.chart-tag {
  background: var(--bg-elevated);
  padding: 0.25rem 0.75rem;
  border-radius: 20px;
  font-size: 0.75rem;
  color: var(--text-muted);
}

.chart-legend {
  display: flex;
  gap: 1rem;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 0.25rem;
  font-size: 0.75rem;
  color: var(--text-muted);
}

.dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.dot.green { background: var(--accent-green); }
.dot.red { background: var(--accent-red); }

.chart-wrapper {
  height: 280px;
}

.recent-signals {
  background: var(--bg-card);
  border: 1px solid var(--border-color);
  border-radius: 16px;
  padding: 1.5rem;
}

.recent-signals h3 {
  font-size: 1rem;
  margin-bottom: 1rem;
}

.signals-table {
  overflow-x: auto;
}

.table-header, .table-row {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr 1.5fr;
  gap: 1rem;
  padding: 0.75rem 1rem;
}

.table-header {
  background: var(--bg-elevated);
  border-radius: 8px;
  color: var(--text-muted);
  font-size: 0.8rem;
  font-weight: 600;
  text-transform: uppercase;
}

.table-row {
  border-bottom: 1px solid var(--border-color);
  color: var(--text-secondary);
  font-size: 0.9rem;
}

.table-row:hover {
  background: var(--bg-elevated);
}

.date { color: var(--accent-gold); }
.gsr { font-weight: 600; }
.gsr.high { color: var(--accent-green); }
.gsr.low { color: var(--accent-red); }
.zscore.high { color: var(--accent-gold); }
.regime.low { color: var(--accent-green); }
.regime.high { color: var(--accent-red); }

.position {
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.75rem;
}

.position.buy_gold_sell_silver { background: rgba(38, 222, 129, 0.2); color: var(--accent-green); }
.position.buy_silver_sell_gold { background: rgba(252, 92, 101, 0.2); color: var(--accent-red); }
.position.flat { background: rgba(139, 148, 158, 0.2); color: var(--text-muted); }
.position.reduced { background: rgba(255, 165, 0, 0.2); color: #FFA500; }

.fetch-card {
  background: var(--bg-card);
  border: 1px solid var(--border-color);
  border-radius: 16px;
  padding: 1.5rem;
  margin-bottom: 1.5rem;
}

.fetch-card h3 {
  font-size: 1rem;
  margin-bottom: 0.5rem;
}

.fetch-desc {
  color: var(--text-muted);
  font-size: 0.85rem;
  margin-bottom: 1.5rem;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 1rem;
  align-items: end;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.form-group label {
  font-size: 0.8rem;
  color: var(--text-muted);
}

.form-group input,
.form-group select {
  padding: 0.75rem 1rem;
  background: var(--bg-elevated);
  border: 1px solid var(--border-color);
  border-radius: 8px;
  color: var(--text-primary);
  font-size: 0.9rem;
}

.form-group input:focus,
.form-group select:focus {
  outline: none;
  border-color: var(--accent-gold);
}

.data-table-card {
  background: var(--bg-card);
  border: 1px solid var(--border-color);
  border-radius: 16px;
  overflow: hidden;
}

.table-header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem;
  border-bottom: 1px solid var(--border-color);
}

.table-header-bar h3 {
  font-size: 1rem;
}

.record-count {
  background: var(--bg-elevated);
  padding: 0.25rem 0.75rem;
  border-radius: 20px;
  font-size: 0.75rem;
  color: var(--text-muted);
}

.table-container {
  overflow-x: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 1rem 1.5rem;
  text-align: left;
}

th {
  background: var(--bg-elevated);
  color: var(--text-muted);
  font-size: 0.75rem;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

td {
  border-bottom: 1px solid var(--border-color);
  color: var(--text-secondary);
}

tr:hover td {
  background: var(--bg-elevated);
}

.price {
  color: var(--text-primary);
  font-weight: 500;
}

.badge {
  padding: 0.25rem 0.75rem;
  border-radius: 20px;
  font-size: 0.75rem;
  font-weight: 500;
}

.badge.low { background: rgba(38, 222, 129, 0.2); color: var(--accent-green); }
.badge.high { background: rgba(252, 92, 101, 0.2); color: var(--accent-red); }

.position-tag {
  padding: 0.25rem 0.75rem;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: 500;
}

.position-tag.buy_gold_sell_silver { background: rgba(38, 222, 129, 0.2); color: var(--accent-green); }
.position-tag.buy_silver_sell_gold { background: rgba(252, 92, 101, 0.2); color: var(--accent-red); }
.position-tag.flat { background: rgba(139, 148, 158, 0.2); color: var(--text-muted); }
.position-tag.reduced { background: rgba(255, 165, 0, 0.2); color: #FFA500; }

.signals-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 1rem;
}

.signal-card {
  background: var(--bg-card);
  border: 1px solid var(--border-color);
  border-radius: 12px;
  padding: 1.25rem;
  transition: all 0.3s ease;
}

.signal-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.3);
}

.signal-card.buy_gold_sell_silver { border-left: 3px solid var(--accent-green); }
.signal-card.buy_silver_sell_gold { border-left: 3px solid var(--accent-red); }
.signal-card.flat { border-left: 3px solid var(--text-muted); }

.signal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.signal-date {
  color: var(--accent-gold);
  font-weight: 600;
}

.signal-badge {
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.7rem;
  font-weight: 600;
}

.signal-badge.buy_gold_sell_silver { background: rgba(38, 222, 129, 0.2); color: var(--accent-green); }
.signal-badge.buy_silver_sell_gold { background: rgba(252, 92, 101, 0.2); color: var(--accent-red); }
.signal-badge.flat { background: rgba(139, 148, 158, 0.2); color: var(--text-muted); }

.signal-body {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 0.5rem;
}

.signal-metric {
  text-align: center;
}

.metric-label {
  display: block;
  font-size: 0.7rem;
  color: var(--text-muted);
  margin-bottom: 0.25rem;
}

.metric-value {
  font-size: 0.9rem;
  font-weight: 600;
  color: var(--text-primary);
}

.backtest-actions {
  margin-bottom: 2rem;
}

.no-results {
  text-align: center;
  padding: 3rem;
  background: var(--bg-card);
  border: 1px solid var(--border-color);
  border-radius: 16px;
  color: var(--text-muted);
}

.result-details {
  margin-top: 1rem;
  text-align: center;
  color: var(--text-muted);
  font-size: 0.85rem;
}

.results-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 1rem;
}

.result-card {
  background: var(--bg-card);
  border: 1px solid var(--border-color);
  border-radius: 16px;
  padding: 1.5rem;
  display: flex;
  align-items: center;
  gap: 1rem;
  transition: all 0.3s ease;
}

.result-card:hover {
  transform: translateY(-4px);
  border-color: var(--accent-gold);
}

.result-icon {
  font-size: 1.5rem;
}

.result-content {
  display: flex;
  flex-direction: column;
}

.result-label {
  font-size: 0.75rem;
  color: var(--text-muted);
  text-transform: uppercase;
}

.result-value {
  font-size: 1.5rem;
  font-weight: 700;
  color: var(--text-primary);
}

.result-value.positive { color: var(--accent-green); }
.result-value.negative { color: var(--accent-red); }

.docs-section {
  background: var(--bg-card);
  border: 1px solid var(--border-color);
  border-radius: 16px;
  padding: 2rem;
  margin-bottom: 1.5rem;
}

.docs-section h2 {
  font-size: 1.25rem;
  color: var(--accent-gold);
  margin-bottom: 1.5rem;
  padding-bottom: 0.5rem;
  border-bottom: 1px solid var(--border-color);
}

.architecture-diagram {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.5rem;
  padding: 1rem 0;
}

.arch-layer {
  width: 100%;
  max-width: 400px;
}

.arch-box {
  background: var(--bg-elevated);
  border: 2px solid var(--border-color);
  border-radius: 12px;
  padding: 1.25rem;
  text-align: center;
  transition: all 0.3s ease;
}

.arch-box.frontend { border-color: var(--accent-blue); }
.arch-box.backend { border-color: var(--accent-gold); }
.arch-box.database { border-color: var(--accent-green); }

.arch-title {
  font-weight: 600;
  font-size: 1rem;
  margin-bottom: 0.5rem;
}

.arch-desc {
  font-size: 0.8rem;
  color: var(--text-muted);
}

.arch-arrow {
  color: var(--text-muted);
  font-size: 1.5rem;
}

.strategy-card {
  background: var(--bg-elevated);
  border: 1px solid var(--border-color);
  border-radius: 12px;
  padding: 1.5rem;
  margin-bottom: 1rem;
}

.strategy-header {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 1rem;
}

.strategy-num {
  width: 32px;
  height: 32px;
  background: var(--accent-gold);
  color: #000;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
}

.strategy-header h3 {
  font-size: 1rem;
  color: var(--text-primary);
}

.strategy-card p {
  color: var(--text-secondary);
  font-size: 0.9rem;
  margin-bottom: 1rem;
  line-height: 1.6;
}

.formula {
  background: var(--bg-dark);
  padding: 0.75rem 1rem;
  border-radius: 8px;
  margin-bottom: 1rem;
}

.formula code {
  color: var(--accent-gold);
  font-family: 'Monaco', 'Consolas', monospace;
  font-size: 0.85rem;
}

.signal-rule {
  background: rgba(247, 183, 49, 0.1);
  border: 1px solid rgba(247, 183, 49, 0.3);
  padding: 0.75rem 1rem;
  border-radius: 8px;
  font-size: 0.85rem;
}

.signal-cond {
  color: var(--accent-gold);
  font-weight: 600;
}

.workflow-steps {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 1rem;
}

.step {
  background: var(--bg-elevated);
  border-radius: 12px;
  padding: 1.25rem;
  text-align: center;
  position: relative;
}

.step-num {
  width: 28px;
  height: 28px;
  background: var(--accent-blue);
  color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  font-size: 0.85rem;
  margin: 0 auto 0.75rem;
}

.step-title {
  font-weight: 600;
  font-size: 0.9rem;
  margin-bottom: 0.5rem;
  color: var(--text-primary);
}

.step-desc {
  font-size: 0.75rem;
  color: var(--text-muted);
}

.params-table {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 1rem;
}

.param-row {
  background: var(--bg-elevated);
  border-radius: 8px;
  padding: 1rem;
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.param-name {
  font-size: 0.75rem;
  color: var(--text-muted);
  text-transform: uppercase;
}

.param-value {
  font-size: 1rem;
  font-weight: 600;
  color: var(--accent-gold);
}

.settings-card {
  background: var(--bg-card);
  border: 1px solid var(--border-color);
  border-radius: 16px;
  padding: 2rem;
}

.settings-form {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 1.5rem;
  max-width: 800px;
}

.settings-form .form-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.settings-form .form-group label {
  font-size: 0.85rem;
  color: var(--text-muted);
  font-weight: 500;
}

.settings-form .form-group input {
  padding: 0.75rem 1rem;
  background: var(--bg-elevated);
  border: 1px solid var(--border-color);
  border-radius: 8px;
  color: var(--text-primary);
  font-size: 1rem;
}

.settings-form .form-group input:focus {
  outline: none;
  border-color: var(--accent-gold);
}

.settings-form .btn-primary {
  grid-column: span 3;
  max-width: 200px;
  justify-self: start;
}

.profiles-section {
  margin-bottom: 2rem;
}

.profiles-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.profiles-header h3 {
  font-size: 1rem;
  color: var(--text-primary);
}

.btn-secondary {
  background: var(--bg-elevated);
  color: var(--text-primary);
  border: 1px solid var(--border-color);
  padding: 0.5rem 1rem;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-secondary:hover {
  border-color: var(--accent-gold);
  color: var(--accent-gold);
}

.profiles-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.profile-card {
  background: var(--bg-card);
  border: 1px solid var(--border-color);
  border-radius: 12px;
  padding: 1rem;
  cursor: pointer;
  transition: all 0.2s;
  position: relative;
}

.profile-card:hover {
  border-color: var(--accent-gold);
}

.profile-card.active {
  border-color: var(--accent-gold);
  background: linear-gradient(135deg, rgba(247, 183, 49, 0.1), rgba(247, 183, 49, 0.05));
}

.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
}

.profile-name {
  font-weight: 600;
  color: var(--text-primary);
}

.profile-badge {
  font-size: 0.7rem;
  padding: 0.2rem 0.5rem;
  background: var(--accent-gold);
  color: #000;
  border-radius: 4px;
}

.profile-desc {
  font-size: 0.8rem;
  color: var(--text-muted);
  margin-bottom: 0.75rem;
}

.profile-params {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  font-size: 0.75rem;
  color: var(--text-secondary);
}

.profile-params span {
  background: var(--bg-elevated);
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
}

.delete-btn {
  position: absolute;
  top: 0.5rem;
  right: 0.5rem;
  background: transparent;
  border: none;
  color: var(--accent-red);
  font-size: 0.75rem;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.2s;
}

.profile-card:hover .delete-btn {
  opacity: 1;
}

.profile-form-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.profile-form {
  background: var(--bg-card);
  border: 1px solid var(--border-color);
  border-radius: 16px;
  padding: 2rem;
  width: 400px;
}

.profile-form h3 {
  margin-bottom: 1.5rem;
  color: var(--text-primary);
}

.profile-form .form-group {
  margin-bottom: 1rem;
}

.profile-form .form-group label {
  display: block;
  font-size: 0.85rem;
  color: var(--text-muted);
  margin-bottom: 0.5rem;
}

.profile-form .form-group input {
  width: 100%;
  padding: 0.75rem;
  background: var(--bg-elevated);
  border: 1px solid var(--border-color);
  border-radius: 8px;
  color: var(--text-primary);
}

.form-actions {
  display: flex;
  gap: 1rem;
  justify-content: flex-end;
  margin-top: 1.5rem;
}

.settings-card h3 {
  font-size: 1rem;
  margin-bottom: 1rem;
  color: var(--text-primary);
}

@media (max-width: 1200px) {
  .stats-grid { grid-template-columns: repeat(2, 1fr); }
  .charts-grid { grid-template-columns: 1fr; }
  .results-grid { grid-template-columns: repeat(3, 1fr); }
  .signals-grid { grid-template-columns: repeat(2, 1fr); }
}

@media (max-width: 768px) {
  .sidebar { width: 80px; padding: 1rem; }
  .logo h2, .tagline, .nav-text { display: none; }
  .sidebar nav a { justify-content: center; padding: 1rem; }
  .stats-grid { grid-template-columns: 1fr; }
  .form-grid { grid-template-columns: 1fr; }
  .results-grid { grid-template-columns: 1fr; }
  .signals-grid { grid-template-columns: 1fr; }
}

.toast {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 1rem 1.5rem;
  border-radius: 8px;
  font-weight: 500;
  z-index: 3000;
  animation: slideIn 0.3s ease;
}

.toast.success {
  background: linear-gradient(135deg, var(--accent-green), #22c55e);
  color: #fff;
}

.toast.error {
  background: linear-gradient(135deg, var(--accent-red), #ef4444);
  color: #fff;
}

@keyframes slideIn {
  from { transform: translateX(100%); opacity: 0; }
  to { transform: translateX(0); opacity: 1; }
}

.confirm-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2500;
}

.confirm-modal {
  background: var(--bg-card);
  border: 1px solid var(--border-color);
  border-radius: 16px;
  padding: 2rem;
  text-align: center;
  max-width: 400px;
}

.confirm-modal p {
  color: var(--text-primary);
  margin-bottom: 1.5rem;
  font-size: 1rem;
}

.confirm-actions {
  display: flex;
  gap: 1rem;
  justify-content: center;
}
</style>