<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 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-screen 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"
            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>
          <input
            id="password"
            type="password"
            bind:value={password}
            placeholder="Enter your password"
            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>

        {#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>
