<script>
	import { onMount } from 'svelte';
	import { authentication } from '../store.js';
	import { goto } from '$app/navigation';
	import { fade } from 'svelte/transition';

	let isAuthenticated = false;
	let isLoading = true;
	let showPassword = false;

	$: authentication.subscribe((value) => {
		isAuthenticated = !!value;
	});

	onMount(() => {
		try {
			const storedAuth = localStorage.getItem('authentication');
			if (storedAuth) {
				authentication.set(JSON.parse(storedAuth));
			}
		} catch (error) {
			console.error('Error parsing stored auth:', error);
		} finally {
			isLoading = false;
		}
	});

	async function submit(event) {
		event.preventDefault();

		const formData = new FormData(event.target);
		const username = formData.get('username');
		const password = formData.get('password');

		if (!username || !password) {
			alert('Please enter both username and password.');
			return;
		}

		const data = {
			username: username,
			password: password
		};

		try {
			const response = await fetch(import.meta.env.VITE_AUTH_HOST + '/api/authenticate', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json'
				},
				body: JSON.stringify(data)
			});

			if (response.ok) {
				const result = await response.json();
				authentication.set(result);
				localStorage.setItem('authentication', JSON.stringify(result));
				await goto('/portfolio');
			} else {
				const error = await response.json();
				console.error('Login failed:', error);
				alert('Login failed: ' + error.message);
			}
		} catch (err) {
			console.error('Error during login:', err);
			alert('An error occurred. Please try again.');
		}
	}

	function navigateToRegister() {
		window.location.href = '/register';
	}

	function togglePasswordVisibility() {
		showPassword = !showPassword;
	}
</script>

<svelte:head>
	<title>Login</title>
	<meta name="description" content="Login page" />
</svelte:head>

<div in:fade class="text-column">
	{#if isLoading}
		<p>Loading...</p>
	{:else if !isAuthenticated}
		<div class="card">
			<form on:submit={submit}>
				<input type="text" name="username" placeholder="username" class="input-field" />

				<div class="password-container">
					<input
						type={showPassword ? 'text' : 'password'}
						name="password"
						placeholder="password"
						class="input-field"
					/>
					<span class="eye-icon" on:click={togglePasswordVisibility}>
						{#if showPassword}
							👁️‍🗨️
						{:else}
							👁️‍🗨️
						{/if}
					</span>
				</div>

				<button type="submit" class="add-button">Login</button>
				<button type="button" class="register-button" on:click={navigateToRegister}>Register</button>
			</form>
		</div>
	{/if}
</div>

<style>
    input::placeholder {
        opacity: 0.5;
    }

    .password-container {
        position: relative;
    }

    .eye-icon {
        position: absolute;
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
        cursor: pointer;
        font-size: 1.1rem;
        color: #666;
        user-select: none;
    }

    .input-field {
        width: 100%;
        padding: 0.5rem 2.5rem 0.5rem 0.5rem;
        margin-bottom: 1rem;
        box-sizing: border-box;
    }

    .add-button,
    .register-button {
        padding: 0.5rem 1rem;
        margin-top: 0.5rem;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-weight: bold;
    }

    .add-button {
        background-color: #4caf50;
        color: white;
        margin-right: 0.5rem;
    }

    .register-button {
        background-color: #2196f3;
        color: white;
    }
</style>
