/**
 * Personalliggare — mobile clock in/out page.
 */
(function () {
    'use strict';

    var SESSION_KEY = 'maca_menulist_attendance_session';

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

    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('attendance_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 formatStatusLabel(status) {
        if (!status) {
            return t('notClockedIn');
        }

        if (status.is_clocked_in && status.last_occurred_at_label) {
            return t('clockedInSince').replace('%s', status.last_occurred_at_label);
        }

        if (!status.is_clocked_in && status.last_occurred_at_label) {
            return t('clockedOutAt').replace('%s', status.last_occurred_at_label);
        }

        return t('notClockedIn');
    }

    function updateClockButtons(status) {
        var inBtn = $('maca-attendance-clock-in');
        var outBtn = $('maca-attendance-clock-out');

        if (!inBtn || !outBtn) {
            return;
        }

        if (status && status.is_clocked_in) {
            inBtn.hidden = true;
            outBtn.hidden = false;
        } else {
            inBtn.hidden = false;
            outBtn.hidden = true;
        }
    }

    function showClockPanel(data) {
        var pinPanel = $('maca-attendance-pin');
        var clockPanel = $('maca-attendance-clock');
        var nameEl = $('maca-attendance-employee-name');
        var statusEl = $('maca-attendance-status');

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

        if (clockPanel) {
            clockPanel.hidden = false;
        }

        if (nameEl && data.employee) {
            nameEl.textContent = data.employee.name || '';
        }

        if (statusEl) {
            statusEl.textContent = formatStatusLabel(data.status || {});
        }

        updateClockButtons(data.status || {});
        showError($('maca-attendance-clock-message'), '');
    }

    function showPinPanel() {
        var pinPanel = $('maca-attendance-pin');
        var clockPanel = $('maca-attendance-clock');

        if (pinPanel) {
            pinPanel.hidden = false;
        }

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

        showError($('maca-attendance-pin-error'), '');
    }

    function handleVerifyPin() {
        var input = $('maca-attendance-pin-input');
        var pin = input ? String(input.value || '').replace(/\D/g, '') : '';

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

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

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

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

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

            showClockPanel(data);
        }).catch(function () {
            showError($('maca-attendance-pin-error'), t('errorGeneric'));
        });
    }

    function handleClock(actionType) {
        postAttendance('clock', { clock_action: actionType }).then(function (result) {
            var payload = result.payload || {};
            var data = payload.data || {};

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

            var statusEl = $('maca-attendance-status');
            if (statusEl) {
                statusEl.textContent = formatStatusLabel(data.status || {});
            }

            updateClockButtons(data.status || {});
            showError($('maca-attendance-clock-message'), data.message || '');
        }).catch(function () {
            showError($('maca-attendance-clock-message'), t('errorGeneric'));
        });
    }

    function handleLogout() {
        postAttendance('logout').finally(function () {
            setSession('');
            showPinPanel();
        });
    }

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

        postAttendance('status').then(function (result) {
            var payload = result.payload || {};
            var data = payload.data || {};

            if (!result.ok || !payload.success) {
                setSession('');
                return;
            }

            showClockPanel(data);
        }).catch(function () {
            setSession('');
        });
    }

    function bindEvents() {
        var pinSubmit = $('maca-attendance-pin-submit');
        var pinInput = $('maca-attendance-pin-input');
        var clockIn = $('maca-attendance-clock-in');
        var clockOut = $('maca-attendance-clock-out');
        var logout = $('maca-attendance-logout');

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

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

        if (clockIn) {
            clockIn.addEventListener('click', function () {
                handleClock('in');
            });
        }

        if (clockOut) {
            clockOut.addEventListener('click', function () {
                handleClock('out');
            });
        }

        if (logout) {
            logout.addEventListener('click', handleLogout);
        }
    }

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