<script lang="ts">
	import { onMount } from 'svelte';
	import { goto } from '$app/navigation';
	import * as api from '$lib/api';
	import type { LogScanRuleInput } from '$lib/api';
	import type { EntityPickerItem, Workload } from '$lib/types';
	import ForgeHero from '$lib/components/ForgeHero.svelte';
	import ToggleSwitch from '$lib/components/ToggleSwitch.svelte';
	import RegexTestBox from '$lib/components/RegexTestBox.svelte';
	import EntityPicker from '$lib/components/EntityPicker.svelte';
	import { IconX } from '$lib/components/icons';
	import { t } from '$lib/i18n';

	let name = $state('');
	let pattern = $state('');
	let severity = $state<'info' | 'warn' | 'error'>('warn');
	let streams = $state<'all' | 'stdout' | 'stderr'>('all');
	let cooldownSeconds = $state(60);
	let workloadID = $state(''); // empty = global
	let enabled = $state(true);
	let sampleLine = $state('');

	let submitting = $state(false);
	let error = $state('');

	// Workload picker state. Loaded once on mount so the modal is
	// instant when the user opens it. Failure to load is non-fatal —
	// the operator can still type-paste an id via the (legacy)
	// advanced toggle if we ever surface one; for now we just
	// surface the load error in the page-level alert.
	let workloads = $state<Workload[]>([]);
	let pickerOpen = $state(false);

	// Map each workload to a picker item. Plugin-native rows
	// surface their source plugin; legacy rows show their kind
	// (project / stack / site). The group label lets the picker's
	// grouped layout cluster related entries together.
	const pickerItems = $derived<EntityPickerItem[]>(
		workloads.map((w) => ({
			value: w.id,
			label: w.name,
			description: w.source_kind || w.kind,
			group: (w.source_kind || w.kind || 'other').toUpperCase()
		}))
	);

	const selectedWorkload = $derived(workloads.find((w) => w.id === workloadID));

	const regexValid = $derived.by(() => {
		if (!pattern) return true;
		try {
			new RegExp(pattern);
			return true;
		} catch {
			return false;
		}
	});

	onMount(async () => {
		try {
			workloads = await api.listWorkloads();
		} catch (e) {
			error = e instanceof Error ? e.message : 'Failed to load workloads';
		}
	});

	function pickWorkload(value: string): void {
		workloadID = value;
		pickerOpen = false;
	}

	function clearWorkload(): void {
		workloadID = '';
	}

	async function submit(e: Event): Promise<void> {
		e.preventDefault();
		if (submitting) return;
		error = '';
		submitting = true;
		try {
			const body: LogScanRuleInput = {
				name: name.trim(),
				pattern,
				severity,
				streams,
				cooldown_seconds: cooldownSeconds,
				workload_id: workloadID.trim(),
				enabled
			};
			const created = await api.createLogScanRule(body);
			goto(`/log-scan-rules/${created.id}`);
		} catch (e) {
			error = e instanceof Error ? e.message : 'Create failed';
		} finally {
			submitting = false;
		}
	}
</script>

<svelte:head>
	<title>{$t('logscan.titleNew')} · Tinyforge</title>
</svelte:head>

