<script>
	/**
	 * @type {string}
	 */
	export let activeReport;

	/**
	 * @type {(reportName: string) => void}
	 */
	export let onSelect;

	/** @type {HTMLElement|null} */
	let popoverEl = null;

	const groups = [
		{
			label: 'Common',
			reports: [
				{ label: 'Pending', value: 'list' },
				{ label: 'Next', value: 'next' },
				{ label: 'Active', value: 'active' },
				{ label: 'Ready', value: 'ready' }
			]
		},
		{
			label: 'Time-based',
			reports: [
				{ label: 'Overdue', value: 'overdue' },
				{ label: 'Waiting', value: 'waiting' },
				{ label: 'Newest', value: 'newest' },
				{ label: 'Oldest', value: 'oldest' }
			]
		},
		{
			label: 'Recurring',
			reports: [
				{ label: 'Recurring', value: 'recurring' },
				{ label: 'Template', value: 'template' }
			]
		},
		{
			label: 'Archive',
			reports: [
				{ label: 'Completed', value: 'completed' }
			]
		}
	];

	export function toggle() {
		if (popoverEl) {
			popoverEl.togglePopover();
		}
	}

	/**
	 * @param {string} value
	 */
	function select(value) {
		onSelect(value);
		if (popoverEl) {
			popoverEl.hidePopover();
		}
	}
</script>

<div class="report-picker" popover bind:this={popoverEl}>
	{#each groups as group}
		<div class="group">
			<div class="group-label">{group.label}</div>
			{#each group.reports as report}
				<button
					class="report-option"
					class:active={activeReport === report.value}
					on:click={() => select(report.value)}
				>
					{report.label}
				</button>
			{/each}
		</div>
	{/each}
</div>

<style>
	.report-picker {
		position: fixed;
		position-anchor: --report-btn;
		position-area: bottom span-right;
		margin: 0;
		padding: var(--spacing-sm);
		background-color: var(--bg-primary);
		border: 1px solid var(--border-color);
		border-radius: var(--border-radius);
		box-shadow: var(--shadow-lg);
		min-width: 180px;
		max-width: 240px;
	}

	.group {
		padding: var(--spacing-xs) 0;
	}

	.group + .group {
		border-top: 1px solid var(--border-color);
	}

	.group-label {
		font-size: var(--font-size-xs);
		font-weight: 600;
		color: var(--text-tertiary);
		text-transform: uppercase;
		letter-spacing: 0.05em;
		padding: var(--spacing-xs) var(--spacing-sm);
	}

	.report-option {
		display: block;
		width: 100%;
		padding: var(--spacing-sm) var(--spacing-sm);
		background: none;
		border: none;
		border-radius: 0.25rem;
		font-size: var(--font-size-sm);
		font-family: inherit;
		color: var(--text-primary);
		text-align: left;
		cursor: pointer;
		min-height: 36px;
		min-width: unset;
	}

	.report-option:hover {
		background-color: var(--bg-secondary);
	}

	.report-option.active {
		background-color: var(--color-primary);
		color: white;
	}
</style>
