<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)
    const defaultOptionIndex = options.findIndex(option => option.default)
    const selectedOptionIndex = options.findIndex(option => option.selected)

    let current: number = selectedOptionIndex
    let currentOptionEl: HTMLElement
    $: currentOption = options[current]

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


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

        // Dispatch event to parent
        dispatch('change', options[current].value)
    }
</script>

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

    <span bind:this={currentOptionEl}>
        {currentOption.name}
    </span>

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