<div class="forge">
	{#snippet lede()}
		{$t('logscan.ledeNew')}
	{/snippet}

	<ForgeHero
		backHref="/log-scan-rules"
		backLabel={$t('logscan.toolbar.backToList')}
		eyebrowSuffix={$t('logscan.toolbar.newButton').toUpperCase()}
		title={$t('logscan.titleNew')}
		size="lg"
		lede_html={lede}
	/>

	<form onsubmit={submit} class="form" aria-busy={submitting}>
		{#if error}
			<div class="alert" role="alert">
				<span class="alert-tag">ERR</span><span>{error}</span>
			</div>
		{/if}

		<div class="field">
			<label for="r-name" class="field-label">
				<span class="num" aria-hidden="true">01</span>
				<span class="lbl">{$t('logscan.form.name')}</span>
				<span class="req">{$t('logscan.form.required')}</span>
			</label>
			<input
				id="r-name"
				type="text"
				class="input"
				bind:value={name}
				required
				placeholder={$t('logscan.form.namePlaceholder')}
			/>
		</div>

		<div class="field">
			<label for="r-pattern" class="field-label">
				<span class="num" aria-hidden="true">02</span>
				<span class="lbl">{$t('logscan.form.pattern')}</span>
				<span class="req">{$t('logscan.form.regex')}</span>
			</label>
			<input
				id="r-pattern"
				type="text"
				class="input mono"
				class:bad={!regexValid}
				bind:value={pattern}
				placeholder={$t('logscan.form.patternPlaceholder')}
				spellcheck="false"
				aria-invalid={!regexValid}
				aria-describedby={!regexValid ? 'r-pattern-err' : undefined}
				required
			/>
			{#if !regexValid}
				<span id="r-pattern-err" class="hint danger" role="alert">
					{$t('logscan.form.invalidRegex')}
				</span>
			{/if}
			<RegexTestBox {pattern} bind:sample={sampleLine} />
		</div>

		<div class="field group">
			<div class="field-label">
				<span class="num" aria-hidden="true">03</span>
				<span class="lbl">{$t('logscan.form.matchShape')}</span>
				<span class="opt">{$t('logscan.form.matchShapeOpts')}</span>
			</div>
			<div class="row three">
				<label class="sub" for="r-severity">
					<span class="sub-label">{$t('logscan.form.severity')}</span>
					<select id="r-severity" class="input" bind:value={severity}>
						<option value="info">info</option>
						<option value="warn">warn</option>
						<option value="error">error</option>
					</select>
				</label>
				<label class="sub" for="r-streams">
					<span class="sub-label">{$t('logscan.form.streams')}</span>
					<select id="r-streams" class="input" bind:value={streams}>
						<option value="all">all</option>
						<option value="stdout">stdout</option>
						<option value="stderr">stderr</option>
					</select>
				</label>
				<label class="sub" for="r-cooldown">
					<span class="sub-label">{$t('logscan.form.cooldown')}</span>
					<input
						id="r-cooldown"
						type="number"
						min="0"
						class="input"
						bind:value={cooldownSeconds}
					/>
				</label>
			</div>
			<p class="hint">{$t('logscan.form.cooldownHint')}</p>
		</div>

		<div class="field">
			<div class="field-label">
				<span class="num" aria-hidden="true">04</span>
				<span class="lbl">{$t('logscan.form.scope')}</span>
				<span class="opt">{$t('logscan.form.optional')}</span>
			</div>
			<div class="scope-picker">
				{#if workloadID === ''}
					<div class="scope-state global">
						<span class="scope-icon" aria-hidden="true">●</span>
						<span class="scope-text">{$t('logscan.form.scopeGlobal')}</span>
						<button
							type="button"
							class="forge-btn-ghost xs"
							onclick={() => (pickerOpen = true)}
						>
							{$t('logscan.form.scopePick')}
						</button>
					</div>
				{:else}
					<div class="scope-state workload">
						<span class="scope-tag">{$t('logscan.form.scopeSelected')}</span>
						{#if selectedWorkload}
							<span class="scope-text">{selectedWorkload.name}</span>
							<code class="scope-meta">
								{selectedWorkload.source_kind || selectedWorkload.kind}
							</code>
						{:else}
							<span class="scope-text muted">{$t('logscan.form.scopeUnknown')}</span>
							<code class="scope-meta">{workloadID}</code>
						{/if}
						<button
							type="button"
							class="forge-btn-ghost xs"
							onclick={() => (pickerOpen = true)}
						>
							{$t('observability.edit')}
						</button>
						<button
							type="button"
							class="scope-clear"
							onclick={clearWorkload}
							aria-label={$t('logscan.form.scopeClear')}
							title={$t('logscan.form.scopeClear')}
						>
							<IconX size={14} />
						</button>
					</div>
				{/if}
			</div>
			<p class="hint">{$t('logscan.form.scopeHint')}</p>
		</div>

		<div class="field row-toggle">
			<div class="toggle-copy">
				<span class="lbl small" aria-hidden="true">{$t('logscan.form.enabled')}</span>
				<p class="hint">{$t('logscan.form.enabledHint')}</p>
			</div>
			<ToggleSwitch bind:checked={enabled} label={$t('logscan.form.enabled')} />
		</div>

		<div class="actions">
			<a href="/log-scan-rules" class="forge-btn-ghost">{$t('observability.cancel')}</a>
			<button
				type="submit"
				class="forge-btn"
				disabled={submitting || !name.trim() || !pattern || !regexValid}
				aria-busy={submitting}
			>
				{submitting ? $t('logscan.form.submitting') : $t('logscan.form.submit')}
			</button>
		</div>
	</form>

	<EntityPicker
		bind:open={pickerOpen}
		items={pickerItems}
		current={workloadID}
		title={$t('logscan.form.scopePickTitle')}
		onselect={pickWorkload}
		onclose={() => (pickerOpen = false)}
	/>
</div>

<style>
	.forge {
		display: flex;
		flex-direction: column;
		gap: 1rem;
		max-width: 820px;
		margin: 0 auto;
	}
	.form {
		display: flex;
		flex-direction: column;
		gap: 1.5rem;
		background: var(--surface-card);
		border: 1px solid var(--border-primary);
		border-radius: var(--radius-2xl);
		padding: 1.75rem;
	}
	@media (max-width: 600px) {
		.form {
			padding: 1.1rem;
			gap: 1.25rem;
		}
	}

	/* ── Alert ─────────────────────────────────────── */
	.alert {
		display: flex;
		gap: 0.7rem;
		align-items: center;
		padding: 0.7rem 0.9rem;
		background: var(--color-danger-light);
		color: var(--color-danger-dark);
		border: 1px solid var(--color-danger);
		border-left-width: 4px;
		border-radius: var(--radius-lg);
		font-size: 0.875rem;
	}
	.alert-tag {
		font-family: var(--forge-mono);
		font-weight: 700;
		font-size: 0.65rem;
		letter-spacing: 0.16em;
		padding: 0.15rem 0.4rem;
		background: var(--color-danger);
		color: var(--surface-card);
		border-radius: var(--radius-sm);
	}
	:global([data-theme='dark']) .alert {
		background: color-mix(in srgb, var(--color-danger) 14%, transparent);
		color: color-mix(in srgb, var(--color-danger) 60%, var(--text-primary));
	}

	/* ── Field structure ────────────────────────────── */
	.field {
		display: flex;
		flex-direction: column;
		gap: 0.55rem;
		margin: 0;
		padding: 0;
		border: 0;
	}
	.field.group {
		gap: 0.75rem;
	}
	.field-label {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		gap: 0.55rem;
	}
	.num {
		display: inline-flex;
		width: 26px;
		height: 26px;
		justify-content: center;
		align-items: center;
		background: var(--text-primary);
		color: var(--surface-card);
		border-radius: var(--radius-sm);
		font-family: var(--forge-mono);
		font-size: 0.7rem;
		font-weight: 700;
		flex: 0 0 auto;
	}
	.lbl {
		font-weight: 600;
		font-size: 1.1rem;
		letter-spacing: -0.01em;
		color: var(--text-primary);
	}
	.lbl.small {
		font-size: 0.95rem;
	}
	.req,
	.opt {
		font-family: var(--forge-mono);
		font-size: 0.58rem;
		font-weight: 600;
		text-transform: uppercase;
		letter-spacing: 0.14em;
	}
	.req {
		color: var(--color-danger);
	}
	.opt {
		color: var(--text-tertiary);
	}

	/* ── Inputs ─────────────────────────────────────── */
	.input {
		width: 100%;
		background: var(--surface-input);
		border: 1px solid var(--border-input);
		border-radius: var(--radius-lg);
		padding: 0.55rem 0.75rem;
		font-size: 0.9rem;
		color: var(--text-primary);
		font-family: inherit;
		outline: none;
		transition: border-color 120ms ease, box-shadow 120ms ease;
	}
	.input:focus {
		border-color: var(--border-focus);
		box-shadow: 0 0 0 3px var(--forge-accent-soft);
	}
	.input.mono {
		font-family: var(--forge-mono);
		font-size: 0.85rem;
	}
	.input.bad {
		border-color: var(--color-danger);
	}
	.input.bad:focus {
		box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-danger) 22%, transparent);
	}

	.row.three {
		display: grid;
		grid-template-columns: 1fr 1fr 1fr;
		gap: 0.9rem;
	}
	@media (max-width: 720px) {
		.row.three {
			grid-template-columns: 1fr 1fr;
		}
	}
	@media (max-width: 480px) {
		.row.three {
			grid-template-columns: 1fr;
		}
	}
	.sub {
		display: flex;
		flex-direction: column;
		gap: 0.35rem;
		min-width: 0;
	}
	.sub-label {
		font-family: var(--forge-mono);
		font-size: 0.62rem;
		font-weight: 600;
		letter-spacing: 0.14em;
		text-transform: uppercase;
		color: var(--text-secondary);
	}

	/* ── Hints ──────────────────────────────────────── */
	.hint {
		font-size: 0.78rem;
		color: var(--text-tertiary);
		line-height: 1.5;
		margin: 0;
	}
	.hint.danger {
		color: var(--color-danger);
	}

	/* ── Toggle row ─────────────────────────────────── */
	.row-toggle {
		display: flex;
		flex-direction: row;
		align-items: flex-start;
		justify-content: space-between;
		gap: 1rem;
		padding-top: 0.6rem;
		border-top: 1px dashed var(--border-primary);
	}
	.toggle-copy {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 0.25rem;
	}

	/* ── Action footer ──────────────────────────────── */
	.actions {
		display: flex;
		justify-content: flex-end;
		gap: 0.55rem;
		flex-wrap: wrap;
	}
	@media (max-width: 480px) {
		.actions {
			flex-direction: column-reverse;
			align-items: stretch;
		}
		.actions :global(.forge-btn),
		.actions :global(.forge-btn-ghost) {
			justify-content: center;
		}
	}

	/* ── Scope picker chip ────────────────────────────────────
	   Replaces the free-text workload-id input with a single
	   state-rendering row: either "Global · [Pick workload…]"
	   or "Workload · <name> <kind> [Edit] [×]". Visual style
	   mirrors the apps detail page's chain/status chips. */
	.scope-picker {
		display: flex;
		flex-direction: column;
		gap: 0.4rem;
	}
	.scope-state {
		display: flex;
		flex-wrap: wrap;
		align-items: center;
		gap: 0.55rem;
		padding: 0.55rem 0.75rem;
		background: var(--surface-card-hover);
		border: 1px solid var(--border-primary);
		border-radius: var(--radius-lg);
	}
	.scope-state.global {
		border-style: dashed;
	}
	.scope-state.workload {
		background: color-mix(in srgb, var(--color-brand-500) 8%, var(--surface-card-hover));
		border-color: color-mix(in srgb, var(--color-brand-500) 35%, var(--border-primary));
	}
	.scope-icon {
		font-size: 0.7rem;
		color: var(--text-tertiary);
	}
	.scope-text {
		font-weight: 600;
		font-size: 0.92rem;
		color: var(--text-primary);
	}
	.scope-text.muted {
		color: var(--text-tertiary);
		font-style: italic;
	}
	.scope-tag {
		font-family: var(--forge-mono);
		font-size: 0.6rem;
		font-weight: 700;
		letter-spacing: 0.14em;
		text-transform: uppercase;
		padding: 0.12rem 0.4rem;
		background: var(--color-brand-500);
		color: var(--surface-card);
		border-radius: var(--radius-sm);
	}
	.scope-meta {
		font-family: var(--forge-mono);
		font-size: 0.72rem;
		color: var(--text-secondary);
		padding: 0.1rem 0.35rem;
		background: var(--surface-card);
		border: 1px solid var(--border-primary);
		border-radius: var(--radius-sm);
	}
	.scope-state .forge-btn-ghost {
		margin-left: auto;
	}
	.scope-state.workload .forge-btn-ghost {
		margin-left: auto;
		margin-right: 0;
	}
	.scope-clear {
		display: inline-flex;
		align-items: center;
		justify-content: center;
		width: 26px;
		height: 26px;
		background: transparent;
		border: 1px solid var(--border-primary);
		border-radius: var(--radius-md);
		color: var(--text-tertiary);
		cursor: pointer;
		transition: color 120ms ease, border-color 120ms ease;
	}
	.scope-clear:hover {
		color: var(--color-danger);
		border-color: var(--color-danger);
	}
	:global(.forge-btn-ghost.xs) {
		padding: 0.2rem 0.55rem;
		font-size: 0.62rem;
	}
</style>
