<?php
$context = ru_ufpe_theme_get_unit_page_context();
get_header();
?>

<main class="min-h-screen">
	<div class="mx-auto max-w-ru px-4 py-10 md:py-14 space-y-8">

		<?php if (!$context): ?>
			<div class="notice notice-error"><i data-lucide="circle-x"></i><span>Esta página de cardápio não está vinculada corretamente.</span></div>
		<?php else:
			$unit_post        = $context['unit_post'];
			$unit_meta        = $context['unit_meta'];
			$page_links       = $context['page_links'];
			$weekly_menu_data = ru_ufpe_theme_get_weekly_menu_data_for_unit($unit_post->ID);
			$weekly_menu_days = $weekly_menu_data ? $weekly_menu_data['menu']['days'] : [];
			$week_range       = $weekly_menu_data ? ru_ufpe_theme_format_weekly_menu_range($weekly_menu_data['week_start_date'], $weekly_menu_data['week_end_date']) : '';
			$day_labels       = ru_ufpe_theme_get_weekly_menu_day_labels();
			$meal_labels      = ru_ufpe_theme_get_weekly_menu_meal_labels();
			$section_labels   = ru_ufpe_theme_get_weekly_menu_section_labels();
			$allergen_labels  = ru_ufpe_theme_get_weekly_menu_allergen_options();
			$dietary_labels   = ru_ufpe_theme_get_weekly_menu_dietary_options();
			$day_css_map      = ['segunda' => 'seg', 'terca' => 'ter', 'quarta' => 'qua', 'quinta' => 'qui', 'sexta' => 'sex', 'sabado' => 'sab', 'domingo' => 'dom'];
			$day_short_labels = ['segunda' => 'Seg', 'terca' => 'Ter', 'quarta' => 'Qua', 'quinta' => 'Qui', 'sexta' => 'Sex', 'sabado' => 'Sáb', 'domingo' => 'Dom'];
			$current_day_map  = [0 => 'domingo', 1 => 'segunda', 2 => 'terca', 3 => 'quarta', 4 => 'quinta', 5 => 'sexta', 6 => 'sabado'];
			$current_day_key  = $current_day_map[(int) current_time('w')] ?? 'segunda';
			$available_days   = [];
			foreach ($day_labels as $day_key => $_):
				$day_data  = isset($weekly_menu_days[$day_key]) ? $weekly_menu_days[$day_key] : [];
				$has_items = false;
				foreach ($meal_labels as $meal_key => $_):
					foreach ($section_labels as $section_key => $_):
						if (!empty($day_data[$meal_key][$section_key])) { $has_items = true; break 2; }
					endforeach;
				endforeach;
				if ($has_items) { $available_days[] = $day_key; }
			endforeach;
			$active_day_key = in_array($current_day_key, $available_days, true) ? $current_day_key : ($available_days[0] ?? '');
		?>

		<!-- Page header -->
		<header class="space-y-3">
			<nav class="flex items-center gap-1.5 text-sm text-base-muted" aria-label="Breadcrumb">
				<?php $archive_url = get_post_type_archive_link('unidade'); if ($archive_url): ?>
					<a class="no-underline hover:underline" href="<?php echo esc_url($archive_url); ?>">Unidades</a>
					<span aria-hidden="true">&rsaquo;</span>
				<?php endif; ?>
				<a class="no-underline hover:underline" href="<?php echo esc_url($page_links['overview']); ?>"><?php echo esc_html(get_the_title($unit_post)); ?></a>
				<span aria-hidden="true">&rsaquo;</span>
				<span class="font-semibold text-base-content">Cardápio</span>
			</nav>
			<div>
				<h1 class="text-4xl font-semibold leading-tight tracking-tight text-base-content md:text-5xl">
					Cardápio &mdash; <?php echo esc_html(get_the_title($unit_post)); ?>
				</h1>
				<?php if ($week_range): ?>
					<p class="mt-1 text-sm text-base-muted"><?php echo esc_html($week_range); ?></p>
				<?php endif; ?>
			</div>
			<div class="flex flex-wrap gap-2">
				<a class="btn btn-outline" href="<?php echo esc_url($page_links['overview']); ?>">Visão geral</a>
				<a class="btn btn-primary" href="<?php echo esc_url($page_links['cardapio']); ?>">Cardápio</a>
				<a class="btn btn-outline" href="<?php echo esc_url($page_links['avisos']); ?>">Avisos</a>
			</div>
		</header>

		<!-- Weekly menu -->
		<?php if (empty($available_days)): ?>
			<div class="notice notice-info"><i data-lucide="info"></i><span>Nenhum cardápio disponível para esta semana.</span></div>
		<?php else: ?>
			<div class="weekly-menu-tabs" data-weekly-menu-tabs>
				<div class="weekly-menu-tablist" role="tablist" aria-label="Dias da semana">
					<?php foreach ($available_days as $day_key):
						$day_label = $day_labels[$day_key];
						$day_css   = isset($day_css_map[$day_key]) ? $day_css_map[$day_key] : '';
						$is_today  = $day_key === $current_day_key;
						$is_active = $day_key === $active_day_key;
					?>
						<button
							type="button"
							id="weekly-menu-tab-<?php echo esc_attr($day_key); ?>"
							class="weekly-menu-tab<?php echo $day_css ? ' day-' . esc_attr($day_css) : ''; ?><?php echo $is_today ? ' is-today' : ''; ?><?php echo $is_active ? ' is-active' : ''; ?>"
							role="tab"
							aria-selected="<?php echo $is_active ? 'true' : 'false'; ?>"
							aria-controls="weekly-menu-panel-<?php echo esc_attr($day_key); ?>"
							tabindex="<?php echo $is_active ? '0' : '-1'; ?>"
							data-weekly-menu-tab
							data-weekly-menu-target="weekly-menu-panel-<?php echo esc_attr($day_key); ?>"
						>
							<span class="weekly-menu-tab-short"><?php echo esc_html($day_short_labels[$day_key] ?? $day_label); ?></span>
							<span class="weekly-menu-tab-full"><?php echo esc_html($day_label); ?></span>
							<?php if ($is_today): ?><span class="weekly-menu-today-badge">Hoje</span><?php endif; ?>
						</button>
					<?php endforeach; ?>
				</div>

				<?php foreach ($available_days as $day_key):
					$day_label  = $day_labels[$day_key];
					$day_data   = isset($weekly_menu_days[$day_key]) ? $weekly_menu_days[$day_key] : [];
					$day_css    = isset($day_css_map[$day_key]) ? $day_css_map[$day_key] : '';
					$is_today   = $day_key === $current_day_key;
					$is_active  = $day_key === $active_day_key;
				?>
					<section
						id="weekly-menu-panel-<?php echo esc_attr($day_key); ?>"
						class="weekly-menu-panel<?php echo $day_css ? ' day-' . esc_attr($day_css) : ''; ?><?php echo $is_today ? ' is-today' : ''; ?>"
						role="tabpanel"
						aria-labelledby="weekly-menu-tab-<?php echo esc_attr($day_key); ?>"
						data-weekly-menu-panel
						<?php echo $is_active ? '' : 'hidden'; ?>
					>
						<div class="weekly-menu-panel-heading">
							<div>
								<p class="text-xs font-semibold uppercase tracking-normal text-base-muted">Cardápio do dia</p>
								<h2 class="text-2xl font-semibold text-base-content"><?php echo esc_html($day_label); ?></h2>
							</div>
							<?php if ($is_today): ?><span class="tag tag-primary">Hoje</span><?php endif; ?>
						</div>

						<div class="weekly-menu-table-wrap">
							<div class="weekly-menu-table" role="table" aria-label="<?php echo esc_attr('Cardápio de ' . $day_label); ?>">
								<div class="weekly-menu-table-head" role="row">
									<div role="columnheader">Refeição</div>
									<?php foreach ($section_labels as $section_label): ?>
										<div role="columnheader"><?php echo esc_html($section_label); ?></div>
									<?php endforeach; ?>
								</div>

								<?php foreach ($meal_labels as $meal_key => $meal_label):
									$meal_has_items = false;
									foreach ($section_labels as $sk => $_):
										if (!empty($day_data[$meal_key][$sk])) { $meal_has_items = true; break; }
									endforeach;
									if (!$meal_has_items) continue;
								?>
									<div class="weekly-menu-table-row" role="row">
										<div class="weekly-menu-table-meal" role="rowheader">
											<span><?php echo esc_html($meal_label); ?></span>
										</div>

										<?php foreach ($section_labels as $section_key => $section_label):
											$items = isset($day_data[$meal_key][$section_key]) ? $day_data[$meal_key][$section_key] : [];
										?>
											<div class="weekly-menu-table-cell<?php echo empty($items) ? ' is-empty' : ''; ?>" role="cell">
												<span class="weekly-menu-cell-label"><?php echo esc_html($section_label); ?></span>
												<?php if (empty($items)): ?>
													<span class="weekly-menu-empty">—</span>
												<?php else: ?>
													<ul class="weekly-menu-content-list">
														<?php foreach ($items as $item): ?>
															<li class="weekly-menu-content-item">
																<span class="text-sm font-medium"><?php echo esc_html($item['name']); ?></span>
																<?php if (!empty($item['allergens']) || !empty($item['dietary']) || !empty($item['traces']) || $section_key === 'vegetariano'): ?>
																	<div class="mt-1 flex flex-wrap gap-1">
																		<?php $dietary_key = !empty($item['dietary'][0]) ? $item['dietary'][0] : ''; ?>
																		<?php if ($dietary_key): ?>
																			<span class="tag tag-success tag-sm gap-0.5"><i data-lucide="leaf"></i><?php echo esc_html($dietary_labels[$dietary_key] ?? $dietary_key); ?></span>
																		<?php elseif ($section_key === 'vegetariano'): ?>
																			<span class="tag tag-success tag-sm gap-0.5"><i data-lucide="leaf"></i>Vegetariano</span>
																		<?php endif; ?>
																		<?php foreach (($item['allergens'] ?? []) as $al): ?><span class="tag tag-warning tag-sm gap-0.5"><i data-lucide="triangle-alert"></i><?php echo esc_html($allergen_labels[$al] ?? $al); ?></span><?php endforeach; ?>
																		<?php if (!empty($item['traces'])): foreach ($item['traces'] as $tr): ?><span class="tag tag-outline-warning tag-sm gap-0.5"><i data-lucide="info"></i>Traços: <?php echo esc_html($allergen_labels[$tr] ?? $tr); ?></span><?php endforeach; endif; ?>
																	</div>
																<?php endif; ?>
															</li>
														<?php endforeach; ?>
													</ul>
												<?php endif; ?>
											</div>
										<?php endforeach; ?>
									</div>
								<?php endforeach; ?>
							</div>
						</div>
					</section>
				<?php endforeach; ?>
			</div>
		<?php endif; ?>

		<?php
		if ( function_exists( 'ru_ufpe_theme_render_comments_thread' ) && ! empty( $weekly_menu_data['post'] ) ) {
			ru_ufpe_theme_render_comments_thread(
				$weekly_menu_data['post']->ID,
				array(
					'title'       => 'Comentários sobre o cardápio semanal',
					'description' => 'Compartilhe dúvidas e observações sobre o cardápio desta semana.',
				)
			);
		}
		?>

		<?php endif; ?>
	</div>
</main>

<?php get_footer(); ?>
