<script lang="ts">
import { m } from '$lib/paraglide/messages.js';
import { parseFilename, stripExtension, type FilenameParseResult } from '$lib/document/filename';

let {
	onfileParsed
}: {
	onfileParsed?: (result: FilenameParseResult) => void;
} = $props();

let selectedFilename = $state<string | null>(null);

function handleFileChange(e: Event) {
	const file = (e.target as HTMLInputElement).files?.[0];
	if (!file) return;
	selectedFilename = file.name;
	const parsed = parseFilename(file.name);
	const result: FilenameParseResult = {
		...parsed,
		suggestedTitle: parsed.suggestedTitle ?? stripExtension(file.name)
	};
	onfileParsed?.(result);
}
</script>

<div class="rounded-sm border border-line bg-surface shadow-sm">
	<div class="border-b border-line px-6 py-4">
		<h2 class="text-xs font-bold tracking-widest text-ink-3 uppercase">
			{m.doc_section_file()}
		</h2>
	</div>

	<label
		for="file-upload"
		class="flex cursor-pointer flex-col items-center gap-3 px-6 py-10 transition-colors hover:bg-muted/40"
	>
		<svg
			class="h-10 w-10 text-ink-3"
			fill="none"
			stroke="currentColor"
			viewBox="0 0 24 24"
			aria-hidden="true"
		>
			<path
				stroke-linecap="round"
				stroke-linejoin="round"
				stroke-width="1.5"
				d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"
			/>
		</svg>
		{#if selectedFilename}
			<span class="text-ink-1 text-sm font-medium">{selectedFilename}</span>
		{:else}
			<span class="text-sm font-medium text-ink-2">{m.doc_file_upload_label()}</span>
			<span class="text-xs text-ink-3">{m.doc_file_upload_note()}</span>
		{/if}
	</label>
	<input id="file-upload" type="file" name="file" onchange={handleFileChange} class="sr-only" />
</div>
