<script lang="ts">
	import './layout.css';
	import Avatar from '$lib/components/Avatar.svelte';
	import favicon from '$lib/assets/favicon.svg';
	import { setUserContext, getUserContext } from '$lib/context';
	import * as TID from '@atcute/tid';
	import { getClient, login } from '$lib/atproto';

	let { children, data } = $props();

	setUserContext({
		loggedIn: data.loggedIn,
		profile: data.profile
	});

	const user = getUserContext();
	let handle = $state('');
	let loggingIn = $state(false);
	let composerDialog: HTMLDialogElement;
	let postContent = $state('');

	async function handleLogin() {
		if (!handle.trim()) return;
		loggingIn = true;
		try {
			await login(handle.trim());
		} catch (exception) {
			console.error(exception);
			loggingIn = false;
		}
	}

	async function createPost() {
		if (!user.profile?.did) {
			throw new Error('need to be authenticated to make a post');
		}

		const client = await getClient();
		const { ok } = await client.post('com.atproto.repo.createRecord', {
			input: {
				repo: user.profile.did,
				collection: 'app.bsky.feed.post',
				rkey: TID.now(), // generates a sortable timestamp-based key
				record: {
					$type: 'app.bsky.feed.post',
					text: postContent,
					createdAt: new Date().toISOString(),
					langs: ['en']
				}
			}
		});
		if (!ok) {
			throw new Error('failed to create post');
		}
		console.log('success!');
		composerDialog.close();
	}
</script>

<svelte:head><link rel="icon" href={favicon} /></svelte:head>
<div class="layout">
	<div class="sidebar sidebar--left p-4">
		{#if user.loggedIn && user.profile}
			<div class="flex items-center gap-2">
				<Avatar user={user.profile} />
				{user.profile?.handle}
			</div>
			<button
				class="align-items flex gap-3 rounded-full bg-post-button px-6 py-3 text-white hover:cursor-pointer"
				onclick={() => composerDialog.showModal()}
			>
				New Post
			</button>
		{:else}
			<form
				onsubmit={(e) => {
					e.preventDefault();
					handleLogin();
				}}
			>
				<input
					type="text"
					placeholder="handle (e.g. alice.bsky.social)"
					bind:value={handle}
					class="mb-2 w-full rounded border px-2 py-1 text-sm"
				/>
				<button
					type="submit"
					disabled={loggingIn}
					class="w-full rounded bg-blue-500 px-3 py-1.5 text-sm text-white hover:bg-blue-600 disabled:opacity-50"
				>
					{loggingIn ? 'Logging in...' : 'Log in'}
				</button>
			</form>
		{/if}
	</div>
	<div class="main">
		{@render children()}
	</div>
	<div class="sidebar sidebar--right">owo</div>
</div>
<dialog
	bind:this={composerDialog}
	class="mx-auto mt-[50px] w-full max-w-[600px] rounded-[8px] border border-modal-border p-2"
>
	<form
		onsubmit={async (e) => {
			e.preventDefault();
			await createPost();
		}}
	>
		<header class="flex h-[54px] items-center justify-between">
			<div>
				<button
					type="button"
					onclick={() => composerDialog.close()}
					class="p-2 text-secondary-blue hover:cursor-pointer"
				>
					Cancel
				</button>
			</div>
			<div>
				<button class="rounded-full bg-post-button px-3.5 py-2 text-white"> Post </button>
			</div>
		</header>
		<main class="flex pl-2">
			{#if user.loggedIn && user.profile}
				<div class="shrink-0">
					<Avatar user={user.profile} />
				</div>
			{/if}
			<textarea
				class="m-[1px] mb-[11px] ml-[9px] min-h-[140px] grow resize-none p-[4px] text-[16.9px] leading-[24px]"
				placeholder="What's up?"
				bind:value={postContent}
			></textarea>
		</main>
	</form>
</dialog>

<style>
	.sidebar {
		position: sticky;
		top: 0;
		bottom: 0;
		max-width: 279px;
		width: 100%;
	}
	.layout {
		height: 100%;
		overflow-y: scroll;
		display: flex;
		justify-content: center;
		align-items: flex-start;
	}
	.main {
		width: 602px;
	}
	dialog::backdrop {
		background-color: rgba(0, 0, 0, 0.8);
	}
</style>
