<script>
	import { onMount } from 'svelte';
	import { api, get, post } from '../../urls.svelte';
	import { error, yikes } from '../../warn.svelte';
	import { user } from '../../user.svelte';
	import Notes from '../notes/RelatedNotes.svelte';

	let { id } = $props();
	import { t } from '../../translations.svelte';
	let poll = $state(null);
	let selection = $state({});
	let editor = $state(user ? { name: user.name, user_id : user.id } : { name : '', user_id : -1 })
	let disabled = $state(false);

	async function load(){
		let url = api('poll/'+id);
		let res = await get(url);
		if (res.ok){
			poll = await res.json();
			if (poll.selection) selection = poll.selection;
			yikes();
		} else error(res);
	}

	async function save(ev){
		disabled = true;
		let url = api(`poll/${id}/select`);
		let res = await post(url,{editor,selection});
		if (res.ok) {
			yikes();
		} else error(res);
	}

	function select(option,weight){
		disabled = false;
		selection[option.id] = +weight;
	}

	onMount(load);
</script>

<style>
	table td:nth-child(n+2) {
		text-align: center;
	}
	.radio {
		vertical-align: middle;
	}
</style>

<fieldset>
	<legend>{t('User')}</legend>
{#if user.name}
	<div>{t('logged in as: {user}',{user:user.name})}</div>
{:else}
	<label>
		{t('Your name')}
		<input type="text" bind:value={editor.name} />
	</label>
{/if}
</fieldset>
{#if poll}
<fieldset>
	<legend>{t('poll')}: {poll.name}</legend>
	<div class="description">
		{@html poll.description.rendered}
	</div>
	<table class="poll">
		<thead>
			<tr>
				<td>{t('option')}</td>
				{#each Object.entries(poll.weights).sort((a,b) => a[0] - b[0]) as [weight,name]}
				<td class="weight">
					{weight}
					<span class="description">
						{name}
					</span>
				</td>
				{/each}
			</tr>
		</thead>
		<tbody>
			{#each Object.entries(poll.options) as [option_id,option]}
			<tr>
				<td class="option">
					{option.name}
					<span class="description">
						{@html option.description.rendered}
					</span>
				</td>
				{#each Object.entries(poll.weights) as [weight,name]}
				<td class="radio" onclick={e => select(option,weight)} title={t('click to select')} >
					{#if selection[option_id] == weight}
					X
					{/if}
				</td>
				{/each}
			</tr>
			{/each}
		</tbody>
	</table>
	<button onclick={save} disabled={disabled || !editor.name || !Object.keys(selection).length}>{t('save')} </button>
</fieldset>
{/if}
<Notes module="poll" entity_id={id} />