<template>
    <div class="checkoutSectionWrap">
        <div class="row">
            <label for="how_did_you_hear_about_us">How did you hear about us?</label>
            <div class="inputWrap">
                <select
                    name="how_did_you_hear_about_us"
                    id="how_did_you_hear_about_us"
                    :value="basket.info.how_did_you_hear_about_us"
                    @change="onSelectChange"
                >
                    <option value="">Choose Option</option>
                    <option
                        v-for="(choice, index) in choices"
                        :key="index"
                        :value="choice"
                        :selected="basket.info.how_did_you_hear_about_us === choice"
                    >
                        {{ choice }}
                    </option>
                    <option
                        value="other"
                        :selected="isOtherSelected"
                    >
                        Other (please specify)
                    </option>
                </select>
            </div>
        </div>

        <!-- Other text field -->
        <div class="row" v-if="isOtherSelected">
            <label for="how_did_you_hear_about_us_other">Other:</label>
            <div class="inputWrap">
                <input
                    type="text"
                    name="how_did_you_hear_about_us_other"
                    id="how_did_you_hear_about_us_other"
                    :value="basket.info.how_did_you_hear_about_us_text"
                    @input="onOtherInput"
                    class="text"
                />
            </div>
        </div>
    </div>
</template>

<script>
export default {
    name: 'how-did-you-hear',

    props: {
        basket: {
            type: Object,
            required: true
        },
        choices: {
            type: Array,
            default: () => []
        }
    },

    computed: {
        isOtherSelected() {
            const value = this.basket.info?.how_did_you_hear_about_us;
            return value === 'other' ||
                (value !== '' && this.choices.indexOf(value) === -1);
        }
    },

    methods: {
        onSelectChange(event) {
            this.$emit('update-field', {
                path: 'info.how_did_you_hear_about_us',
                value: event.target.value
            });
        },

        onOtherInput(event) {
            this.$emit('update-field', {
                path: 'info.how_did_you_hear_about_us_text',
                value: event.target.value
            });
        }
    }
};
</script>
