<script lang="ts">
	import { Folder } from 'lucide-svelte';
	import { cn } from '$lib/utils.js';

	let {
		value = '',
		placeholder = 'Seleccionar archivo',
		accept = '',
		disabled = false,
		onchange,
		class: className = '',
		id = ''
	}: {
		value?: string;
		placeholder?: string;
		accept?: string;
		disabled?: boolean;
		onchange?: (file: File) => void;
		class?: string;
		id?: string;
	} = $props();

	let fileInputEl: HTMLInputElement | null = $state(null);
	let buttonEl: HTMLButtonElement | null = $state(null);
	let focused = $state(false);

function handleButtonClick() {
	if (disabled) return;
		fileInputEl?.click();
	}

function handleContainerClick(event: MouseEvent) {
	if (disabled) return;
	const target = event.target as HTMLElement | null;
	if (target?.closest('button')) return;
	handleButtonClick();
}

	function handleFileChange(e: Event) {
		const input = e.target as HTMLInputElement;
		const file = input.files?.[0];
		if (file) onchange?.(file);
		// Resetear para que el mismo archivo pueda re-seleccionarse
		input.value = '';
	}
</script>

<!--
	Contenedor unificado: el input de texto es sólo display (tabindex="-1"),
	el botón de carpeta recibe el foco y su focus-state dibuja el halo sobre ambos.
-->
<div
	class={cn(
		'border-input bg-background dark:bg-input/30 shadow-xs flex h-9 w-full items-center rounded-md border transition-[color,box-shadow]',
		!disabled && 'cursor-pointer',
		focused && 'border-ring ring-ring/50 ring-[3px]',
		disabled && 'cursor-not-allowed opacity-50',
		className
	)}
	onclick={handleContainerClick}
>
	<!-- read-only display: sin tabstop, sin foco propio.
	     Cuando value coincide con el placeholder (sin archivo seleccionado),
	     dejamos value vacío para que el navegador muestre el placeholder muted. -->
	<input
		type="text"
		readonly
		tabindex="-1"
		aria-hidden="true"
		value={value === placeholder ? '' : value}
		{placeholder}
		{disabled}
		class="placeholder:text-muted-foreground min-w-0 flex-1 border-0 bg-transparent px-3 py-1 text-base shadow-none outline-none md:text-sm"
		onfocus={() => buttonEl?.focus()}
	/>

	<!-- input file real, oculto -->
	<input
		type="file"
		class="hidden"
		{accept}
		{id}
		bind:this={fileInputEl}
		onchange={handleFileChange}
	/>

	<!-- separador + botón, único elemento focusable -->
	<button
		type="button"
		{disabled}
		bind:this={buttonEl}
		class="hover:text-foreground text-muted-foreground flex h-full w-10 shrink-0 items-center justify-center rounded-r-md border-0 bg-transparent outline-none transition-colors disabled:cursor-not-allowed"
		onclick={(event) => {
			event.stopPropagation();
			handleButtonClick();
		}}
		onfocus={() => (focused = true)}
		onblur={() => (focused = false)}
	>
		<Folder class="h-4 w-4" />
	</button>
</div>
