<script>
	import { colabs } from '$lib/stores/store';

	/** @type {HTMLInputElement} */ let fileinput;

	const onFileSelected = (/** @type {Event} */ e) => {
		// @ts-ignore
		let image = e.target.files[0];
		let reader = new FileReader();
		reader.readAsDataURL(image);
		reader.onload = (e) => {
			// @ts-ignore
			$colabs = [...$colabs, { image: e.target.result, text: '' }];
		};
	};

	const removecolabs = (/** @type {number} */ index) => {
		if (index > -1) {
			$colabs.splice(index, 1);
			$colabs = $colabs;
		}
	};
</script>

<div class="colabs">
	{#if $colabs[0]}
		{#each $colabs as organization, i}
			<div class="organization">
				<div
					class="remove"
					on:click|preventDefault={() => {
						removecolabs(i);
					}}
				>
					x
				</div>
				<img class="organization-logo" src={organization.image} alt={organization.text} />
				<input
					class="logo-title"
					type="text"
					bind:value={organization.text}
					placeholder="Nombre(opcional)"
				/>
			</div>
		{/each}
	{/if}
</div>

<button
	on:click|preventDefault={() => {
		fileinput.click();
	}}>Añadir logo</button
>
<input
	style="display:none;"
	type="file"
	accept=".jpg, .jpeg, .png"
	on:change={(e) => onFileSelected(e)}
	bind:this={fileinput}
/>

<style>
	.colabs {
		display: grid;
		grid-template-columns: repeat(3, min-content);
		align-items: center;
		justify-content: start;
	}

	.organization {
		position: relative;
		display: grid;
		grid-template-rows: min-content min-content;
		grid-gap: 0.5rem;
		align-items: center;
		justify-content: center;
		margin: 0.25rem 1rem;
		background-color: #ddd;
		padding: 0.25rem;
	}

	.organization-logo {
		max-height: 72px;
		max-width: 144px;
		margin: 0 auto;
		background-color: #fff;
	}

	.remove {
		position: absolute;
		top: -4px;
		right: -0.25rem;
		color: red;
		cursor: pointer;
		background-color: white;
		padding: 0 0.25rem;
		z-index: 2;
	}

	input {
		display: block;
		width: 100%;
	}

	button {
		display: block;
		padding: 0.5rem;
		cursor: pointer;
		margin: 1rem;
	}
</style>
