<script module lang="ts">
	import { tv } from "tailwind-variants";

	export const pipelineWorkflows = tv({
		slots: {
			waiting: "inline-flex items-center gap-1 italic",
			trigger: "flex items-center gap-1 text-foreground-muted hover:underline",
			icon: "size-3 shrink-0",
			// Button hugs its children, so stretch that span to get a two-column row
			item: "[&>span]:w-full",
			row: "flex w-full items-center justify-between gap-2",
			name: "flex min-w-0 items-center gap-1.5",
			label: "truncate",
			outcome: "shrink-0 text-foreground-muted"
		}
	});
</script>

<script lang="ts">
	import ChevronDown from "$icon/chevron-down";
	import Hourglass from "$icon/hourglass";
	import Dropdown from "$lib/components/ui/Dropdown.svelte";
	import DropdownItem from "$lib/components/ui/DropdownItem.svelte";
	import { formatDuration } from "$lib/format";
	import type { PipelineSummary } from "$lib/components/repo/types";
	import { finishedCount, longSummary, STATUS_LABELS } from "./pipeline";
	import PipelineStatusIcon from "./PipelineStatusIcon.svelte";

	interface Props {
		ownerHandle: string;
		repoName: string;
		pipeline: PipelineSummary;
	}

	let { ownerHandle, repoName, pipeline }: Props = $props();

	const count = $derived(pipeline.workflows.length);
	const finished = $derived(finishedCount(pipeline));
	const noun = $derived(count === 1 ? "workflow" : "workflows");
	// show the ratio only while something is still running
	const label = $derived(finished === count ? `${count} ${noun}` : `${finished}/${count} ${noun}`);

	const classes = pipelineWorkflows();
</script>

{#if count === 0}
	<!-- no workflows yet, so nothing to open -->
	<span class={classes.waiting()}>
		<Hourglass class={classes.icon()} aria-hidden="true" />
		Waiting for a spindle…
	</span>
{:else}
	<Dropdown group="pipeline-workflows" align="left" menuClass="w-72" label={longSummary(pipeline)}>
		{#snippet trigger()}
			<span class={classes.trigger()}>
				{label}
				<ChevronDown class={classes.icon()} aria-hidden="true" />
			</span>
		{/snippet}

		{#each pipeline.workflows as workflow (workflow.name)}
			<!-- TODO: the workflow log route does not exist in the svelte app yet -->
			<DropdownItem
				href={`/${ownerHandle}/${repoName}/pipelines/${pipeline.id}/workflow/${workflow.name}`}
				class={classes.item()}
			>
				<span class={classes.row()}>
					<span class={classes.name()}>
						<PipelineStatusIcon status={workflow.status} colored />
						<span class={classes.label()}>{workflow.name}</span>
					</span>
					<span class={classes.outcome()}>
						{workflow.duration > 0
							? formatDuration(workflow.duration)
							: STATUS_LABELS[workflow.status]}
					</span>
				</span>
			</DropdownItem>
		{/each}
	</Dropdown>
{/if}
