document.addEventListener('DOMContentLoaded', function () {
    function getCsrfToken() {
        var el = document.querySelector('input[name="__RequestVerificationToken"]');
        return el ? el.value : '';
    }

    document.body.addEventListener('click', function (e) {
        var target = e.target;
        var btn = target.closest ? target.closest('.btn-toggle-panel') : null;
        if (!btn) return;

        e.stopPropagation();
        var itemId = btn.getAttribute('data-item-id');
        var hasPanel = btn.getAttribute('data-has-panel');
        var row = btn.closest ? btn.closest('tr') : null;
        var csrf = getCsrfToken();

        btn.disabled = true;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span>';

        fetch('/Inventory/ToggleSamplePanel', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'RequestVerificationToken': csrf
            },
            body: 'id=' + itemId + '&hasPanel=' + hasPanel + '&__RequestVerificationToken=' + encodeURIComponent(csrf)
        })
        .then(function (r) { return r.json(); })
        .then(function (data) {
            if (data.success) {
                if (row) {
                    row.style.transition = 'opacity .25s';
                    row.style.opacity = '0';
                    setTimeout(function () { location.reload(); }, 300);
                } else {
                    location.reload();
                }
            } else {
                btn.disabled = false;
                alert(data.message || 'An error occurred.');
            }
        })
        .catch(function () { btn.disabled = false; });
    });

    var printBtn = document.getElementById('btnPrintList');
    if (printBtn) {
        printBtn.addEventListener('click', function () {
            var printArea = document.getElementById('printArea');
            var content = printArea ? printArea.innerHTML : '';
            var win = window.open('', '_blank', 'width=900,height=700');
            win.document.open();
            win.document.write('<!DOCTYPE html><html><head><title>Need to Order</title>');
            win.document.write('<style>body{font-family:sans-serif;padding:20px}table{width:100%;border-collapse:collapse}th,td{border:1px solid #ccc;padding:6px 10px;text-align:left}th{background:#f0f0f0}</style>');
            win.document.write('</head><body>');
            win.document.write(content);
            win.document.write('</body></html>');
            win.document.close();
            win.focus();
            setTimeout(function () { win.print(); }, 500);
        });
    }
});
