/* modules/free/qr-setup/assets/js/admin.js */
(function (window, $) {
    'use strict';

    var modules = window.noesiaSwaAdminModules || (window.noesiaSwaAdminModules = {});
    var nsVars = window.noesia_admin_vars || {};
    var state = {
        booted: false,
        bound: false,
        maxBatch: 300
    };

    function escHtml(text) {
        return String(text == null ? '' : text)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    function hasUi() {
        return $('#btn-gen-qr').length > 0;
    }

    function strings() {
        var s = nsVars.strings || {};

        return {
            missingBase: String(s.qr_missing_base || 'Please enter a Base URL.'),
            invalidRange: String(s.qr_invalid_range || 'Invalid start/end range.'),
            popupBlocked: String(s.err_popup || 'Please allow popups to print QR codes.'),
            missingLib: String(s.qr_missing_lib || 'QR library is not available.'),
            rangeTooLarge: String(s.qr_range_too_large || 'Too many QR codes requested at once. Please use a smaller range.'),
            printTitle: String(s.qr_print_title || 'Print QR Codes'),
            printNow: String(s.qr_print_now || 'PRINT NOW'),
            scanText: String(s.qr_scan_text || 'Scan to Order')
        };
    }

    function normalizeBaseUrl(raw) {
        return String(raw || '').trim();
    }

    function normalizePrefix(raw) {
        raw = String(raw || '').trim();
        return raw || 'Table';
    }

    function collectConfig() {
        return {
            baseUrl: normalizeBaseUrl($('#qr_base_url').val()),
            prefix: normalizePrefix($('#qr_prefix').val()),
            start: parseInt(String($('#qr_start').val() || '1'), 10),
            end: parseInt(String($('#qr_end').val() || '1'), 10)
        };
    }

    function validateConfig(config) {
        var i18n = strings();
        var total;

        if (!config.baseUrl) {
            return {
                valid: false,
                message: i18n.missingBase,
                field: '#qr_base_url'
            };
        }

        if (
            isNaN(config.start) ||
            isNaN(config.end) ||
            config.start < 1 ||
            config.end < 1 ||
            config.end < config.start
        ) {
            return {
                valid: false,
                message: i18n.invalidRange,
                field: '#qr_start'
            };
        }

        total = (config.end - config.start) + 1;

        if (total > state.maxBatch) {
            return {
                valid: false,
                message: i18n.rangeTooLarge,
                field: '#qr_end'
            };
        }

        return {
            valid: true
        };
    }

    function buildQrUrl(baseUrl, label) {
        var sep = baseUrl.indexOf('?') !== -1 ? '&' : '?';
        return baseUrl + sep + 'loc=' + encodeURIComponent(label);
    }

    function createHiddenMount() {
        return $('<div />', {
            class: 'noesia-swa-temp-qr',
            css: {
                position: 'absolute',
                left: '-9999px',
                top: '-9999px',
                width: '1px',
                height: '1px',
                overflow: 'hidden'
            }
        }).appendTo('body');
    }

    function generateQrImageData(text) {
        var $mount;
        var imgData = '';
        var canvas;

        if (typeof window.QRCode === 'undefined') {
            return '';
        }

        $mount = createHiddenMount();

        try {
            new window.QRCode($mount[0], {
                text: String(text || ''),
                width: 128,
                height: 128,
                correctLevel: window.QRCode.CorrectLevel.H
            });

            imgData = String($mount.find('img').attr('src') || '');

            if (!imgData) {
                canvas = $mount.find('canvas')[0];
                if (canvas && typeof canvas.toDataURL === 'function') {
                    imgData = canvas.toDataURL('image/png');
                }
            }
        } catch (err) {
            imgData = '';
        }

        $mount.remove();
        return imgData;
    }

    function buildPrintHtml(items) {
        var i18n = strings();
        var html = '<!DOCTYPE html><html><head><meta charset="utf-8"><title>' + escHtml(i18n.printTitle) + '</title><style>';

        html += 'body{font-family:Arial,sans-serif;text-align:center;padding:20px;color:#111}';
        html += 'h1{margin:0 0 18px 0;font-size:28px}';
        html += '.print-btn{margin:0 0 22px 0;padding:10px 18px;border:0;border-radius:10px;background:#111;color:#fff;font-weight:700;cursor:pointer}';
        html += '.qr-grid{display:flex;flex-wrap:wrap;justify-content:center;gap:18px}';
        html += '.qr-container{display:inline-flex;flex-direction:column;align-items:center;justify-content:flex-start;width:170px;min-height:220px;border:1px solid #ddd;border-radius:14px;padding:18px;page-break-inside:avoid;background:#fff;box-sizing:border-box}';
        html += '.qr-container h2{font-size:18px;line-height:1.25;margin:0 0 12px 0;word-break:break-word}';
        html += '.qr-container img{display:block;width:128px;height:128px}';
        html += '.scan-text{margin-top:10px;font-size:12px;color:#555}';
        html += '@media print{.print-btn{display:none}body{padding:10px}}';
        html += '</style></head><body>';
        html += '<h1>' + escHtml(i18n.printTitle) + '</h1>';
        html += '<button onclick="window.print()" class="print-btn">' + escHtml(i18n.printNow) + '</button>';
        html += '<div class="qr-grid">';

        items.forEach(function (item) {
            html += '<div class="qr-container">';
            html += '<h2>' + escHtml(item.label) + '</h2>';
            html += '<img src="' + item.imgData + '" alt="QR Code">';
            html += '<p class="scan-text">' + escHtml(i18n.scanText) + '</p>';
            html += '</div>';
        });

        html += '</div></body></html>';

        return html;
    }

    function generateQrBatch(config) {
        var out = [];
        var i;
        var label;
        var fullUrl;
        var imgData;

        for (i = config.start; i <= config.end; i += 1) {
            label = config.prefix + ' ' + i;
            fullUrl = buildQrUrl(config.baseUrl, label);
            imgData = generateQrImageData(fullUrl);

            if (!imgData) {
                continue;
            }

            out.push({
                label: label,
                fullUrl: fullUrl,
                imgData: imgData
            });
        }

        return out;
    }

    function openPrintWindow(html) {
        var printWindow = window.open('', '_blank');

        if (!printWindow) {
            return null;
        }

        printWindow.document.open();
        printWindow.document.write(String(html || ''));
        printWindow.document.close();
        printWindow.focus();

        return printWindow;
    }

    function generateAndPrintQr() {
        var i18n = strings();
        var config = collectConfig();
        var validation = validateConfig(config);
        var items;
        var html;
        var printWindow;

        if (!validation.valid) {
            window.alert(validation.message);
            if (validation.field) {
                $(validation.field).trigger('focus');
            }
            return false;
        }

        if (typeof window.QRCode === 'undefined') {
            window.alert(i18n.missingLib);
            return false;
        }

        items = generateQrBatch(config);

        if (!items.length) {
            window.alert(i18n.missingLib);
            return false;
        }

        html = buildPrintHtml(items);
        printWindow = openPrintWindow(html);

        if (!printWindow) {
            window.alert(i18n.popupBlocked);
            return false;
        }

        return true;
    }


    function copyTextFallback(text) {
        var area = document.createElement('textarea');
        area.value = String(text || '');
        area.setAttribute('readonly', 'readonly');
        area.style.position = 'absolute';
        area.style.left = '-9999px';
        document.body.appendChild(area);
        area.select();

        try {
            document.execCommand('copy');
        } catch (err) {
            // Ignore legacy fallback errors.
        }

        document.body.removeChild(area);
    }

    function copyText(text) {
        if (navigator.clipboard && typeof navigator.clipboard.writeText === 'function') {
            return navigator.clipboard.writeText(String(text || '')).catch(function () {
                copyTextFallback(text);
            });
        }

        copyTextFallback(text);
        return Promise.resolve();
    }

    function bindCopyButtons() {
        $(document)
            .off('click.noesiaSwaQrCopy', '.noesia-swa-qr-copy-btn')
            .on('click.noesiaSwaQrCopy', '.noesia-swa-qr-copy-btn', function (event) {
                var $button = $(event.currentTarget);
                var text = String($button.attr('data-noesia-swa-copy-target') || '').trim();
                var originalLabel = $button.data('original-label');

                event.preventDefault();

                if (!originalLabel) {
                    originalLabel = $button.text();
                    $button.data('original-label', originalLabel);
                }

                if (!text) {
                    return;
                }

                copyText(text).finally(function () {
                    $button.addClass('is-copied').text('Copied');

                    window.setTimeout(function () {
                        $button.removeClass('is-copied').text(originalLabel);
                    }, 1200);
                });
            });
    }

    function bindEvents() {
        if (state.bound) {
            return true;
        }

        state.bound = true;

        $(document)
            .off('click.noesiaSwaQrSetup', '#btn-gen-qr')
            .on('click.noesiaSwaQrSetup', '#btn-gen-qr', function (e) {
                e.preventDefault();
                e.stopPropagation();
                generateAndPrintQr();
            });

        return true;
    }

    function boot() {
        if (state.booted) {
            return true;
        }

        if (!hasUi()) {
            return false;
        }

        bindEvents();
        state.booted = true;

        return true;
    }

    function init() {
        return boot();
    }

    function onSectionOpen(target) {
        if (String(target || 'qr-setup') !== 'qr-setup') {
            return false;
        }

        return init();
    }

    function onShow() {
        return onSectionOpen('qr-setup');
    }

    function show() {
        return onSectionOpen('qr-setup');
    }

    modules['qr-setup'] = {
        boot: boot,
        init: init,
        onSectionOpen: onSectionOpen,
        onShow: onShow,
        show: show,
        initQrSetup: init,
        initQrGenerator: init,
        generateAndPrintQr: generateAndPrintQr
    };

    $(boot);
})(window, jQuery);