<script lang="ts">
	import { Label } from '$lib/components/ui/label/index.js';
	import { Settings2 } from 'lucide-svelte';
	import { globalCsvParams, tabSettings, type CsvUploadField } from '$lib/config/csv-upload';
	import { cn } from '$lib/utils';
	import { csvMsg } from '$lib/i18n/csv-msg';

	const TAB_LABEL: Record<string, string> = {
		catalogos: 'tab_catalogos',
		transportes: 'tab_transportes',
		importacion: 'tab_importacion',
		exportacion: 'tab_exportacion'
	};

	let {
		globalSettings = $bindable(),
		activeTab,
		tabSettingsValues = $bindable(),
		embedded = false
	}: {
		globalSettings: Record<string, string>;
		activeTab: string;
		tabSettingsValues: Record<string, any>;
		/** Si true, el padre aporta el contenedor fijo (p. ej. pie apilado con progreso CSV). */
		embedded?: boolean;
	} = $props();

	const globalParamNames = $derived(new Set(globalCsvParams.map((p) => p.name)));
	// Tab fields excluding those already in global params (e.g. mode) to avoid duplication
	let currentTabFields = $derived(
		((tabSettings[activeTab] || []) as CsvUploadField[]).filter((f) => !globalParamNames.has(f.name))
	);
	// Guard: parent may pass undefined on first tick; avoid reading from undefined
	let safeGlobalSettings = $derived(globalSettings ?? {});
	let safeTabSettings = $derived(tabSettingsValues ?? {});
	const selectClass =
		'flex h-8 min-w-[120px] rounded-md border border-input bg-background px-3 py-1 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50';
</script>

<!-- Fixed bar: z-index below help bubble (help uses z-50) so help stays on top -->
<div
	class={cn(
		'w-full bg-background/95 supports-[backdrop-filter]:bg-background/80',
		embedded
			? ''
			: 'fixed right-0 bottom-0 left-0 z-40 ml-[calc(var(--sidebar-width))] border-t shadow-lg backdrop-blur group-has-data-[state=collapsed]/sidebar-wrapper:ml-[calc(var(--sidebar-width-icon))]'
	)}
>
	<div class="mx-auto max-w-[1400px] px-4 py-3">
		<div class="flex flex-wrap items-end gap-6">
			<!-- Parámetros globales -->
			<div class="flex flex-wrap items-center gap-4">
				<div class="flex items-center gap-2 text-muted-foreground border-r border-border pr-4">
					<Settings2 class="h-4 w-4 shrink-0" />
					<span class="text-xs font-semibold uppercase tracking-wider whitespace-nowrap"
						>{csvMsg('params_header')}</span
					>
				</div>
				{#each globalCsvParams as param}
					<div class="flex flex-col gap-1">
						<Label for="global-{param.name}" class="text-xs font-medium text-muted-foreground"
							>{csvMsg(param.labelKey)}</Label
						>
						<select
							id="global-{param.name}"
							class={selectClass}
							value={safeGlobalSettings[param.name]}
							oninput={(e) => {
								if (globalSettings) globalSettings[param.name] = e.currentTarget.value;
							}}
						>
							{#each param.options as opt}
								<option value={opt.value}>{csvMsg(opt.labelKey)}</option>
							{/each}
						</select>
					</div>
				{/each}
			</div>

			<!-- Configuración del tab actual -->
			{#if currentTabFields.length > 0}
				<div class="flex flex-wrap items-center gap-4 border-l border-border pl-4">
					<span class="text-xs font-semibold uppercase tracking-wider text-muted-foreground whitespace-nowrap"
						>{csvMsg('config_prefix')}: {csvMsg(TAB_LABEL[activeTab] ?? activeTab)}</span
					>
					{#each currentTabFields as field}
						<div class="flex flex-col gap-1">
							{#if field.type !== 'boolean'}
								<Label for="tab-{field.name}" class="text-xs font-medium text-muted-foreground"
									>{csvMsg(field.labelKey)}</Label
								>
							{/if}
							{#if field.type === 'select' && field.options}
								<select
									id="tab-{field.name}"
									class={selectClass}
									value={safeTabSettings[field.name]}
									oninput={(e) => {
										if (tabSettingsValues) tabSettingsValues[field.name] = e.currentTarget.value;
									}}
								>
									{#each field.options as opt}
										<option value={opt.value}>{csvMsg(opt.labelKey)}</option>
									{/each}
								</select>
							{:else if field.type === 'radio' && field.options}
								<div class="flex gap-3 items-center h-8">
									{#each field.options as opt}
										<label class="flex items-center gap-2 cursor-pointer text-sm">
											<input
												type="radio"
												name="tab-{field.name}"
												value={opt.value}
												checked={safeTabSettings[field.name] === opt.value}
												onchange={() => {
													if (tabSettingsValues) tabSettingsValues[field.name] = opt.value;
												}}
											/>
											{csvMsg(opt.labelKey)}
										</label>
									{/each}
								</div>
							{:else if field.type === 'boolean'}
								<label class="flex items-center gap-2 cursor-pointer text-sm h-8">
									<input
										type="checkbox"
										checked={!!safeTabSettings[field.name]}
										onchange={(e) => {
											if (tabSettingsValues) tabSettingsValues[field.name] = e.currentTarget.checked;
										}}
									/>
									{csvMsg(field.labelKey)}
								</label>
							{/if}
						</div>
					{/each}
				</div>
			{/if}
		</div>
	</div>
</div>
