<script lang="ts">
	import { t } from 'svelte-i18n';
	import type { PageData } from './$types.js';
	import AppCard from '$lib/components/app/AppCard.svelte';
	import AppForm from '$lib/components/app/AppForm.svelte';

	let { data }: { data: PageData } = $props();

	let showForm = $state(false);
</script>

<svelte:head>
	<title>{$t('app.title')} — {$t('app_title')}</title>
</svelte:head>

<div class="p-6">
	<div class="mx-auto max-w-6xl">
		<div class="mb-6 flex items-center justify-between">
			<div>
				<h1 class="text-2xl font-bold text-foreground">{$t('app.title')}</h1>
				<p class="mt-1 text-sm text-muted-foreground">
					{$t('app.apps_registered', { values: { count: data.apps.length } })}
				</p>
			</div>
			<button
				type="button"
				onclick={() => (showForm = !showForm)}
				class="rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-colors hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-ring"
			>
				{showForm ? $t('common.cancel') : $t('app.add')}
			</button>
		</div>

		{#if showForm}
			<div class="mb-6 rounded-xl border border-border bg-card p-6 shadow-sm">
				<h2 class="mb-4 text-lg font-semibold text-card-foreground">{$t('app.new')}</h2>
				<AppForm form={data.form} action="?/create" />
			</div>
		{/if}

		{#if data.categories.length > 0}
			<div class="mb-4 flex flex-wrap gap-2">
				<a
					href="/apps"
					class="rounded-full border border-border px-3 py-1 text-sm text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
				>
					{$t('app.all_categories')}
				</a>
				{#each data.categories as category (category)}
					<a
						href="/apps?category={encodeURIComponent(category)}"
						class="rounded-full border border-border px-3 py-1 text-sm text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
					>
						{category}
					</a>
				{/each}
			</div>
		{/if}

		{#if data.apps.length === 0}
			<div class="flex flex-col items-center justify-center rounded-xl border border-border bg-card/50 py-16 text-muted-foreground">
				<svg
					class="mb-3 h-12 w-12 text-muted-foreground/40"
					xmlns="http://www.w3.org/2000/svg"
					viewBox="0 0 24 24"
					fill="none"
					stroke="currentColor"
					stroke-width="1.5"
					stroke-linecap="round"
					stroke-linejoin="round"
				>
					<circle cx="12" cy="12" r="10" />
					<line x1="12" y1="8" x2="12" y2="12" />
					<line x1="12" y1="16" x2="12.01" y2="16" />
				</svg>
				<p class="text-lg">{$t('app.no_apps')}</p>
				<p class="mt-1 text-sm">{$t('app.no_apps_hint')}</p>
			</div>
		{:else}
			<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4">
				{#each data.apps as app (app.id)}
					<AppCard {app} />
				{/each}
			</div>
		{/if}
	</div>
</div>
