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

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

	interface Props {
		open: boolean;
		onclose: () => void;
	}

	let { open = $bindable(), onclose }: Props = $props();

	let loading = $state(true);
	let overdueTasks = $state<Task[]>([]);
	let todayTasks = $state<Task[]>([]);
	let upcomingTasks = $state<Task[]>([]);
	let projects = $state<{ id: string; name: string }[]>([]);
	let completing = $state<Set<string>>(new Set());

	// Quick add
	let quickTitle = $state('');
	let quickProjectId = $state('');
	let saving = $state(false);

	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(), 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 formatDueLabel(task: Task): string {
		const d = task.startDate || task.dueDate;
		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 === 0) return '';
			if (diff === 1) return 'Tomorrow';
			if (diff === -1) return 'Yesterday';
			if (diff < -1) return `${Math.abs(diff)}d overdue`;
			if (diff <= 7) return date.toLocaleDateString('en-US', { weekday: 'short' });
			return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
		} catch { return ''; }
	}

	function isOverdue(task: Task): boolean {
		const d = task.startDate || task.dueDate;
		if (!d) return false;
		return new Date(d) < new Date(new Date().toDateString());
	}

	async function loadAll() {
		loading = true;
		try {
			const [todayData, allData, projData] = await Promise.all([
				api('/today'),
				api('/tasks'),
				api('/projects'),
			]);

			overdueTasks = (todayData.overdue || []).sort((a: Task, b: Task) =>
				(a.startDate || a.dueDate || '').localeCompare(b.startDate || b.dueDate || ''));
			todayTasks = (todayData.today || []).sort((a: Task, b: Task) =>
				(a.startDate || a.dueDate || '').localeCompare(b.startDate || b.dueDate || ''));

			// Upcoming = tasks with future dates, not today
			const todayStr = new Date().toISOString().split('T')[0];
			upcomingTasks = (allData.tasks || [])
				.filter((t: Task) => {
					const d = (t.startDate || t.dueDate || '')?.slice(0, 10);
					return d > todayStr && t.status === 0;
				})
				.sort((a: Task, b: Task) =>
					(a.startDate || a.dueDate || '').localeCompare(b.startDate || b.dueDate || ''))
				.slice(0, 8);

			projects = (projData.projects || []).map((p: any) => ({ id: p.id, name: p.name }));
			if (projects.length > 0 && !quickProjectId) quickProjectId = projects[0].id;
		} catch { /* silent */ }
		loading = false;
		completing = new Set();
	}

	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(loadAll, 400);
		} catch {
			completing = new Set([...completing].filter(id => id !== task.id));
		}
	}

	async function quickAdd() {
		if (!quickTitle.trim()) return;
		saving = true;
		try {
			const now = new Date();
			const todayStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}T00:00:00+0000`;
			await api('/tasks', {
				method: 'POST',
				headers: { 'Content-Type': 'application/json' },
				body: JSON.stringify({
					title: quickTitle.trim(),
					projectId: quickProjectId || undefined,
					dueDate: todayStr,
					isAllDay: true,
				})
			});
			quickTitle = '';
			await loadAll();
		} catch { /* silent */ }
		saving = false;
	}

	function handleKeydown(e: KeyboardEvent) {
		if (e.key === 'Escape') onclose();
	}

	function handleQuickKeydown(e: KeyboardEvent) {
		if (e.key === 'Enter') quickAdd();
	}

	$effect(() => {
		if (open) loadAll();
	});
</script>

<svelte:window onkeydown={open ? handleKeydown : undefined} />

{#if open}
	<!-- svelte-ignore a11y_no_static_element_interactions -->
	<div class="so-overlay" class:so-visible={open} onclick={(e) => { if (e.target === e.currentTarget) onclose(); }} onkeydown={() => {}}>
		<div class="so-panel" class:so-enter={open}>

			<!-- Header -->
			<div class="so-header">
				<div>
					<div class="so-label">Tasks</div>
					<div class="so-summary">
						{#if overdueTasks.length > 0}
							<span class="so-overdue-count">{overdueTasks.length} overdue</span>
							<span class="so-sep">&middot;</span>
						{/if}
						{todayTasks.length} today
					</div>
				</div>
				<div class="so-header-actions">
					<a href="/tasks" class="so-manage" onclick={onclose}>Manage</a>
					<button class="so-close" onclick={onclose}>
						<svg width="18" height="18" viewBox="0 0 18 18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="4" y1="4" x2="14" y2="14"/><line x1="14" y1="4" x2="4" y2="14"/></svg>
					</button>
				</div>
			</div>

			<!-- Body -->
			<div class="so-body">
				{#if loading}
					<div class="so-loading">
						<div class="skeleton" style="height:40px;margin-bottom:8px"></div>
						<div class="skeleton" style="height:40px;margin-bottom:8px"></div>
						<div class="skeleton" style="height:40px"></div>
					</div>
				{:else}

					<!-- Next Up (first overdue or first today) -->
					{@const nextTask = overdueTasks[0] || todayTasks[0]}
					{#if nextTask}
						<div class="so-section">
							<div class="so-section-label">Next up</div>
							<div class="so-next" class:so-next-overdue={isOverdue(nextTask)}>
								<button class="so-check-lg" onclick={() => completeTask(nextTask)} class:so-completing={completing.has(nextTask.id)}>
									<svg width="22" height="22" viewBox="0 0 22 22" fill="none">
										<rect x="1.5" y="1.5" width="19" height="19" rx="5" stroke="{isOverdue(nextTask) ? 'var(--error)' : 'var(--accent)'}" stroke-width="2"/>
									</svg>
								</button>
								<div class="so-next-content">
									<div class="so-next-title">{nextTask.title}</div>
									<div class="so-next-meta">
										{#if formatTime(nextTask)}{formatTime(nextTask)} &middot; {/if}{nextTask._projectName}
										{#if isOverdue(nextTask)}
											<span class="so-overdue-badge">{formatDueLabel(nextTask)}</span>
										{/if}
									</div>
								</div>
							</div>
						</div>
					{/if}

					<!-- Today -->
					{@const restToday = nextTask ? [...overdueTasks.slice(isOverdue(nextTask) ? 1 : 0), ...todayTasks.slice(isOverdue(nextTask) ? 0 : 1)] : []}
					{#if restToday.length > 0}
						<div class="so-section">
							<div class="so-section-label">{overdueTasks.length > 0 ? 'Today & Overdue' : 'Today'} &middot; {restToday.length}</div>
							{#each restToday as task (task.id)}
								<div class="so-row" class:so-completing={completing.has(task.id)}>
									<button class="so-check" onclick={() => completeTask(task)}>
										<svg width="16" height="16" viewBox="0 0 16 16" fill="none">
											<rect x="1" y="1" width="14" height="14" rx="3.5" stroke="{isOverdue(task) ? 'var(--error)' : 'var(--border-strong)'}" stroke-width="1.5"/>
										</svg>
									</button>
									<span class="so-row-title" class:so-row-overdue={isOverdue(task)}>{task.title}</span>
									<span class="so-row-meta">
										{#if formatTime(task)}{formatTime(task)}{:else}{task._projectName}{/if}
									</span>
								</div>
							{/each}
						</div>
					{/if}

					<!-- Upcoming -->
					{#if upcomingTasks.length > 0}
						<div class="so-section">
							<div class="so-section-label">Upcoming</div>
							{#each upcomingTasks as task (task.id)}
								<div class="so-row" class:so-completing={completing.has(task.id)}>
									<button class="so-check" onclick={() => completeTask(task)}>
										<svg width="16" height="16" viewBox="0 0 16 16" fill="none">
											<rect x="1" y="1" width="14" height="14" rx="3.5" stroke="var(--border-strong)" stroke-width="1.5"/>
										</svg>
									</button>
									<span class="so-row-title">{task.title}</span>
									<span class="so-row-meta">{formatDueLabel(task)}</span>
								</div>
							{/each}
						</div>
					{/if}

					<!-- Empty -->
					{#if !nextTask && restToday.length === 0 && upcomingTasks.length === 0}
						<div class="so-empty">All clear. Nothing on the agenda.</div>
					{/if}

				{/if}
			</div>

			<!-- Quick Add -->
			<div class="so-footer">
				<div class="so-quick-add">
					<input
						class="so-quick-input"
						placeholder="Quick add task..."
						bind:value={quickTitle}
						onkeydown={handleQuickKeydown}
						disabled={saving}
					/>
					{#if quickTitle.trim()}
						<button class="so-quick-submit" onclick={quickAdd} disabled={saving}>
							{saving ? '...' : 'Add'}
						</button>
					{/if}
				</div>
			</div>

		</div>
	</div>
{/if}

<style>
	/* ── Overlay ── */
	.so-overlay {
		position: fixed;
		inset: 0;
		z-index: 90;
		background: rgba(0, 0, 0, 0);
		transition: background 0.3s ease;
	}
	.so-overlay.so-visible {
		background: var(--overlay);
	}

	/* ── Panel ── */
	.so-panel {
		position: absolute;
		right: 0;
		top: 0;
		bottom: 0;
		width: 400px;
		max-width: 100vw;
		background: var(--surface);
		box-shadow: -8px 0 32px rgba(0,0,0,0.1);
		display: flex;
		flex-direction: column;
		transform: translateX(100%);
		transition: transform 0.35s cubic-bezier(0.16, 1, 0.3, 1);
	}
	.so-panel.so-enter {
		transform: translateX(0);
	}

	/* ── Header ── */
	.so-header {
		display: flex;
		align-items: flex-start;
		justify-content: space-between;
		padding: var(--sp-6) var(--sp-6) var(--sp-4);
		border-bottom: 1px solid var(--border);
		flex-shrink: 0;
	}

	.so-label {
		font-size: var(--text-lg);
		font-weight: 700;
		color: var(--text-1);
		letter-spacing: -0.02em;
	}

	.so-summary {
		font-size: var(--text-sm);
		color: var(--text-3);
		margin-top: 2px;
	}

	.so-overdue-count { color: var(--error); font-weight: 600; }
	.so-sep { color: var(--text-4); margin: 0 2px; }

	.so-header-actions {
		display: flex;
		align-items: center;
		gap: var(--sp-3);
	}

	.so-manage {
		font-size: var(--text-sm);
		color: var(--accent);
		text-decoration: none;
		font-weight: 500;
	}
	.so-manage:hover { text-decoration: underline; }

	.so-close {
		width: 32px;
		height: 32px;
		border-radius: var(--radius-md);
		border: none;
		background: none;
		color: var(--text-3);
		cursor: pointer;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: all 0.15s;
	}
	.so-close:hover { background: var(--card-hover); color: var(--text-1); }

	/* ── Body ── */
	.so-body {
		flex: 1;
		overflow-y: auto;
		padding: var(--sp-2) var(--sp-6);
	}

	.so-loading { padding: var(--sp-4) 0; }

	/* ── Section ── */
	.so-section {
		padding: var(--sp-4) 0 var(--sp-2);
	}

	.so-section-label {
		font-size: 10px;
		font-weight: 700;
		text-transform: uppercase;
		letter-spacing: 0.1em;
		color: var(--text-4);
		margin-bottom: var(--sp-2);
	}

	/* ── Next Up (hero task) ── */
	.so-next {
		display: flex;
		align-items: flex-start;
		gap: var(--sp-3);
		padding: var(--sp-4);
		background: var(--accent-dim);
		border-radius: var(--radius);
		transition: opacity 0.3s;
	}
	.so-next.so-next-overdue { background: var(--error-dim); }

	.so-check-lg {
		flex-shrink: 0;
		padding: 0;
		background: none;
		border: none;
		cursor: pointer;
		margin-top: 1px;
		transition: transform 0.15s;
	}
	.so-check-lg:hover { transform: scale(1.1); }
	.so-check-lg.so-completing { opacity: 0.3; }
	.so-check-lg:hover svg rect { fill: var(--accent-dim); }

	.so-next-content { flex: 1; min-width: 0; }

	.so-next-title {
		font-size: var(--text-md);
		font-weight: 600;
		color: var(--text-1);
		line-height: var(--leading-snug);
	}

	.so-next-meta {
		font-size: var(--text-sm);
		color: var(--text-3);
		margin-top: 3px;
		display: flex;
		align-items: center;
		gap: var(--sp-2);
		flex-wrap: wrap;
	}

	.so-overdue-badge {
		font-size: 10px;
		font-weight: 700;
		color: var(--error);
		text-transform: uppercase;
		letter-spacing: 0.04em;
	}

	/* ── Task rows ── */
	.so-row {
		display: flex;
		align-items: center;
		gap: var(--sp-2);
		padding: 9px 0;
		transition: opacity 0.3s;
	}
	.so-row.so-completing { opacity: 0.15; }

	.so-check {
		flex-shrink: 0;
		padding: 0;
		background: none;
		border: none;
		cursor: pointer;
		display: flex;
		align-items: center;
		opacity: 0.5;
		transition: opacity 0.15s;
	}
	.so-row:hover .so-check { opacity: 1; }
	.so-check:hover svg rect { stroke: var(--accent); fill: var(--accent-dim); }

	.so-row-title {
		flex: 1;
		font-size: var(--text-sm);
		color: var(--text-1);
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		min-width: 0;
	}
	.so-row-title.so-row-overdue { color: var(--error); }

	.so-row-meta {
		flex-shrink: 0;
		font-size: 11px;
		color: var(--text-4);
		font-family: var(--mono);
	}

	.so-empty {
		padding: var(--sp-10) var(--sp-4);
		text-align: center;
		color: var(--text-4);
		font-size: var(--text-sm);
	}

	/* ── Quick Add ── */
	.so-footer {
		flex-shrink: 0;
		padding: var(--sp-4) var(--sp-6);
		border-top: 1px solid var(--border);
		background: var(--surface);
	}

	.so-quick-add {
		display: flex;
		gap: var(--sp-2);
		align-items: center;
	}

	.so-quick-input {
		flex: 1;
		padding: 10px 14px;
		border-radius: var(--radius-md);
		background: var(--surface-secondary);
		border: 1px solid var(--border);
		color: var(--text-1);
		font-size: var(--text-sm);
		font-family: var(--font);
		outline: none;
		transition: border-color 0.15s;
	}
	.so-quick-input:focus { border-color: var(--accent); }
	.so-quick-input::placeholder { color: var(--text-4); }

	.so-quick-submit {
		padding: 10px var(--sp-4);
		border-radius: var(--radius-md);
		background: var(--accent);
		color: white;
		border: none;
		font-size: var(--text-sm);
		font-weight: 600;
		cursor: pointer;
		white-space: nowrap;
		transition: opacity 0.15s;
	}
	.so-quick-submit:hover { opacity: 0.9; }

	/* ── Mobile ── */
	@media (max-width: 480px) {
		.so-panel { width: 100vw; }
		.so-header { padding: var(--sp-5) var(--sp-5) var(--sp-3); }
		.so-body { padding: var(--sp-2) var(--sp-5); }
		.so-footer { padding: var(--sp-4) var(--sp-5); }
	}
</style>
