<script lang="ts">
	import type { DemoData } from '$types';
	import type { ScheduleSlot } from '$lib/features/schedule/api/schedule';
	import type { StudentHomework, StudentHomeworkDetail } from '$lib/features/homework/api/studentHomework';
	import { fetchChildDaySchedule } from '$lib/features/schedule/api/parentSchedule';
	import type { ChildHomework } from '$lib/features/homework/api/parentHomework';
	import { fetchChildrenHomework, fetchParentHomeworkDetail, getParentAttachmentUrl } from '$lib/features/homework/api/parentHomework';
	import { recordSync } from '$lib/features/schedule/stores/scheduleCache.svelte';
	import HomeworkDetail from '$lib/components/organisms/StudentHomework/HomeworkDetail.svelte';
	import SerenityScorePreview from '$lib/components/molecules/SerenityScore/SerenityScorePreview.svelte';
	import SerenityScoreExplainer from '$lib/components/molecules/SerenityScore/SerenityScoreExplainer.svelte';
	import DashboardSection from '$lib/components/molecules/DashboardSection.svelte';
	import SkeletonCard from '$lib/components/atoms/Skeleton/SkeletonCard.svelte';
	import SkeletonList from '$lib/components/atoms/Skeleton/SkeletonList.svelte';
	import ScheduleWidget from '$lib/components/organisms/StudentSchedule/ScheduleWidget.svelte';
	import MultiChildSummary from '$lib/components/organisms/ParentSchedule/MultiChildSummary.svelte';
	import type { SerenityEmoji } from '$lib/features/dashboard/serenity-score';
	import { getActiveRole } from '$features/roles/roleContext.svelte';

	let {
		demoData,
		isFirstLogin = false,
		isLoading = false,
		hasRealData = false,
		serenityEnabled = false,
		childName = '',
		selectedChildId = null,
		onToggleSerenity
	}: {
		demoData: DemoData;
		isFirstLogin?: boolean;
		isLoading?: boolean;
		hasRealData?: boolean;
		serenityEnabled?: boolean;
		childName?: string;
		selectedChildId?: string | null;
		onToggleSerenity?: (enabled: boolean) => void;
	} = $props();

	let isParent = $derived(getActiveRole() === 'ROLE_PARENT');

	// Schedule widget state — mirrors DashboardStudent pattern
	let scheduleSlots = $state<ScheduleSlot[]>([]);
	let scheduleNextSlotId = $state<string | null>(null);
	let scheduleLoading = $state(false);
	let scheduleError = $state<string | null>(null);

	function formatLocalDate(d: Date): string {
		const y = d.getFullYear();
		const m = String(d.getMonth() + 1).padStart(2, '0');
		const day = String(d.getDate()).padStart(2, '0');
		return `${y}-${m}-${day}`;
	}

	async function loadChildSchedule(childId: string) {
		scheduleLoading = true;
		scheduleError = null;

		try {
			const today = formatLocalDate(new Date());
			scheduleSlots = await fetchChildDaySchedule(childId, today);
			recordSync();

			// Compute next slot
			const now = new Date();
			const currentTime = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
			const next = scheduleSlots.find((s) => s.date === today && s.startTime > currentTime);
			scheduleNextSlotId = next?.slotId ?? null;
		} catch (e) {
			scheduleError = e instanceof Error ? e.message : 'Erreur de chargement';
		} finally {
			scheduleLoading = false;
		}
	}

	// Homework widget state
	let childrenHomework = $state<ChildHomework[]>([]);
	let homeworkLoading = $state(false);

	interface HomeworkWithChild extends StudentHomework {
		childFirstName: string;
	}

	let parentHomeworks = $derived<HomeworkWithChild[]>(
		childrenHomework.flatMap((c) =>
			c.homework.map((hw) => ({ ...hw, childFirstName: c.firstName }))
		).sort((a, b) => a.dueDate.localeCompare(b.dueDate)).slice(0, 5)
	);

	async function loadHomeworks() {
		homeworkLoading = true;

		try {
			childrenHomework = await fetchChildrenHomework();
		} catch {
			// Silently fail on dashboard widget
		} finally {
			homeworkLoading = false;
		}
	}

	// Homework detail modal
	let selectedHomeworkDetail = $state<StudentHomeworkDetail | null>(null);

	async function openHomeworkDetail(homeworkId: string) {
		try {
			selectedHomeworkDetail = await fetchParentHomeworkDetail(homeworkId);
		} catch {
			window.location.href = '/dashboard/parent-homework';
		}
	}

	function closeHomeworkDetail() {
		selectedHomeworkDetail = null;
	}

	function handleOverlayClick(e: MouseEvent) {
		if (e.target === e.currentTarget) closeHomeworkDetail();
	}

	function handleModalKeydown(e: KeyboardEvent) {
		if (e.key === 'Escape') closeHomeworkDetail();
	}

	function formatShortDate(dateStr: string): string {
		const date = new Date(dateStr + 'T00:00:00');
		return date.toLocaleDateString('fr-FR', { day: 'numeric', month: 'short' });
	}

	// Load schedule and homework when selectedChildId changes
	$effect(() => {
		if (isParent && selectedChildId) {
			loadChildSchedule(selectedChildId);
		}
	});

	$effect(() => {
		if (isParent) {
			loadHomeworks();
		}
	});

	let showExplainer = $state(false);

	const isDemo = $derived(!hasRealData);

	function openExplainer() {
		showExplainer = true;
	}

	function closeExplainer() {
		showExplainer = false;
	}
