(function () {
    'use strict';

    var cfg = typeof window.zertiShopOrder === 'object' && window.zertiShopOrder !== null ? window.zertiShopOrder : {};
    var comp =
        typeof window.zertiComponents === 'object' && window.zertiComponents !== null ? window.zertiComponents : {};
    var ajaxUrl = cfg.ajaxUrl || '';
    var nonce = cfg.nonce || '';
    var action = cfg.action || 'zerti_shop_order_action';
    var i18n = cfg.i18n || {};
    var feedbackDurationMs =
        typeof i18n.feedbackDurationMs === 'number' && i18n.feedbackDurationMs > 0
            ? i18n.feedbackDurationMs
            : 2000;
    var feedbackTimer = null;

    function parseJson(res) {
        if (!res.ok) {
            throw new Error('http ' + res.status);
        }
        return res.json();
    }

    function getAdminRoot() {
        return document.getElementById('zertiAdmin');
    }

    function getShopSlot(root) {
        return root ? root.querySelector('[data-zerti-slot="shop"]') : null;
    }

    function getDetailWrap(el) {
        return el && el.closest ? el.closest('.zerti-shop-order-detail[data-zerti-order-id]') : null;
    }

    function getDetailByOrderId(orderId) {
        var slot = getShopSlot(getAdminRoot());
        if (!slot || !(orderId > 0)) {
            return null;
        }
        return slot.querySelector('.zerti-shop-order-detail[data-zerti-order-id="' + String(orderId) + '"]');
    }

    function getShopPanelCard(wrap) {
        if (!wrap || !wrap.closest) {
            return null;
        }
        var slot = wrap.closest('[data-zerti-slot="shop"]');
        return slot ? slot.closest('.zerti-panel') : null;
    }

    function getOverlayEl(wrap) {
        if (!wrap) {
            return null;
        }
        var panelCard = getShopPanelCard(wrap);
        if (panelCard) {
            var onPanel = panelCard.querySelector(':scope > .zerti-shop-order-detail__status-overlay');
            if (onPanel) {
                return onPanel;
            }
        }
        return wrap.querySelector('.zerti-shop-order-detail__status-overlay');
    }

    function getFeedbackEl(wrap) {
        var overlay = getOverlayEl(wrap);
        return overlay ? overlay.querySelector('.zerti-shop-order-detail__feedback') : null;
    }

    function mountOverlayOnPanel(wrap) {
        var overlay = wrap ? wrap.querySelector('.zerti-shop-order-detail__status-overlay') : null;
        var panelCard = getShopPanelCard(wrap);
        if (overlay && panelCard && overlay.parentNode !== panelCard) {
            panelCard.appendChild(overlay);
        }
        return panelCard;
    }

    function restoreOverlayToDetail(wrap) {
        if (!wrap) {
            return;
        }
        var overlay = getOverlayEl(wrap);
        if (overlay && overlay.parentNode !== wrap) {
            wrap.appendChild(overlay);
        }
        var panelCard = getShopPanelCard(wrap);
        if (panelCard) {
            panelCard.classList.remove('zerti-shop-panel--status-feedback');
        }
    }

    function hideFeedback(wrap) {
        if (!wrap) {
            return;
        }
        var box = getFeedbackEl(wrap);
        var overlay = getOverlayEl(wrap);
        if (feedbackTimer) {
            window.clearTimeout(feedbackTimer);
            feedbackTimer = null;
        }
        restoreOverlayToDetail(wrap);
        if (overlay) {
            overlay.hidden = true;
            overlay.setAttribute('aria-hidden', 'true');
        }
        if (!box) {
            return;
        }
        box.hidden = true;
        box.textContent = '';
        box.className = 'zerti-shop-order-detail__feedback';
    }

    function showFeedback(wrap, message, isError, autoHideMs) {
        if (!wrap) {
            return;
        }
        var panelCard = mountOverlayOnPanel(wrap);
        var overlay = getOverlayEl(wrap);
        var box = getFeedbackEl(wrap);
        if (!box || !overlay) {
            return;
        }
        if (feedbackTimer) {
            window.clearTimeout(feedbackTimer);
            feedbackTimer = null;
        }
        if (panelCard) {
            panelCard.classList.add('zerti-shop-panel--status-feedback');
        }
        overlay.hidden = false;
        overlay.setAttribute('aria-hidden', 'false');
        box.hidden = false;
        box.className =
            'zerti-shop-order-detail__feedback alert py-3 px-4 mb-0 text-center ' +
            (isError ? 'alert-danger' : 'alert-success');
        box.textContent = message;
        if (typeof autoHideMs === 'number' && autoHideMs > 0) {
            feedbackTimer = window.setTimeout(function () {
                hideFeedback(wrap);
                feedbackTimer = null;
            }, autoHideMs);
        }
    }

    function postShopOrder(op, orderId, extra) {
        var body = new window.FormData();
        body.append('action', action);
        body.append('nonce', nonce);
        body.append('op', op);
        body.append('order_id', String(orderId));
        if (extra) {
            Object.keys(extra).forEach(function (key) {
                body.append(key, extra[key]);
            });
        }
        return window.fetch(ajaxUrl, {
            method: 'POST',
            credentials: 'same-origin',
            body: body,
        }).then(parseJson);
    }

    function reloadShopOrderDetail(orderId) {
        var root = getAdminRoot();
        var slot = getShopSlot(root);
        var compNonce = cfg.componentNonce || comp.nonce || '';
        var compAction = cfg.componentAction || comp.action || 'zerti_load_component';
        var compAjax = comp.ajaxUrl || ajaxUrl;

        if (!slot || !(orderId > 0) || !compAjax || !compNonce) {
            return window.Promise.reject(new Error(i18n.reloadError || i18n.statusError));
        }

        slot.setAttribute('aria-busy', 'true');
        var body = new window.FormData();
        body.append('action', compAction);
        body.append('nonce', compNonce);
        body.append('slug', 'shop');
        body.append('partial', '1');
        body.append('shop_order_id', String(orderId));
        body.append('shop_order_view', 'detail');

        return window
            .fetch(compAjax, {
                method: 'POST',
                credentials: 'same-origin',
                body: body,
            })
            .then(parseJson)
            .then(function (data) {
                if (!data || !data.success || !data.data || typeof data.data.html !== 'string') {
                    var reloadMsg =
                        data && data.data && data.data.message
                            ? String(data.data.message)
                            : i18n.reloadError || i18n.statusError;
                    throw new Error(reloadMsg);
                }
                slot.innerHTML = data.data.html;
                slot.setAttribute('data-zerti-loaded', '1');
                return true;
            })
            .catch(function (err) {
                throw err;
            })
            .finally(function () {
                slot.removeAttribute('aria-busy');
            });
    }

    function setBusy(el, busy) {
        if (!el) {
            return;
        }
        if (busy) {
            el.setAttribute('disabled', 'disabled');
            el.setAttribute('aria-busy', 'true');
        } else {
            el.removeAttribute('disabled');
            el.removeAttribute('aria-busy');
        }
    }

    function invoiceAllowedForStatus(status) {
        var allowed = cfg.invoiceAllowedStatuses;
        if (!Array.isArray(allowed) || allowed.length === 0) {
            allowed = ['completed', 'processing', 'pending'];
        }
        return allowed.indexOf(status) !== -1;
    }

    function applyStatusUpdateToDetail(wrap, status) {
        if (!wrap || !status) {
            return;
        }
        var selectEl = wrap.querySelector('.zerti-shop-order-status-select');
        if (selectEl) {
            selectEl.value = status;
            selectEl.setAttribute('data-zerti-current-status', status);
        }
        var invoiceBtn = wrap.querySelector('.zerti-shop-order-invoice-btn[data-zerti-order-id]');
        if (!invoiceBtn) {
            return;
        }
        var canOpen = invoiceAllowedForStatus(status);
        invoiceBtn.classList.toggle('disabled', !canOpen);
        if (canOpen) {
            invoiceBtn.removeAttribute('aria-disabled');
            invoiceBtn.removeAttribute('tabindex');
            invoiceBtn.removeAttribute('title');
            return;
        }
        invoiceBtn.setAttribute('aria-disabled', 'true');
        invoiceBtn.setAttribute('tabindex', '-1');
        if (i18n.invoiceUnavailable) {
            invoiceBtn.setAttribute('title', i18n.invoiceUnavailable);
        }
    }

    function refreshNavBadgesInBackground() {
        if (typeof window.zertiRefreshNavBadges === 'function') {
            window.zertiRefreshNavBadges();
        } else if (typeof window.zertiRefreshProcessingOrdersBadge === 'function') {
            window.zertiRefreshProcessingOrdersBadge();
        }
    }

    function onStatusApply(btn) {
        var wrap = getDetailWrap(btn);
        var orderId = parseInt(btn.getAttribute('data-zerti-order-id') || '0', 10);
        var selectEl = wrap ? wrap.querySelector('.zerti-shop-order-status-select') : null;
        if (!wrap || !selectEl || !(orderId > 0)) {
            return;
        }

        var status = selectEl.value;
        var current = selectEl.getAttribute('data-zerti-current-status') || status;
        if (status === current) {
            showFeedback(wrap, i18n.statusUnchanged || '', false, feedbackDurationMs);
            return;
        }

        setBusy(btn, true);
        setBusy(selectEl, true);

        postShopOrder('update_status', orderId, { status: status })
            .then(function (data) {
                if (!data || !data.success) {
                    throw new Error((data && data.data && data.data.message) || i18n.statusError);
                }
                var payload = data.data || {};
                var newStatus = payload.status || status;
                var msg = payload.message || i18n.statusUpdated;
                applyStatusUpdateToDetail(wrap, newStatus);
                showFeedback(wrap, msg, false, feedbackDurationMs);
                refreshNavBadgesInBackground();
            })
            .catch(function (err) {
                selectEl.value = current;
                showFeedback(
                    wrap,
                    (err && err.message) || i18n.statusError || '',
                    true,
                    feedbackDurationMs
                );
            })
            .finally(function () {
                setBusy(btn, false);
                setBusy(selectEl, false);
            });
    }

    function onPrintClick(btn) {
        var wrap = getDetailWrap(btn);
        var orderId = parseInt(btn.getAttribute('data-zerti-order-id') || '0', 10);
        var doc = btn.getAttribute('data-zerti-doc') === 'shipping' ? 'shipping' : 'invoice';
        if (!wrap || !(orderId > 0)) {
            return;
        }

        setBusy(btn, true);
        postShopOrder('print_link', orderId, { doc: doc })
            .then(function (data) {
                if (!data || !data.success || !data.data || !data.data.url) {
                    throw new Error(i18n.printError);
                }
                window.open(data.data.url, '_blank', 'noopener,noreferrer');
            })
            .catch(function (err) {
                showFeedback(wrap, (err && err.message) || i18n.printError || '', true, feedbackDurationMs);
            })
            .finally(function () {
                setBusy(btn, false);
            });
    }

    function onNoteAdd(btn) {
        var wrap = getDetailWrap(btn);
        var orderId = parseInt(btn.getAttribute('data-zerti-order-id') || '0', 10);
        if (!wrap || !(orderId > 0)) {
            return;
        }

        var textarea = wrap.querySelector('.zerti-shop-order-note-input[data-zerti-order-id="' + String(orderId) + '"]');
        var notifyEl = wrap.querySelector('.zerti-shop-order-note-notify[data-zerti-order-id="' + String(orderId) + '"]');
        var note = textarea ? String(textarea.value || '').trim() : '';
        if (note === '') {
            showFeedback(wrap, i18n.noteRequired || '', true, feedbackDurationMs);
            if (textarea && typeof textarea.focus === 'function') {
                textarea.focus();
            }
            return;
        }

        setBusy(btn, true);
        if (textarea) {
            setBusy(textarea, true);
        }
        showFeedback(wrap, i18n.working || '', false, 0);

        postShopOrder('add_note', orderId, {
            note: note,
            notify_customer: notifyEl && notifyEl.checked ? '1' : '0',
        })
            .then(function (data) {
                if (!data || !data.success) {
                    throw new Error((data && data.data && data.data.message) || i18n.noteError);
                }
                var msg = (data.data && data.data.message) || i18n.noteAdded || '';
                return reloadShopOrderDetail(orderId).then(function () {
                    var newWrap = getDetailByOrderId(orderId) || wrap;
                    showFeedback(newWrap, msg, false, feedbackDurationMs);
                });
            })
            .catch(function (err) {
                showFeedback(wrap, (err && err.message) || i18n.noteError || '', true, feedbackDurationMs);
            })
            .finally(function () {
                setBusy(btn, false);
                if (textarea) {
                    setBusy(textarea, false);
                }
            });
    }

    function onEmailClick(btn) {
        var wrap = getDetailWrap(btn);
        var orderId = parseInt(btn.getAttribute('data-zerti-order-id') || '0', 10);
        if (!wrap || !(orderId > 0)) {
            return;
        }

        setBusy(btn, true);
        showFeedback(wrap, i18n.working || '', false, 0);

        postShopOrder('email_invoice', orderId, {})
            .then(function (data) {
                if (!data || !data.success) {
                    throw new Error((data && data.data && data.data.message) || i18n.emailError);
                }
                showFeedback(
                    wrap,
                    (data.data && data.data.message) || i18n.emailSent || '',
                    false,
                    feedbackDurationMs
                );
            })
            .catch(function (err) {
                showFeedback(wrap, (err && err.message) || i18n.emailError || '', true, feedbackDurationMs);
            })
            .finally(function () {
                setBusy(btn, false);
            });
    }

    document.addEventListener('click', function (e) {
        if (!getAdminRoot()) {
            return;
        }
        var applyBtn =
            e.target && e.target.closest
                ? e.target.closest('.zerti-shop-order-status-apply-btn[data-zerti-order-id]')
                : null;
        if (applyBtn) {
            e.preventDefault();
            onStatusApply(applyBtn);
            return;
        }
        var printBtn =
            e.target && e.target.closest ? e.target.closest('.zerti-shop-order-print-btn[data-zerti-order-id]') : null;
        if (printBtn) {
            e.preventDefault();
            onPrintClick(printBtn);
            return;
        }
        var emailBtn =
            e.target && e.target.closest
                ? e.target.closest('.zerti-shop-order-email-invoice-btn[data-zerti-order-id]')
                : null;
        if (emailBtn) {
            e.preventDefault();
            onEmailClick(emailBtn);
            return;
        }
        var noteBtn =
            e.target && e.target.closest
                ? e.target.closest('.zerti-shop-order-note-add-btn[data-zerti-order-id]')
                : null;
        if (noteBtn) {
            e.preventDefault();
            onNoteAdd(noteBtn);
        }
    });
})();
