<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Tanco Dev App</title>
  <link rel="stylesheet" href="/static/style.css">
</head>
<body>

<h1>hello <span id="username"></span></h1>

<button style="display:none" id="sign-out">Sign Out</button>

<form id="successForm" method="post" style="display:none">
{% if pre %}
  <label for="preToken">preToken:</label>
  <input type="text" name="preToken" value="{{ pre }}">
  <br/>
{% else %}
  <input type="text" name="whence" value="">
{% endif %}
  <label for="accessToken">accessToken:</label>
  <input type="text" name="accessToken">
  <br/>
  <input type="submit" value="submit">
</form>

<div id="login-buttons" style="display:none">
  <button onclick="loginWith('google')">Login with Google</button>
  <!-- <button onclick="attemptLogin('github')">Login with Github</button> -->
</div>

<script type="module">
  import {
    signOut,
    currentUser,
    attemptLogin} from "/static/login.mjs";

  function show(eid) {
    document.getElementById(eid).style.display ='block' }


  function onLoginSuccess() {
    const successForm = document.getElementById('successForm')
  {% if pre %}
    successForm.action = '/auth/success'
  {% else %}
    successForm.action = '/login/success'
    successForm.whence.value = document.referrer
  {% endif %}
    successForm.accessToken.value = currentUser().accessToken
    successForm.submit() }


  // --- main code ----------------------------------------


  document.getElementById('sign-out').addEventListener('click', () => {
    signOut()
      .then(() => {
        console.log('signed out')
        document.location.reload() })
      .catch((error) => { console.error(error)}) })



  {% if pre == '??' %}
    {# disallow /auth/login if no ?pre given #}
    document.body.innerHTML = `
      <h1>error</h1>
      <p>You should only visit this page by running <code>tanco login</code></p>
      <p>To log in directly, go to <a href="/login">/login</a></p>`
  {% else %}
    if (currentUser()) { onLoginSuccess() }
    else { show('login-buttons') }
  {% endif %}

  window.loginWith = async function (how) {
    return await attemptLogin(how, onLoginSuccess) };

  window.currentUser = currentUser;

  let u = currentUser();
  if (u) { document.getElementById('username').innerText = u.displayName; }


</script>
</body>
</html>