import { useState, useCallback } from 'react'
import { ThemeProvider } from './contexts/ThemeContext'
import { LanguageProvider, useLanguage } from './contexts/LanguageContext'
import FloatingHeader from './components/FloatingHeader'
import IpInput from './components/IpInput'
import LatencyMap from './components/LatencyMap'
import ResultsPanel from './components/ResultsPanel'
import { testAllNodes } from './api/latency'
import { LatencyResult } from '@shared/types'
import './styles/index.css'

function AppContent() {
  const [results, setResults] = useState<Map<string, LatencyResult>>(new Map())
  const [testing, setTesting] = useState(false)
  const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null)
  const { t } = useLanguage()

  const handleTest = useCallback(async (target: string) => {
    setTesting(true)
    setResults(new Map())
    setSelectedNodeId(null)

    await testAllNodes(target, (result) => {
      setResults((prev) => new Map(prev).set(result.nodeId, result))
    })

    setTesting(false)
  }, [])

  const handleNodeSelect = useCallback((nodeId: string | null) => {
    setSelectedNodeId(nodeId)
  }, [])

  return (
    <div className="app">
      <FloatingHeader />

      <main className="app-main" style={{ paddingTop: '8rem' }}>
        <p className="app-description">
          {t('从全球各地测试到任意IP地址或域名的网络延迟', 'Test network latency from global locations to any IP address or domain')}
        </p>
        <IpInput onTest={handleTest} testing={testing} />
        <LatencyMap
          results={results}
          selectedNodeId={selectedNodeId}
          onNodeSelect={handleNodeSelect}
        />
        <ResultsPanel
          results={results}
          selectedNodeId={selectedNodeId}
          onNodeSelect={handleNodeSelect}
        />
      </main>

      <footer className="app-footer">
        <p>{t('© 2025 全球延迟测试。由 GlobalPing 提供服务支持。', '© 2025 Global Latency Test. Powered by GlobalPing.')}</p>
      </footer>
    </div>
  )
}

export default function App() {
  return (
    <ThemeProvider>
      <LanguageProvider>
        <AppContent />
      </LanguageProvider>
    </ThemeProvider>
  )
}
