<script>
	import { organizedBy } 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
			$organizedBy = [...$organizedBy, { image: e.target.result, text: '' }];
		};
	};

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

<div class="form-organized-by">
	{#if $organizedBy[0]}
		{#each $organizedBy as organization, i}
			<div class="organization">
				<div
					class="remove"
					on:click|preventDefault={() => {
						removeOrganizer(i);
					}}
				>
					x
				</div>
				<img class="organized-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>
	.form-organized-by {
		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;
	}
	.organized-logo {
		max-height: 72px;
		max-width: 128px;
		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;
	}

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

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