<script lang="ts">
import { onMount, untrack } from 'svelte';
import PersonMentionEditor from './PersonMentionEditor.svelte';
import type { components } from '$lib/generated/api';

type PersonMention = components['schemas']['PersonMention'];

type Props = {
	initialValue?: string;
	initialMentions?: PersonMention[];
	placeholder?: string;
	disabled?: boolean;
	onChange: (snapshot: { value: string; mentionedPersons: PersonMention[] }) => void;
	/** Hands the test a setter so it can flip `disabled` after mount — used to
	 *  exercise the editor's reactive `disabled` $effect (mid-session toggle). */
	onReady?: (api: { setDisabled: (value: boolean) => void }) => void;
};

let {
	initialValue = '',
	initialMentions = [],
	placeholder,
	disabled = false,
	onChange,
	onReady
}: Props = $props();

// initial* props seed mount-time state; reading them inside untrack signals
// the intentional one-shot capture and silences state_referenced_locally.
let value = $state(untrack(() => initialValue));
let mentionedPersons = $state<PersonMention[]>(untrack(() => [...initialMentions]));
let disabledState = $state(untrack(() => disabled));

onMount(() => {
	onReady?.({ setDisabled: (next: boolean) => (disabledState = next) });
});

$effect(() => {
	onChange({ value, mentionedPersons: [...mentionedPersons] });
});
</script>

<PersonMentionEditor
	bind:value={value}
	bind:mentionedPersons={mentionedPersons}
	placeholder={placeholder}
	disabled={disabledState}
/>
