<script lang="ts">
  import { goto } from "$app/navigation";
  import { auth, isAuthenticated, isLoading, authError } from "$lib/stores/auth";

  let step = $state<"server" | "login">("server");
  let serverUrl = $state("");
  let serverName = $state("");
  let username = $state("");
  let password = $state("");
  let showPassword = $state(false);
  let connecting = $state(false);
  let loggingIn = $state(false);
  let localError = $state<string | null>(null);

  // Redirect to library if already authenticated
  $effect(() => {
    if ($isAuthenticated && !$isLoading) {
      goto("/");
    }
  });

  async function handleConnectServer(e: Event) {
    e.preventDefault();
    if (!serverUrl.trim()) return;

    connecting = true;
    localError = null;

    // Reject plain HTTP — all connections must use HTTPS
    if (serverUrl.trim().toLowerCase().startsWith("http://")) {
      localError = "HTTP connections are not allowed. Please use HTTPS (e.g., https://your-server.com).";
      connecting = false;
      return;
    }

    try {
      const info = await auth.connectToServer(serverUrl);
      serverName = info.name;
      serverUrl = info.normalizedUrl; // Use normalized URL with https://
      step = "login";
    } catch (error) {
      localError = error instanceof Error ? error.message : "Failed to connect to server";
    } finally {
      connecting = false;
    }
  }

  async function handleLogin(e: Event) {
    e.preventDefault();
    if (!username.trim()) return;

    loggingIn = true;
    localError = null;

    try {
      await auth.login(username, password, serverUrl, serverName);
      // Redirect will happen automatically via $effect
    } catch (error) {
      localError = error instanceof Error ? error.message : "Login failed";
    } finally {
      loggingIn = false;
    }
  }

  function goBackToServer() {
    step = "server";
    localError = null;
    auth.clearError();
  }
</script>

<div class="min-h-full flex items-center justify-center p-4">
  <div class="w-full max-w-md">
    <!-- Logo/Title -->
    <div class="text-center mb-8">
      <h1 class="text-4xl font-bold text-[var(--color-jellyfin)] mb-2">JellyTau</h1>
      <p class="text-gray-400">Connect to your Jellyfin server</p>
    </div>

    {#if $isLoading}
      <!-- Loading state -->
      <div class="flex justify-center">
        <div class="w-8 h-8 border-2 border-[var(--color-jellyfin)] border-t-transparent rounded-full animate-spin"></div>
      </div>
    {:else if step === "server"}
      <!-- Server connection form -->
      <form onsubmit={handleConnectServer} class="space-y-4">
        <div>
          <label for="server-url" class="block text-sm font-medium text-gray-300 mb-2">
            Server URL
          </label>
          <input
            id="server-url"
            type="text"
            bind:value={serverUrl}
            placeholder="https://jellyfin.example.com"
            class="w-full px-4 py-3 bg-[var(--color-surface)] border border-gray-700 rounded-lg focus:outline-none focus:border-[var(--color-jellyfin)] text-white placeholder-gray-500"
            disabled={connecting}
          />
        </div>

        {#if localError || $authError}
          <div class="p-3 bg-red-900/50 border border-red-700 rounded-lg text-red-200 text-sm">
            {localError || $authError}
          </div>
        {/if}

        <button
          type="submit"
          disabled={connecting || !serverUrl.trim()}
          class="w-full py-3 px-4 bg-[var(--color-jellyfin)] hover:bg-[var(--color-jellyfin-dark)] disabled:opacity-50 disabled:cursor-not-allowed rounded-lg font-medium transition-colors flex items-center justify-center gap-2"
        >
          {#if connecting}
            <div class="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
            Connecting...
          {:else}
            Connect
          {/if}
        </button>
      </form>
    {:else}
      <!-- Login form -->
      <div class="mb-6">
        <button
          onclick={goBackToServer}
          class="text-gray-400 hover:text-white text-sm flex items-center gap-1"
        >
          <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
          </svg>
          Back
        </button>
      </div>

      <div class="text-center mb-6">
        <p class="text-[var(--color-jellyfin)] font-medium">{serverName}</p>
        <p class="text-gray-500 text-sm">{serverUrl}</p>
      </div>

      <form onsubmit={handleLogin} class="space-y-4">
        <div>
          <label for="username" class="block text-sm font-medium text-gray-300 mb-2">
            Username
          </label>
          <input
            id="username"
            type="text"
            bind:value={username}
            placeholder="Enter your username"
            autocapitalize="none"
            autocorrect="off"
            autocomplete="username"
            spellcheck="false"
            class="w-full px-4 py-3 bg-[var(--color-surface)] border border-gray-700 rounded-lg focus:outline-none focus:border-[var(--color-jellyfin)] text-white placeholder-gray-500"
            disabled={loggingIn}
          />
        </div>

        <div>
          <label for="password" class="block text-sm font-medium text-gray-300 mb-2">
            Password
          </label>
          <div class="relative">
            <!-- `type` is dynamic, so bind:value is not allowed here (Svelte); wire it manually. -->
            <input
              id="password"
              type={showPassword ? "text" : "password"}
              value={password}
              oninput={(e) => (password = e.currentTarget.value)}
              placeholder="Enter your password"
              autocapitalize="none"
              autocorrect="off"
              autocomplete="current-password"
              spellcheck="false"
              class="w-full pl-4 pr-12 py-3 bg-[var(--color-surface)] border border-gray-700 rounded-lg focus:outline-none focus:border-[var(--color-jellyfin)] text-white placeholder-gray-500"
              disabled={loggingIn}
            />
            <button
              type="button"
              onclick={() => (showPassword = !showPassword)}
              disabled={loggingIn}
              aria-label={showPassword ? "Hide password" : "Show password"}
              aria-pressed={showPassword}
              class="absolute inset-y-0 right-0 px-3 flex items-center text-gray-400 hover:text-white disabled:opacity-50 focus:outline-none focus:text-white"
            >
              {#if showPassword}
                <!-- eye-off -->
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
                </svg>
              {:else}
                <!-- eye -->
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                </svg>
              {/if}
            </button>
          </div>
        </div>

        {#if localError || $authError}
          <div class="p-3 bg-red-900/50 border border-red-700 rounded-lg text-red-200 text-sm">
            {localError || $authError}
          </div>
        {/if}

        <button
          type="submit"
          disabled={loggingIn || !username.trim()}
          class="w-full py-3 px-4 bg-[var(--color-jellyfin)] hover:bg-[var(--color-jellyfin-dark)] disabled:opacity-50 disabled:cursor-not-allowed rounded-lg font-medium transition-colors flex items-center justify-center gap-2"
        >
          {#if loggingIn}
            <div class="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
            Signing in...
          {:else}
            Sign In
          {/if}
        </button>
      </form>
    {/if}
  </div>
</div>
