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

  const uriData = await optima.auth.fetchAuthRedirectUri(PUBLIC_API_URL);
  let loading = writable(false);
  /** Track whether the server-side form action has finished */
  let formActionDone = false;

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

    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) {
      // Popup was blocked — reset so the user can try again
      $loading = false;
      return;
    }

    // Only hide the spinner when BOTH the popup has closed AND the
    // server-side form action (awaitAuthCallback) has completed.
    // Previously the spinner was removed as soon as the popup closed,
    // leaving a gap while the server was still processing the callback.
    const popupCheckInterval = setInterval(() => {
      if (popup.closed) {
        clearInterval(popupCheckInterval);
        if (formActionDone) {
          $loading = false;
        }
        // If the form action isn't done yet the spinner stays;
        // the enhance callback below will clear it.
      }
    }, 500);
  }
</script>

<div class="container">
  <button
    class="theme-toggle login-theme-toggle"
    onclick={() => theme.toggle()}
    aria-label="Toggle {$theme === 'dark' ? 'light' : 'dark'} mode"
    title="Switch to {$theme === 'dark' ? 'light' : 'dark'} mode"
  >
    <svg
      class="theme-icon sun-icon"
      class:visible={$theme === "dark"}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      stroke-width="2"
    >
      <circle cx="12" cy="12" r="5" />
      <line x1="12" y1="1" x2="12" y2="3" />
      <line x1="12" y1="21" x2="12" y2="23" />
      <line x1="4.22" y1="4.22" x2="5.64" y2="5.64" />
      <line x1="18.36" y1="18.36" x2="19.78" y2="19.78" />
      <line x1="1" y1="12" x2="3" y2="12" />
      <line x1="21" y1="12" x2="23" y2="12" />
      <line x1="4.22" y1="19.78" x2="5.64" y2="18.36" />
      <line x1="18.36" y1="5.64" x2="19.78" y2="4.22" />
    </svg>
    <svg
      class="theme-icon moon-icon"
      class:visible={$theme === "light"}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      stroke-width="2"
    >
      <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
    </svg>
  </button>

  <form
    action="?/login"
    method="POST"
    onsubmit={handleSubmit}
    use:enhance={() => {
      // Called when the form action response comes back from the server
      return async ({ update }) => {
        formActionDone = true;
        $loading = false;
        await update();
      };
    }}
  >
    <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: var(--bg-base);
    transition: background 0.2s ease;
  }
  .ms-button {
    display: inline-flex;
    align-items: center;
    gap: 12px;
    padding: 12px 18px;
    background: var(--bg-elevated);
    color: var(--text-primary);
    border: 1px solid var(--border-default);
    border-radius: 6px;
    font-weight: 600;
    cursor: pointer;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
    transition:
      background 0.2s ease,
      color 0.2s ease,
      border-color 0.2s ease;
  }
  .ms-button:hover:not([disabled]) {
    background: var(--card-hover-bg);
    border-color: var(--border-strong);
  }
  .ms-button[disabled] {
    opacity: 0.6;
    cursor: default;
  }
  .login-theme-toggle {
    position: absolute;
    top: 16px;
    right: 16px;
  }
  .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>
