<script>
	import Header from '$lib/layout/Header.svelte';
	import { onMount } from 'svelte';
	import { browser } from '$app/environment';
	import { logo_id, companyName_id } from '$lib/utils/store';

	let categoriaSelecionada = null;
	let cardapio = [];
	let token = null;
	let company = null;
	let categories = [];
	let products = [];

	if (browser) {
		token = localStorage.getItem('token');
		localStorage.setItem('typePage', 'false');
	}

	function filtrarCategoria(categoria) {
		categoriaSelecionada = categoriaSelecionada === categoria ? null : categoria;
	}

	onMount(() => {
		const params = new URLSearchParams(window.location.search);
		const id = params.get('id');
		company = localStorage.setItem('company', id);

		switch (id) {
			case '1':
				logo_id.set(
					'https://i.postimg.cc/bNNBcTZj/Whats-App-Image-2025-07-29-at-19-59-16-removebg-preview.png'
				);
				companyName_id.set('Bar do Ferlin');
				break;
		}

		if (id) {
			fetch(`https://bartender.mixtab.com.br/menu/get/${id}`)
				.then((res) => res.json())
				.then((data) => {
					//console.log(data.data);
					cardapio = data.data;
				})
				.catch((err) => console.error("Erro ao buscar o cardapio:', err"));
		} else {
			console.log('ID não encontrado na URL');
		}
	});
</script>

<Header />
<div class="flex flex-nowrap justify-center gap-4 overflow-x-auto bg-gray-700 p-5">
	{#each cardapio as secao}
		<button
			class="rounded-lg px-4 py-2 text-sm font-semibold transition-colors duration-200
			{categoriaSelecionada === secao.categoria
				? 'bg-violet-700 text-white'
				: 'bg-gray-600 text-gray-100'}"
			on:click={() => filtrarCategoria(secao.categoria)}
		>
			{secao.categoria}
		</button>
	{/each}
</div>

<main class="flex min-h-screen bg-gray-800">
	<div class="flex flex-1 items-start justify-center bg-gray-700 pt-5">
		<div class="h- max-w-370 w-full rounded-2xl bg-gray-800 p-8 shadow-lg">
			<h1 class="mb-8 text-center text-3xl font-bold text-gray-200">Cardápio</h1>

			{#each cardapio.filter((secao) => !categoriaSelecionada || secao.categoria === categoriaSelecionada) as secao}
				<div class="mb-6">
					<h2 class="mb-3 text-center text-xl font-semibold text-gray-200">{secao.categoria}</h2>
					{#each secao.produtos as item}
						<div class="mb-2 rounded-lg bg-gray-700 px-4 py-2">
							<div class="flex items-start justify-between">
								<div class="flex-1">
									<span class="block font-medium text-gray-200">{item.nome}</span>
									<p class="mt-1 text-sm text-gray-400">{item.descricao}</p>
								</div>
								<span class="ml-4 whitespace-nowrap text-sm text-gray-300">{item.preco}</span>
							</div>
						</div>
					{/each}
				</div>
			{/each}
		</div>
	</div>
</main>
