<script lang="ts">
	import { onMount } from 'svelte';
	import { goto } from '$app/navigation';

	let authorized = false;
	let refreshToken = '';

	let to = '';
	let subject = '';
	let body = '';

	onMount(() => {
		refreshToken = localStorage.getItem('gmail_refresh_token') ?? '';
		authorized = !!refreshToken;
	});

	/* ⇢ redirects straight to Google via server 302 */
	const connect = () => goto('/private/api/gmail?action=auth');

	async function sendEmail() {
		const r = await fetch('/private/api/gmail', {
			method: 'POST',
			headers: { 'Content-Type': 'application/json' },
			body: JSON.stringify({
				action: 'send',
				to,
				subject,
				text: body,
				refreshToken
			})
		});
		r.ok ? alert('Sent!') : alert(await r.text());
		to = subject = body = '';
	}

	async function disconnect() {
		if (!confirm('Disconnect Google account?')) return;
		await fetch('/private/api/gmail', {
			method: 'POST',
			headers: { 'Content-Type': 'application/json' },
			body: JSON.stringify({ action: 'revoke', refreshToken })
		});
		localStorage.removeItem('gmail_refresh_token');
		refreshToken = '';
		authorized = false;
	}
</script>

{#if !authorized}
	<section class="space-y-4">
		<p>You haven’t connected your Google account yet.</p>
		<button class="btn" on:click={connect}>Connect Google</button>
	</section>
{:else}
	<button class="btn-secondary mb-4" on:click={disconnect}>Disconnect Google</button>

	<form class="space-y-4" on:submit|preventDefault={sendEmail}>
		<input  class="input w-full" type="email" placeholder="recipient@example.com" bind:value={to} required />
		<input  class="input w-full" placeholder="Subject" bind:value={subject} required />
		<textarea class="textarea w-full" rows="6" placeholder="Message" bind:value={body} required />
		<button class="btn-primary">Send</button>
	</form>
{/if}
