import { useEffect, useState } from 'react';
import { Preferences } from '@capacitor/preferences';
import SetupScreen from './SetupScreen';

export default function App() {
  const [ready, setReady] = useState(false);

  useEffect(() => {
    Preferences.get({ key: 'serverUrl' }).then(({ value }) => {
      if (value) {
        // Navigate the WebView to the saved server URL.
        // From this point the remote server's UI takes over entirely.
        window.location.replace(value);
      } else {
        setReady(true);
      }
    });
  }, []);

  async function handleConnect(url: string) {
    await Preferences.set({ key: 'serverUrl', value: url });
    window.location.replace(url);
  }

  if (!ready) {
    // Brief blank while we check preferences before redirecting
    return (
      <div style={{ background: '#09090b', height: '100dvh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div className="spinner" />
      </div>
    );
  }

  return <SetupScreen onConnect={handleConnect} />;
}
