<script lang="ts">
	import { onMount } from 'svelte';

	interface Task {
		id: string;
		title: string;
		projectId: string;
		_projectName: string;
		_projectId: string;
		dueDate?: string;
		startDate?: string;
		isAllDay?: boolean;
		priority: number;
	}

	let loading = $state(true);
	let todayTasks = $state<Task[]>([]);
	let overdueTasks = $state<Task[]>([]);
	let completing = $state<Set<string>>(new Set());

	async function api(path: string, opts: RequestInit = {}) {
		const res = await fetch(`/api/tasks${path}`, { credentials: 'include', ...opts });
		if (!res.ok) throw new Error(`${res.status}`);
		return res.json();
	}

	function formatTime(task: Task): string {
		const d = task.startDate || task.dueDate;
		if (!d || task.isAllDay) return '';
		try {
			const date = new Date(d);
			const h = date.getHours();
			const m = date.getMinutes();
			if (h === 0 && m === 0) return '';
			const ampm = h >= 12 ? 'PM' : 'AM';
			const hour = h % 12 || 12;
			return m > 0 ? `${hour}:${String(m).padStart(2, '0')} ${ampm}` : `${hour} ${ampm}`;
		} catch { return ''; }
	}

	function formatOverdueDate(task: Task): string {
		const d = task.dueDate || task.startDate;
		if (!d) return '';
		try {
			const date = new Date(d);
			const now = new Date();
			const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
			const taskDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
			const diff = Math.round((taskDate.getTime() - today.getTime()) / 86400000);
			if (diff === -1) return 'Yesterday';
			if (diff < -1) return `${Math.abs(diff)}d ago`;
			return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
		} catch { return ''; }
	}

	function sortByTime(tasks: Task[]): Task[] {
		return [...tasks].sort((a, b) => {
			const aDate = a.startDate || a.dueDate || '9999';
			const bDate = b.startDate || b.dueDate || '9999';
			return aDate.localeCompare(bDate);
		});
	}

	async function completeTask(task: Task) {
		completing = new Set([...completing, task.id]);
		try {
			await api(`/tasks/${task.id}/complete`, {
				method: 'POST',
				headers: { 'Content-Type': 'application/json' },
				body: JSON.stringify({ projectId: task.projectId || task._projectId })
			});
			setTimeout(loadTasks, 300);
		} catch {
			completing = new Set([...completing].filter(id => id !== task.id));
		}
	}

	async function loadTasks() {
		try {
			const data = await api('/today');
			overdueTasks = sortByTime(data.overdue || []).slice(0, 5);
			todayTasks = sortByTime(data.today || []).slice(0, 5);
			loading = false;
		} catch { loading = false; }
	}

	onMount(loadTasks);
</script>

<div class="module tasks-mobile-module">
	<div class="module-header">
		<div class="module-title">Tasks</div>
		<a href="/tasks" class="module-action">View all &rarr;</a>
	</div>

	{#if loading}
		<div class="skeleton" style="height: 80px"></div>
	{:else if overdueTasks.length === 0 && todayTasks.length === 0}
		<div class="tm-empty">All clear for today</div>
	{:else}
		{#if overdueTasks.length > 0}
			<div class="tm-section overdue">Overdue · {overdueTasks.length}</div>
			{#each overdueTasks as task (task.id)}
				<div class="tm-row" class:completing={completing.has(task.id)}>
					<button class="tm-check" onclick={() => completeTask(task)}>
						<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
							<rect x="1.5" y="1.5" width="17" height="17" rx="4" stroke="var(--error)" stroke-width="2"/>
						</svg>
					</button>
					<div class="tm-body">
						<span class="tm-title">{task.title}</span>
						<span class="tm-time">{formatOverdueDate(task)}{#if formatTime(task)} · {formatTime(task)}{/if}</span>
					</div>
					<span class="tm-project">{task._projectName}</span>
				</div>
			{/each}
		{/if}

		{#if todayTasks.length > 0}
			<div class="tm-section">Today · {todayTasks.length}</div>
			{#each todayTasks as task (task.id)}
				<div class="tm-row" class:completing={completing.has(task.id)}>
					<button class="tm-check" onclick={() => completeTask(task)}>
						<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
							<rect x="1.5" y="1.5" width="17" height="17" rx="4" stroke="var(--border-strong)" stroke-width="2"/>
						</svg>
					</button>
					<div class="tm-body">
						<span class="tm-title">{task.title}</span>
						{#if formatTime(task)}
							<span class="tm-time">{formatTime(task)}</span>
						{/if}
					</div>
					<span class="tm-project">{task._projectName}</span>
				</div>
			{/each}
		{/if}
	{/if}
</div>

<style>
	.tasks-mobile-module {
		display: none;
	}

	@media (max-width: 1100px) {
		.tasks-mobile-module {
			display: block;
			margin-bottom: var(--module-gap);
		}
	}

	.tm-section {
		font-size: var(--text-xs);
		font-weight: 600;
		text-transform: uppercase;
		letter-spacing: 0.05em;
		color: var(--text-3);
		padding: var(--sp-3) 0 var(--sp-1);
	}

	.tm-section.overdue {
		color: var(--error);
	}

	.tm-row {
		display: flex;
		align-items: center;
		gap: var(--sp-3);
		padding: var(--sp-3) 0;
		border-bottom: 1px solid var(--border);
		transition: opacity 0.3s;
	}

	.tm-row:last-child {
		border-bottom: none;
	}

	.tm-row.completing {
		opacity: 0.2;
		text-decoration: line-through;
	}

	.tm-check {
		flex-shrink: 0;
		padding: 0;
		background: none;
		border: none;
		cursor: pointer;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.tm-check:hover svg rect {
		stroke: var(--accent);
		fill: var(--accent-dim);
	}

	.tm-body {
		flex: 1;
		min-width: 0;
	}

	.tm-title {
		display: block;
		font-size: var(--text-base);
		font-weight: 500;
		color: var(--text-1);
		line-height: var(--leading-snug);
	}

	.tm-time {
		display: block;
		font-size: var(--text-sm);
		color: var(--text-3);
		margin-top: 2px;
	}

	.tm-project {
		flex-shrink: 0;
		font-size: var(--text-sm);
		color: var(--text-3);
		text-align: right;
		max-width: 120px;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.tm-empty {
		padding: var(--sp-6) 0;
		text-align: center;
		color: var(--text-3);
		font-size: var(--text-sm);
	}
</style>
