/**
 * Jogging screen logic.
 * Each axis gets its own row with 6 step buttons: -100 -10 -1 +1 +10 +100
 * In mock mode: calls MockWebSocket.jog()
 * In live mode: calls REST API
 */
var Jogging = (function () {

    var mode = 'joint'; // 'joint' or 'cartesian'
    var STEPS = [100, 10, 1];
    var JOINT_UNIT = 'mm/\u00B0';

    // Joint-mode axis names (populated from state)
    var jointAxes = [];
    // Cartesian-mode axes
    var cartAxes = [
        { name: 'X', unit: 'mm' },
        { name: 'Y', unit: 'mm' },
        { name: 'Z', unit: 'mm' },
        { name: 'A', unit: '\u00B0' },
        { name: 'B', unit: '\u00B0' },
        { name: 'C', unit: '\u00B0' }
    ];

    // Cached robot state
    var lastState = null;
    var isReady = false;

    function init() {
        // Mode toggle
        var modeBtns = document.querySelectorAll('.jog-mode-btn');
        for (var i = 0; i < modeBtns.length; i++) {
            modeBtns[i].addEventListener('click', function () {
                if (this.classList.contains('active')) return;
                mode = this.getAttribute('data-mode');
                for (var j = 0; j < modeBtns.length; j++) {
                    modeBtns[j].classList.remove('active');
                }
                this.classList.add('active');
                renderAxisList();
            });
        }

        // Stop button
        var stopBtn = document.getElementById('jog-btn-stop');
        if (stopBtn) {
            stopBtn.addEventListener('click', function () {
                doJogAction('jog/stop', {});
            });
        }
    }

    function sendJog(axisIndex, delta) {
        if (!isReady) return;
        if (mode === 'joint') {
            doJogAction('jog/joint-relative', {
                axis: axisIndex,
                delta: delta
            });
        } else {
            var axes = ['x', 'y', 'z', 'a', 'b', 'c'];
            doJogAction('jog/cart-relative', {
                axis: axes[axisIndex] || 'x',
                delta: delta
            });
        }
    }

    function doJogAction(action, payload) {
        if (Config.MOCK_MODE) {
            MockWebSocket.jog(action, payload);
        } else {
            fetch(Config.API_URL + '/' + action, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            })
                .then(function (r) { return r.json(); })
                .catch(function (err) {
                    console.error('Jog action error:', err);
                });
        }
    }

    function renderAxisList() {
        var container = document.getElementById('jog-axis-list');
        if (!container) return;
        container.innerHTML = '';

        var axes = mode === 'joint' ? jointAxes : cartAxes;

        for (var i = 0; i < axes.length; i++) {
            var row = document.createElement('div');
            row.className = 'jog-axis-row';

            // Axis name (left)
            var nameEl = document.createElement('span');
            nameEl.className = 'jog-axis-name';
            nameEl.textContent = axes[i].name;
            row.appendChild(nameEl);

            // Current value (middle)
            var valueEl = document.createElement('span');
            valueEl.className = 'jog-axis-value';
            valueEl.setAttribute('id', 'jog-axis-val-' + i);
            if (mode === 'joint') {
                valueEl.textContent = formatPosition(axes[i].position, JOINT_UNIT);
            } else {
                valueEl.textContent = getCartValue(i);
            }
            row.appendChild(valueEl);

            // Buttons right: [-100 -10 -1] [+1 +10 +100]
            var btnGroup = document.createElement('div');
            btnGroup.className = 'jog-btn-group';

            var minusGroup = document.createElement('div');
            minusGroup.className = 'jog-btn-pack';
            for (var s = 0; s < STEPS.length; s++) {
                minusGroup.appendChild(createStepBtn(i, -STEPS[s]));
            }
            btnGroup.appendChild(minusGroup);

            var plusGroup = document.createElement('div');
            plusGroup.className = 'jog-btn-pack';
            for (var p = STEPS.length - 1; p >= 0; p--) {
                plusGroup.appendChild(createStepBtn(i, STEPS[p]));
            }
            btnGroup.appendChild(plusGroup);

            row.appendChild(btnGroup);

            container.appendChild(row);
        }
    }

    function createStepBtn(axisIndex, delta) {
        var btn = document.createElement('button');
        btn.className = 'jog-step-btn' + (delta < 0 ? ' minus' : ' plus');
        if (!isReady) btn.classList.add('disabled');
        var absVal = Math.abs(delta);
        var label = (delta < 0 ? '\u2212' : '+') + absVal;
        btn.textContent = label;
        btn.addEventListener('click', function () {
            if (btn.classList.contains('disabled')) return;
            sendJog(axisIndex, delta);
        });
        return btn;
    }

    function getCartValue(index) {
        if (!lastState || !lastState.robot || !lastState.robot.tcp) return '--';
        var tcp = lastState.robot.tcp;
        var keys = ['x', 'y', 'z', 'a', 'b', 'c'];
        var val = tcp[keys[index]];
        var unit = cartAxes[index].unit;
        return formatPosition(val, unit);
    }

    function formatPosition(val, unit) {
        if (val === undefined || val === null) return '--';
        return Number(val).toFixed(1) + ' ' + unit;
    }

    function updateFromState(state) {
        lastState = state;
        if (!state.robot) return;

        var robot = state.robot;
        isReady = !!robot.isEnabled
            && robot.referencingState === 'referenced'
            && robot.hardwareState === 'NoError';

        // Update disabled state on all step buttons
        var allBtns = document.querySelectorAll('.jog-step-btn');
        for (var b = 0; b < allBtns.length; b++) {
            if (isReady) { allBtns[b].classList.remove('disabled'); }
            else { allBtns[b].classList.add('disabled'); }
        }

        // Build joint axis list from state
        var joints = state.robot.joints || [];
        var robotAxisCount = (state.system && state.system.robotAxisCount) || 6;
        var newJointAxes = [];
        for (var i = 0; i < robotAxisCount && i < joints.length; i++) {
            newJointAxes.push({
                name: joints[i].name || ('A' + (i + 1)),
                position: joints[i].targetPosition
            });
        }

        if (newJointAxes.length !== jointAxes.length) {
            jointAxes = newJointAxes;
            renderAxisList();
        } else {
            jointAxes = newJointAxes;
            updateAxisValues();
        }
    }

    function updateAxisValues() {
        var axes = mode === 'joint' ? jointAxes : cartAxes;
        for (var i = 0; i < axes.length; i++) {
            var el = document.getElementById('jog-axis-val-' + i);
            if (!el) continue;
            if (mode === 'joint') {
                el.textContent = formatPosition(axes[i].position, JOINT_UNIT);
            } else {
                el.textContent = getCartValue(i);
            }
        }
    }

    return {
        init: init,
        updateFromState: updateFromState
    };
})();
