'use client';
import { useEffect } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { useAuth } from '@/lib/auth';
import { getToken } from '@/lib/api';
import Sidebar from './sidebar';

export default function AuthGate({ children }: { children: React.ReactNode }) {
  const { user, fetchMe } = useAuth();
  const router = useRouter();
  const pathname = usePathname();
  const isLogin = pathname === '/login';

  useEffect(() => {
    if (!getToken() && !isLogin) {
      router.replace('/login');
      return;
    }
    if (getToken() && !user) {
      fetchMe();
    }
  }, [pathname]);

  if (isLogin) return <>{children}</>;
  if (!getToken()) return null;

  return (
    <div className="flex">
      <Sidebar />
      <main className="flex-1 min-h-screen p-4 lg:p-6 overflow-x-auto">
        {children}
      </main>
    </div>
  );
}
