// entrypoints/popup/App.tsx
import { useState, useEffect } from 'react';
import { HashRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { Link, useNavigate } from 'react-router-dom';
import './App.css';
import '../../assets/tailwind.css'
import '@alifd/next/dist/next.css';
// import BtnTest from './src/Components/BtnTest.jsx'
// import Home from './pages/Home'
// import About from './pages/About'
import Login from './pages/Login'

// 创建一个保护路由组件
function ProtectedRoute({ children }: { children: React.ReactNode }) {
  const isLoggedIn = localStorage.getItem('isLoggedIn');
  return isLoggedIn ? <>{children}</> : <Navigate to="/login" replace />;
}

// 创建带登出功能的导航组件
function Navigation({ onLogout }: { onLogout: () => void }) {
  const navigate = useNavigate();

  const handleLogout = () => {
    onLogout();
    navigate('/login');
  };

  return (
    <nav className="flex gap-4 p-4 items-center">
      <Link to="/" className="text-blue-500 hover:underline">首页</Link>
      {/* <Link to="/about" className="text-blue-500 hover:underline">关于</Link>
      <Link to="/home" className="text-blue-500 hover:underline">主页</Link> */}
      <button 
        onClick={handleLogout}
        className="ml-auto text-red-500 hover:underline"
      >
        退出登录
      </button>
    </nav>
  );
}

function App() {
  const [count, setCount] = useState(0);
  const [isLoggedIn, setIsLoggedIn] = useState(false);

  // 检查登录状态
  useEffect(() => {
    const loggedIn = localStorage.getItem('isLoggedIn') === 'true';
    setIsLoggedIn(loggedIn);
  }, []);

  // 处理登出逻辑
  const handleLogout = () => {
    localStorage.removeItem('isLoggedIn');
    setIsLoggedIn(false);
  };

  return (
    <Router>
      {/* 只在登录后显示导航栏 */}
      {isLoggedIn && <Navigation onLogout={handleLogout} />}
      
      <Routes>
        <Route path="/login" element={<Login setIsLoggedIn={setIsLoggedIn} />} />
        <Route path="/" element={
          <ProtectedRoute>
            <div>
              <button className='text-red-300'>按钮</button>
            </div>
          </ProtectedRoute>
        } />
        {/* <Route path="/about" element={
          <ProtectedRoute>
            <About />
          </ProtectedRoute>
        } />
        <Route path="/home" element={
          <ProtectedRoute>
            <Home />
          </ProtectedRoute>
        } /> */}
      </Routes>
    </Router>
  );
}

export default App;