/**
 * Searchable room picker — replaces a plain <select> full of every room
 * (painful to scroll through once a hotel has 100+ rooms) with a type-
 * to-filter text input backed by a hidden field that carries the real
 * room_id, same as the select it replaces. No server round-trip: the
 * room list a page already has server-side is embedded as JSON and
 * filtered entirely client-side, since a hotel's room count (even a
 * large one) is small enough to ship in one page load.
 *
 * Markup contract (see housekeeping/form.php, maintenance/form.php,
 * bookings/change_room.php, bookings/search_results.php for usage):
 *   <div class="dropdown">
 *     <input type="text" id="{inputId}" class="form-control" autocomplete="off">
 *     <input type="hidden" name="room_id" id="{hiddenId}">
 *     <div class="dropdown-menu w-100" id="{dropdownId}"></div>
 *   </div>
 *
 * Pass `selectedId` (the room already on the record being edited) and the
 * input's starting text is looked up from `rooms` automatically — callers
 * don't need their own controller query joined just to format that label.
 *
 * @param {{inputId: string, hiddenId: string, dropdownId: string, rooms: {id: number, label: string}[], emptyLabel: ?string, selectedId: ?number}} config
 */
function initRoomPicker(config) {
    var input = document.getElementById(config.inputId);
    var hidden = document.getElementById(config.hiddenId);
    var dropdown = document.getElementById(config.dropdownId);

    if (!input || !hidden || !dropdown) {
        return;
    }

    if (config.selectedId) {
        // Room ids coming from PHP/mysqli often arrive as numeric strings
        // once JSON-encoded — compare numerically, not with ===, so
        // "1" (from the rooms list) matches 1 (from (int) casting the
        // record being edited).
        var preselected = (config.rooms || []).filter(function (r) { return Number(r.id) === Number(config.selectedId); })[0];
        if (preselected) {
            input.value = preselected.label;
            hidden.value = preselected.id;
        }
    }

    var rooms = config.rooms || [];
    var maxResults = 50; // plenty to scroll a short list, cheap to render

    function render(list, showEmptyOption) {
        dropdown.innerHTML = '';

        if (config.emptyLabel && showEmptyOption) {
            var emptyItem = document.createElement('button');
            emptyItem.type = 'button';
            emptyItem.className = 'dropdown-item small text-muted';
            emptyItem.textContent = config.emptyLabel;
            emptyItem.addEventListener('click', function () {
                hidden.value = '';
                input.value = '';
                dropdown.classList.remove('show');
            });
            dropdown.appendChild(emptyItem);
        }

        if (list.length === 0) {
            var none = document.createElement('div');
            none.className = 'text-muted small px-3 py-2';
            none.textContent = 'No rooms match.';
            dropdown.appendChild(none);
            return;
        }

        list.slice(0, maxResults).forEach(function (room) {
            var item = document.createElement('button');
            item.type = 'button';
            item.className = 'dropdown-item small';
            item.textContent = room.label;
            item.addEventListener('click', function () {
                hidden.value = room.id;
                input.value = room.label;
                input.classList.remove('is-invalid');
                dropdown.classList.remove('show');
            });
            dropdown.appendChild(item);
        });

        if (list.length > maxResults) {
            var more = document.createElement('div');
            more.className = 'text-muted small px-3 py-2';
            more.textContent = 'Keep typing to narrow down ' + (list.length - maxResults) + ' more…';
            dropdown.appendChild(more);
        }
    }

    function filter(term) {
        term = term.trim().toLowerCase();

        if (term === '') {
            return rooms;
        }

        return rooms.filter(function (room) {
            return room.label.toLowerCase().indexOf(term) !== -1;
        });
    }

    input.addEventListener('input', function () {
        hidden.value = ''; // typing invalidates whatever was picked before
        render(filter(input.value), input.value.trim() === '');
        dropdown.classList.add('show');
    });

    input.addEventListener('focus', function () {
        render(filter(input.value), input.value.trim() === '');
        dropdown.classList.add('show');
    });

    document.addEventListener('click', function (e) {
        if (e.target !== input && !dropdown.contains(e.target)) {
            dropdown.classList.remove('show');
        }
    });

    // Enter selects the top visible match instead of submitting the form.
    input.addEventListener('keydown', function (e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            var first = dropdown.querySelector('.dropdown-item');
            if (first) {
                first.click();
            }
        }
    });
}
