<!-- #region EnvSelector [C:3] [TYPE Component] [SEMANTICS environment, selector, dropdown, migration] -->
<!-- @ingroup UI -->
<!-- @BRIEF Dropdown selector for choosing a Superset environment (source/target). -->
<!-- @LAYER UI -->
<!-- @RELATION BINDS_TO -> [EXT:frontend:environments] -->
<!-- @INVARIANT Source and target environments must be selectable from the list of configured environments. -->
<!-- @UX_STATE: Empty -> Placeholder "choose environment" shown, no env selected. -->
<!-- @UX_STATE: Selected -> Selected environment name and URL displayed. -->
<script lang="ts">
    import { t } from '$lib/i18n/index.svelte.js';
    import { HelpTooltip } from '$lib/ui';

    let {
        label = "",
        helpText = "",
        selectedId = $bindable(""),
        environments = [],
        onchange = () => {},
    }: {
        label?: string;
        helpText?: string;
        selectedId: string;
        environments: Array<{ id: string; name: string; url: string }>;
        onchange?: (_payload: { id: string }) => void;
    } = $props();

    // #region handleSelect [C:2] [TYPE Function] [SEMANTICS selection,event]
// @ingroup UI
    // @BRIEF Propagates the selection change through callback prop.
    // @PRE event.target is an HTMLSelectElement.
    // @POST selectedId is updated and parent callback receives the selected environment id.
    function handleSelect(event: Event) {
        const target = event.target as HTMLSelectElement;
        selectedId = target.value;
        onchange({ id: selectedId });
    }
    // #endregion handleSelect
</script>

<div class="flex flex-col space-y-1">
    <label for="env-select" class="text-sm font-medium text-text flex items-center gap-1.5">
        {label}
        {#if helpText}
            <HelpTooltip text={helpText} />
        {/if}
    </label>
    <select
        id="env-select"
        class="block w-full pl-3 pr-10 py-2 text-base border-border-strong focus:outline-none focus:ring-primary-ring focus:border-primary-ring sm:text-sm rounded-md"
        value={selectedId}
        onchange={handleSelect}
    >
        <option value="" disabled>{$t.common?.choose_environment}</option>
        {#each environments as env}
            <option value={env.id}>{env.name} ({env.url})</option>
        {/each}
    </select>
</div>
<!-- #endregion EnvSelector -->
