<template>
    <div class="siteMenuAdmin__picker">
        <div class="siteMenuAdmin__pickerSearch">
            <input type="text" class="siteMenuAdmin__control"
                   v-model="term" @input="onInput" @focus="onInput"
                   placeholder="Search categories or products…" autocomplete="off" />

            <ul v-if="showResults" class="siteMenuAdmin__pickerResults">
                <li v-if="searching" class="siteMenuAdmin__pickerHint">
                    <i class="fa fa-spinner fa-spin"></i> Searching…
                </li>
                <li v-else-if="!results.length" class="siteMenuAdmin__pickerHint">No matches.</li>
                <li v-for="result in results" :key="result.type + '_' + result.id"
                    class="siteMenuAdmin__pickerResult"
                    :class="{ 'siteMenuAdmin__pickerResult--added': isSelected(result) }"
                    @mousedown.prevent="add(result)">
                    <span class="siteMenuAdmin__pickerResult-name">{{ result.name }}</span>
                    <span class="siteMenuAdmin__pickerTag" :class="'siteMenuAdmin__pickerTag--' + result.type">
                        {{ result.type }}
                    </span>
                    <span v-if="isSelected(result)" class="siteMenuAdmin__pickerAdded"><i class="fa fa-check"></i></span>
                </li>
            </ul>
        </div>

        <ul v-if="value.length" class="siteMenuAdmin__pickerSelected">
            <li v-for="(item, index) in value" :key="item.type + '_' + item.id" class="siteMenuAdmin__pickerItem">
                <span class="siteMenuAdmin__pickerItem-name">{{ item.name }}</span>
                <span class="siteMenuAdmin__pickerTag" :class="'siteMenuAdmin__pickerTag--' + item.type">
                    {{ item.type }}
                </span>
                <span class="siteMenuAdmin__pickerItem-actions">
                    <button type="button" class="siteMenuAdmin__pickerBtn" :disabled="index === 0"
                            title="Move up" @click="move(index, -1)"><i class="fa fa-arrow-up"></i></button>
                    <button type="button" class="siteMenuAdmin__pickerBtn" :disabled="index === value.length - 1"
                            title="Move down" @click="move(index, 1)"><i class="fa fa-arrow-down"></i></button>
                    <button type="button" class="siteMenuAdmin__pickerBtn siteMenuAdmin__pickerBtn--remove"
                            title="Remove" @click="remove(index)"><i class="fa fa-times"></i></button>
                </span>
            </li>
        </ul>
        <p v-else class="siteMenuAdmin__hint">No items chosen yet — search above to add categories and products.</p>
    </div>
</template>

<script>
/**
 * Mega-menu content builder. Hand-picks individual categories and products (via
 * a debounced search against the site-menu API) into an ordered list. Emits the
 * ordered list of { type, id, name, url } objects through v-model (`input`); the
 * parent form serialises just the { type, id } refs into a hidden field.
 */
export default {
    name: 'site-menu-mega-picker',
    props: {
        base: { type: String, required: true },
        value: { type: Array, default: () => [] },
    },
    data() {
        return {
            term: '',
            results: [],
            searching: false,
            showResults: false,
            debounceTimer: null,
        };
    },
    methods: {
        onInput() {
            this.showResults = true;
            if (this.debounceTimer) { clearTimeout(this.debounceTimer); }
            const term = this.term.trim();
            if (term.length < 2) {
                this.results = [];
                this.searching = false;
                return;
            }
            this.searching = true;
            this.debounceTimer = setTimeout(() => this.runSearch(term), 250);
        },
        runSearch(term) {
            fetch(this.base + '/api/search?term=' + encodeURIComponent(term), {
                headers: { Accept: 'application/json' },
                credentials: 'same-origin',
            })
                .then(response => response.json())
                .then(data => { this.results = (data && data.results) || []; })
                .catch(() => { this.results = []; })
                .finally(() => { this.searching = false; });
        },
        isSelected(result) {
            return this.value.some(item => item.type === result.type && item.id === result.id);
        },
        add(result) {
            if (this.isSelected(result)) { return; }
            this.$emit('input', this.value.concat([{
                type: result.type, id: result.id, name: result.name, url: result.url,
            }]));
        },
        remove(index) {
            const next = this.value.slice();
            next.splice(index, 1);
            this.$emit('input', next);
        },
        move(index, delta) {
            const target = index + delta;
            if (target < 0 || target >= this.value.length) { return; }
            const next = this.value.slice();
            const [moved] = next.splice(index, 1);
            next.splice(target, 0, moved);
            this.$emit('input', next);
        },
    },
};
</script>
