import React, { useState, useEffect } from 'react'
import Home from './pages/Home'
import Settings from './pages/Settings'
import List from './pages/List'
import Add from './pages/Add'
import Stats from './pages/Stats'
import News from './pages/News'
import Login from './pages/Login'
import Detail from './pages/Detail'
import Edit from './pages/Edit'
import Admin from './pages/Admin'

export default function App() {
  const [path, setPath] = useState(window.location.hash.slice(1) || '/')

  useEffect(() => {
    const handleHashChange = () => {
      setPath(window.location.hash.slice(1) || '/')
    }
    window.addEventListener('hashchange', handleHashChange)
    return () => window.removeEventListener('hashchange', handleHashChange)
  }, [])

  const handleNavigate = (newPath) => {
    window.location.hash = '#' + newPath
    setPath(newPath)
  }

  const getComponent = () => {
    const basePath = path.split('?')[0]
    if (basePath === '/') return <Home />
    if (basePath === '/news') return <News />
    if (basePath === '/stats') return <Stats />
    if (basePath === '/list') return <List />
    if (basePath === '/add') return <Add />
    if (basePath === '/login') return <Login />
    if (basePath === '/settings') return <Settings />
    if (basePath === '/admin') return <Admin />
    if (basePath.startsWith('/edit')) return <Edit />
    if (basePath.startsWith('/detail')) return <Detail />
    return <Home />
  }

  const token = localStorage.getItem('token')
  const userStr = localStorage.getItem('user')
  let user = null
  try {
    user = userStr ? JSON.parse(userStr) : null
  } catch (e) {
    console.error('Parse user error:', e)
  }
  const isAdmin = user && user.role === 'admin'
  const isEditor = user && user.role === 'editor'
  
  // 登录页面独立渲染，不显示底部导航
  if (!token) {
    // 强制刷新页面，确保状态同步
    if (path !== '/login') {
      window.location.hash = '#/login'
    }
    return <Login />
  }
  
  // 如果已登录且在登录页，强制跳转到首页
  if (path === '/login') {
    // 使用 href 强制刷新页面
    window.location.href = window.location.origin + window.location.pathname + '#/'
    return null
  }

  return (
    <div style={{ minHeight: '100vh', background: '#0f172a' }}>
      {getComponent()}
      
      <div style={{
          position: 'fixed',
          bottom: 0,
          left: 0,
          right: 0,
          height: '60px',
          background: 'rgba(15, 23, 42, 0.98)',
          display: 'flex',
          borderTop: '1px solid rgba(255,255,255,0.1)',
          zIndex: 1000
        }}>
          {[
            { path: '/', icon: '🏠', label: '首页' },
            { path: '/news', icon: '📰', label: '行情' },
            { path: '/stats', icon: '📊', label: '统计' },
            { path: '/list', icon: '📚', label: '我的' },
            { path: '/add', icon: '🎯', label: '录入' },
            ...(isAdmin ? [{ path: '/admin', icon: '⚙️', label: '管理' }] : [])
          ].map(tab => (
            <div
              key={tab.path}
              onClick={() => handleNavigate(tab.path)}
              style={{
                flex: 1,
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                justifyContent: 'center',
                color: path === tab.path ? '#fbbf24' : '#94a3b8',
                cursor: 'pointer'
              }}
            >
              <div style={{ fontSize: '22px' }}>{tab.icon}</div>
              <div style={{ fontSize: '11px', marginTop: '2px' }}>{tab.label}</div>
            </div>
          ))}
        </div>
    </div>
  )
}
// Fri Apr 10 03:44:24 PM CST 2026
