/**
 * Personalliggare — in-venue control view (/stampla/kontroll/).
 */
(function () {
    'use strict';

    var SESSION_KEY = 'maca_menulist_attendance_control_session';

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

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

    function $(id) {
        return document.getElementById(id);
    }

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

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

    function postAttendance(action, extra) {
        var body = new URLSearchParams();
        body.set('attendance_action', action);

        var session = getSession();
        if (session) {
            body.set('control_session', session);
        }

        if (extra) {
            Object.keys(extra).forEach(function (key) {
                if (extra[key] !== undefined && extra[key] !== null) {
                    body.set(key, String(extra[key]));
                }
            });
        }

        return fetch(cfg().restUrl || '', {
            method: 'POST',
            credentials: 'same-origin',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            },
            body: body.toString(),
        }).then(function (response) {
            return response.json().then(function (payload) {
                return {
                    ok: response.ok,
                    payload: payload,
                };
            });
        });
    }

    function showError(element, message) {
        if (!element) {
            return;
        }

        if (!message) {
            element.hidden = true;
            element.textContent = '';
            return;
        }

        element.hidden = false;
        element.textContent = message;
    }

    function statusLabel(row) {
        if (row.is_clocked_in) {
            return t('clockedIn');
        }

        if (row.clock_in || row.clock_out) {
            return t('clockedOut');
        }

        return t('noActivity');
    }

    function renderRows(data) {
        var tbody = $('maca-attendance-control-tbody');
        var dateLabel = $('maca-attendance-control-date-label');
        if (!tbody) {
            return;
        }

        if (dateLabel && data.date_label) {
            dateLabel.textContent = data.date_label;
        }

        tbody.innerHTML = '';
        var rows = data.rows || [];

        if (!rows.length) {
            var empty = document.createElement('tr');
            empty.innerHTML = '<td colspan="4">' + t('noEmployees') + '</td>';
            tbody.appendChild(empty);
            return;
        }

        rows.forEach(function (row) {
            var tr = document.createElement('tr');
            tr.innerHTML =
                '<td>' + escapeHtml(row.name || '') + '</td>' +
                '<td>' + escapeHtml(row.clock_in || '—') + '</td>' +
                '<td>' + escapeHtml(row.clock_out || '—') + '</td>' +
                '<td>' + escapeHtml(statusLabel(row)) + '</td>';
            tbody.appendChild(tr);
        });
    }

    function escapeHtml(value) {
        return String(value)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;');
    }

    function showReportPanel() {
        var pinPanel = $('maca-attendance-control-pin');
        var reportPanel = $('maca-attendance-control-report');
        if (pinPanel) {
            pinPanel.hidden = true;
        }
        if (reportPanel) {
            reportPanel.hidden = false;
        }
    }

    function showPinPanel() {
        var pinPanel = $('maca-attendance-control-pin');
        var reportPanel = $('maca-attendance-control-report');
        if (pinPanel) {
            pinPanel.hidden = false;
        }
        if (reportPanel) {
            reportPanel.hidden = true;
        }
        showError($('maca-attendance-control-pin-error'), '');
    }

    function loadReport() {
        var dateInput = $('maca-attendance-control-date');
        var date = dateInput ? dateInput.value : '';

        return postAttendance('control_report', { date: date }).then(function (result) {
            var payload = result.payload || {};
            var data = payload.data || {};

            if (!result.ok || !payload.success) {
                if (data.message && String(data.message).toLowerCase().indexOf('session') !== -1) {
                    setSession('');
                    showPinPanel();
                }
                showError($('maca-attendance-control-report-error'), data.message || t('errorGeneric'));
                return;
            }

            showError($('maca-attendance-control-report-error'), '');
            renderRows(data);
        }).catch(function () {
            showError($('maca-attendance-control-report-error'), t('errorGeneric'));
        });
    }

    function handleVerifyPin() {
        var input = $('maca-attendance-control-pin-input');
        var pin = input ? String(input.value || '').trim() : '';

        if (!pin) {
            showError($('maca-attendance-control-pin-error'), t('enterStaffPin'));
            return;
        }

        postAttendance('verify_staff_pin', { staff_pin: pin }).then(function (result) {
            var payload = result.payload || {};
            var data = payload.data || {};

            if (!result.ok || !payload.success) {
                showError($('maca-attendance-control-pin-error'), data.message || t('errorGeneric'));
                return;
            }

            if (data.control_session) {
                setSession(data.control_session);
            }

            if (input) {
                input.value = '';
            }

            showReportPanel();
            loadReport();
        }).catch(function () {
            showError($('maca-attendance-control-pin-error'), t('errorGeneric'));
        });
    }

    function bindEvents() {
        var pinSubmit = $('maca-attendance-control-pin-submit');
        var pinInput = $('maca-attendance-control-pin-input');
        var refresh = $('maca-attendance-control-refresh');
        var todayBtn = $('maca-attendance-control-today');
        var printBtn = $('maca-attendance-control-print');
        var logout = $('maca-attendance-control-logout');
        var dateInput = $('maca-attendance-control-date');

        if (pinSubmit) {
            pinSubmit.addEventListener('click', handleVerifyPin);
        }

        if (pinInput) {
            pinInput.addEventListener('keydown', function (event) {
                if (event.key === 'Enter') {
                    handleVerifyPin();
                }
            });
        }

        if (refresh) {
            refresh.addEventListener('click', loadReport);
        }

        if (todayBtn) {
            todayBtn.addEventListener('click', function () {
                if (dateInput && cfg().today) {
                    dateInput.value = cfg().today;
                }
                loadReport();
            });
        }

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

        if (printBtn) {
            printBtn.addEventListener('click', function () {
                window.print();
            });
        }

        if (logout) {
            logout.addEventListener('click', function () {
                setSession('');
                showPinPanel();
            });
        }
    }

    function restoreSession() {
        if (!getSession()) {
            return;
        }

        showReportPanel();
        loadReport();
    }

    bindEvents();
    restoreSession();
}());
