<script lang="ts">
	import { t } from '$lib/i18n';
	import MdiIcon from '$lib/components/MdiIcon.svelte';
	import Button from '$lib/components/Button.svelte';

	type SecretsMode = 'exclude' | 'masked' | 'include';

	interface Props {
		selectedCategories: Record<string, boolean>;
		exportSecrets: SecretsMode;
		exporting: boolean;
		onCategoriesChange: (next: Record<string, boolean>) => void;
		onSecretsChange: (next: SecretsMode) => void;
		onExport: () => void;
	}

	let {
		selectedCategories,
		exportSecrets,
		exporting,
		onCategoriesChange,
		onSecretsChange,
		onExport,
	}: Props = $props();

	const categoryGroups: Array<{ key: string; labelKey: string; icon: string; cats: Array<{ key: string; labelKey: string }> }> = [
		{
			key: 'identity',
			labelKey: 'backup.catGroupIdentity',
			icon: 'mdiAccountNetwork',
			cats: [
				{ key: 'providers', labelKey: 'backup.catProviders' },
				{ key: 'telegram_bots', labelKey: 'backup.catTelegramBots' },
				{ key: 'matrix_bots', labelKey: 'backup.catMatrixBots' },
				{ key: 'email_bots', labelKey: 'backup.catEmailBots' },
				{ key: 'targets', labelKey: 'backup.catTargets' },
			],
		},
		{
			key: 'notif',
			labelKey: 'backup.catGroupNotif',
			icon: 'mdiBellOutline',
			cats: [
				{ key: 'tracking_configs', labelKey: 'backup.catTrackingConfigs' },
				{ key: 'template_configs', labelKey: 'backup.catTemplateConfigs' },
				{ key: 'notification_trackers', labelKey: 'backup.catNotificationTrackers' },
			],
		},
		{
			key: 'cmd',
			labelKey: 'backup.catGroupCmd',
			icon: 'mdiConsoleLine',
			cats: [
				{ key: 'command_configs', labelKey: 'backup.catCommandConfigs' },
				{ key: 'command_template_configs', labelKey: 'backup.catCommandTemplateConfigs' },
				{ key: 'command_trackers', labelKey: 'backup.catCommandTrackers' },
			],
		},
		{
			key: 'system',
			labelKey: 'backup.catGroupSystem',
			icon: 'mdiCog',
			cats: [
				{ key: 'actions', labelKey: 'backup.catActions' },
				{ key: 'app_settings', labelKey: 'backup.catAppSettings' },
			],
		},
	];

	function toggleCat(key: string): void {
		onCategoriesChange({ ...selectedCategories, [key]: !selectedCategories[key] });
	}

	function groupState(groupKey: string): 'all' | 'none' | 'some' {
		const group = categoryGroups.find(g => g.key === groupKey);
		if (!group) return 'none';
		const flags = group.cats.map(c => !!selectedCategories[c.key]);
		if (flags.every(v => v)) return 'all';
		if (flags.every(v => !v)) return 'none';
		return 'some';
	}

	function toggleGroup(groupKey: string): void {
		const group = categoryGroups.find(g => g.key === groupKey);
		if (!group) return;
		const target = groupState(groupKey) !== 'all';
		const next = { ...selectedCategories };
		for (const c of group.cats) next[c.key] = target;
		onCategoriesChange(next);
	}

	const noneSelected = $derived(Object.values(selectedCategories).every(v => !v));
	const totalSelected = $derived(Object.values(selectedCategories).filter(v => v).length);

	const secretsModes: Array<{ value: SecretsMode; icon: string; labelKey: string }> = [
		{ value: 'exclude', icon: 'mdiShieldCheckOutline', labelKey: 'backup.secretsExclude' },
		{ value: 'masked', icon: 'mdiEyeOffOutline', labelKey: 'backup.secretsMasked' },
		{ value: 'include', icon: 'mdiKeyVariant', labelKey: 'backup.secretsInclude' },
	];
</script>

