import { useEffect } from 'react';
import { useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { CircularProgress } from '@mui/material';

import { NO_CATEGORY_LABEL, selectNodeTree } from '../common/HostsTree/store';

export const EmptyState = () => {
  const navigate = useNavigate();
  const nodeTree = useSelector(selectNodeTree);

  // Auto-select the first top-level category in the tree once it loads so the
  // landing view shows real data instead of an empty placeholder. The user
  // can still navigate elsewhere from the sidebar.
  useEffect(() => {
    if (!nodeTree) return;
    const firstChild = nodeTree.children?.find(c => c.label !== NO_CATEGORY_LABEL);
    if (!firstChild) return;
    const params = new URLSearchParams();
    if (firstChild.classRegex) params.set('inc', firstChild.classRegex);
    const search = params.toString();
    navigate(
      `/label/${encodeURIComponent(firstChild.label)}${search ? `?${search}` : ''}`,
      { replace: true }
    );
  }, [navigate, nodeTree]);

  // Brief loader while the tree resolves and we redirect.
  return (
    <div style={{ display: 'flex', justifyContent: 'center', padding: 40 }}>
      <CircularProgress size={28} />
    </div>
  );
};
