import { matchPath, useLocation, useNavigate, useSearchParams } from 'react-router-dom';
import { MindSpaceView } from '../components/MindSpaceView';
import type { MindSpaceSaveCategory, PortalUser } from '../types';

const CATEGORY_CODES = new Set<MindSpaceSaveCategory>(['draft', 'oa', 'private', 'public']);

function parseCategory(value: string | null): MindSpaceSaveCategory | null {
  if (!value || !CATEGORY_CODES.has(value as MindSpaceSaveCategory)) return null;
  return value as MindSpaceSaveCategory;
}

export function MindSpaceRoute({
  user,
  onLogout,
}: {
  user: PortalUser;
  onLogout: () => void;
}) {
  const navigate = useNavigate();
  const location = useLocation();
  const [searchParams] = useSearchParams();
  const pageMatch = matchPath('/space/page/:pageId', location.pathname);
  const pageId = pageMatch?.params.pageId ?? null;
  const categoryCode = parseCategory(searchParams.get('category'));

  return (
    <MindSpaceView
      user={user}
      initialPageId={pageId}
      initialCategoryCode={categoryCode}
      onBack={() => navigate('/')}
      onLogout={onLogout}
      routeSync={{
        pushHome: () => navigate('/space'),
        pushCategory: (code) => navigate(`/space?category=${code}`),
        pushPage: (id) => navigate(`/space/page/${id}`),
      }}
    />
  );
}
