import { useState } from 'react';
import { invoke } from '@tauri-apps/api/core';

export default function Root() {
  const [signedIn, setSignedIn] = useState<{serverDomain: string, username: string} | null>(null)
  const [accountData, setAccountData] = useState('')

  async function signIn() {
    let [serverDomain, username] = await invoke('start_account_auth', {instanceDomain: 'social.tempest.dev'}) as string[]
    setSignedIn({serverDomain, username})
  }

  async function getSelf() {
    if (!signedIn) throw new Error("Not signed in")
    const {serverDomain, username} = signedIn;
    let result = await invoke('get_self', {serverDomain, username}) as string
    setAccountData(JSON.parse(result))
  }

  return (
    <>
      {!signedIn ? (
        <button onClick={signIn}>Sign in</button>
      ) : (!accountData ? (
        <button onClick={getSelf}>Retrieve account data</button>
      ):(
        <p>Result from rust: <pre style={{whiteSpace:'pre'}}>{JSON.stringify(accountData, null, 2)}</pre></p>
      ))}
    </>
  )
}
