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

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

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

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

	function select(option,weight){
		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}
<div>{t('logged in as: {user}',{user:user.name})}</div>
{:else}
	<label>
		<input type="text" bind:value={editor.name} />
		{t('Your 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) 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>
	{#if Object.keys(selection).length}
	<button onclick={save}>{t('save')}</button>
	{/if}
</fieldset>
<div class="warn">TODO: add notes</div>
{/if}