// App root — real Supabase magic-link auth gate + live data bootstrap.

const { useState, useEffect } = React;
const BE = window.SweepifyBackend;

function BootSplash() {
  return (
    <div className="gate">
      <div className="gate__logo"><img src="assets/sweepify-logo.svg" alt="Sweepify" /></div>
      <div className="gate__hint"><span className="pulse" /> Loading your dashboard…</div>
    </div>
  );
}

function App() {
  const [phase, setPhase] = useState("loading"); // loading | gate | ready
  const [email, setEmail] = useState(null);
  const [data, setData] = useState(null);

  async function boot() {
    const session = await BE.getSession();
    if (!session) { setPhase("gate"); return; }
    setEmail(session.user.email);
    try {
      setData(await BE.load());
    } catch (e) {
      console.error("dashboard load failed", e);
      setData({ balance: 0, searches: [], notifications: [], shield: null });
    }
    setPhase("ready");
    // Strip the magic-link tokens from the URL bar once consumed.
    if (window.location.hash.includes("access_token")) {
      history.replaceState(null, "", window.location.pathname);
    }
  }

  useEffect(() => {
    boot();
    const { data: sub } = sbClient.auth.onAuthStateChange((event) => {
      if (event === "SIGNED_IN" || event === "TOKEN_REFRESHED") boot();
      if (event === "SIGNED_OUT") { setEmail(null); setData(null); setPhase("gate"); }
    });
    return () => sub.subscription.unsubscribe();
  }, []);

  if (phase === "loading") return <BootSplash />;
  if (phase === "gate") {
    // onSubmit returns the sendOtp promise so EmailGate can await + show "check your email".
    return <EmailGate onSubmit={(addr) => BE.api.sendOtp(addr)} />;
  }
  return (
    <Dashboard
      email={email}
      data={data}
      onLogout={async () => { await BE.signOut(); }}
    />
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
