<script lang="ts">
	import { goto } from '$app/navigation';
	import * as api from '$lib/api';
	import type { EventTriggerInput } from '$lib/api';
	import ForgeHero from '$lib/components/ForgeHero.svelte';
	import ToggleSwitch from '$lib/components/ToggleSwitch.svelte';
	import { t } from '$lib/i18n';

	let name = $state('');
	let filterSeverity = $state('');
	let filterSource = $state('');
	let filterMessageRegex = $state('');
	let actionTarget = $state('');
	let actionSecret = $state('');
	let enabled = $state(true);
	let submitting = $state(false);
	let error = $state('');

	// Client-side regex sanity check. Doesn't replicate Go's regex flavour
	// (e.g. ECMAScript vs RE2), but catches the most common typos before
	// the operator hits Submit. Server is authoritative.
	const regexValid = $derived.by(() => {
		if (!filterMessageRegex) return true;
		try {
			new RegExp(filterMessageRegex);
			return true;
		} catch {
			return false;
		}
	});

	async function submit(e: Event): Promise<void> {
		e.preventDefault();
		if (submitting) return;
		error = '';
		submitting = true;
		try {
			const body: EventTriggerInput = {
				name: name.trim(),
				filter_severity: filterSeverity.trim(),
				filter_source: filterSource.trim(),
				filter_message_regex: filterMessageRegex,
				action_type: 'webhook',
				action_target: actionTarget.trim(),
				action_secret: actionSecret,
				enabled
			};
			const created = await api.createEventTrigger(body);
			goto(`/event-triggers/${created.id}`);
		} catch (e) {
			error = e instanceof Error ? e.message : 'Create failed';
		} finally {
			submitting = false;
		}
	}
</script>

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

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

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

	<form onsubmit={submit} class="form" novalidate 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="trig-name" class="field-label">
				<span class="num" aria-hidden="true">01</span>
				<span class="lbl">{$t('triggers.form.name')}</span>
				<span class="req">{$t('triggers.form.required')}</span>
			</label>
			<input
				id="trig-name"
				type="text"
				bind:value={name}
				class="input"
				placeholder={$t('triggers.form.namePlaceholder')}
				autocomplete="off"
				required
			/>
		</div>

		<fieldset class="field group">
			<legend class="field-label as-legend">
				<span class="num" aria-hidden="true">02</span>
				<span class="lbl">{$t('triggers.form.filtersLabel')}</span>
				<span class="opt">{$t('triggers.form.andComposed')}</span>
			</legend>
			<div class="row two">
				<label class="sub" for="trig-sev">
					<span class="sub-label">{$t('triggers.form.severityCsv')}</span>
					<input
						id="trig-sev"
						type="text"
						class="input"
						bind:value={filterSeverity}
						placeholder={$t('triggers.form.severityPlaceholder')}
						autocomplete="off"
					/>
				</label>
				<label class="sub" for="trig-src">
					<span class="sub-label">{$t('triggers.form.sourceCsv')}</span>
					<input
						id="trig-src"
						type="text"
						class="input"
						bind:value={filterSource}
						placeholder={$t('triggers.form.sourcePlaceholder')}
						autocomplete="off"
					/>
				</label>
			</div>
			<label class="sub" for="trig-msg">
				<span class="sub-label">{$t('triggers.form.messageRegex')}</span>
				<input
					id="trig-msg"
					type="text"
					class="input mono"
					class:bad={!regexValid}
					bind:value={filterMessageRegex}
					placeholder={$t('triggers.form.messageRegexPlaceholder')}
					autocomplete="off"
					spellcheck="false"
					aria-invalid={!regexValid}
					aria-describedby={!regexValid ? 'trig-msg-err' : undefined}
				/>
				{#if !regexValid}
					<span id="trig-msg-err" class="hint danger" role="alert">
						{$t('triggers.form.invalidRegex')}
					</span>
				{/if}
			</label>
		</fieldset>

		<fieldset class="field group">
			<legend class="field-label as-legend">
				<span class="num" aria-hidden="true">03</span>
				<span class="lbl">{$t('triggers.form.actionLabel')}</span>
				<span class="req">{$t('triggers.form.actionWebhookBadge')}</span>
			</legend>
			<label class="sub" for="trig-target">
				<span class="sub-label">{$t('triggers.form.urlLabel')}</span>
				<input
					id="trig-target"
					type="url"
					class="input"
					bind:value={actionTarget}
					placeholder={$t('triggers.form.urlPlaceholder')}
					autocomplete="off"
					required
				/>
			</label>
			<label class="sub" for="trig-secret">
				<span class="sub-label">{$t('triggers.form.secretLabel')}</span>
				<input
					id="trig-secret"
					type="password"
					class="input"
					bind:value={actionSecret}
					placeholder={$t('triggers.form.secretPlaceholder')}
					autocomplete="new-password"
				/>
				<span class="hint">{$t('triggers.form.secretHint')}</span>
			</label>
		</fieldset>

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

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

<style>
	.forge {
		display: flex;
		flex-direction: column;
		gap: 1rem;
		max-width: 760px;
		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;
		margin: 0;
	}
	.field-label.as-legend {
		float: none;
		width: 100%;
	}
	.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;
		line-height: 1.2;
		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.6rem 0.8rem;
		font-size: 0.92rem;
		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.two {
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 0.9rem;
	}
	@media (max-width: 600px) {
		.row.two {
			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 {
		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;
	}

	/* ── Actions ────────────────────────────────────── */
	.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;
		}
	}
</style>
