<script lang="ts">
	import type { Notification } from '$lib/graphql/queries/notifications';

	interface Props {
		notification: Notification;
		onMarkAsRead?: (notification: Notification) => void;
		onDelete?: (notification: Notification) => void;
		compact?: boolean;
	}

	let { notification, onMarkAsRead, onDelete, compact = false }: Props = $props();

	function formatRelativeTime(dateStr: string): string {
		const date = new Date(dateStr);
		const now = new Date();
		const diffMs = now.getTime() - date.getTime();
		const diffSecs = Math.floor(diffMs / 1000);
		const diffMins = Math.floor(diffSecs / 60);
		const diffHours = Math.floor(diffMins / 60);
		const diffDays = Math.floor(diffHours / 24);

		if (diffSecs < 60) return 'Just now';
		if (diffMins < 60) return `${diffMins}m ago`;
		if (diffHours < 24) return `${diffHours}h ago`;
		if (diffDays < 7) return `${diffDays}d ago`;
		return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
	}

	function handleClick() {
		if (onMarkAsRead && !notification.isRead) {
			onMarkAsRead(notification);
		}
	}

	function handleDelete(e: MouseEvent) {
		e.stopPropagation();
		if (onDelete) {
			onDelete(notification);
		}
	}
</script>

<div
	class="group hover:bg-theme-hover relative rounded-lg border border-theme bg-theme-card p-3 transition-colors {!notification.isRead
		? 'border-l-4 border-l-accent-500'
		: ''} {compact ? 'p-2' : 'p-3'}"
>
	<button type="button" class="w-full text-left" onclick={handleClick}>
		<div class="flex items-start justify-between gap-3">
			<div class="min-w-0 flex-1">
				<!-- Subject -->
				<h4
					class="text-sm font-medium {!notification.isRead
						? 'text-theme'
						: 'text-theme-secondary'} {compact ? 'text-xs' : 'text-sm'}"
				>
					{notification.subject}
				</h4>

				{#if !compact}
					<!-- Body preview -->
					<p class="mt-1 line-clamp-2 text-xs text-theme-muted">
						{notification.body}
					</p>
				{/if}

				<!-- Time -->
				<span class="mt-1 block text-xs text-theme-muted">
					{formatRelativeTime(notification.createdAt)}
				</span>
			</div>

			<!-- Unread indicator -->
			{#if !notification.isRead}
				<span class="mt-1 h-2 w-2 shrink-0 rounded-full bg-accent-500"></span>
			{/if}
		</div>
	</button>

	<!-- Delete button -->
	{#if onDelete}
		<button
			type="button"
			class="absolute top-1 right-1 rounded p-1 text-theme-muted opacity-0 transition-opacity group-hover:opacity-100 hover:bg-red-100 hover:text-red-600 dark:hover:bg-red-900/30 dark:hover:text-red-400"
			onclick={handleDelete}
			aria-label="Delete notification"
		>
			<svg class="h-3.5 w-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
				<path
					stroke-linecap="round"
					stroke-linejoin="round"
					stroke-width="2"
					d="M6 18L18 6M6 6l12 12"
				/>
			</svg>
		</button>
	{/if}
</div>
