/**
 * Admin seat availability matrix (times × seats).
 */
(function () {
    'use strict';

    var config = window.macaMenulistAdminBookingMatrix || {};
    var strings = config.strings || {};
    var root = document.getElementById('maca-booking-matrix');

    if (!root) {
        return;
    }

    var dateInput = root.querySelector('.maca-booking-matrix-date');
    var wrapEl = document.getElementById('maca-booking-matrix-table-wrap');
    var messageEl = document.getElementById('maca-booking-matrix-message');
    var loadToken = 0;

    function clampDate(value) {
        if (!value) {
            return config.today || '';
        }
        if (config.minDate && value < config.minDate) {
            return config.minDate;
        }
        if (config.maxDate && value > config.maxDate) {
            return config.maxDate;
        }
        return value;
    }

    function setMessage(text, isError) {
        if (!messageEl) {
            return;
        }
        messageEl.textContent = text || '';
        messageEl.className = 'maca-booking-matrix-message' + (isError ? ' is-error' : '');
    }

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

    function postMatrix(date) {
        var body = new FormData();
        body.append('action', 'maca_admin_booking_seat_matrix');
        body.append('nonce', config.nonce || '');
        body.append('booking_date', date);

        return fetch(config.ajaxUrl, {
            method: 'POST',
            credentials: 'same-origin',
            body: body
        }).then(function (response) {
            return response.json();
        });
    }

    function renderMatrix(data) {
        if (!wrapEl) {
            return;
        }

        if (data.closed) {
            wrapEl.innerHTML =
                '<p class="maca-booking-matrix-empty">' + escapeHtml(data.message || strings.closed || '') + '</p>';
            return;
        }

        var columns = data.columns || [];
        var times = data.times || [];
        var cells = data.cells || {};

        if (!columns.length || !times.length) {
            wrapEl.innerHTML =
                '<p class="maca-booking-matrix-empty">' + escapeHtml(data.message || strings.closed || '') + '</p>';
            return;
        }

        var html = '<div class="maca-booking-matrix-scroll"><table class="maca-booking-matrix-table">';
        html += '<thead><tr><th scope="col" class="maca-booking-matrix-time-col">' + escapeHtml(strings.time || 'Tid') + '</th>';

        columns.forEach(function (col) {
            html +=
                '<th scope="col" class="maca-booking-matrix-seat-col" title="' +
                escapeHtml(col.label) +
                '"><span class="maca-booking-matrix-seat-label">' +
                escapeHtml(col.label) +
                '</span></th>';
        });
        html += '</tr></thead><tbody>';

        times.forEach(function (time) {
            var rowCells = cells[time] || {};
            html += '<tr><th scope="row" class="maca-booking-matrix-time-col">' + escapeHtml(time) + '</th>';

            columns.forEach(function (col) {
                var state = rowCells[col.key] === 'busy' ? 'busy' : 'free';
                var title =
                    (state === 'busy' ? strings.occupied : strings.available) +
                    ' · ' +
                    col.label +
                    ' · ' +
                    time;
                html +=
                    '<td class="maca-booking-matrix-cell maca-booking-matrix-cell-' +
                    state +
                    '" title="' +
                    escapeHtml(title) +
                    '"><span class="maca-booking-matrix-cell-inner" aria-hidden="true"></span><span class="screen-reader-text">' +
                    escapeHtml(title) +
                    '</span></td>';
            });

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

        html += '</tbody></table></div>';
        wrapEl.innerHTML = html;
    }

    function loadMatrix() {
        if (!dateInput) {
            return;
        }

        var date = clampDate(dateInput.value);
        dateInput.value = date;
        var token = ++loadToken;

        if (wrapEl) {
            wrapEl.setAttribute('aria-busy', 'true');
            wrapEl.innerHTML =
                '<p class="maca-booking-matrix-loading">' + escapeHtml(strings.loading || 'Laddar…') + '</p>';
        }
        setMessage('', false);

        postMatrix(date)
            .then(function (result) {
                if (token !== loadToken) {
                    return;
                }

                if (!result || !result.success || !result.data) {
                    setMessage(strings.error || '', true);
                    if (wrapEl) {
                        wrapEl.removeAttribute('aria-busy');
                        wrapEl.innerHTML = '';
                    }
                    return;
                }

                renderMatrix(result.data);
                if (wrapEl) {
                    wrapEl.removeAttribute('aria-busy');
                }
            })
            .catch(function () {
                if (token !== loadToken) {
                    return;
                }
                setMessage(strings.error || '', true);
                if (wrapEl) {
                    wrapEl.removeAttribute('aria-busy');
                    wrapEl.innerHTML = '';
                }
            });
    }

    if (dateInput) {
        dateInput.addEventListener('change', loadMatrix);
    }

    loadMatrix();
})();
