<script lang="ts">
    import { createEventDispatcher } from 'svelte';

    interface Option {
        value: string
        name: string
        default?: boolean
        selected?: boolean
    }

    export let id: string
    export let name: string
    export let options: Option[]
    export let value: string = undefined

    const dispatch = createEventDispatcher()
    const defaultOption = options.find(option => option.default)

    let selected = value || options[0].value
    $: currentOption = options.find(option => option.value === selected)

    // Redefine value from parent (when reset)
    $: if (value === defaultOption.value) {
        selected = defaultOption.value
    }


    /**
     * When changing select value
     */
    const handleChange = ({ target: { value }}: any) => {
        const option = options.find(option => option.value === value)

        // Dispatch event to parent
        dispatch('change', option.value)
    }
</script>

<div class="select">
    <slot />

    <span>{currentOption.name}</span>

    <select {name} {id} bind:value={selected} on:change={handleChange}>
        {#each options as { value, name }}
            <option {value} selected={value === selected}>
                {name}
            </option>
        {/each}
    </select>
</div>