(function () {
    'use strict';

    var config = window.SwairishXAdmin || {};

    function collectNotices() {
        var drawer = document.querySelector('[data-swx-notice-drawer]');
        if (!drawer) { return; }
        var notices = Array.prototype.filter.call(
            document.querySelectorAll('#wpbody-content > .notice, #wpbody-content > .updated, #wpbody-content > .error, .swairishx-admin .notice, .swairishx-admin .updated, .swairishx-admin .error'),
            function (notice) { return !notice.closest('[data-swx-notice-drawer]'); }
        );
        if (!notices.length) { return; }
        var details = drawer.querySelector('details');
        var summary;
        var content;
        if (!details) {
            details = document.createElement('details');
            summary = document.createElement('summary');
            content = document.createElement('div');
            summary.innerHTML = '<span>WordPress notices</span><strong>0</strong>';
            details.appendChild(summary);
            details.appendChild(content);
            drawer.appendChild(details);
        } else {
            summary = details.querySelector('summary');
            content = details.querySelector('div');
        }
        notices.forEach(function (notice) { content.appendChild(notice); });
        summary.querySelector('strong').textContent = content.querySelectorAll('.notice, .updated, .error').length;
    }

    function watchNotices() {
        var target = document.querySelector('#wpbody-content');
        if (!target || !window.MutationObserver) { return; }
        var timer;
        new MutationObserver(function () {
            window.clearTimeout(timer);
            timer = window.setTimeout(collectNotices, 50);
        }).observe(target, { childList: true, subtree: true });
    }

    function initCampaignFilters() {
        var rows = Array.prototype.slice.call(document.querySelectorAll('[data-swx-campaign-row]'));
        if (!rows.length) { return; }
        var search = document.querySelector('[data-swx-campaign-search]');
        var filters = Array.prototype.slice.call(document.querySelectorAll('[data-swx-campaign-filter]'));
        var empty = document.querySelector('[data-swx-campaign-empty]');
        var active = 'all';

        function apply() {
            var query = search ? search.value.trim().toLowerCase() : '';
            var visible = 0;
            rows.forEach(function (row) {
                var matchesState = 'all' === active || row.dataset.status === active;
                var matchesQuery = !query || (row.dataset.name || '').indexOf(query) !== -1;
                row.hidden = !(matchesState && matchesQuery);
                if (!row.hidden) { visible += 1; }
            });
            if (empty) { empty.hidden = visible !== 0; }
        }

        if (search) { search.addEventListener('input', apply); }
        filters.forEach(function (button) {
            button.addEventListener('click', function () {
                active = button.dataset.swxCampaignFilter;
                filters.forEach(function (item) { item.classList.toggle('is-active', item === button); });
                apply();
            });
        });
    }

    function initIntegrationFilters() {
        var cards = Array.prototype.slice.call(document.querySelectorAll('[data-swx-integration]'));
        if (!cards.length) { return; }
        var search = document.querySelector('[data-swx-integration-search]');
        var filters = Array.prototype.slice.call(document.querySelectorAll('[data-swx-integration-filter]'));
        var empty = document.querySelector('[data-swx-integration-empty]');
        var active = 'all';

        function apply() {
            var query = search ? search.value.trim().toLowerCase() : '';
            var visible = 0;
            cards.forEach(function (card) {
                var matchesState = 'all' === active || card.dataset.state === active;
                var matchesQuery = !query || (card.dataset.name || '').indexOf(query) !== -1;
                card.hidden = !(matchesState && matchesQuery);
                if (!card.hidden) { visible += 1; }
            });
            if (empty) { empty.hidden = visible !== 0; }
        }

        if (search) { search.addEventListener('input', apply); }
        filters.forEach(function (button) {
            button.addEventListener('click', function () {
                active = button.dataset.swxIntegrationFilter;
                filters.forEach(function (item) { item.classList.toggle('is-active', item === button); });
                apply();
            });
        });
    }

    function initCampaignActions() {
        document.querySelectorAll('[data-swx-delete]').forEach(function (link) {
            link.addEventListener('click', function (event) {
                if (!window.confirm(config.deleteConfirm || 'Move this campaign to the trash?')) {
                    event.preventDefault();
                }
            });
        });

        document.addEventListener('click', function (event) {
            document.querySelectorAll('.swx-row-actions details[open]').forEach(function (details) {
                if (!details.contains(event.target)) { details.removeAttribute('open'); }
            });
        });
    }

    function initBuilder() {
        var builder = document.querySelector('[data-swx-builder]');
        if (!builder) { return; }
        var tabs = Array.prototype.slice.call(builder.querySelectorAll('[data-swx-tab]'));
        var panels = Array.prototype.slice.call(builder.querySelectorAll('[data-swx-panel]'));
        var back = builder.querySelector('[data-swx-back]');
        var next = builder.querySelector('[data-swx-next]');
        var finalActions = Array.prototype.slice.call(builder.querySelectorAll('.is-final-action'));
        var progress = builder.querySelector('[data-swx-progress]');
        var stepStatus = builder.querySelector('[data-swx-step-status]');
        var preview = builder.querySelector('[data-swx-preview]');
        var previewStage = builder.querySelector('[data-swx-preview-stage]');
        var current = 0;
        var dirty = false;
        var submitting = false;

        function visiblePanel() { return panels[current]; }

        function showStep(index) {
            current = Math.max(0, Math.min(panels.length - 1, index));
            tabs.forEach(function (tab, tabIndex) {
                tab.classList.toggle('is-active', tabIndex === current);
                tab.classList.toggle('is-complete', tabIndex < current);
                tab.setAttribute('aria-selected', tabIndex === current ? 'true' : 'false');
            });
            panels.forEach(function (panel, panelIndex) {
                panel.classList.toggle('is-active', panelIndex === current);
                panel.hidden = panelIndex !== current;
            });
            if (back) { back.disabled = current === 0; }
            if (next) { next.hidden = current === panels.length - 1; }
            finalActions.forEach(function (button) { button.hidden = current !== panels.length - 1; });
            if (progress) { progress.style.width = ((current + 1) / panels.length * 100) + '%'; }
            if (stepStatus) { stepStatus.textContent = (config.stepLabel || 'Step') + ' ' + (current + 1) + ' of ' + panels.length; }
        }

        function validateStep() {
            var name = builder.querySelector('[name="name"]');
            if (name && !name.value.trim()) {
                name.setCustomValidity('Add a campaign name.');
                name.reportValidity();
                name.setCustomValidity('');
                return false;
            }
            var required = Array.prototype.slice.call(visiblePanel().querySelectorAll('[required]'));
            return required.every(function (field) { return field.reportValidity(); });
        }

        tabs.forEach(function (tab, index) {
            tab.addEventListener('click', function () {
                if (index <= current || validateStep()) { showStep(index); }
            });
        });
        if (back) { back.addEventListener('click', function () { showStep(current - 1); }); }
        if (next) { next.addEventListener('click', function () { if (validateStep()) { showStep(current + 1); } }); }

        function input(name) { return builder.querySelector('[name="' + name + '"]'); }
        function checked(name) { return builder.querySelector('[name="' + name + '"]:checked'); }
        function output(selector) { return preview ? preview.querySelector(selector) : null; }

        function bindText(name, selector, fallback) {
            var field = input(name);
            var target = output(selector);
            if (!field || !target) { return; }
            var update = function () { target.textContent = field.value.trim() || fallback; };
            field.addEventListener('input', update);
            update();
        }

        bindText('headline', '[data-swx-preview-headline]', 'Weekend offer');
        bindText('message', '[data-swx-preview-message]', 'Make your announcement clear and useful.');
        bindText('cta_label', '[data-swx-preview-cta]', 'View offer');

        var couponCode = input('coupon_code');
        var previewCoupon = output('[data-swx-preview-coupon]');
        var countdownToggle = input('show_countdown');
        var previewCountdown = output('[data-swx-preview-countdown]');
        function updateConversionHelpers() {
            if (previewCoupon) {
                previewCoupon.textContent = couponCode ? couponCode.value.trim() : '';
                previewCoupon.hidden = !previewCoupon.textContent;
            }
            if (previewCountdown) { previewCountdown.hidden = !(countdownToggle && countdownToggle.checked); }
        }
        [couponCode, countdownToggle].forEach(function (field) {
            if (!field) { return; }
            field.addEventListener('input', updateConversionHelpers);
            field.addEventListener('change', updateConversionHelpers);
        });

        var imageUrl = input('image_url');
        var imageAlt = input('image_alt');
        var imagePosition = input('image_position');
        var mediaThumb = builder.querySelector('[data-swx-media-thumb]');
        var mediaArt = builder.querySelector('[data-swx-media-art]');
        var removeImage = builder.querySelector('[data-swx-remove-image]');

        function updateImage() {
            var url = imageUrl ? imageUrl.value.trim() : '';
            var previewImage = output('[data-swx-preview-image]');
            var previewMark = output('.swx-preview-notice__mark');
            var previewNotice = output('[data-swx-preview-notice]');
            var position = imagePosition ? imagePosition.value : 'start';
            if (mediaThumb) {
                mediaThumb.src = url;
                mediaThumb.hidden = !url;
            }
            if (mediaArt) { mediaArt.classList.toggle('is-empty', !url); }
            if (removeImage) { removeImage.hidden = !url; }
            if (previewImage) {
                previewImage.src = url;
                previewImage.alt = imageAlt ? imageAlt.value.trim() : '';
                previewImage.hidden = !url;
                previewImage.classList.toggle('is-start', 'start' === position);
                previewImage.classList.toggle('is-end', 'end' === position);
            }
            if (previewMark) { previewMark.hidden = Boolean(url); }
            if (previewNotice) {
                previewNotice.classList.toggle('has-image', Boolean(url));
                previewNotice.classList.toggle('has-image-end', Boolean(url) && 'end' === position);
            }
        }

        [imageUrl, imageAlt, imagePosition].forEach(function (field) {
            if (!field) { return; }
            field.addEventListener('input', updateImage);
            field.addEventListener('change', updateImage);
        });

        var chooseImage = builder.querySelector('[data-swx-choose-image]');
        var mediaFrame;
        if (chooseImage) {
            chooseImage.addEventListener('click', function () {
                if (!window.wp || !window.wp.media) { return; }
                if (!mediaFrame) {
                    mediaFrame = window.wp.media({
                        title: config.chooseImage || 'Choose offer image',
                        button: { text: config.useImage || 'Use this image' },
                        library: { type: 'image' },
                        multiple: false
                    });
                    mediaFrame.on('select', function () {
                        var attachment = mediaFrame.state().get('selection').first().toJSON();
                        if (imageUrl) { imageUrl.value = attachment.url || ''; }
                        if (imageAlt && !imageAlt.value.trim()) { imageAlt.value = attachment.alt || attachment.title || ''; }
                        updateImage();
                        dirty = true;
                    });
                }
                mediaFrame.open();
            });
        }
        if (removeImage) {
            removeImage.addEventListener('click', function () {
                if (imageUrl) { imageUrl.value = ''; }
                updateImage();
                dirty = true;
            });
        }

        function updatePreview() {
            if (!preview) { return; }
            var notice = output('[data-swx-preview-notice]');
            var typeField = checked('type');
            var typeCard = typeField ? typeField.closest('.swx-type-card') : null;
            var typeLabel = typeCard ? typeCard.querySelector('strong').textContent : 'Notification';
            var positionField = input('position');
            var position = positionField ? positionField.value : 'top';
            var background = input('background');
            var foreground = input('foreground');
            var accent = input('accent');
            var close = input('close_button');
            var cta = output('[data-swx-preview-cta]');
            var closeMark = output('.swx-preview-notice__close');
            var typeOutput = builder.querySelector('[data-swx-preview-type]');
            var positionOutput = builder.querySelector('[data-swx-preview-position]');
            var isBar = typeField && ['notification_bar', 'discount_alert', 'offer_announcement', 'cookie_notice'].indexOf(typeField.value) !== -1;

            notice.classList.toggle('is-toast', !isBar);
            notice.classList.toggle('is-bottom', 'bottom' === position && isBar);
            notice.style.backgroundColor = background ? background.value : '#10261f';
            notice.style.color = foreground ? foreground.value : '#f5fbf7';
            if (cta && accent) { cta.style.backgroundColor = accent.value; }
            if (closeMark) { closeMark.hidden = close ? !close.checked : false; }
            if (typeOutput) { typeOutput.textContent = typeLabel; }
            if (positionOutput) { positionOutput.textContent = position.charAt(0).toUpperCase() + position.slice(1); }
        }

        builder.querySelectorAll('[name="type"], [name="position"], [name="background"], [name="foreground"], [name="accent"], [name="close_button"]').forEach(function (field) {
            field.addEventListener('input', updatePreview);
            field.addEventListener('change', updatePreview);
        });

        builder.querySelectorAll('input[type="color"]').forEach(function (field) {
            var value = builder.querySelector('[data-swx-color-value="' + field.name + '"]');
            var update = function () { if (value) { value.textContent = field.value.toUpperCase(); } };
            field.addEventListener('input', update);
            update();
        });

        var integration = input('integration');
        var sourceIdentifier = builder.querySelector('[data-swx-source-identifier]');
        function updateSourceField() {
            if (!integration || !sourceIdentifier) { return; }
            sourceIdentifier.hidden = integration.value !== 'wordpress_org';
        }
        if (integration) { integration.addEventListener('change', updateSourceField); }
        updateSourceField();

        var reappearance = input('reappearance');
        var dismissHours = builder.querySelector('[data-swx-dismiss-hours]');
        function updateReappearance() {
            if (reappearance && dismissHours) { dismissHours.hidden = 'after_hours' !== reappearance.value; }
        }
        if (reappearance) { reappearance.addEventListener('change', updateReappearance); }
        updateReappearance();

        var presetButtons = Array.prototype.slice.call(builder.querySelectorAll('[data-swx-offer-preset]'));
        function applyPreset(button) {
            var preset;
            try {
                preset = JSON.parse(button.dataset.swxPresetConfig || '{}');
            } catch (error) {
                return;
            }
            Object.keys(preset).forEach(function (name) {
                var fields = Array.prototype.slice.call(builder.querySelectorAll('[name="' + name + '"]'));
                if (!fields.length) { return; }
                var field = fields[0];
                if ('radio' === field.type) {
                    field = fields.filter(function (candidate) { return candidate.value === String(preset[name]); })[0];
                    if (!field) { return; }
                    field.checked = true;
                } else if ('checkbox' === field.type) {
                    field.checked = Boolean(preset[name]);
                } else {
                    field.value = preset[name];
                }
                field.dispatchEvent(new Event('input', { bubbles: true }));
                field.dispatchEvent(new Event('change', { bubbles: true }));
            });
            presetButtons.forEach(function (candidate) {
                var selected = candidate === button;
                candidate.classList.toggle('is-selected', selected);
                candidate.setAttribute('aria-pressed', selected ? 'true' : 'false');
                var label = candidate.querySelector('.swx-offer-preset__meta em span');
                if (label) { label.textContent = selected ? (config.presetApplied || 'Applied') : (config.usePreset || 'Use preset'); }
            });
            updateSourceField();
            updatePreview();
        }
        presetButtons.forEach(function (button) {
            button.addEventListener('click', function () { applyPreset(button); });
        });

        builder.querySelectorAll('[data-swx-device]').forEach(function (button) {
            button.addEventListener('click', function () {
                builder.querySelectorAll('[data-swx-device]').forEach(function (item) { item.classList.toggle('is-active', item === button); });
                if (previewStage) { previewStage.classList.toggle('is-mobile', button.dataset.swxDevice === 'mobile'); }
            });
        });

        builder.addEventListener('input', function () { dirty = true; });
        builder.addEventListener('change', function () { dirty = true; });
        builder.addEventListener('submit', function () { submitting = true; });
        window.addEventListener('beforeunload', function (event) {
            if (!dirty || submitting) { return; }
            event.preventDefault();
            event.returnValue = '';
        });

        updatePreview();
        updateImage();
        updateConversionHelpers();
        showStep(0);
    }

    collectNotices();
    watchNotices();
    window.setTimeout(collectNotices, 250);
    window.setTimeout(collectNotices, 1200);
    initCampaignFilters();
    initIntegrationFilters();
    initCampaignActions();
    initBuilder();
}());
