import { useCallback, useEffect, useState } from "react";
import { getState, UiState } from "./lib/ipc";
import LoginView from "./views/LoginView";
import HubView from "./views/HubView";

export default function App() {
  const [state, setState] = useState<UiState | null>(null);
  const [loadError, setLoadError] = useState<string | null>(null);

  const refresh = useCallback(async () => {
    try {
      setState(await getState());
      setLoadError(null);
    } catch (e) {
      setLoadError(String(e));
    }
  }, []);

  useEffect(() => {
    refresh();
    // Periodischer Refresh: spiegelt Server-State (z.B. Release durch Cron)
    const id = setInterval(refresh, 60_000);
    return () => clearInterval(id);
  }, [refresh]);

  if (!state) {
    return (
      <div className="app">
        <div className="center-fill">
          {loadError ? <p className="error">{loadError}</p> : <div className="spin" />}
        </div>
      </div>
    );
  }

  return (
    <div className="app">
      {state.loggedIn ? (
        <HubView state={state} onState={setState} />
      ) : (
        <LoginView onState={setState} />
      )}
      <div className="footer">
        <span>ReBreak Magic für Windows</span>
        <span>{state.hostname}</span>
      </div>
    </div>
  );
}
