"use client";

// Wallet-only register and login on one page. There is no email anywhere.
// The first successful sign-in creates the account from the verified address.

import { useCallback, useEffect, useState } from "react";
import SignInWithQid from "../components/SignInWithQid";

export default function Home() {
  const [session, setSession] = useState(null);

  useEffect(() => {
    fetch("/api/qid/session")
      .then((r) => (r.ok ? r.json() : null))
      .then(setSession)
      .catch(() => {});
  }, []);

  const onSignedIn = useCallback((s) => setSession(s), []);

  async function signOut() {
    await fetch("/api/qid/logout", { method: "POST" });
    setSession(null);
  }

  if (!session) {
    return (
      <main>
        <h1>Sign in</h1>
        <p>Your BTX address is your account. Prove you own it and you are in.</p>
        <SignInWithQid appName="Next demo" onSignedIn={onSignedIn} />
      </main>
    );
  }

  return (
    <main>
      <h1>Welcome</h1>
      <p>Signed in as {session.address}</p>
      <button onClick={signOut}>Sign out</button>
    </main>
  );
}
