<script lang="ts">
	// Imports
	// Import components and elements

	// Import storage, functions, and libraries
	import type { key_val } from '$lib/stores/ae_stores';

	import { api } from '$lib/api/api';
	import { ae_util } from '$lib/ae_utils/ae_utils';
	import {
		ae_snip,
		ae_loc,
		ae_sess,
		ae_api,
		ae_trig,
		slct,
		slct_trigger
	} from '$lib/stores/ae_stores';

	// Exports

	// export let hosted_file_id_li: string[] = [];
	// export let hosted_file_obj_li: any[] = [];

	interface Props {
		log_lvl?: number;
		// export let hosted_file_obj_kv: key_val = {};
		video_clip_file_kv?: key_val;
		class_li_default?: string;
		class_li?: string;
		link_to_type: string;
		link_to_id: string;
	}

	let {
		log_lvl = 0,
		video_clip_file_kv = $bindable({}),
		class_li_default = 'flex flex-row flex-wrap gap-2 items-center justify-center w-full max-w-2xl p-2 mx-auto my-1 border border-gray-300 rounded-lg',
		class_li = '',
		link_to_type,
		link_to_id
	}: Props = $props();

	let ae_promises: key_val = $state({});
</script>

<h3 class="h3">{Object.entries($ae_loc.files).length}× files clipped</h3>
<div class="{class_li_default} {class_li} ">
	{#each Object.entries(video_clip_file_kv) as [hosted_file_id, hosted_file_obj]}
		<button
			type="button"
			disabled={!$ae_loc.trusted_access}
			onclick={() => {
				ae_promises[hosted_file_id] = api.download_hosted_file({
					api_cfg: $ae_api,
					hosted_file_id: hosted_file_id,
					return_file: true,
					filename: hosted_file_obj.filename,
					auto_download: true,
					log_lvl: log_lvl
				});

				// window.postMessage({ type: 'download_event_file', hosted_file_id: idaa_archive_content_obj.hosted_file_id, filename: idaa_archive_content_obj.filename, auto_download: true }, '*');
			}}
			class="novi_btn btn btn-sm lg:btn-md preset-tonal-primary hover:preset-filled-primary-500 min-w-72 lg:min-w-96"
			title={`Download this file:\n${hosted_file_obj.filename}\n[API] SHA256: ${hosted_file_obj?.hash_sha256?.slice(0, 10)}... Hosted ID: ${hosted_file_obj.hosted_file_id_random}`}
		>
			{#await ae_promises[hosted_file_id]}
				<span class="fas fa-spinner fa-spin mx-1"></span>
				<span class="">
					Downloading
					{#if $ae_sess.api_download_kv[hosted_file_id]}
						{$ae_sess.api_download_kv[hosted_file_id].percent_completed}%
					{/if}
					:
				</span>
			{:then}
				<span class="fas fa-{ae_util.file_extension_icon(hosted_file_obj?.file_extension)}"></span>
			{/await}

			<span class="grow">
				{ae_util.shorten_filename({ filename: hosted_file_obj?.filename, max_length: 30 })}
			</span>

			<span class="shrink">
				{ae_util.format_bytes(hosted_file_obj?.size)}
			</span>
		</button>
	{/each}
</div>
