<!-- #region LoginPage [C:3] [TYPE Page] [SEMANTICS sveltekit, auth, login, sso, form] -->
<!-- @ingroup Routes -->
<!-- @BRIEF Provides the user interface for local (username/password) and ADFS SSO authentication. -->
<!-- @LAYER Page -->
<!-- @RELATION BINDS_TO -> [EXT:frontend:authStore] -->
<!-- @RELATION CALLS -> [EXT:frontend:api_module] -->
<!-- @UX_STATE Idle -> Login form visible with username/password fields and SSO button. -->
<!-- @UX_STATE Loading -> Form submitting, button shows "Logging in..." with disabled state. -->
<!-- @UX_STATE Error -> Error banner displayed above form with error message. -->
<!-- @UX_STATE Success -> User authenticated, redirected to homepage. -->
<!-- @UX_FEEDBACK Error banner with red background on auth failure. -->
<!-- @UX_FEEDBACK Loading text on submit button while authenticating. -->
<!-- @UX_RECOVERY User can retry login after error. -->
<!-- @INVARIANT Shows both local login form and ADFS SSO button. -->
<script lang="ts">
import { SvelteURLSearchParams } from "svelte/reactivity";
    import { onMount } from 'svelte';
    import { auth } from '../../lib/auth/store.svelte.js';
    import { api } from '../../lib/api';
    import { goto } from '$app/navigation';
    import { log } from '$lib/cot-logger';
    import { t } from '$lib/i18n/index.svelte.js';

    let username = '';
    let password = '';
    let error = '';
    let loading = false;

    async function handleLogin() {
        if (!username || !password) {
            error = $t.auth?.enter_credentials ;
            return;
        }

        loading = true;
        error = '';

        try {
            const formData = new SvelteURLSearchParams();
            formData.append('username', username);
            formData.append('password', password);

            const response = await fetch('/api/auth/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: formData
            });

            if (response.ok) {
                const data = await response.json();
                auth.setToken(data.access_token);
                
                // Fetch user profile
                try {
                    const user = await api.fetchApi('/auth/me');
                    auth.setUser(user);
                    goto('/');
                } catch (err) {
                    error = ($t.auth?.profile_fetch_failed ?? 'Failed to fetch profile')
                        .replace('{error}', err.message);
                }
            } else {
                const errData = await response.json();
                error = errData.detail || ($t.auth?.invalid_credentials );
            }
        } catch (e) {
            error = $t.auth?.login_error ;
            log("LoginPage", "EXPLORE", "Login failed", {}, String(e));
        } finally {
            loading = false;
        }
    }

    function handleADFSLogin() {
        window.location.href = '/api/auth/login/adfs';
    }

    onMount(() => {
        if ($auth.isAuthenticated) {
            goto('/');
        }
    });
</script>

<div class="max-w-md mx-auto mt-10 p-6 bg-surface-card rounded-lg shadow-md">
    <h2 class="text-2xl font-bold mb-6 text-center">{$t.auth?.login }</h2>

    {#if error}
        <div class="mb-4 p-3 bg-destructive-light text-destructive rounded border border-destructive-light">
            {error}
        </div>
    {/if}

    <form onsubmit={(event) => { event.preventDefault(); handleLogin(); }} class="space-y-4">
        <div>
            <label for="username" class="block text-sm font-medium text-text">{$t.admin?.users?.username }</label>
            <input
                type="text"
                id="username"
                bind:value={username}
                class="mt-1 block w-full px-3 py-2 border border-border-strong rounded-md shadow-sm focus:outline-none focus-visible:ring-primary-ring focus:border-primary-ring"
                required
            />
        </div>

        <div>
            <label for="password" class="block text-sm font-medium text-text">{$t.admin?.users?.password }</label>
            <input
                type="password"
                id="password"
                bind:value={password}
                class="mt-1 block w-full px-3 py-2 border border-border-strong rounded-md shadow-sm focus:outline-none focus-visible:ring-primary-ring focus:border-primary-ring"
                required
            />
        </div>

        <button
            type="submit"
            disabled={loading}
            class="w-full py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary hover:bg-primary-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-primary-ring disabled:opacity-50"
        >
            {loading ? ($t.auth?.logging_in ) : ($t.auth?.login )}
        </button>
    </form>

    <div class="mt-6">
        <div class="relative">
            <div class="absolute inset-0 flex items-center">
                <div class="w-full border-t border-border-strong"></div>
            </div>
            <div class="relative flex justify-center text-sm">
                <span class="px-2 bg-surface-card text-text-muted">{$t.auth?.or_continue_with }</span>
            </div>
        </div>

        <div class="mt-6">
            <button
                onclick={handleADFSLogin}
                class="w-full flex justify-center py-2 px-4 border border-border-strong rounded-md shadow-sm text-sm font-medium text-text bg-surface-card hover:bg-surface-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-primary-ring"
            >
                {$t.auth?.corporate_sso }
            </button>
        </div>
    </div>
</div>

<!-- #endregion LoginPage -->