</script>

<div class="dashboard-parent">
	{#if isFirstLogin}
		<div class="onboarding-banner">
			<div class="onboarding-content">
				<span class="onboarding-icon">👋</span>
				<div class="onboarding-text">
					<h2>Bienvenue sur Classeo !</h2>
					<p>
						Découvrez le Score Sérénité, un indicateur unique qui vous donne en un coup d'œil une vision globale de la scolarité de votre enfant.
						{#if isDemo}
							Les données actuelles sont des exemples. Vos vraies données apparaîtront bientôt.
						{/if}
					</p>
				</div>
			</div>
		</div>
	{/if}

	<div class="dashboard-grid">
		<!-- Score Serenite - Always visible as demo or real -->
		<div class="score-section">
			{#if isLoading}
				<SkeletonCard message={childName ? `Calcul du Score Sérénité de ${childName}...` : 'Calcul du Score Sérénité...'} />
			{:else}
				<SerenityScorePreview
					value={demoData.serenityScore.value}
					emoji={demoData.serenityScore.emoji as SerenityEmoji}
					isDemo={isDemo}
					onClick={openExplainer}
				/>
			{/if}
		</div>

		<!-- EDT Section -->
		<DashboardSection
			title="Emploi du temps"
			subtitle={isParent ? "Aujourd'hui" : (hasRealData ? "Aujourd'hui" : undefined)}
			isPlaceholder={!isParent && !hasRealData}
			placeholderMessage="L'emploi du temps sera disponible une fois les cours configurés"
		>
			{#if isParent && selectedChildId}
				<ScheduleWidget
					slots={scheduleSlots}
					nextSlotId={scheduleNextSlotId}
					isLoading={scheduleLoading}
					error={scheduleError}
				/>
			{:else if isParent}
				<MultiChildSummary />
			{:else if hasRealData}
				{#if isLoading}
					<SkeletonList items={4} message={childName ? `Chargement de l'emploi du temps de ${childName}...` : "Chargement de l'emploi du temps..."} />
				{:else}
					<ul class="schedule-list">
						{#each demoData.schedule.today as item}
							<li class="schedule-item">
								<span class="schedule-time">{item.time}</span>
								<span class="schedule-subject">{item.subject}</span>
								<span class="schedule-room">{item.room}</span>
							</li>
						{/each}
					</ul>
				{/if}
			{/if}
		</DashboardSection>

		<!-- Notes Section -->
		<DashboardSection
			title="Notes récentes"
			isPlaceholder={!hasRealData}
			placeholderMessage="Les notes apparaîtront ici dès qu'elles seront saisies"
		>
			{#if hasRealData}
				{#if isLoading}
					<SkeletonList items={3} message="Récupération des notes..." />
				{:else}
					<ul class="grades-list">
						{#each demoData.grades.recent as grade}
							<li class="grade-item">
								<span class="grade-subject">{grade.subject}</span>
								<span class="grade-value">{grade.value}/{grade.max}</span>
								<span class="grade-eval">{grade.evaluation}</span>
							</li>
						{/each}
					</ul>
				{/if}
			{/if}
		</DashboardSection>

		<!-- Devoirs Section -->
		<DashboardSection
			title="Devoirs à venir"
			isPlaceholder={!isParent && !hasRealData}
			placeholderMessage="Les devoirs seront affichés ici une fois assignés"
		>
			{#if isParent}
				{#if homeworkLoading}
					<SkeletonList items={3} message="Chargement des devoirs..." />
				{:else if parentHomeworks.length === 0}
					<p class="empty-homework">Aucun devoir à venir</p>
				{:else}
					<ul class="homework-list">
						{#each parentHomeworks as homework}
							<li>
								<button class="homework-item" style:border-left-color={homework.subjectColor ?? '#3b82f6'} onclick={() => openHomeworkDetail(homework.id)}>
									<div class="homework-header">
										<span class="homework-subject" style:color={homework.subjectColor ?? '#3b82f6'}>{homework.subjectName}</span>
										<span class="homework-child">{homework.childFirstName}</span>
									</div>
									<span class="homework-title">{homework.title}</span>
									<span class="homework-due">Pour le {formatShortDate(homework.dueDate)}</span>
								</button>
							</li>
						{/each}
					</ul>
					<a href="/dashboard/parent-homework" class="view-all-link">
						Voir tous les devoirs →
					</a>
				{/if}
			{:else if hasRealData}
				{#if isLoading}
					<SkeletonList items={3} message="Chargement des devoirs..." />
				{:else}
					<ul class="homework-list">
						{#each demoData.homework.upcoming as homework}
							<li class="homework-item" class:done={homework.status === 'done'}>
								<span class="homework-subject">{homework.subject}</span>
								<span class="homework-title">{homework.title}</span>
								<span class="homework-due">Pour le {homework.dueDate}</span>
								{#if homework.status === 'done'}
									<span class="homework-status done">✓ Fait</span>
								{:else if homework.status === 'late'}
									<span class="homework-status late">En retard</span>
								{/if}
							</li>
						{/each}
					</ul>
				{/if}
			{/if}
		</DashboardSection>
	</div>
</div>

{#if selectedHomeworkDetail}
	<!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
	<div class="homework-modal-overlay" onclick={handleOverlayClick} onkeydown={handleModalKeydown} role="presentation">
		<div class="homework-modal" role="dialog" aria-modal="true" aria-label="Détail du devoir">
			<button class="homework-modal-close" onclick={closeHomeworkDetail} aria-label="Fermer">&times;</button>
			<HomeworkDetail detail={selectedHomeworkDetail} onBack={closeHomeworkDetail} getAttachmentUrl={getParentAttachmentUrl} />
		</div>
	</div>
{/if}

{#if showExplainer}
	<SerenityScoreExplainer
		score={demoData.serenityScore}
		isEnabled={serenityEnabled}
		isDemo={isDemo}
		onClose={closeExplainer}
		onToggleOptIn={onToggleSerenity}
	/>
{/if}

<style>
	.dashboard-parent {
		display: flex;
		flex-direction: column;
		gap: 1.5rem;
	}

	.onboarding-banner {
		background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
		border-radius: 1rem;
		color: white;
		overflow: hidden;
	}

	.onboarding-content {
		display: flex;
		gap: 1rem;
		padding: 1.5rem;
		align-items: flex-start;
	}

	.onboarding-icon {
		font-size: 2rem;
		flex-shrink: 0;
	}

	.onboarding-text h2 {
		margin: 0 0 0.5rem;
		font-size: 1.25rem;
		font-weight: 600;
	}

	.onboarding-text p {
		margin: 0;
		font-size: 0.875rem;
		opacity: 0.9;
		line-height: 1.5;
	}

	.dashboard-grid {
		display: grid;
		gap: 1.5rem;
		grid-template-columns: 1fr;
	}

	@media (min-width: 768px) {
		.dashboard-grid {
			grid-template-columns: repeat(2, 1fr);
		}

		.score-section {
			grid-column: 1 / -1;
		}
	}

	@media (min-width: 1024px) {
		.dashboard-grid {
			grid-template-columns: repeat(3, 1fr);
		}

		.score-section {
			grid-column: 1 / 2;
		}
	}

	.score-section {
		display: flex;
	}

	/* Schedule List */
	.schedule-list {
		list-style: none;
		margin: 0;
		padding: 0;
		display: flex;
		flex-direction: column;
		gap: 0.75rem;
	}

	.schedule-item {
		display: grid;
		grid-template-columns: auto 1fr auto;
		gap: 1rem;
		padding: 0.75rem;
		background: #f9fafb;
		border-radius: 0.5rem;
		align-items: center;
	}

	.schedule-time {
		font-weight: 600;
		color: #3b82f6;
		font-size: 0.875rem;
	}

	.schedule-subject {
		font-weight: 500;
		color: #1f2937;
	}

	.schedule-room {
		font-size: 0.875rem;
		color: #6b7280;
	}

	/* Grades List */
	.grades-list {
		list-style: none;
		margin: 0;
		padding: 0;
		display: flex;
		flex-direction: column;
		gap: 0.75rem;
	}

	.grade-item {
		display: grid;
		grid-template-columns: 1fr auto;
		gap: 0.5rem;
		padding: 0.75rem;
		background: #f9fafb;
		border-radius: 0.5rem;
	}

	.grade-subject {
		font-weight: 500;
		color: #1f2937;
	}

	.grade-value {
		font-weight: 600;
		color: #22c55e;
	}

	.grade-eval {
		font-size: 0.875rem;
		color: #6b7280;
		grid-column: 1 / -1;
	}

	/* Homework List */
	.homework-list {
		list-style: none;
		margin: 0;
		padding: 0;
		display: flex;
		flex-direction: column;
		gap: 0.75rem;
	}

	.homework-item {
		display: flex;
		flex-direction: column;
		gap: 0.25rem;
		padding: 0.75rem;
		background: #f9fafb;
		border-radius: 0.5rem;
		border-left: 3px solid #3b82f6;
	}

	.homework-item.done {
		border-left-color: #22c55e;
		opacity: 0.7;
	}

	.homework-subject {
		font-size: 0.75rem;
		font-weight: 600;
		color: #3b82f6;
		text-transform: uppercase;
	}

	.homework-title {
		font-weight: 500;
		color: #1f2937;
	}

	.homework-due {
		font-size: 0.875rem;
		color: #6b7280;
	}

	.homework-status {
		font-size: 0.75rem;
		padding: 0.125rem 0.5rem;
		border-radius: 0.25rem;
		width: fit-content;
	}

	.homework-status.done {
		background: #dcfce7;
		color: #166534;
	}

	.homework-status.late {
		background: #fee2e2;
		color: #991b1b;
	}

	button.homework-item {
		width: 100%;
		text-align: left;
		cursor: pointer;
		border: none;
		background: #f9fafb;
	}

	button.homework-item:hover {
		background: #f3f4f6;
		box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
	}

	.homework-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 0.125rem;
	}

	.homework-child {
		font-size: 0.75rem;
		font-weight: 500;
		color: #6b7280;
		background: #f3f4f6;
		padding: 0.0625rem 0.375rem;
		border-radius: 0.25rem;
	}

	.view-all-link {
		display: block;
		text-align: center;
		margin-top: 0.5rem;
		padding: 0.5rem;
		font-size: 0.875rem;
		font-weight: 500;
		color: #3b82f6;
		text-decoration: none;
	}

	.view-all-link:hover {
		color: #2563eb;
		text-decoration: underline;
	}

	.empty-homework {
		text-align: center;
		padding: 1rem;
		color: #6b7280;
		font-size: 0.875rem;
	}

	/* Homework detail modal */
	.homework-modal-overlay {
		position: fixed;
		inset: 0;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 50;
		padding: 1rem;
	}

	.homework-modal {
		position: relative;
		background: white;
		border-radius: 0.75rem;
		padding: 1.5rem;
		max-width: 40rem;
		width: 100%;
		max-height: 80vh;
		overflow-y: auto;
		box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
	}

	.homework-modal-close {
		position: absolute;
		top: 0.75rem;
		right: 0.75rem;
		background: none;
		border: none;
		font-size: 1.5rem;
		color: #6b7280;
		cursor: pointer;
		line-height: 1;
		padding: 0.25rem;
	}

	.homework-modal-close:hover {
		color: #1f2937;
	}
</style>
