<script lang="ts">
    import "../app.css";
    import { goto } from "$app/navigation";
    import { api } from "$lib/api";

    let error = $state("");
    let loading = $state(false);

    async function handleSubmit(event: SubmitEvent) {
        event.preventDefault();

        const form = event.currentTarget as HTMLFormElement;
        const password = new FormData(form).get("password")?.toString() ?? "";

        loading = true;
        const { status } = await api.auth.login.post({ password });
        loading = false;

        if (status === 401) {
            error = "Invalid password";
            return;
        }

        await goto("/");
    }
</script>

<div class="min-h-screen flex items-center justify-center bg-base-200">
    <div class="card bg-base-100 w-full max-w-sm shadow-xl">
        <div class="card-body gap-4">
            {#if error}
                <div role="alert" class="alert alert-error">
                    <span>{error}</span>
                </div>
            {/if}

            <form onsubmit={handleSubmit} class="flex flex-col gap-4">
                <label class="floating-label">
                    <input
                        type="password"
                        name="password"
                        placeholder="Password"
                        class="input input-bordered w-full"
                        required
                    />
                    <span>Password</span>
                </label>

                <button
                    type="submit"
                    class="btn btn-primary w-full"
                    disabled={loading}
                >
                    Sign in
                </button>
            </form>
        </div>
    </div>
</div>
