// Implements: REQ-d00010-A
// Partial: _req-search-dropdown.js.j2 — Reusable searchable requirement picker component

/**
 * createReqPicker(container, options) — Searchable requirement dropdown.
 *
 * Options:
 *   placeholder  — Input placeholder text (default: "Search requirements...")
 *   onSelect     — Callback(item) when a requirement is selected. item has {id, title, level, assertions}
 *   onClear      — Callback() when selection is cleared
 *   fetchAssertions — Boolean, fetch full requirement details on select (default: true)
 *
 * Returns API object: { clear(), getSelected(), destroy() }
 */
function createReqPicker(container, options) {
    options = options || {};
    var placeholder = options.placeholder || 'Search requirements...';
    var onSelect = options.onSelect || function() {};
    var onClear = options.onClear || function() {};
    var fetchAssertions = options.fetchAssertions !== false;

    var state = {
        selected: null,
        results: [],
        highlightIndex: -1,
        debounceTimer: null,
        open: false
    };

    // Build DOM
    var picker = document.createElement('div');
    picker.className = 'req-picker';

    var input = document.createElement('input');
    input.type = 'text';
    input.className = 'req-picker-input';
    input.placeholder = placeholder;

    var dropdown = document.createElement('div');
    dropdown.className = 'req-picker-dropdown';

    var selectedDisplay = document.createElement('div');
    selectedDisplay.className = 'req-picker-selected';
    selectedDisplay.style.display = 'none';

    picker.appendChild(input);
    picker.appendChild(dropdown);
    picker.appendChild(selectedDisplay);
    container.appendChild(picker);

    // Search with debounce
    function doSearch(query) {
        if (!query || query.length < 2) {
            closeDropdown();
            return;
        }

        dropdown.innerHTML = '<div class="req-picker-loading">Searching...</div>';
        openDropdown();

        apiFetch('/api/search?q=' + encodeURIComponent(query) + '&limit=10').then(function(data) {
            if (!data) {
                dropdown.innerHTML = '<div class="req-picker-empty">Search failed</div>';
                return;
            }
            state.results = data.results || [];
            state.highlightIndex = -1;
            renderResults();
        });
    }

    function renderResults() {
        if (state.results.length === 0) {
            dropdown.innerHTML = '<div class="req-picker-empty">No requirements found</div>';
            return;
        }

        dropdown.innerHTML = '';
        state.results.forEach(function(item, i) {
            var el = document.createElement('div');
            el.className = 'req-picker-item' + (i === state.highlightIndex ? ' highlighted' : '');

            var level = (item.level || '').toLowerCase();
            el.innerHTML =
                '<span class="req-picker-item-level ' + level + '">' + (item.level || '').toUpperCase() + '</span>' +
                '<span class="req-picker-item-id">' + escapeHtml(item.id.replace('REQ-', '')) + '</span>' +
                '<span class="req-picker-item-title">' + escapeHtml(item.title || '') + '</span>';

            el.addEventListener('click', function() {
                selectItem(item);
            });

            dropdown.appendChild(el);
        });
    }

    function selectItem(item) {
        closeDropdown();
        input.value = '';

        if (fetchAssertions) {
            // Fetch full requirement details for assertions
            apiFetch('/api/requirement/' + encodeURIComponent(item.id)).then(function(data) {
                if (data) {
                    item.assertions = data.assertions || [];
                }
                setSelected(item);
            });
        } else {
            setSelected(item);
        }
    }

    function setSelected(item) {
        state.selected = item;
        input.style.display = 'none';

        var level = (item.level || '').toLowerCase();
        selectedDisplay.innerHTML =
            '<span class="req-picker-item-level ' + level + '">' + (item.level || '').toUpperCase() + '</span>' +
            '<span class="req-picker-selected-id">' + escapeHtml(item.id) + '</span>' +
            '<span class="req-picker-selected-title">' + escapeHtml(item.title || '') + '</span>' +
            '<button class="req-picker-clear" title="Clear selection">&times;</button>';

        selectedDisplay.querySelector('.req-picker-clear').addEventListener('click', function() {
            clearSelection();
        });

        selectedDisplay.style.display = 'flex';
        onSelect(item);
    }

    function clearSelection() {
        state.selected = null;
        selectedDisplay.style.display = 'none';
        selectedDisplay.innerHTML = '';
        input.style.display = '';
        input.value = '';
        input.focus();
        onClear();
    }

    function openDropdown() {
        state.open = true;
        dropdown.classList.add('open');
    }

    function closeDropdown() {
        state.open = false;
        dropdown.classList.remove('open');
        state.highlightIndex = -1;
    }

    // Event handlers
    input.addEventListener('input', function() {
        clearTimeout(state.debounceTimer);
        var query = input.value.trim();
        state.debounceTimer = setTimeout(function() {
            doSearch(query);
        }, 300);
    });

    input.addEventListener('keydown', function(e) {
        if (!state.open) return;

        if (e.key === 'ArrowDown') {
            e.preventDefault();
            state.highlightIndex = Math.min(state.highlightIndex + 1, state.results.length - 1);
            renderResults();
        } else if (e.key === 'ArrowUp') {
            e.preventDefault();
            state.highlightIndex = Math.max(state.highlightIndex - 1, 0);
            renderResults();
        } else if (e.key === 'Enter') {
            e.preventDefault();
            if (state.highlightIndex >= 0 && state.highlightIndex < state.results.length) {
                selectItem(state.results[state.highlightIndex]);
            }
        } else if (e.key === 'Escape') {
            e.preventDefault();
            closeDropdown();
            input.blur();
        }
    });

    // Close dropdown when clicking outside
    function onDocumentClick(e) {
        if (!picker.contains(e.target)) {
            closeDropdown();
        }
    }
    document.addEventListener('click', onDocumentClick);

    // Public API
    return {
        clear: function() {
            clearSelection();
        },
        getSelected: function() {
            return state.selected;
        },
        destroy: function() {
            clearTimeout(state.debounceTimer);
            document.removeEventListener('click', onDocumentClick);
            if (picker.parentNode) {
                picker.parentNode.removeChild(picker);
            }
        }
    };
}
