import React from 'react';
import {Navigate, useLocation} from 'react-router-dom';
import {useAuth} from '../context/AuthContext';

const AdminRoute: React.FC<{ children: JSX.Element }> = ({ children }) => {
    const { loggedIn, role, loading } = useAuth();
    const location = useLocation();

    if (loading) {
        return <div>Loading...</div>; // Or a proper spinner component
    }

    if (!loggedIn) {
        // Not logged in, redirect to login page. No alert needed here
        // as the user is simply redirected.
        return <Navigate to="/login" state={{ from: location }} replace />;
    }

    if (role !== 'ADMIN') {
        // Logged in but not an admin, show alert and redirect.
        alert('접근 권한이 없어요. 관리자에게 문의해주세요.');
        return <Navigate to="/" replace />;
    }

    return children;
};

export default AdminRoute;
