<script lang="ts">
	import ParallaxLandscape from "$lib/components/ParallaxLandscape.svelte";
	import Icon from "@iconify/svelte";
	import ChatMessage from "$lib/components/chat/ChatMessage.svelte";
	import ChatInput from "$lib/components/chat/ChatInput.svelte";
	import Mascot from "$lib/components/chat/Mascot.svelte";
	import LoadingBubble from "$lib/components/chat/LoadingBubble.svelte";

	type Message = {
		id: number;
		text: string;
		sender: "user" | "ai";
	};

	let messages = $state<Message[]>([
		{
			id: 1,
			text: "Hello! I'm Ethix AI. Ask me anything about recycling, sustainability, or green products.",
			sender: "ai",
		},
	]);
	let inputText = $state("");
	let isLoading = $state(false);
	let chatWindowFn = $state<HTMLDivElement>();

	function scrollToBottom() {
		if (chatWindowFn) {
			setTimeout(() => {
				chatWindowFn!.scrollTop = chatWindowFn!.scrollHeight;
			}, 0);
		}
	}

	$effect(() => {
		messages;
		isLoading;
		scrollToBottom();
	});

	async function sendMessage() {
		if (!inputText.trim() || isLoading) return;

		const userText = inputText;
		const userMsg = {
			id: Date.now(),
			text: userText,
			sender: "user" as const,
		};
		messages = [...messages, userMsg];
		inputText = "";
		isLoading = true;

		try {
			const response = await fetch(
				"/api/gemini/ask",
				{
					method: "POST",
					headers: { "Content-Type": "application/json" },
					body: JSON.stringify({ prompt: userText }),
				},
			);

			const data = await response.json();

			if (data.status === "success") {
				const aiMsg = {
					id: Date.now() + 1,
					text: data.reply,
					sender: "ai" as const,
				};
				messages = [...messages, aiMsg];
			} else {
				throw new Error(data.message || "Failed to get response");
			}
		} catch (error) {
			const errorMsg = {
				id: Date.now() + 1,
				text: "Sorry, I'm having trouble connecting to my brain right now. Please try again later.",
				sender: "ai" as const,
			};
			messages = [...messages, errorMsg];
			console.error("Chat Error:", error);
		} finally {
			isLoading = false;
		}
	}
</script>

<svelte:head>
	<title>Ethix - Chat Assistant</title>
	<meta
		name="description"
		content="Chat with Ethix AI to get instant answers about recycling, sustainability, and eco-friendly product alternatives."
	/>
</svelte:head>

<div class="fixed inset-0 w-full h-full overflow-hidden bg-[#0c0c0c]">
	<div class="hidden md:block absolute inset-0 pointer-events-none">
		<ParallaxLandscape />
	</div>

	<div
		class="relative z-10 max-w-6xl mx-auto h-full flex flex-col pt-0 pb-20 px-0 md:px-6 md:pt-20 md:pb-10"
	>
		<div
			class="flex flex-col h-full bg-[#0d2e25] md:bg-black/40 md:backdrop-blur-xl border-x md:border border-[#1f473b] md:border-white/10 md:rounded-[32px] overflow-hidden shadow-2xl"
		>
			<div
				class="p-3 px-5 border-b border-[#1f473b] md:border-white/10 bg-[#051f18] md:bg-transparent flex items-center gap-3 shrink-0"
			>
				<Mascot />
				<div class="flex flex-col items-start gap-0.5">
					<h1
						class="text-white text-base font-bold leading-tight m-0"
					>
						Ethix Assistant
					</h1>
					<div
						class="flex items-center gap-1 text-[10px] font-semibold text-emerald-400 tracking-wide bg-emerald-500/10 px-2 py-0.5 rounded-xl border border-emerald-500/20"
					>
						<Icon icon="ri:shining-fill" width="10" />
						<span>Powered by Gemini</span>
					</div>
				</div>
			</div>

			<div
				class="flex-1 flex flex-col overflow-hidden bg-[#0d2e25] md:bg-transparent"
			>
				<div
					class="flex-1 overflow-y-auto p-6 pb-5 flex flex-col gap-4 scroll-smooth scrollbar-none"
					bind:this={chatWindowFn}
				>
					{#each messages as msg (msg.id)}
						<ChatMessage text={msg.text} sender={msg.sender} />
					{/each}

					{#if isLoading}
						<LoadingBubble />
					{/if}
				</div>

				<ChatInput bind:inputText {isLoading} onSend={sendMessage} />
			</div>
		</div>
	</div>
</div>

<style>
	.scrollbar-none::-webkit-scrollbar {
		display: none;
	}

	.scrollbar-none {
		-ms-overflow-style: none;
		scrollbar-width: none;
	}
</style>
