/**
 * Public management overview — PIN gate.
 */
(function () {
    'use strict';

    var cfg = window.macaMenulistManagementOverview;
    if (!cfg) {
        return;
    }

    var pinWrap = document.getElementById('maca-management-overview-pin');
    var dashboardWrap = document.getElementById('maca-management-overview-dashboard');
    var pinInput = document.getElementById('maca-management-overview-pin-input');
    var unlockBtn = document.getElementById('maca-management-overview-unlock');
    var pinError = document.getElementById('maca-management-overview-pin-error');
    var pinInfo = document.getElementById('maca-management-overview-pin-info');

    function pinStorageKey() {
        return 'maca_menulist_management_pin';
    }

    function setStoredPin(pin) {
        try {
            window.sessionStorage.setItem(pinStorageKey(), pin);
        } catch (e) {
            // ignore
        }
    }

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

    function showPinError(message) {
        if (!pinError) {
            return;
        }
        pinError.textContent = message || '';
        pinError.hidden = !message;
    }

    function updatePinInfo(meta) {
        if (!pinInfo || !meta) {
            return;
        }
        if (meta.is_locked && meta.locked_seconds_remaining > 0) {
            var minutes = Math.max(1, Math.ceil(Number(meta.locked_seconds_remaining || 0) / 60));
            if (cfg.labels && cfg.labels.pinLockedMinutes) {
                pinInfo.textContent = String(cfg.labels.pinLockedMinutes).replace('%d', String(minutes));
            } else if (cfg.labels && cfg.labels.pinLocked) {
                pinInfo.textContent = cfg.labels.pinLocked;
            }
            return;
        }
        if (typeof meta.attempts_left !== 'undefined' && typeof meta.max_attempts !== 'undefined') {
            if (cfg.labels && cfg.labels.attemptsLeft) {
                pinInfo.textContent = String(cfg.labels.attemptsLeft)
                    .replace('%1$d', String(meta.attempts_left))
                    .replace('%2$d', String(meta.max_attempts));
            }
        }
    }

    function showDashboard() {
        if (pinWrap) {
            pinWrap.hidden = true;
        }
        if (dashboardWrap) {
            dashboardWrap.hidden = false;
        }
    }

    function verifyAndUnlock(pin) {
        var body = new URLSearchParams();
        body.append('action', 'maca_management_dashboard_refresh');
        body.append('nonce', cfg.nonce);
        body.append('pin', pin);
        body.append('date_from', cfg.today || '');
        body.append('date_to', cfg.today || '');

        return fetch(cfg.ajaxUrl, {
            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();
        });
    }

    function unlockWithPin(pin) {
        showPinError('');
        if (!pin) {
            showPinError((cfg.labels && cfg.labels.pinInvalid) || 'Invalid PIN.');
            return;
        }

        if (unlockBtn) {
            unlockBtn.disabled = true;
        }

        verifyAndUnlock(pin)
            .then(function (data) {
                if (!data || !data.success) {
                    var msg = (data && data.data && data.data.message) || (cfg.labels && cfg.labels.pinInvalid) || 'Invalid PIN.';
                    showPinError(msg);
                    if (data && data.data && data.data.pin_feedback) {
                        updatePinInfo(data.data.pin_feedback);
                    }
                    return;
                }

                setStoredPin(pin);
                if (window.macaMenulistDashboard) {
                    window.macaMenulistDashboard.initial = data.data;
                }
                showDashboard();
                document.dispatchEvent(new CustomEvent('maca-management-overview-unlocked'));
            })
            .catch(function () {
                showPinError((cfg.labels && cfg.labels.pinInvalid) || 'Invalid PIN.');
            })
            .finally(function () {
                if (unlockBtn) {
                    unlockBtn.disabled = false;
                }
            });
    }

    if (unlockBtn) {
        unlockBtn.addEventListener('click', function () {
            unlockWithPin(pinInput ? pinInput.value : '');
        });
    }

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

    var stored = getStoredPin();
    if (stored) {
        if (pinInput) {
            pinInput.value = stored;
        }
        unlockWithPin(stored);
    }

    if (cfg.pinFeedback) {
        updatePinInfo(cfg.pinFeedback);
    }
})();
