import React, { useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { FullPageSpinner } from '../components/ui/Spinner';
import { useEventStore } from '../store/eventStore';
import { downloadGuests } from '../services/api';

export function LoadingRestore() {
  const navigate = useNavigate();
  const { isSessionValid, clearEvent, setGuests, markLoaded, guests } = useEventStore();
  const ran = useRef(false);

  useEffect(() => {
    if (ran.current) return;
    ran.current = true;

    async function restore() {
      if (!isSessionValid()) {
        clearEvent();
        navigate('/checkin-app', { replace: true });
        return;
      }

      // Cached guests available — go to dashboard instantly, refresh in background
      if (guests.length > 0) {
        navigate('/checkin-app/dashboard', { replace: true });
        downloadGuests()
          .then(({ guests: fresh, total }) => {
            setGuests(fresh);
            markLoaded(total);
          })
          .catch(() => { /* silent — user already working with cached data */ });
        return;
      }

      // No cache — must download first
      try {
        const { guests: fresh, total } = await downloadGuests();
        setGuests(fresh);
        markLoaded(total);
        navigate('/checkin-app/dashboard', { replace: true });
      } catch {
        clearEvent();
        navigate('/checkin-app', { replace: true });
      }
    }

    restore();
  }, []);   // eslint-disable-line react-hooks/exhaustive-deps

  return <FullPageSpinner />;
}
