/**
 * Staff order board for waiter and kitchen views.
 */
(function () {
    'use strict';

    var pollTimer = null;
    var knownOrderIds = {};
    var knownPaymentStatus = {};
    var unlockBusy = false;
    var pollInFlight = false;
    var pollPausedUntil = 0;
    var selectedTable = null;

    function usesTableFirstMode() {
        return cfg().view === 'waiter' && !!cfg().tableFirstMode;
    }

    function selectedTableStorageKey() {
        return 'maca_menulist_staff_selected_table_' + (cfg().view || 'waiter');
    }

    function getSelectedTable() {
        if (selectedTable) {
            return selectedTable;
        }
        try {
            var raw = window.sessionStorage.getItem(selectedTableStorageKey());
            if (!raw) {
                return null;
            }
            return JSON.parse(raw);
        } catch (error) {
            return null;
        }
    }

    function setSelectedTable(table) {
        selectedTable = table || null;
        try {
            if (selectedTable) {
                window.sessionStorage.setItem(selectedTableStorageKey(), JSON.stringify(selectedTable));
            } else {
                window.sessionStorage.removeItem(selectedTableStorageKey());
            }
        } catch (error) {
            // Ignore storage errors.
        }
    }

    function tableFilterPayload() {
        var table = getSelectedTable();
        if (!table) {
            return {};
        }
        var payload = {
            service_mode: table.service_mode || 'dine_in',
        };
        if (table.walk_in || table.key === 'table:walk-in') {
            payload.staff_walk_in = '1';
            payload.service_mode = 'dine_in';
            return payload;
        }
        if (table.table_number) {
            payload.table_number = String(table.table_number);
        }
        return payload;
    }

    function cfg() {
        return window.macaMenulistStaffOrders || {};
    }

    function t(key) {
        var config = cfg();
        return config.i18n && config.i18n[key] ? config.i18n[key] : key;
    }

    function orderLocationLabel(order) {
        if (!order) {
            return t('newOrder');
        }
        if (order.service_mode === 'takeaway') {
            var label = t('takeaway');
            if (order.pickup_name) {
                label += ' — ' + order.pickup_name;
            }
            return label;
        }
        if (order.table_number) {
            return t('table') + ' ' + order.table_number;
        }
        return t('newOrder');
    }

    function getActiveTables() {
        var config = cfg();
        return config.activeTables || [];
    }

    function renderTableNumberControl(order, variant) {
        variant = variant || 'waiter';
        var tables = getActiveTables();
        var current = order.table_number ? String(order.table_number) : '';
        var orderId = escapeHtml(String(order.id));
        var labelText = escapeHtml(t('table'));
        var ariaLabel = escapeHtml(t('changeTableNumber'));
        var headingTag = variant === 'kitchen' ? 'h3' : 'h2';
        var headingClass = variant === 'kitchen' ? 'maca-kds-card-table' : 'maca-staff-order-table';
        var wrapClass = variant === 'kitchen'
            ? 'maca-staff-order-table-change maca-staff-order-table-change--kds'
            : 'maca-staff-order-table-change';

        if (!tables.length) {
            var freeHtml = '<div class="' + wrapClass + '">';
            freeHtml += '<' + headingTag + ' class="' + headingClass + ' maca-staff-order-table-change-label">' + labelText + '</' + headingTag + '>';
            freeHtml += '<div class="maca-staff-order-table-change-row">';
            freeHtml += '<input type="text" class="maca-staff-order-table-input" data-order-id="' + orderId + '" value="' + escapeHtml(current) + '" inputmode="numeric" aria-label="' + ariaLabel + '">';
            freeHtml += '<button type="button" class="maca-staff-order-table-save maca-staff-order-action" data-order-id="' + orderId + '">' + escapeHtml(t('changeTableNumber')) + '</button>';
            freeHtml += '</div></div>';
            return freeHtml;
        }

        var html = '<div class="' + wrapClass + '">';
        html += '<label class="maca-staff-order-table-change-label" for="maca-staff-table-' + orderId + '">' + labelText + '</label>';
        html += '<select id="maca-staff-table-' + orderId + '" class="maca-staff-order-table-select" data-order-id="' + orderId + '" data-current="' + escapeHtml(current) + '" aria-label="' + ariaLabel + '">';

        if (current && tables.indexOf(current) === -1) {
            html += '<option value="' + escapeHtml(current) + '" selected>' + escapeHtml(current) + '</option>';
        }

        tables.forEach(function (num) {
            var selected = num === current ? ' selected' : '';
            html += '<option value="' + escapeHtml(num) + '"' + selected + '>' + escapeHtml(num) + '</option>';
        });

        html += '</select></div>';
        return html;
    }

    function renderOrderLocationHeader(order, variant) {
        variant = variant || 'waiter';

        if (order.service_mode === 'takeaway') {
            var html = variant === 'kitchen'
                ? '<h3 class="maca-kds-card-table">' + escapeHtml(orderLocationLabel(order)) + '</h3>'
                : '<h2 class="maca-staff-order-table">' + escapeHtml(orderLocationLabel(order)) + '</h2>';
            return html;
        }

        if (order.can_change_table) {
            return renderTableNumberControl(order, variant);
        }

        if (order.table_number) {
            return variant === 'kitchen'
                ? '<h3 class="maca-kds-card-table">' + escapeHtml(orderLocationLabel(order)) + '</h3>'
                : '<h2 class="maca-staff-order-table">' + escapeHtml(orderLocationLabel(order)) + '</h2>';
        }

        return variant === 'kitchen'
            ? '<h3 class="maca-kds-card-table">' + escapeHtml(t('newOrder')) + '</h3>'
            : '<h2 class="maca-staff-order-table">' + escapeHtml(t('newOrder')) + '</h2>';
    }

    function renderGuestRecoveryButton(order) {
        if (!order.guest_recovery || !order.guest_recovery.url) {
            return '';
        }

        return '<button type="button" class="maca-staff-order-guest-qr maca-staff-order-action maca-staff-order-action--guest-qr" data-recovery-url="' + escapeHtml(order.guest_recovery.url) + '" aria-haspopup="dialog">' + escapeHtml(t('guestRecoveryQr')) + '</button>';
    }

    function openGuestRecoveryModal(url) {
        var modal = document.getElementById('maca-staff-guest-qr-modal');
        if (!modal || !url) {
            return;
        }

        var config = cfg();
        var img = modal.querySelector('.maca-staff-guest-qr-image');
        var apiBase = (config && config.guestQrImageApi)
            ? config.guestQrImageApi
            : 'https://api.qrserver.com/v1/create-qr-code/?size=220x220&data=';

        if (img) {
            img.src = apiBase + encodeURIComponent(url);
            img.alt = t('guestRecoveryTitle');
        }

        modal.hidden = false;
        document.body.classList.add('maca-staff-guest-qr-open');
    }

    function closeGuestRecoveryModal() {
        var modal = document.getElementById('maca-staff-guest-qr-modal');
        if (modal) {
            modal.hidden = true;
        }
        document.body.classList.remove('maca-staff-guest-qr-open');
    }

    function formatTemplate(template, values) {
        if (!template) {
            return '';
        }
        return String(template).replace(/%(\d+)\$d/g, function (_match, index) {
            var value = values[parseInt(index, 10) - 1];
            return typeof value === 'undefined' ? '0' : String(value);
        });
    }

    function buildPinFeedbackText(meta) {
        if (!meta || typeof meta !== 'object') {
            return '';
        }
        if (meta.is_locked && meta.locked_seconds_remaining > 0) {
            var lockedTemplate = t('pinLockedFor');
            var minutes = Math.max(1, Math.ceil(Number(meta.locked_seconds_remaining || 0) / 60));
            return lockedTemplate.indexOf('%d') !== -1
                ? lockedTemplate.replace('%d', String(minutes))
                : lockedTemplate;
        }

        if (typeof meta.attempts_left !== 'undefined' && typeof meta.max_attempts !== 'undefined') {
            return formatTemplate(t('pinAttemptsLeft'), [meta.attempts_left, meta.max_attempts]);
        }

        return '';
    }

    function pinStorageKey() {
        var rev = cfg().pinRevision || '0';
        return 'maca_menulist_staff_pin_' + (cfg().view || 'waiter') + '_' + rev;
    }

    function staffSessionStorageKey() {
        var rev = cfg().pinRevision || '0';
        return 'maca_menulist_staff_session_' + (cfg().view || 'waiter') + '_' + rev;
    }

    function getStaffSession() {
        try {
            return window.sessionStorage.getItem(staffSessionStorageKey()) || '';
        } catch (error) {
            return '';
        }
    }

    function setStaffSession(token) {
        try {
            if (token) {
                window.sessionStorage.setItem(staffSessionStorageKey(), String(token));
            } else {
                window.sessionStorage.removeItem(staffSessionStorageKey());
            }
        } catch (error) {
            // Ignore storage errors.
        }
    }

    function clearStaffSession() {
        setStaffSession('');
    }

    function isPollingPaused() {
        return Date.now() < pollPausedUntil;
    }

    function pausePolling(ms) {
        pollPausedUntil = Date.now() + (ms || 90000);
        if (pollTimer) {
            window.clearInterval(pollTimer);
            pollTimer = null;
        }
    }

    function filterStorageKey() {
        return 'maca_menulist_staff_filter_' + (cfg().view || 'waiter');
    }

    function getStaffFilter() {
        var config = cfg();
        if (!config.staffFilterEnabled) {
            return { scope: 'all', waiterId: 0 };
        }

        try {
            var raw = window.localStorage.getItem(filterStorageKey());
            if (!raw) {
                return { scope: 'all', waiterId: 0 };
            }
            var parsed = JSON.parse(raw);
            if (parsed && parsed.scope === 'waiter' && parsed.waiterId) {
                return { scope: 'waiter', waiterId: parseInt(parsed.waiterId, 10) || 0 };
            }
        } catch (error) {
            return { scope: 'all', waiterId: 0 };
        }

        return { scope: 'all', waiterId: 0 };
    }

    function setStaffFilter(filter) {
        try {
            window.localStorage.setItem(filterStorageKey(), JSON.stringify(filter || { scope: 'all', waiterId: 0 }));
        } catch (error) {
            // Ignore storage errors.
        }
    }

    function appendStaffFilterToFormData(formData) {
        var filter = getStaffFilter();
        formData.append('staff_scope', filter.scope || 'all');
        if (filter.scope === 'waiter' && filter.waiterId) {
            formData.append('staff_waiter_id', String(filter.waiterId));
        }
    }

    function appendStaffFilterToPayload(payload) {
        var filter = getStaffFilter();
        payload.staff_scope = filter.scope || 'all';
        if (filter.scope === 'waiter' && filter.waiterId) {
            payload.staff_waiter_id = String(filter.waiterId);
        }
        return payload;
    }

    function buildStaffRequestPayload(action, pin, extra) {
        var session = getStaffSession();
        var payload = {
            maca_staff_action: action,
            action: action,
        };

        if (session) {
            payload.staff_session = session;
        }
        if (pin) {
            payload.staff_pin = pin;
            payload.pin = pin;
        }

        if (extra && typeof extra === 'object') {
            Object.keys(extra).forEach(function (key) {
                payload[key] = extra[key];
            });
        }

        return appendStaffFilterToPayload(payload);
    }

    function staffAdminAjaxUrl() {
        var config = cfg();
        if (config.adminAjaxUrl && config.adminAjaxUrl !== 'undefined') {
            return config.adminAjaxUrl;
        }
        if (config.ajaxUrl && config.ajaxUrl !== 'undefined') {
            return config.ajaxUrl;
        }
        if (typeof window.ajaxurl === 'string' && window.ajaxurl !== '') {
            return window.ajaxurl;
        }

        var origin = window.location.origin || '';
        if (origin !== '') {
            return origin + '/wp-admin/admin-ajax.php';
        }

        return '/wp-admin/admin-ajax.php';
    }

    function staffPostUrl() {
        var config = cfg();
        if (config.postUrl && config.postUrl !== 'undefined') {
            return config.postUrl;
        }

        if (window.location && window.location.pathname) {
            return window.location.origin + window.location.pathname;
        }

        return '';
    }

    function staffRestUrl() {
        var config = cfg();
        return config.restUrl && config.restUrl !== 'undefined' ? config.restUrl : '';
    }

    function staffPrefersSamePageApi() {
        var config = cfg();
        if (typeof config.preferSamePageApi !== 'undefined') {
            return !!config.preferSamePageApi;
        }

        return !!staffPostUrl();
    }

    function isStaffTransportError(err) {
        return !!(err && (err.network || err.serverError || err.rateLimited));
    }

    function staffTransportErrorMessage(err) {
        if (err && err.rateLimited) {
            return t('rateLimited');
        }
        return t('connectionError');
    }

    function staffUrlStorageKey() {
        return 'maca_menulist_staff_api_url_' + (cfg().view || 'waiter');
    }

    function getRememberedStaffUrl() {
        try {
            return window.sessionStorage.getItem(staffUrlStorageKey()) || '';
        } catch (error) {
            return '';
        }
    }

    function rememberStaffUrl(url) {
        try {
            if (url) {
                window.sessionStorage.setItem(staffUrlStorageKey(), String(url));
            }
        } catch (error) {
            // Ignore storage errors.
        }
    }

    function staffRequestTimeoutMs() {
        if (getSelectedTable()) {
            return 45000;
        }
        return 20000;
    }

    function sendStaffFormRequest(url, payload) {
        if (!url || url === 'undefined' || String(url).indexOf('undefined') !== -1) {
            return Promise.reject({
                network: true,
                data: { message: t('connectionError') },
            });
        }

        var formData = new FormData();
        Object.keys(payload).forEach(function (key) {
            formData.append(key, payload[key]);
        });

        var controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
        var timeoutId = null;

        if (controller) {
            timeoutId = window.setTimeout(function () {
                controller.abort();
            }, staffRequestTimeoutMs());
        }

        return fetch(url, {
            method: 'POST',
            credentials: 'same-origin',
            body: formData,
            signal: controller ? controller.signal : undefined,
        }).then(function (response) {
            return parseStaffFetchResponse(response);
        }).catch(function (err) {
            if (err && err.name === 'AbortError') {
                throw { network: true, timedOut: true };
            }
            throw err;
        }).finally(function () {
            if (timeoutId) {
                window.clearTimeout(timeoutId);
            }
        });
    }

    function staffRequestUrls() {
        var urls = [];
        var seen = {};
        var postUrl = staffPostUrl();
        var restUrl = staffRestUrl();
        var ajaxUrl = staffAdminAjaxUrl();

        function pushUrl(url) {
            if (!url || url === 'undefined' || seen[url]) {
                return;
            }
            seen[url] = true;
            urls.push(url);
        }

        pushUrl(getRememberedStaffUrl());

        if (staffPrefersSamePageApi()) {
            pushUrl(postUrl);
        } else {
            pushUrl(restUrl);
            pushUrl(postUrl);
            pushUrl(ajaxUrl);
        }

        return urls;
    }

    function postStaffRequest(action, pin, extra) {
        var payload = buildStaffRequestPayload(action, pin, extra || {});
        var urls = staffRequestUrls();
        var index = 0;

        function tryNext() {
            if (index >= urls.length) {
                return Promise.reject({ network: true });
            }

            var url = urls[index];
            index += 1;

            return sendStaffFormRequest(url, payload).then(function (result) {
                rememberStaffUrl(url);
                return result;
            }).catch(function (err) {
                if (err && err.rateLimited) {
                    pausePolling(90000);
                    throw err;
                }
                if (isStaffTransportError(err) && index < urls.length) {
                    return tryNext();
                }
                throw err;
            });
        }

        return tryNext();
    }

    function verifyStaffPin(pin) {
        var config = cfg();
        return postStaffRequest('maca_verify_staff_pin', pin, {
            view: config.view || 'waiter',
        });
    }

    function getWaiterNameById(waiterId) {
        var config = cfg();
        if (!config.waiters || !waiterId) {
            return '';
        }

        for (var i = 0; i < config.waiters.length; i++) {
            if (config.waiters[i].id === waiterId) {
                return config.waiters[i].name || '';
            }
        }

        return '';
    }

    function updateStaffHeaderTitle() {
        var heading = document.getElementById('maca-staff-orders-heading');
        if (!heading) {
            return;
        }

        var filter = getStaffFilter();
        var waiterName = filter.scope === 'waiter' ? getWaiterNameById(filter.waiterId) : '';

        if (waiterName) {
            heading.textContent = waiterName;
            heading.classList.add('maca-staff-orders-heading--waiter');
        } else {
            heading.textContent = t('waiterTitle');
            heading.classList.remove('maca-staff-orders-heading--waiter');
        }
    }

    function setupWaiterFilterUI() {
        var config = cfg();
        var wrap = document.getElementById('maca-staff-waiter-filter');
        var select = document.getElementById('maca-staff-waiter-filter-select');

        if (!wrap || !select || !config.staffFilterEnabled || !config.waiters || !config.waiters.length) {
            if (wrap) {
                wrap.hidden = true;
            }
            updateStaffHeaderTitle();
            return;
        }

        var current = getStaffFilter();
        var html = '<option value="all">' + escapeHtml(t('allTables')) + '</option>';

        config.waiters.forEach(function (waiter) {
            var value = 'waiter:' + String(waiter.id);
            var selected = current.scope === 'waiter' && current.waiterId === waiter.id ? ' selected' : '';
            html += '<option value="' + escapeHtml(value) + '"' + selected + '>' + escapeHtml(waiter.name) + '</option>';
        });

        select.innerHTML = html;
        wrap.hidden = false;
        updateStaffHeaderTitle();

        if (!select.dataset.macaBound) {
            select.dataset.macaBound = '1';
            select.addEventListener('change', function () {
                var value = select.value || 'all';
                if (value.indexOf('waiter:') === 0) {
                    setStaffFilter({
                        scope: 'waiter',
                        waiterId: parseInt(value.replace('waiter:', ''), 10) || 0,
                    });
                } else {
                    setStaffFilter({ scope: 'all', waiterId: 0 });
                }

                updateStaffHeaderTitle();

                knownOrderIds = {};
                knownPaymentStatus = {};
                var pin = getPin();
                if (pin) {
                    if (usesTableFirstMode()) {
                        showTableBoardView();
                    }
                    pollOrders(pin);
                }
            });
        }
    }

    function getPin() {
        try {
            return window.sessionStorage.getItem(pinStorageKey()) || '';
        } catch (error) {
            return '';
        }
    }

    function setPin(pin) {
        try {
            window.sessionStorage.setItem(pinStorageKey(), pin);
        } catch (error) {
            // Ignore storage errors.
        }
    }

    function clearPin() {
        try {
            window.sessionStorage.removeItem(pinStorageKey());
        } catch (error) {
            // Ignore storage errors.
        }
        clearStaffSession();
    }

    function parseStaffFetchResponse(response) {
        return response.text().then(function (body) {
            var payload = null;
            var trimmed = body ? String(body).trim() : '';

            if (trimmed === '0' || trimmed === '-1') {
                throw {
                    serverError: true,
                    data: {
                        message: t('connectionError'),
                    },
                };
            }

            if (trimmed !== '') {
                try {
                    payload = JSON.parse(trimmed);
                } catch (error) {
                    payload = null;
                }
            }

            if (payload === null || typeof payload !== 'object') {
                if (response.status === 429 || response.status === 503 || response.status === 502) {
                    throw { rateLimited: true };
                }
                if (!response.ok) {
                    throw { network: true, status: response.status };
                }
                throw {
                    serverError: true,
                    data: {
                        message: t('connectionError'),
                    },
                };
            }

            return payload;
        });
    }

    function escapeHtml(text) {
        var div = document.createElement('div');
        div.textContent = text == null ? '' : String(text);
        return div.innerHTML;
    }

    function isKitchenKds() {
        return cfg().view === 'kitchen';
    }

    function parseOrderCreatedAt(order) {
        if (!order || !order.created_at) {
            return null;
        }
        var raw = String(order.created_at).trim();
        var parsed = new Date(raw.replace(' ', 'T'));
        if (Number.isNaN(parsed.getTime())) {
            parsed = new Date(raw);
        }
        return Number.isNaN(parsed.getTime()) ? null : parsed;
    }

    function orderElapsedMinutes(order) {
        var created = parseOrderCreatedAt(order);
        if (!created) {
            return 0;
        }
        return Math.max(0, Math.floor((Date.now() - created.getTime()) / 60000));
    }

    function formatMinutesLabel(minutes) {
        var template = t('kdsMinutes');
        if (template.indexOf('%d') !== -1) {
            return template.replace('%d', String(minutes));
        }
        return minutes + ' min';
    }

    function parseStatusUpdatedAt(raw) {
        if (!raw) {
            return null;
        }
        var value = String(raw).trim();
        var parsed = new Date(value.replace(' ', 'T'));
        if (Number.isNaN(parsed.getTime())) {
            parsed = new Date(value);
        }
        return Number.isNaN(parsed.getTime()) ? null : parsed;
    }

    function getKitchenEtaDeadlineMs(etaMinutes, statusUpdatedAt) {
        var eta = parseInt(String(etaMinutes), 10);
        if (Number.isNaN(eta) || eta <= 0) {
            return null;
        }
        var updated = parseStatusUpdatedAt(statusUpdatedAt);
        if (!updated) {
            return null;
        }
        return updated.getTime() + eta * 60000;
    }

    function formatKitchenOverdueLabel(overdueSeconds) {
        var minutes = Math.floor(overdueSeconds / 60);
        var seconds = overdueSeconds % 60;
        return '-' + minutes + ':' + String(seconds).padStart(2, '0');
    }

    function isKitchenOrderOverdue(order) {
        if (!order || order.status !== 'preparing' || !(order.eta_minutes > 0)) {
            return false;
        }
        var deadlineMs = getKitchenEtaDeadlineMs(order.eta_minutes, order.status_updated_at);
        return deadlineMs !== null && Date.now() >= deadlineMs;
    }

    function getKitchenOverdueSeconds(etaMinutes, statusUpdatedAt) {
        var deadlineMs = getKitchenEtaDeadlineMs(etaMinutes, statusUpdatedAt);
        if (deadlineMs === null || Date.now() < deadlineMs) {
            return 0;
        }
        return Math.floor((Date.now() - deadlineMs) / 1000);
    }

    function updateKitchenOverdueState() {
        if (!isKitchenKds()) {
            return;
        }

        document.querySelectorAll('.maca-kds-card[data-eta-minutes][data-status-updated-at]').forEach(function (card) {
            var overdueSeconds = getKitchenOverdueSeconds(
                card.getAttribute('data-eta-minutes'),
                card.getAttribute('data-status-updated-at')
            );
            var isOverdue = overdueSeconds > 0;
            card.classList.toggle('maca-kds-card--overdue', isOverdue);

            var timerEl = card.querySelector('.maca-kds-card-timer');
            var overdueEl = card.querySelector('.maca-kds-card-overdue');
            if (isOverdue) {
                if (!overdueEl && timerEl) {
                    overdueEl = document.createElement('span');
                    overdueEl.className = 'maca-kds-card-overdue';
                    overdueEl.setAttribute('aria-live', 'polite');
                    timerEl.insertAdjacentElement('afterend', overdueEl);
                }
                if (overdueEl) {
                    overdueEl.textContent = formatKitchenOverdueLabel(overdueSeconds);
                }
            } else if (overdueEl) {
                overdueEl.remove();
            }

            var readyButton = card.querySelector('.maca-kds-card-action[data-status="ready"]');
            if (readyButton) {
                readyButton.classList.toggle('maca-kds-card-action--overdue', isOverdue);
            }
        });
    }

    function kitchenColumnForStatus(status) {
        if (status === 'new') {
            return 'new';
        }
        if (status === 'accepted' || status === 'preparing') {
            return 'progress';
        }
        if (status === 'ready') {
            return 'ready';
        }
        return null;
    }

    function updateKitchenClock() {
        var clock = document.getElementById('maca-kds-clock');
        if (!clock) {
            return;
        }
        var now = new Date();
        var hours = String(now.getHours()).padStart(2, '0');
        var minutes = String(now.getMinutes()).padStart(2, '0');
        clock.textContent = hours + ':' + minutes;
    }

    function updateKitchenStats(orders, stats) {
        updateKitchenClock();

        var avgEl = document.getElementById('maca-kds-avg-time');
        if (avgEl && orders.length) {
            var totalMinutes = 0;
            orders.forEach(function (order) {
                totalMinutes += orderElapsedMinutes(order);
            });
            var avg = Math.round(totalMinutes / orders.length);
            avgEl.textContent = formatMinutesLabel(avg);
        } else if (avgEl) {
            avgEl.textContent = '—';
        }

        var todayEl = document.getElementById('maca-kds-orders-today');
        if (todayEl && stats && typeof stats.orders_today !== 'undefined') {
            todayEl.textContent = String(stats.orders_today);
        }
    }

    function renderKitchenCard(order) {
        var column = kitchenColumnForStatus(order.status);
        if (!column) {
            return '';
        }

        var elapsed = orderElapsedMinutes(order);
        var isOverdue = isKitchenOrderOverdue(order);
        var cardClass = 'maca-kds-card maca-kds-card--' + column;
        if (isOverdue) {
            cardClass += ' maca-kds-card--overdue';
        }
        var html = '<article class="' + cardClass + '" data-order-id="' + escapeHtml(String(order.id)) + '"';
        if (order.status === 'preparing' && order.eta_minutes > 0 && order.status_updated_at) {
            html += ' data-eta-minutes="' + escapeHtml(String(order.eta_minutes)) + '"';
            html += ' data-status-updated-at="' + escapeHtml(String(order.status_updated_at)) + '"';
        }
        html += '>';

        html += renderOrderLocationHeader(order, 'kitchen');
        if (order.service_mode === 'takeaway' && order.pickup_phone) {
            html += '<p class="maca-kds-card-pickup-phone">' + escapeHtml(order.pickup_phone) + '</p>';
        }

        html += '<ul class="maca-kds-card-lines">';
        order.lines.forEach(function (line) {
            html += '<li>' + escapeHtml(String(line.qty)) + '× ' + escapeHtml(line.title) + '</li>';
            if (line.note) {
                html += '<li class="maca-kds-card-line-note">' + escapeHtml(line.note) + '</li>';
            }
        });
        html += '</ul>';

        if (order.order_note) {
            html += '<p class="maca-kds-card-order-note"><strong>' + escapeHtml(t('orderNote')) + ':</strong> ' + escapeHtml(order.order_note) + '</p>';
        }

        var actions = order.kitchen_actions || [];
        var timerText = formatMinutesLabel(elapsed);
        if (order.status === 'preparing' && order.eta_minutes > 0) {
            timerText = formatMinutesLabel(order.eta_minutes);
        } else if (order.status === 'ready' && order.eta_minutes > 0) {
            timerText = formatMinutesLabel(order.eta_minutes);
        }

        html += '<div class="maca-kds-card-footer">';
        html += '<span class="maca-kds-card-timer-wrap">';
        html += '<span class="maca-kds-card-timer">' + escapeHtml(timerText) + '</span>';
        if (isOverdue) {
            html += '<span class="maca-kds-card-overdue" aria-live="polite">' + escapeHtml(formatKitchenOverdueLabel(getKitchenOverdueSeconds(order.eta_minutes, order.status_updated_at))) + '</span>';
        }
        html += '</span>';
        if (order.payment) {
            if (order.payment.payment_summary_label) {
                var kdsPayClass = 'maca-kds-card-paid';
                if (!order.payment.payment_is_complete) {
                    kdsPayClass += ' maca-kds-card-paid--partial';
                }
                html += '<span class="' + kdsPayClass + '">' + escapeHtml(order.payment.payment_summary_label) + '</span>';
            } else if (order.payment.payment_is_complete) {
                html += '<span class="maca-kds-card-paid">' + escapeHtml(t('kdsPaid')) + '</span>';
            }
        }
        html += '</div>';

        if (actions.length) {
            actions.forEach(function (action) {
                var actionClass = 'maca-kds-card-action maca-staff-order-action';
                if (isOverdue && action.status === 'ready') {
                    actionClass += ' maca-kds-card-action--overdue';
                }
                html += '<button type="button" class="' + actionClass + '" data-order-id="' + escapeHtml(String(order.id)) + '" data-status="' + escapeHtml(action.status) + '"';
                if (action.needs_eta) {
                    html += ' data-needs-eta="1"';
                }
                if (action.update_eta_only) {
                    html += ' data-update-eta-only="1"';
                }
                html += '>' + escapeHtml(action.label) + '</button>';
            });
        } else if (column === 'ready') {
            html += '<span class="maca-kds-card-ready-icon" aria-hidden="true">✓</span>';
        }

        html += renderGuestRecoveryButton(order);

        html += '</article>';
        return html;
    }

    function renderKitchenOrders(orders, stats) {
        var empty = document.getElementById('maca-staff-orders-empty');
        var columns = {
            new: '',
            progress: '',
            ready: '',
        };
        var counts = { new: 0, progress: 0, ready: 0 };

        orders.forEach(function (order) {
            var column = kitchenColumnForStatus(order.status);
            if (!column) {
                return;
            }
            counts[column] += 1;
            columns[column] += renderKitchenCard(order);
        });

        Object.keys(columns).forEach(function (key) {
            var body = document.querySelector('[data-column-body="' + key + '"]');
            if (body) {
                body.innerHTML = columns[key];
            }
            var countEl = document.querySelector('[data-count-for="' + key + '"]');
            if (countEl) {
                countEl.textContent = String(counts[key]);
            }
        });

        if (empty) {
            empty.hidden = orders.length > 0;
        }

        updateKitchenStats(orders, stats);
        updateKitchenOverdueState();
    }

    function renderOrders(orders, stats) {
        if (isKitchenKds()) {
            renderKitchenOrders(orders, stats);
            return;
        }
        var list = document.getElementById('maca-staff-orders-list');
        var empty = document.getElementById('maca-staff-orders-empty');
        var status = document.getElementById('maca-staff-orders-status');
        var config = cfg();

        if (!list || !empty) {
            return;
        }

        if (!orders.length) {
            list.innerHTML = '';
            empty.hidden = false;
            if (getSelectedTable()) {
                setTableDetailStatus('');
            }
            if (status) {
                status.textContent = '';
            }
            return;
        }

        empty.hidden = true;
        if (getSelectedTable()) {
            setTableDetailStatus('');
        }
        if (status) {
            status.textContent = orders.length + ' ' + (orders.length === 1 ? t('newOrder') : t('newOrder') + 's');
        }

        var html = '';
        orders.forEach(function (order) {
            var cardClass = 'maca-staff-order-card';
            var paymentComplete = order.payment && order.payment.payment_is_complete;
            if (paymentComplete) {
                cardClass += ' maca-staff-order-card--payment-paid';
            } else if (order.payment && order.payment.payment_summary_label) {
                cardClass += ' maca-staff-order-card--payment-partial';
            }
            if (order.status === 'paid') {
                cardClass += ' maca-staff-order-card--paid';
            } else if (order.status === 'served') {
                cardClass += ' maca-staff-order-card--served';
            } else if (order.status === 'ready') {
                cardClass += ' maca-staff-order-card--ready';
            }

            html += '<article class="' + cardClass + '" data-order-id="' + escapeHtml(String(order.id)) + '">';
            html += '<div class="maca-staff-order-card-header">';
            html += '<div>';
            html += renderOrderLocationHeader(order, 'waiter');
            if (order.service_mode === 'takeaway' && order.pickup_phone) {
                html += '<p class="maca-staff-order-pickup-phone">' + escapeHtml(order.pickup_phone) + '</p>';
            }
            if (order.time_label) {
                html += '<p class="maca-staff-order-time">' + escapeHtml(order.time_label) + '</p>';
            }
            if (order.status_label) {
                html += '<span class="maca-staff-order-status-badge">' + escapeHtml(order.status_label) + '</span>';
            }
            if (order.payment && order.payment.payment_summary_label) {
                var summaryClass = 'maca-staff-order-payment-summary';
                if (!paymentComplete) {
                    summaryClass += ' maca-staff-order-payment-summary--partial';
                }
                html += '<p class="' + summaryClass + '">' + escapeHtml(order.payment.payment_summary_label) + '</p>';
            } else if (order.payment && order.payment.badge) {
                var payClass = 'maca-staff-order-payment-badge';
                if (order.payment.payment_method === 'manual' && !paymentComplete) {
                    payClass += ' maca-staff-order-payment-badge--manual';
                } else if (paymentComplete) {
                    payClass += ' maca-staff-order-payment-badge--paid';
                } else if (order.payment.payment_status === 'pending') {
                    payClass += ' maca-staff-order-payment-badge--pending';
                } else {
                    payClass += ' maca-staff-order-payment-badge--partial';
                }
                html += '<span class="' + payClass + '">' + escapeHtml(order.payment.badge) + '</span>';
            }
            if (order.payment && order.payment.show_receipt) {
                html += '<div class="maca-staff-order-payment-receipt">';
                if (order.payment.subtotal_label) {
                    html += '<p><strong>' + escapeHtml(t('subtotal')) + ':</strong> ' + escapeHtml(order.payment.subtotal_label) + '</p>';
                }
                if (order.payment.tip_label) {
                    html += '<p><strong>' + escapeHtml(t('tip')) + ':</strong> ' + escapeHtml(order.payment.tip_label) + '</p>';
                }
                if (!order.payment.payment_summary_label && order.payment.amount_paid_label) {
                    html += '<p><strong>' + escapeHtml(t('amountPaid')) + ':</strong> ' + escapeHtml(order.payment.amount_paid_label) + '</p>';
                }
                if (order.payment.amount_remaining_label) {
                    html += '<p><strong>' + escapeHtml(t('amountRemaining')) + ':</strong> ' + escapeHtml(order.payment.amount_remaining_label) + '</p>';
                }
                if (!order.payment.payment_summary_label && !order.payment.amount_paid_label && order.payment.total_label) {
                    html += '<p><strong>' + escapeHtml(t('total')) + ':</strong> ' + escapeHtml(order.payment.total_label) + '</p>';
                }
                if (order.payment.paid_at_label) {
                    html += '<p><strong>' + escapeHtml(t('paidAt')) + ':</strong> ' + escapeHtml(order.payment.paid_at_label) + '</p>';
                }
                if (order.payment.method_label) {
                    html += '<p><strong>' + escapeHtml(t('howPaid')) + ':</strong> ' + escapeHtml(order.payment.method_label);
                    if (order.payment.provider_label && order.payment.provider_label !== '—') {
                        html += ' · ' + escapeHtml(order.payment.provider_label);
                    }
                    html += '</p>';
                }
                if (order.payment.payment_transactions && order.payment.payment_transactions.length) {
                    html += '<div class="maca-staff-order-payment-transactions">';
                    if (order.payment.payment_transactions_label) {
                        html += '<p><strong>' + escapeHtml(t('paymentTransactions')) + ':</strong> ' + escapeHtml(order.payment.payment_transactions_label) + '</p>';
                    }
                    html += '<ul class="maca-staff-order-payment-transactions-list">';
                    order.payment.payment_transactions.forEach(function (tx) {
                        html += '<li>';
                        html += '<strong>' + escapeHtml(t('paymentNumber').replace('%d', String(tx.number))) + '</strong> ';
                        html += escapeHtml(tx.amount_label);
                        if (tx.kind_label) {
                            html += ' <span class="description">(' + escapeHtml(tx.kind_label) + ')</span>';
                        }
                        if (tx.paid_at_label) {
                            html += '<br><span class="description">' + escapeHtml(tx.paid_at_label) + '</span>';
                        }
                        if (tx.external_id) {
                            html += '<br><code>' + escapeHtml(tx.external_id) + '</code>';
                        }
                        html += '</li>';
                    });
                    html += '</ul></div>';
                } else if (order.payment.payment_id) {
                    html += '<p class="maca-staff-order-payment-id"><strong>' + escapeHtml(t('paymentId')) + ':</strong> <code>' + escapeHtml(order.payment.payment_id) + '</code></p>';
                }
                html += '</div>';
            } else if (order.payment && order.payment.total_label) {
                html += '<p class="maca-staff-order-payment-total">' + escapeHtml(order.payment.total_label) + '</p>';
            }
            html += '</div>';
            html += '<div class="maca-staff-order-actions">';

            var actions = [];
            if (config.view === 'kitchen' && order.kitchen_actions) {
                actions = order.kitchen_actions;
            } else if (config.view === 'waiter' && order.waiter_actions) {
                actions = order.waiter_actions;
            }

            if (actions.length) {
                actions.forEach(function (action) {
                    html += '<button type="button" class="maca-staff-order-action" data-order-id="' + escapeHtml(String(order.id)) + '" data-status="' + escapeHtml(action.status) + '"';
                    if (action.needs_eta) {
                        html += ' data-needs-eta="1"';
                    }
                    if (action.update_eta_only) {
                        html += ' data-update-eta-only="1"';
                    }
                    html += '>' + escapeHtml(action.label) + '</button>';
                });
            }

            html += renderGuestRecoveryButton(order);

            html += '</div>';
            html += '</div>';
            html += '<ul class="maca-staff-order-lines">';

            if (config.showPrices) {
                html += '<li class="maca-staff-order-line maca-staff-order-line--header" aria-hidden="true">';
                html += '<span class="maca-staff-order-qty"></span>';
                html += '<span class="maca-staff-order-title"></span>';
                html += '<span class="maca-staff-order-prices">';
                html += '<span class="maca-staff-order-unit-price">' + escapeHtml(t('unitPrice')) + '</span>';
                html += '<span class="maca-staff-order-line-total">' + escapeHtml(t('lineTotal')) + '</span>';
                html += '</span>';
                html += '</li>';
            }

            (order.lines || []).forEach(function (line) {
                html += '<li class="maca-staff-order-line">';
                html += '<span class="maca-staff-order-qty">' + escapeHtml(String(line.qty)) + '×</span>';
                html += '<span class="maca-staff-order-title">' + escapeHtml(line.title) + '</span>';
                if (config.showPrices) {
                    html += '<span class="maca-staff-order-prices">';
                    html += '<span class="maca-staff-order-unit-price">';
                    html += line.unit_price_label ? escapeHtml(line.unit_price_label) : '—';
                    html += '</span>';
                    html += '<span class="maca-staff-order-line-total">';
                    html += line.line_total_label ? escapeHtml(line.line_total_label) : '—';
                    html += '</span>';
                    html += '</span>';
                }
                html += '</li>';
                if (line.note) {
                    html += '<li class="maca-staff-order-line-note">' + escapeHtml(line.note) + '</li>';
                }
            });

            html += '</ul>';

            if (order.order_note) {
                html += '<p class="maca-staff-order-note"><strong>' + escapeHtml(t('orderNote')) + ':</strong> ' + escapeHtml(order.order_note) + '</p>';
            }

            if (config.showPrices && order.total_label) {
                html += '<p class="maca-staff-order-total"><strong>' + escapeHtml(t('total')) + ':</strong> ' + escapeHtml(order.total_label) + '</p>';
            }

            html += '</article>';
        });

        list.innerHTML = html;
    }

    function playStaffAlert() {
        if (typeof window.Audio === 'undefined') {
            return;
        }
        try {
            var audio = new Audio('data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAESsAACJWAAACABAAZGF0YQAAAAA=');
            audio.play().catch(function () {});
        } catch (error) {
            // Ignore audio errors.
        }
    }

    function notifyNewOrders(orders) {
        var hasNew = false;
        var hasNewPayment = false;
        var config = cfg();

        orders.forEach(function (order) {
            if (!knownOrderIds[order.id]) {
                if (!order.status || order.status === 'new') {
                    hasNew = true;
                }
            }
            knownOrderIds[order.id] = true;

            if (config.paymentAlerts && order.payment) {
                var wasComplete = knownPaymentStatus[order.id] === 'complete';
                if (order.payment.payment_is_complete && !wasComplete) {
                    hasNewPayment = true;
                }
                knownPaymentStatus[order.id] = order.payment.payment_is_complete ? 'complete' : (order.payment.payment_status || '');
            }
        });

        if (hasNew || hasNewPayment) {
            playStaffAlert();
        }
    }

    function fetchOrders(pin) {
        var config = cfg();
        var extra = {
            view: config.view || 'waiter',
        };
        if (usesTableFirstMode()) {
            Object.assign(extra, tableFilterPayload());
        }
        return postStaffRequest('maca_get_staff_orders', pin, extra);
    }

    function fetchTableSummary(pin) {
        var config = cfg();
        return postStaffRequest('maca_get_staff_table_summary', pin, {
            view: config.view || 'waiter',
        });
    }

    function renderTableGrid(tables) {
        var grid = document.getElementById('maca-staff-table-grid');
        var empty = document.getElementById('maca-staff-table-empty');
        if (!grid) {
            return;
        }

        if (!tables || !tables.length) {
            grid.innerHTML = '';
            if (empty) {
                empty.hidden = false;
            }
            return;
        }

        if (empty) {
            empty.hidden = true;
        }

        var html = '';
        tables.forEach(function (entry) {
            var tileClass = 'maca-staff-table-tile';
            if (entry.has_ready) {
                tileClass += ' maca-staff-table-tile--ready';
            } else if (entry.has_new) {
                tileClass += ' maca-staff-table-tile--new';
            }
            html += '<button type="button" class="' + tileClass + '" role="listitem"';
            html += ' data-table-key="' + escapeHtml(entry.key || '') + '"';
            html += ' data-table-number="' + escapeHtml(entry.table_number || '') + '"';
            html += ' data-service-mode="' + escapeHtml(entry.service_mode || 'dine_in') + '"';
            html += ' data-walk-in="' + (entry.walk_in ? '1' : '0') + '"';
            html += ' data-table-label="' + escapeHtml(entry.label || '') + '">';
            html += '<span class="maca-staff-table-tile-label">' + escapeHtml(entry.label || '') + '</span>';
            html += '<span class="maca-staff-table-tile-count">' + escapeHtml(String(entry.order_count || 0)) + ' ' + escapeHtml(t('tableOrders')) + '</span>';
            if (entry.has_ready) {
                html += '<span class="maca-staff-table-tile-badge">' + escapeHtml(t('tableReady')) + '</span>';
            }
            html += '</button>';
        });
        grid.innerHTML = html;
    }

    function setTableDetailStatus(message) {
        var detailStatus = document.getElementById('maca-staff-table-detail-status');
        if (!detailStatus) {
            return;
        }
        detailStatus.textContent = message || '';
        detailStatus.hidden = !message;
    }

    function showTableBoardView() {
        var board = document.getElementById('maca-staff-table-board');
        var detail = document.getElementById('maca-staff-table-detail');
        if (board) {
            board.hidden = false;
        }
        if (detail) {
            detail.hidden = true;
        }
        setTableDetailStatus('');
        setSelectedTable(null);
        knownOrderIds = {};
        knownPaymentStatus = {};
    }

    function showTableDetailView(table) {
        var board = document.getElementById('maca-staff-table-board');
        var detail = document.getElementById('maca-staff-table-detail');
        var title = document.getElementById('maca-staff-table-detail-title');
        var list = document.getElementById('maca-staff-orders-list');
        var empty = document.getElementById('maca-staff-orders-empty');
        if (board) {
            board.hidden = true;
        }
        if (detail) {
            detail.hidden = false;
        }
        if (title && table) {
            title.textContent = table.label || '';
        }
        if (list) {
            list.innerHTML = '';
        }
        if (empty) {
            empty.hidden = true;
        }
        setTableDetailStatus(t('loadingOrders'));
        setSelectedTable(table);
        knownOrderIds = {};
        knownPaymentStatus = {};
    }

    function pollTableSummary(pin) {
        if (pollInFlight || getSelectedTable()) {
            return;
        }
        pollInFlight = true;
        fetchTableSummary(pin)
            .then(function (payload) {
                if (!payload || !payload.success) {
                    throw payload;
                }
                var tables = payload.data && payload.data.tables ? payload.data.tables : [];
                renderTableGrid(tables);
            })
            .catch(function (err) {
                var status = document.getElementById('maca-staff-orders-status');
                if (status && isStaffTransportError(err)) {
                    status.textContent = staffTransportErrorMessage(err);
                }
            })
            .finally(function () {
                pollInFlight = false;
            });
    }

    function pollOrders(pin) {
        if (pollInFlight || isPollingPaused()) {
            return;
        }
        if (usesTableFirstMode() && !getSelectedTable()) {
            pollTableSummary(pin);
            return;
        }

        pollInFlight = true;
        fetchOrders(pin)
            .then(function (payload) {
                if (!payload || !payload.success) {
                    throw payload || { data: { message: t('invalidPin') } };
                }
                var orders = payload.data && payload.data.orders ? payload.data.orders : [];
                var stats = payload.data && payload.data.stats ? payload.data.stats : null;
                notifyNewOrders(orders);
                renderOrders(orders, stats);
            })
            .catch(function (err) {
                var status = document.getElementById('maca-staff-orders-status');
                var message;
                if (isStaffTransportError(err)) {
                    if (err && err.rateLimited) {
                        pausePolling(90000);
                    }
                    message = staffTransportErrorMessage(err);
                } else if (err && err.data && err.data.message) {
                    message = err.data.message;
                } else {
                    message = t('invalidPin');
                }
                if (status) {
                    status.textContent = message;
                }
                if (getSelectedTable()) {
                    setTableDetailStatus(message);
                }
            })
            .finally(function () {
                pollInFlight = false;
            });
    }

    function currentPollInterval() {
        if (usesTableFirstMode() && getSelectedTable()) {
            return cfg().tableDetailPollInterval || 45000;
        }
        if (usesTableFirstMode() && !getSelectedTable()) {
            return cfg().tableSummaryPollInterval || 30000;
        }
        return cfg().pollInterval || 30000;
    }

    function restartPolling(pin) {
        if (pollTimer) {
            window.clearInterval(pollTimer);
            pollTimer = null;
        }

        function schedulePoll() {
            if (pollTimer) {
                window.clearInterval(pollTimer);
            }
            if (document.hidden) {
                return;
            }
            pollOrders(pin);
            pollTimer = window.setInterval(function () {
                if (!document.hidden) {
                    pollOrders(pin);
                }
            }, currentPollInterval());
        }

        schedulePoll();

        if (!document.macaStaffPollVisibilityBound) {
            document.macaStaffPollVisibilityBound = true;
            document.addEventListener('visibilitychange', function () {
                if (!document.hidden && getPin()) {
                    schedulePoll();
                } else if (pollTimer) {
                    window.clearInterval(pollTimer);
                    pollTimer = null;
                }
            });
        }
    }

    function startPolling(pin) {
        restartPolling(pin);
    }

    function showBoard() {
        var pinScreen = document.getElementById('maca-staff-orders-pin');
        var board = document.getElementById('maca-staff-orders-board');
        if (pinScreen) {
            pinScreen.hidden = true;
        }
        if (board) {
            board.hidden = false;
        }
        setupWaiterFilterUI();
        if (usesTableFirstMode()) {
            showTableBoardView();
        }
    }

    function unlockWithPin(pin) {
        if (unlockBusy || cfg().pinLocked) {
            return;
        }

        var error = document.getElementById('maca-staff-orders-pin-error');
        var pinInfo = document.getElementById('maca-staff-orders-pin-info');
        var unlockButton = document.getElementById('maca-staff-orders-unlock');

        unlockBusy = true;
        if (unlockButton) {
            unlockButton.disabled = true;
        }
        if (error) {
            error.hidden = true;
        }

        verifyStaffPin(pin)
            .then(function (payload) {
                if (!payload || !payload.success) {
                    throw payload;
                }
                setPin(pin);
                if (payload.data && payload.data.staff_session) {
                    setStaffSession(payload.data.staff_session);
                }
                showBoard();
                if (error) {
                    error.hidden = true;
                }
                if (pinInfo) {
                    var okInfo = buildPinFeedbackText(payload.data || {});
                    if (okInfo) {
                        pinInfo.textContent = okInfo;
                    }
                }
                return usesTableFirstMode() ? fetchTableSummary(pin) : fetchOrders(pin);
            })
            .then(function (payload) {
                if (!payload) {
                    return;
                }
                if (!payload.success) {
                    throw payload || { data: { message: t('connectionError') } };
                }
                if (usesTableFirstMode() && !getSelectedTable()) {
                    var tables = payload.data && payload.data.tables ? payload.data.tables : [];
                    renderTableGrid(tables);
                    startPolling(pin);
                    return;
                }
                var orders = payload.data && payload.data.orders ? payload.data.orders : [];
                var stats = payload.data && payload.data.stats ? payload.data.stats : null;
                notifyNewOrders(orders);
                renderOrders(orders, stats);
                startPolling(pin);
            })
            .catch(function (err) {
                var pinWasVerified = getPin() === pin;

                if (pinWasVerified && isStaffTransportError(err)) {
                    var status = document.getElementById('maca-staff-orders-status');
                    if (status) {
                        status.textContent = staffTransportErrorMessage(err);
                    }
                    return;
                }

                if (error) {
                    var message;
                    if (isStaffTransportError(err)) {
                        message = staffTransportErrorMessage(err);
                    } else if (err && err.data && err.data.missing_pin) {
                        message = err.data.message || t('connectionError');
                    } else {
                        message = (err && err.data && err.data.message) ? err.data.message : t('invalidPin');
                    }
                    var feedbackText = buildPinFeedbackText(err && err.data ? err.data : null);
                    error.textContent = feedbackText ? message + ' ' + feedbackText : message;
                    error.hidden = false;
                }
                if (pinInfo) {
                    var infoText = buildPinFeedbackText(err && err.data ? err.data : null);
                    if (infoText) {
                        pinInfo.textContent = infoText;
                    }
                }
                clearPin();
            })
            .finally(function () {
                unlockBusy = false;
                if (unlockButton && !cfg().pinLocked) {
                    unlockButton.disabled = false;
                }
            });
    }

    function updateOrderTableNumber(orderId, tableNumber, pin) {
        var config = cfg();
        return postStaffRequest('maca_update_staff_order_table', pin, {
            order_id: String(orderId),
            table_number: tableNumber,
            view: config.view || 'waiter',
        })
            .then(function (payload) {
                if (!payload || !payload.success) {
                    var message = (payload && payload.data && payload.data.message)
                        ? payload.data.message
                        : t('tableNumberUpdateError');
                    throw new Error(message);
                }
                delete knownOrderIds[orderId];
                pollOrders(pin);
                return payload;
            });
    }

    function updateOrderStatus(orderId, status, pin, etaMinutes) {
        var config = cfg();
        var extra = {
            order_id: String(orderId),
            status: status,
            view: config.view || 'waiter',
        };
        if (etaMinutes !== null && etaMinutes !== undefined) {
            extra.eta_minutes = String(etaMinutes);
        }

        postStaffRequest('maca_update_staff_order_status', pin, extra)
            .then(function (payload) {
                if (!payload || !payload.success) {
                    var message = (payload && payload.data && payload.data.message)
                        ? payload.data.message
                        : t('orderUpdateError');
                    throw new Error(message);
                }
                delete knownOrderIds[orderId];
                pollOrders(pin);
            })
            .catch(function (error) {
                window.alert(error && error.message ? error.message : t('orderUpdateError'));
            });
    }

    function initStaffOrders() {
        var app = document.getElementById('maca-staff-orders-app');
        if (!app) {
            return;
        }

        var unlockButton = document.getElementById('maca-staff-orders-unlock');
        var pinInput = document.getElementById('maca-staff-orders-pin-input');
        var storedPin = getPin();

        if (unlockButton && pinInput) {
            if (cfg().pinLocked) {
                unlockButton.disabled = true;
            }

            unlockButton.addEventListener('click', function () {
                if (unlockButton.disabled) {
                    return;
                }
                unlockWithPin(pinInput.value.trim());
            });

            pinInput.addEventListener('keydown', function (event) {
                if (event.key === 'Enter') {
                    if (unlockButton.disabled) {
                        return;
                    }
                    unlockWithPin(pinInput.value.trim());
                }
            });
        }

        if (isKitchenKds()) {
            updateKitchenClock();
            window.setInterval(updateKitchenClock, 30000);
            updateKitchenOverdueState();
            window.setInterval(updateKitchenOverdueState, 1000);
        }

        document.addEventListener('click', function (event) {
            var tableTile = event.target.closest('.maca-staff-table-tile');
            if (tableTile) {
                var pin = getPin() || (pinInput ? pinInput.value.trim() : '');
                if (!pin) {
                    return;
                }
                var now = Date.now();
                if (document.macaStaffLastTableClick && now - document.macaStaffLastTableClick < 1500) {
                    return;
                }
                document.macaStaffLastTableClick = now;
                showTableDetailView({
                    key: tableTile.getAttribute('data-table-key') || '',
                    table_number: tableTile.getAttribute('data-table-number') || '',
                    service_mode: tableTile.getAttribute('data-service-mode') || 'dine_in',
                    walk_in: tableTile.getAttribute('data-walk-in') === '1',
                    label: tableTile.getAttribute('data-table-label') || '',
                });
                restartPolling(pin);
                return;
            }

            if (event.target.closest('#maca-staff-table-back')) {
                var backPin = getPin() || (pinInput ? pinInput.value.trim() : '');
                showTableBoardView();
                if (backPin) {
                    restartPolling(backPin);
                }
                return;
            }

            var qrButton = event.target.closest('.maca-staff-order-guest-qr');
            if (qrButton) {
                var recoveryUrl = qrButton.getAttribute('data-recovery-url');
                if (recoveryUrl) {
                    openGuestRecoveryModal(recoveryUrl);
                }
                return;
            }

            if (event.target.closest('.maca-staff-guest-qr-close, .maca-staff-guest-qr-modal-backdrop')) {
                closeGuestRecoveryModal();
                return;
            }

            var actionButton = event.target.closest('.maca-staff-order-action, .maca-kds-card-action');
            if (actionButton && !actionButton.classList.contains('maca-staff-order-guest-qr')) {
                if (actionButton.classList.contains('maca-staff-order-table-save')) {
                    var saveOrderId = actionButton.getAttribute('data-order-id');
                    var input = actionButton.closest('.maca-staff-order-table-change-row');
                    input = input ? input.querySelector('.maca-staff-order-table-input') : null;
                    var savePin = getPin() || (pinInput ? pinInput.value.trim() : '');
                    if (saveOrderId && input && savePin) {
                        updateOrderTableNumber(saveOrderId, input.value.trim(), savePin).catch(function (err) {
                            window.alert(err && err.message ? err.message : t('tableNumberUpdateError'));
                        });
                    }
                    return;
                }

                var orderId = actionButton.getAttribute('data-order-id');
                var status = actionButton.getAttribute('data-status');
                var needsEta = actionButton.getAttribute('data-needs-eta') === '1';
                var updateEtaOnly = actionButton.getAttribute('data-update-eta-only') === '1';
                var pin = getPin() || (pinInput ? pinInput.value.trim() : '');
                var etaMinutes = null;

                if (needsEta) {
                    var promptValue = window.prompt(t('etaPrompt'), '10');
                    if (promptValue === null) {
                        return;
                    }
                    etaMinutes = parseInt(promptValue, 10);
                    if (Number.isNaN(etaMinutes) || etaMinutes < 0) {
                        window.alert(t('invalidEta'));
                        return;
                    }
                }

                if (updateEtaOnly) {
                    status = 'preparing';
                }

                if (orderId && status && pin) {
                    updateOrderStatus(orderId, status, pin, etaMinutes);
                }
                return;
            }
        });

        document.addEventListener('change', function (event) {
            var tableSelect = event.target.closest('.maca-staff-order-table-select');
            if (!tableSelect) {
                return;
            }

            var selectOrderId = tableSelect.getAttribute('data-order-id');
            var previous = tableSelect.getAttribute('data-current') || '';
            var nextValue = tableSelect.value.trim();
            var selectPin = getPin() || (pinInput ? pinInput.value.trim() : '');

            if (!selectOrderId || !selectPin || nextValue === previous) {
                return;
            }

            updateOrderTableNumber(selectOrderId, nextValue, selectPin)
                .then(function () {
                    tableSelect.setAttribute('data-current', nextValue);
                })
                .catch(function (err) {
                    tableSelect.value = previous;
                    window.alert(err && err.message ? err.message : t('tableNumberUpdateError'));
                });
        });

        document.addEventListener('keydown', function (event) {
            if (event.key === 'Escape') {
                closeGuestRecoveryModal();
            }
        });

        if (storedPin && pinInput) {
            pinInput.value = storedPin;
        }
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initStaffOrders);
    } else {
        initStaffOrders();
    }
})();
