/**
 * Modulo Derecho de Desistimiento (ecom_desestimiento)
 *
 * @author    Ecom Experts <ecomyseo@gmail.com>
 * @copyright 2026 Ecom Experts
 * @license   https://opensource.org/licenses/AFL-3.0 Academic Free License 3.0 (AFL-3.0)
 */
(function () {
    'use strict';

    document.addEventListener('DOMContentLoaded', function () {
        initDesistForm();
    });

    /**
     * Inicializa la logica del formulario de desistimiento.
     */
    function initDesistForm() {
        var form         = document.getElementById('ecom-desist-form');
        var submitBtn    = document.getElementById('desist-submit-btn');
        var confirmCheck = document.getElementById('desist-confirm-check');
        var checkAll     = document.getElementById('desist-check-all');

        if (!form) {
            return;
        }

        var lineChecks = form.querySelectorAll('.desist-line-check');
        var qtyInputs  = form.querySelectorAll('.desist-qty-input');

        // -----------------------------------------------------------------
        // Seleccionar / deseleccionar todos
        // -----------------------------------------------------------------
        if (checkAll) {
            checkAll.addEventListener('change', function () {
                lineChecks.forEach(function (chk) {
                    chk.checked = checkAll.checked;
                    syncQtyForLine(chk, qtyInputs);
                });
                updateSubmitState(lineChecks, confirmCheck, submitBtn);
            });
        }

        // -----------------------------------------------------------------
        // Cambio en checkbox de linea individual
        // -----------------------------------------------------------------
        lineChecks.forEach(function (chk) {
            chk.addEventListener('change', function () {
                syncQtyForLine(chk, qtyInputs);
                updateAllCheck(lineChecks, checkAll);
                updateSubmitState(lineChecks, confirmCheck, submitBtn);
            });
        });

        // -----------------------------------------------------------------
        // Cambio en cantidad: si el usuario pone 0, desmarcar la linea
        // -----------------------------------------------------------------
        qtyInputs.forEach(function (input) {
            input.addEventListener('input', function () {
                var lineId = input.getAttribute('data-line');
                var chk    = form.querySelector('.desist-line-check[name="desist_lines[' + lineId + ']"]');
                if (chk) {
                    if (parseInt(input.value, 10) < 1) {
                        chk.checked = false;
                    } else {
                        chk.checked = true;
                    }
                    updateAllCheck(lineChecks, checkAll);
                    updateSubmitState(lineChecks, confirmCheck, submitBtn);
                }
            });
        });

        // -----------------------------------------------------------------
        // Checkbox de confirmacion habilita el boton de envio
        // -----------------------------------------------------------------
        if (confirmCheck) {
            confirmCheck.addEventListener('change', function () {
                updateSubmitState(lineChecks, confirmCheck, submitBtn);
            });
        }

        // -----------------------------------------------------------------
        // Validacion antes del envio
        // -----------------------------------------------------------------
        form.addEventListener('submit', function (e) {
            var anyChecked = false;
            lineChecks.forEach(function (chk) {
                if (chk.checked) {
                    anyChecked = true;
                }
            });

            if (!anyChecked) {
                e.preventDefault();
                alert('Debe seleccionar al menos un producto para desistir.');
                return;
            }

            if (confirmCheck && !confirmCheck.checked) {
                e.preventDefault();
                alert('Debe confirmar que desea ejercer su derecho de desistimiento.');
                return;
            }

            // Sincronizar la cantidad del campo oculto name="desist_lines[id]"
            // con el valor del input de cantidad visible.
            lineChecks.forEach(function (chk) {
                if (!chk.checked) {
                    return;
                }
                var lineId   = extractLineId(chk.name);
                var qtyInput = form.querySelector('.desist-qty-input[data-line="' + lineId + '"]');
                if (qtyInput) {
                    chk.value = Math.max(1, parseInt(qtyInput.value, 10) || 1);
                }
            });
        });

        // Estado inicial
        updateSubmitState(lineChecks, confirmCheck, submitBtn);
    }

    // -------------------------------------------------------------------------
    // Funciones auxiliares
    // -------------------------------------------------------------------------

    /**
     * Sincroniza el input de cantidad cuando cambia el estado de un checkbox.
     *
     * @param {HTMLInputElement} chk
     * @param {NodeList}         qtyInputs
     */
    function syncQtyForLine(chk, qtyInputs) {
        var lineId = extractLineId(chk.name);
        qtyInputs.forEach(function (input) {
            if (input.getAttribute('data-line') === lineId) {
                if (!chk.checked) {
                    input.value = 0;
                } else if (parseInt(input.value, 10) < 1) {
                    input.value = input.getAttribute('max') || 1;
                }
            }
        });
    }

    /**
     * Actualiza el estado del checkbox "Seleccionar todos".
     *
     * @param {NodeList}         lineChecks
     * @param {HTMLInputElement} checkAll
     */
    function updateAllCheck(lineChecks, checkAll) {
        if (!checkAll) {
            return;
        }
        var total   = lineChecks.length;
        var checked = 0;
        lineChecks.forEach(function (chk) {
            if (chk.checked) {
                checked++;
            }
        });
        checkAll.checked       = (checked === total && total > 0);
        checkAll.indeterminate = (checked > 0 && checked < total);
    }

    /**
     * Habilita o deshabilita el boton de envio.
     *
     * @param {NodeList}         lineChecks
     * @param {HTMLInputElement} confirmCheck
     * @param {HTMLElement}      submitBtn
     */
    function updateSubmitState(lineChecks, confirmCheck, submitBtn) {
        if (!submitBtn) {
            return;
        }
        var anyChecked    = false;
        var confirmed     = !confirmCheck || confirmCheck.checked;

        lineChecks.forEach(function (chk) {
            if (chk.checked) {
                anyChecked = true;
            }
        });

        submitBtn.disabled = !(anyChecked && confirmed);
    }

    /**
     * Extrae el id de linea del atributo name="desist_lines[ID]".
     *
     * @param {string} name
     *
     * @return {string}
     */
    function extractLineId(name) {
        var match = name.match(/\[(\d+)\]/);
        return match ? match[1] : '';
    }

})();
