<script lang="ts">
	import { sessionStore, activeSession } from '$lib/stores/session';
	import { formatDateTime } from '$lib/utils/formatters';
	import type { Session } from '$lib/types/api';

	export let session: Session;

	let updatingReference = false;

	async function toggleReference() {
		updatingReference = true;
		await sessionStore.updateSessionReference(session.id, !session.is_reference);
		updatingReference = false;
	}
</script>

<div class="session-header border-bottom bg-white p-2 p-md-3 shadow-sm">
	<div class="d-flex justify-content-between align-items-start">
		<div class="flex-grow-1 min-w-0 me-2">
			<div class="d-flex align-items-center mb-1 mb-md-2">
				<h4 class="mb-0 me-2 text-truncate session-title">{session.title}</h4>
				{#if session.is_reference}
					<span class="badge bg-info flex-shrink-0">
						<i class="bi bi-star-fill me-1"></i>
						<span class="d-none d-md-inline">Reference</span>
					</span>
				{/if}
			</div>
			<div class="text-muted small session-meta">
				<span class="d-inline-block">
					<i class="bi bi-calendar3 me-1"></i>
					<span class="d-none d-md-inline">Created </span>{formatDateTime(session.created_at)}
				</span>
				<span class="ms-2 ms-md-3 d-inline-block">
					<i class="bi bi-chat-dots me-1"></i>
					{session.messages.length} <span class="d-none d-sm-inline">messages</span>
				</span>
			</div>
		</div>

		<div class="btn-group flex-shrink-0" role="group">
			<button
				type="button"
				class="btn btn-outline-secondary btn-sm"
				class:active={session.is_reference}
				on:click={toggleReference}
				disabled={updatingReference}
				title={session.is_reference ? 'Remove from reference' : 'Mark as reference'}
			>
				{#if updatingReference}
					<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
				{:else}
					<i class="bi bi-star{session.is_reference ? '-fill' : ''}"></i>
				{/if}
			</button>
		</div>
	</div>
</div>

<style>
	.session-header {
		position: sticky;
		top: 0;
		z-index: 10;
	}

	.min-w-0 {
		min-width: 0;
	}

	.session-title {
		font-size: 1.25rem;
	}

	.session-meta {
		font-size: 0.875rem;
	}

	.btn-group .btn.active {
		background-color: #0dcaf0;
		border-color: #0dcaf0;
		color: white;
	}

	/* Mobile optimizations */
	@media (max-width: 576px) {
		.session-title {
			font-size: 1rem;
		}

		.session-meta {
			font-size: 0.8125rem;
		}

		.badge {
			font-size: 0.7rem;
			padding: 0.2rem 0.35rem;
		}
	}

	/* Tablet and up */
	@media (min-width: 768px) {
		.session-title {
			font-size: 1.5rem;
		}
	}
</style>
