<script lang="ts">
	import { getSettings, updateSettings } from '$lib/api';
	import FormField from '$lib/components/FormField.svelte';
	import Skeleton from '$lib/components/Skeleton.svelte';
	import { toasts } from '$lib/stores/toast';
	import { t } from '$lib/i18n';
	import { IconLoader } from '$lib/components/icons';

	let loading = $state(true);
	let saving = $state(false);

	let traefikEntrypoint = $state('websecure');
	let traefikCertResolver = $state('letsencrypt');
	let traefikNetwork = $state('');
	let traefikApiUrl = $state('');

	async function loadData() {
		loading = true;
		try {
			const settings = await getSettings();
			traefikEntrypoint = settings.traefik_entrypoint ?? 'websecure';
			traefikCertResolver = settings.traefik_cert_resolver ?? 'letsencrypt';
			traefikNetwork = settings.traefik_network ?? '';
			traefikApiUrl = settings.traefik_api_url ?? '';
		} catch (err) {
			toasts.error(err instanceof Error ? err.message : $t('settingsGeneral.loadFailed'));
		} finally { loading = false; }
	}

	async function handleSave() {
		saving = true;
		try {
			await updateSettings({
				traefik_entrypoint: traefikEntrypoint.trim() || 'websecure',
				traefik_cert_resolver: traefikCertResolver.trim(),
				traefik_network: traefikNetwork.trim(),
				traefik_api_url: traefikApiUrl.trim()
			} as any);
			toasts.success($t('settingsGeneral.saved'));
		} catch (err) {
			toasts.error(err instanceof Error ? err.message : $t('settingsGeneral.saveFailed'));
		} finally { saving = false; }
	}

	$effect(() => { loadData(); });
</script>

<svelte:head>
	<title>{$t('settings.traefik')} - {$t('app.name')}</title>
</svelte:head>

<div class="space-y-6">
	<div>
		<h2 class="text-lg font-semibold text-[var(--text-primary)]">{$t('settings.traefik')}</h2>
		<p class="text-sm text-[var(--text-secondary)]">{$t('settings.proxyTraefikDesc')}</p>
	</div>

	{#if loading}
		<div class="space-y-4"><Skeleton height="12rem" /></div>
	{:else}
		<div class="rounded-xl border border-[var(--border-primary)] bg-[var(--surface-card)] p-6 shadow-[var(--shadow-sm)]">
			<div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
				<FormField label={$t('settings.traefikEntrypoint')} name="traefikEntrypoint" bind:value={traefikEntrypoint} placeholder="websecure" helpText={$t('settings.traefikEntrypointHelp')} />
				<FormField label={$t('settings.traefikCertResolver')} name="traefikCertResolver" bind:value={traefikCertResolver} placeholder="letsencrypt" helpText={$t('settings.traefikCertResolverHelp')} />
				<FormField label={$t('settings.traefikNetwork')} name="traefikNetwork" bind:value={traefikNetwork} placeholder="" helpText={$t('settings.traefikNetworkHelp')} />
				<FormField label={$t('settings.traefikApiUrl')} name="traefikApiUrl" bind:value={traefikApiUrl} placeholder="http://traefik:8080" helpText={$t('settings.traefikApiUrlHelp')} />
			</div>

			<button onclick={handleSave} disabled={saving}
				class="mt-6 inline-flex items-center gap-2 rounded-lg bg-[var(--color-brand-600)] px-4 py-2.5 text-sm font-medium text-white shadow-sm hover:bg-[var(--color-brand-700)] disabled:opacity-50 transition-colors active:animate-press">
				{#if saving}<IconLoader size={16} />{/if}
				{saving ? $t('settingsGeneral.saving') : $t('settingsGeneral.saveSettings')}
			</button>
		</div>

		<div class="rounded-xl border border-[var(--border-primary)] bg-[var(--surface-card)] p-6 shadow-[var(--shadow-sm)]">
			<h3 class="text-sm font-semibold text-[var(--text-primary)]">{$t('settings.traefikLabelsTitle')}</h3>
			<p class="mt-1 text-sm text-[var(--text-secondary)]">{$t('settings.traefikLabelsDesc')}</p>
			<pre class="mt-3 overflow-x-auto rounded-lg bg-[var(--surface-card-hover)] p-4 text-xs font-mono text-[var(--text-secondary)] leading-relaxed">traefik.enable=true
traefik.http.routers.&lt;name&gt;.rule=Host(`your-domain.com`)
traefik.http.routers.&lt;name&gt;.entrypoints={traefikEntrypoint || 'websecure'}
traefik.http.services.&lt;name&gt;.loadbalancer.server.port=&lt;port&gt;{#if traefikCertResolver}
traefik.http.routers.&lt;name&gt;.tls.certresolver={traefikCertResolver}{/if}{#if traefikNetwork}
traefik.docker.network={traefikNetwork}{/if}</pre>
		</div>
	{/if}
</div>
