import React, { useState, useEffect } from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { setupAPI } from '../services/api';

export default function SetupGuard({ children }) {
  const location = useLocation();
  const [status, setStatus] = useState(null); // null = loading, true = complete, false = incomplete
  const [error, setError] = useState(false);

  useEffect(() => {
    setupAPI.getStatus()
      .then(r => setStatus(r.data?.complete === true))
      .catch(() => {
        // If the setup endpoint doesn't exist yet, treat setup as complete
        // so the rest of the app functions normally.
        setStatus(true);
        setError(true);
      });
  }, []);

  // Still loading — show nothing to avoid flash of wrong content
  if (status === null) {
    return (
      <div className="min-h-screen bg-gray-950 flex items-center justify-center">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500" />
      </div>
    );
  }

  const onSetupPage = location.pathname === '/setup';

  // Setup incomplete and not already on /setup → redirect there
  if (status === false && !onSetupPage) {
    return <Navigate to="/setup" replace />;
  }

  // Setup complete but user navigated to /setup → send to login
  if (status === true && onSetupPage) {
    return <Navigate to="/login" replace />;
  }

  return children;
}
