<script>
	import Histogram from '../../Components/Histogram.svelte';
	import Notes from '../notes/RelatedNotes.svelte';

	import { onMount } from 'svelte';
	import { api, get } from '../../urls.svelte';
	import { error, yikes } from '../../warn.svelte';
	import { t } from '../../translations.svelte';
	let { id } = $props();
	let poll = $state(null);

	function average(hist){
		let count = 0;
		let sum   = 0;
		for (let [k,v] of Object.entries(hist)) {
			count += v;
			sum   += k*v;
		}
		return count > 0 ? sum/count : '?';
	}

	function max_val(hist){
		return Math.max(...Object.values(hist));
	}

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

	onMount(load);
</script>

{#if poll}
<fieldset>
	<legend>{poll.name}</legend>
	<div class="description">{@html poll.description.rendered}</div>
	<table>
		<thead>
			<tr>
				<td>{t('option')}</td>
				<td>{t('average')}</td>
				<td>{t('histogram')}</td>
			</tr>
		</thead>
		<tbody>
		{#each Object.entries(poll.evaluation).sort((a,b) => b[0] - a[0]) as [avg,optionset]}
			{#each Object.entries(optionset) as [option_id,histo]}
			<tr>
				<td>
					{poll.options[option_id].name}
				</td>
				<td>
					{(+avg).toFixed(3)}
				</td>
				<td>
					<Histogram data={histo} />
				</td>
			</tr>
			{/each}
		{/each}
		</tbody>
	</table>
</fieldset>
{/if}
<Notes module="poll" entity_id={id} />