<script lang="ts">
  import { fetchAuthRedirectUri } from "$lib/authUri";
  import { PUBLIC_API_URL } from "$env/static/public";
  import { enhance } from "$app/forms";
  import { goto } from "$app/navigation";
  import LoadingSpinner from "../../components/LoadingSpinner.svelte";
  import { writable } from "svelte/store";

  const uriData = await fetchAuthRedirectUri(PUBLIC_API_URL);
  let loading = writable(false);

  function handleSubmit(e: SubmitEvent) {
    if ($loading) return;
    $loading = true;

    const url = uriData.uri;
    const width = 420;
    const height = 430;
    const left = Math.round((window.screen.width - width) / 2);
    const top = Math.round((window.screen.height - height) / 2);
    const features = `width=${width},height=${height},left=${left},top=${top},resizable=no,menubar=no,toolbar=no,location=no,status=no,scrollbars=yes`;

    const popup = window.open(url, "msAuth", features);

    if (popup) {
      const popupCheckInterval = setInterval(() => {
        console.log(popup);
        if (popup.closed) {
          clearInterval(popupCheckInterval);
          $loading = false;
        }
      }, 500);
    }
  }
</script>

<div class="container">
  <form action="?/login" method="POST" onsubmit={handleSubmit} use:enhance>
    <input type="hidden" name="callbackKey" value={uriData.callbackKey} />
    <button
      type="submit"
      class="ms-button"
      aria-label="Sign in with Microsoft"
      disabled={$loading}
      aria-busy={$loading}
    >
      <span class="ms-logo" aria-hidden="true"></span>
      Sign in with Microsoft
    </button>
  </form>
</div>

<LoadingSpinner loading={$loading} />

<style>
  :global(html, body, #svelte) {
    height: 100%;
    margin: 0;
  }
  .container {
    min-height: 100vh;
    min-width: 100vw;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f3f2f1;
  }
  .ms-button {
    display: inline-flex;
    align-items: center;
    gap: 12px;
    padding: 12px 18px;
    background: #2f2f2f;
    color: white;
    border: none;
    border-radius: 6px;
    font-weight: 600;
    cursor: pointer;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  }
  .ms-button[disabled] {
    opacity: 0.6;
    cursor: default;
  }
  .ms-logo {
    width: 20px;
    height: 20px;
    background: linear-gradient(
      90deg,
      #f25022 0 25%,
      #7fb900 25% 50%,
      #00a4ef 50% 75%,
      #ffb900 75% 100%
    );
    border-radius: 2px;
    flex-shrink: 0;
  }
</style>
