import { Navigate, useLocation } from 'react-router-dom';
import { useStoreSession } from '../contexts/StoreSessionContext';

const PUBLIC_PATHS = new Set(['/login', '/legal/user-agreement', '/legal/privacy-policy']);
const SELECT_STORE_PATH = '/select-store';

export default function AuthGate({ children }: { children: React.ReactNode }) {
  const { ready, authenticated, needsSelectStore } = useStoreSession();
  const location = useLocation();

  if (!ready) {
    return (
      <div className="session-boot">
        <p className="session-boot-text">加载中…</p>
      </div>
    );
  }

  if (authenticated && location.pathname === '/login') {
    return <Navigate to={needsSelectStore ? SELECT_STORE_PATH : '/'} replace />;
  }

  if (authenticated && needsSelectStore && location.pathname !== SELECT_STORE_PATH) {
    return <Navigate to={SELECT_STORE_PATH} replace />;
  }

  if (!authenticated && !PUBLIC_PATHS.has(location.pathname)) {
    return <Navigate to="/login" replace state={{ from: location }} />;
  }

  return <>{children}</>;
}