<section class="export-panel glass">
	<header class="panel-head">
		<div class="panel-eyebrow">
			<MdiIcon name="mdiDatabaseExport" size={14} />
			<span>{t('backup.export')}</span>
		</div>
		<h3 class="panel-title">{t('backup.exportDescription')}</h3>
	</header>

	<div class="panel-body">
		<!-- Step 1: categories -->
		<div class="step">
			<div class="step-head">
				<span class="step-num">01</span>
				<span class="step-label">{t('backup.stepCategories')}</span>
				<span class="step-count">{totalSelected}</span>
			</div>
			<div class="group-grid">
				{#each categoryGroups as group}
					{@const state = groupState(group.key)}
					<div class="group" class:group-all={state === 'all'} class:group-some={state === 'some'}>
						<button class="group-head" type="button" onclick={() => toggleGroup(group.key)}>
							<span class="group-icon"><MdiIcon name={group.icon} size={14} /></span>
							<span class="group-title">{t(group.labelKey)}</span>
							<span class="group-state">
								{#if state === 'all'}<MdiIcon name="mdiCheckboxMarked" size={14} />
								{:else if state === 'some'}<MdiIcon name="mdiMinusBoxOutline" size={14} />
								{:else}<MdiIcon name="mdiCheckboxBlankOutline" size={14} />{/if}
							</span>
						</button>
						<div class="chip-row">
							{#each group.cats as cat}
								<button class="chip" type="button"
									class:chip-on={selectedCategories[cat.key]}
									onclick={() => toggleCat(cat.key)}>
									{t(cat.labelKey)}
								</button>
							{/each}
						</div>
					</div>
				{/each}
			</div>
		</div>

		<!-- Step 2: secrets -->
		<div class="step">
			<div class="step-head">
				<span class="step-num">02</span>
				<span class="step-label">{t('backup.stepSecrets')}</span>
			</div>
			<div class="segmented" role="radiogroup" aria-label={t('backup.secretsMode')}>
				{#each secretsModes as mode}
					<button type="button"
						role="radio"
						aria-checked={exportSecrets === mode.value}
						class="seg"
						class:seg-on={exportSecrets === mode.value}
						onclick={() => onSecretsChange(mode.value)}>
						<MdiIcon name={mode.icon} size={14} />
						<span>{t(mode.labelKey)}</span>
					</button>
				{/each}
			</div>
			{#if exportSecrets === 'include'}
				<div class="warn-strip" role="status">
					<span class="warn-edge" aria-hidden="true"></span>
					<MdiIcon name="mdiAlertOctagonOutline" size={14} />
					<span>{t('backup.secretsWarningExport')}</span>
				</div>
			{/if}
		</div>

		<!-- Step 3: CTA -->
		<div class="step step-cta">
			<Button onclick={onExport} disabled={exporting || noneSelected}>
				{#if exporting}
					<MdiIcon name="mdiLoading" size={14} />
				{:else}
					<MdiIcon name="mdiDownload" size={14} />
				{/if}
				{exporting ? t('common.loading') : t('backup.exportBtn')}
			</Button>
		</div>
	</div>
</section>

<style>
	.export-panel {
		padding: 1.5rem 1.5rem 1.35rem;
		display: flex;
		flex-direction: column;
		gap: 1.1rem;
		min-height: 100%;
	}
	.panel-head {
		position: relative;
		z-index: 1;
	}
	.panel-eyebrow {
		display: inline-flex;
		align-items: center;
		gap: 0.35rem;
		font-family: var(--font-mono);
		font-size: 0.62rem;
		text-transform: uppercase;
		letter-spacing: 0.18em;
		color: var(--color-muted-foreground);
		margin-bottom: 0.5rem;
	}
	.panel-title {
		margin: 0;
		font-family: var(--font-display);
		font-weight: 400;
		font-size: 1.15rem;
		line-height: 1.35;
		letter-spacing: -0.015em;
		color: var(--color-foreground);
		max-width: 36ch;
	}

	.panel-body {
		position: relative;
		z-index: 1;
		display: flex;
		flex-direction: column;
		gap: 1.25rem;
		flex: 1;
	}

	.step {
		display: flex;
		flex-direction: column;
		gap: 0.6rem;
	}
	.step-head {
		display: flex;
		align-items: baseline;
		gap: 0.6rem;
	}
	.step-num {
		font-family: var(--font-mono);
		font-size: 0.62rem;
		letter-spacing: 0.18em;
		color: var(--color-muted-foreground);
	}
	.step-label {
		font-size: 0.78rem;
		font-weight: 500;
		color: var(--color-foreground);
		letter-spacing: -0.005em;
	}
	.step-count {
		margin-left: auto;
		font-family: var(--font-mono);
		font-size: 0.65rem;
		padding: 0.15rem 0.5rem;
		border-radius: 999px;
		background: var(--color-glass-strong);
		color: var(--color-muted-foreground);
		border: 1px solid var(--color-border);
	}

	.group-grid {
		display: grid;
		grid-template-columns: 1fr;
		gap: 0.55rem;
	}
	@media (min-width: 560px) {
		.group-grid { grid-template-columns: 1fr 1fr; }
	}
	.group {
		border-radius: 14px;
		border: 1px solid var(--color-border);
		background: var(--color-glass-strong);
		padding: 0.55rem 0.65rem 0.7rem;
		transition: border-color 0.18s ease, background 0.18s ease;
	}
	.group-all { border-color: color-mix(in srgb, var(--color-primary) 50%, var(--color-border)); background: color-mix(in srgb, var(--color-primary) 6%, var(--color-glass-strong)); }
	.group-some { border-color: color-mix(in srgb, var(--color-primary) 28%, var(--color-border)); }
	.group-head {
		display: flex;
		align-items: center;
		gap: 0.4rem;
		width: 100%;
		background: transparent;
		border: 0;
		padding: 0.15rem 0.1rem 0.4rem;
		cursor: pointer;
		color: var(--color-foreground);
		font-family: inherit;
	}
	.group-icon { color: var(--color-primary); display: inline-flex; }
	.group-title {
		font-size: 0.74rem;
		font-weight: 500;
		letter-spacing: -0.005em;
		flex: 1;
		text-align: left;
	}
	.group-state {
		display: inline-flex;
		color: var(--color-muted-foreground);
	}
	.group-all .group-state { color: var(--color-primary); }
	.group-some .group-state { color: var(--color-citrus); }

	.chip-row {
		display: flex;
		flex-wrap: wrap;
		gap: 0.3rem;
	}
	.chip {
		font-size: 0.7rem;
		padding: 0.25rem 0.6rem;
		border-radius: 999px;
		border: 1px solid var(--color-border);
		background: transparent;
		color: var(--color-muted-foreground);
		cursor: pointer;
		font-family: inherit;
		transition: background 0.15s ease, border-color 0.15s ease, color 0.15s ease;
	}
	.chip:hover { color: var(--color-foreground); border-color: var(--color-rule-strong); }
	.chip-on {
		background: color-mix(in srgb, var(--color-primary) 18%, transparent);
		border-color: color-mix(in srgb, var(--color-primary) 55%, var(--color-border));
		color: var(--color-foreground);
		box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--color-primary) 25%, transparent);
	}

	.segmented {
		display: grid;
		grid-template-columns: 1fr;
		gap: 0.4rem;
	}
	@media (min-width: 480px) {
		.segmented { grid-template-columns: repeat(3, 1fr); }
	}
	.seg {
		display: inline-flex;
		flex-direction: column;
		align-items: flex-start;
		gap: 0.25rem;
		padding: 0.55rem 0.7rem;
		border-radius: 12px;
		border: 1px solid var(--color-border);
		background: var(--color-glass-strong);
		color: var(--color-muted-foreground);
		cursor: pointer;
		font-family: inherit;
		font-size: 0.72rem;
		text-align: left;
		line-height: 1.25;
		transition: background 0.15s, border-color 0.15s, color 0.15s, box-shadow 0.18s;
	}
	.seg:hover { color: var(--color-foreground); border-color: var(--color-rule-strong); background: var(--color-glass-elev); }
	.seg-on {
		background: linear-gradient(135deg, color-mix(in srgb, var(--color-primary) 16%, transparent), color-mix(in srgb, var(--color-orchid) 14%, transparent));
		border-color: color-mix(in srgb, var(--color-primary) 50%, transparent);
		color: var(--color-foreground);
		box-shadow:
			inset 0 1px 0 var(--color-highlight),
			0 0 0 1px color-mix(in srgb, var(--color-primary) 30%, transparent);
	}

	.warn-strip {
		position: relative;
		display: flex;
		align-items: flex-start;
		gap: 0.5rem;
		padding: 0.55rem 0.75rem 0.55rem 1rem;
		border-radius: 10px;
		font-size: 0.72rem;
		line-height: 1.4;
		color: var(--color-error-fg);
		background: color-mix(in srgb, var(--color-error-fg) 10%, transparent);
		border: 1px solid color-mix(in srgb, var(--color-error-fg) 30%, var(--color-border));
		overflow: hidden;
	}
	.warn-edge {
		position: absolute;
		left: 0; top: 0; bottom: 0;
		width: 3px;
		background: var(--color-coral);
	}

	.step-cta {
		margin-top: auto;
		padding-top: 0.4rem;
	}
</style>
