(function () {
    'use strict';

    function initStylePreview() {
        var frame = document.getElementById('vstrb-style-preview-frame');
        var form = frame && frame.closest('form');
        if (!frame || !form) return;

        var labels = frame.dataset;
        function escapeHtml(text) {
            return String(text || '').replace(/[&<>"']/g, function (character) {
                return {
                    '&': '&amp;',
                    '<': '&lt;',
                    '>': '&gt;',
                    '"': '&quot;',
                    "'": '&#039;'
                }[character];
            });
        }

        var days = [
            ['1', labels.labelAvailable, '120 EUR', ''],
            ['2', labels.labelAvailable, '110 EUR', 'disc'],
            ['3', labels.labelSelected, '105 EUR', 'sel'],
            ['4', labels.labelSelected, '105 EUR', 'inrange'],
            ['5', labels.labelOccupied, '', 'occ'],
            ['6', labels.labelOccupied, '', 'occ'],
            ['7', labels.labelAvailable, '135 EUR', 'surch'],
            ['8', labels.labelAvailable, '120 EUR', ''],
            ['9', labels.labelAvailable, '120 EUR', ''],
            ['10', labels.labelOccupied, '', 'vstrb-checkin'],
            ['11', labels.labelOccupied, '', 'occ'],
            ['12', labels.labelAvailable, '115 EUR', 'vstrb-checkout'],
            ['13', labels.labelAvailable, '115 EUR', ''],
            ['14', labels.labelAvailable, '115 EUR', '']
        ];
        var dayHtml = days.map(function (day) {
            var priceClass = day[3] === 'disc' || day[3] === 'surch' ? ' ' + day[3] : '';
            var stateClass = day[3] === 'disc' || day[3] === 'surch' ? '' : ' ' + day[3];
            return '<div class="vstrb-cal-day' + stateClass + '">' +
                '<div class="top-row"><span class="d">' + day[0] + '</span><span class="tag">' + escapeHtml(day[1]) + '</span></div>' +
                (day[2] ? '<span class="price' + priceClass + '">' + day[2] + '</span>' : '') +
                '</div>';
        }).join('');

        var doc = frame.contentDocument;
        doc.open();
        doc.write('<!doctype html><html><head><meta charset="utf-8">' +
            '<meta name="viewport" content="width=device-width,initial-scale=1">' +
            '<link rel="stylesheet" href="' + frame.dataset.themeCss + '">' +
            '<link rel="stylesheet" href="' + frame.dataset.frontendCss + '">' +
            '<link id="vstrb-preview-custom-css" rel="stylesheet" href="">' +
            '<style>body{margin:0;padding:24px;background:#f6f7f7;font-family:Arial,sans-serif}' +
            '.vstrb-preview-shell{margin:0 auto}.vstrb-booking{box-sizing:border-box}' +
            '.vstrb-cal-h{display:block}.vstrb-preview-form{margin-top:18px;padding-top:18px;border-top:1px solid #e5e7eb}' +
            '.vstrb-preview-form .vstrb-btn-primary{width:100%}</style>' +
            '<style id="vstrb-preview-live-css"></style></head><body>' +
            '<div class="vstrb vstrb-preview-shell vstrb-booking">' +
            '<span class="vstrb-cal-h">' + escapeHtml(labels.labelCalendar) + '</span>' +
            '<div class="vstrb vstrb-calendar">' +
            '<div class="vstrb-cal-head"><button class="vstrb-btn" type="button">&lsaquo;</button>' +
            '<div class="vstrb-cal-title">June 2026</div><button class="vstrb-btn" type="button">&rsaquo;</button></div>' +
            '<div class="vstrb-cal-grid"><div class="vstrb-cal-wd">Mo</div><div class="vstrb-cal-wd">Tu</div>' +
            '<div class="vstrb-cal-wd">We</div><div class="vstrb-cal-wd">Th</div><div class="vstrb-cal-wd">Fr</div>' +
            '<div class="vstrb-cal-wd">Sa</div><div class="vstrb-cal-wd">Su</div>' + dayHtml + '</div>' +
            '<div class="vstrb-cal-legend"><span class="vstrb-pill vstrb-pill-free">' + escapeHtml(labels.labelAvailable) + '</span>' +
            '<span class="vstrb-pill vstrb-pill-occ">' + escapeHtml(labels.labelOccupied) + '</span>' +
            '<span class="vstrb-pill vstrb-pill-sel">' + escapeHtml(labels.labelSelected) + '</span>' +
            '<span class="vstrb-price-mode-label">' + escapeHtml(labels.labelPrice) + '</span></div></div>' +
            '<div class="vstrb-preview-form"><button type="button" class="vstrb-btn vstrb-btn-primary">' +
            escapeHtml(labels.labelButton) + '</button></div></div></body></html>');
        doc.close();

        function field(name) {
            return form.elements.namedItem(name);
        }

        function value(name, fallback) {
            var el = field(name);
            return el && el.value !== '' ? el.value : fallback;
        }

        function enabled(name) {
            var el = field('vis_' + name + '_en');
            return !!(el && el.checked);
        }

        function cssColor(name, fallback) {
            var color = value('vis_' + name, fallback);
            return /^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(color) ? color : fallback;
        }

        function cssNumber(name, fallback) {
            var number = parseInt(value('vis_' + name, fallback), 10);
            return Number.isFinite(number) ? number : fallback;
        }

        function updatePreview() {
            var css = [];
            var liveStyle = doc.getElementById('vstrb-preview-live-css');
            var heading = doc.querySelector('.vstrb-cal-h');
            var button = doc.querySelector('.vstrb-btn-primary');
            var customCss = doc.getElementById('vstrb-preview-custom-css');
            var checkedMode = form.querySelector('[name="vstrb_styling_mode"]:checked');
            var customUrl = value('vstrb_custom_css_url', '');

            if (checkedMode && checkedMode.value === 'css' && /^https?:\/\//i.test(customUrl)) {
                customCss.href = customUrl;
            } else {
                customCss.removeAttribute('href');
            }

            if (enabled('font_family')) css.push('.vstrb{font-family:' + value('vis_font_family', 'inherit') + '!important}');
            if (enabled('max_width')) css.push('.vstrb-preview-shell{max-width:' + cssNumber('max_width', 400) + value('vis_max_width_unit', 'px') + '!important}');
            if (enabled('font_size')) css.push('.vstrb{font-size:' + cssNumber('font_size', 14) + 'px!important}');
            if (enabled('form_bg')) css.push('.vstrb-booking{background-color:' + cssColor('form_bg', '#ffffff') + '!important;border-radius:8px;padding:15px}');
            if (enabled('cal_bg')) css.push('.vstrb-calendar,.vstrb-cal-grid{background-color:' + cssColor('cal_bg', '#f0f0f0') + '!important}');
            if (enabled('cal_text')) css.push('.vstrb-calendar{color:' + cssColor('cal_text', '#333333') + '!important}');

            var active = cssColor('cal_active', '#007cba');
            var occupied = cssColor('cal_occupied', '#ffdddd');
            var selectedText = cssColor('cal_sel_text', '#ffffff');
            var occupiedText = cssColor('cal_occ_text', '#ffffff');
            if (enabled('cal_active')) {
                css.push('.vstrb-pill-sel,.vstrb-cal-day.sel,.vstrb-cal-day.inrange{background-color:' + active + '!important}');
                css.push('.vstrb-cal-day.sel,.vstrb-cal-day.sel .d,.vstrb-cal-day.inrange,.vstrb-cal-day.inrange .d{color:' + selectedText + '!important}');
            }
            if (enabled('cal_occupied')) {
                css.push('.vstrb-calendar{--vstrb-current-occupied:' + occupied + '}');
                css.push('.vstrb-pill-occ,.vstrb-cal-day.occ{background-color:' + occupied + '!important}');
                css.push('.vstrb-cal-day.occ,.vstrb-cal-day.occ .d,.vstrb-cal-day.occ .tag{color:' + occupiedText + '!important}');
                css.push('.vstrb-cal-day.vstrb-checkin{background:linear-gradient(135deg,#fff 50%,' + occupied + ' 50%)!important}');
                css.push('.vstrb-cal-day.vstrb-checkout{background:linear-gradient(135deg,' + occupied + ' 50%,#fff 50%)!important}');
            }

            var shadows = [];
            if (enabled('cal_outline')) {
                var outlineSize = cssNumber('cal_outline_size', 1);
                var outlineColor = cssColor('cal_outline', '#000000');
                shadows.push('-' + outlineSize + 'px -' + outlineSize + 'px 0 ' + outlineColor);
                shadows.push(outlineSize + 'px -' + outlineSize + 'px 0 ' + outlineColor);
                shadows.push('-' + outlineSize + 'px ' + outlineSize + 'px 0 ' + outlineColor);
                shadows.push(outlineSize + 'px ' + outlineSize + 'px 0 ' + outlineColor);
            }
            if (enabled('bs_color')) {
                shadows.push(cssNumber('bs_x', 0) + 'px ' + cssNumber('bs_y', 4) + 'px ' +
                    cssNumber('bs_blur', 10) + 'px ' + cssColor('bs_color', '#000000'));
            }
            if (shadows.length) css.push('.vstrb-cal-day{text-shadow:' + shadows.join(',') + '!important}');

            var dateCss = [];
            if (enabled('cal_date_size')) dateCss.push('font-size:' + cssNumber('cal_date_size', 14) + 'px!important');
            if (enabled('cal_date_color')) dateCss.push('color:' + cssColor('cal_date_color', '#333333') + '!important');
            if (enabled('cal_date_weight')) dateCss.push('font-weight:bold!important');
            if (dateCss.length) css.push('.vstrb-cal-day .d{' + dateCss.join(';') + '}');

            var labelCss = [];
            if (enabled('cal_lbl_size')) labelCss.push('font-size:' + cssNumber('cal_lbl_size', 12) + 'px!important');
            if (enabled('cal_lbl_color')) labelCss.push('color:' + cssColor('cal_lbl_color', '#666666') + '!important');
            if (enabled('cal_lbl_weight')) labelCss.push('font-weight:bold!important');
            if (labelCss.length) css.push('.vstrb-cal-day .tag,.vstrb-cal-legend .vstrb-pill{' + labelCss.join(';') + '}');

            heading.textContent = value('vis_cal_h_text', labels.labelCalendar);
            heading.style.display = enabled('cal_h_text') ? '' : 'none';
            var headingCss = [];
            if (enabled('cal_h_size')) headingCss.push('font-size:' + cssNumber('cal_h_size', 24) + 'px!important');
            if (enabled('cal_h_color')) headingCss.push('color:' + cssColor('cal_h_color', '#333333') + '!important');
            if (enabled('cal_h_weight')) headingCss.push('font-weight:bold!important');
            if (enabled('cal_h_align')) headingCss.push('text-align:' + value('vis_cal_h_align', 'left') + '!important');
            if (headingCss.length) css.push('.vstrb-cal-h{' + headingCss.join(';') + ';margin-bottom:15px}');

            button.textContent = enabled('btn_text') ? value('vis_btn_text', labels.labelButton) : labels.labelButton;
            var buttonCss = [];
            if (enabled('btn_bg')) buttonCss.push('background-color:' + cssColor('btn_bg', '#007cba') + '!important;border-color:' + cssColor('btn_bg', '#007cba') + '!important');
            if (enabled('btn_color')) buttonCss.push('color:' + cssColor('btn_color', '#ffffff') + '!important');
            if (enabled('btn_size')) buttonCss.push('font-size:' + cssNumber('btn_size', 16) + 'px!important');
            if (enabled('btn_radius')) buttonCss.push('border-radius:' + cssNumber('btn_radius', 4) + 'px!important');
            if (enabled('btn_font')) buttonCss.push('font-family:' + value('vis_btn_font', 'inherit') + '!important');
            if (enabled('btn_weight')) buttonCss.push('font-weight:bold!important');
            if (buttonCss.length) css.push('.vstrb-btn-primary{' + buttonCss.join(';') + '}');

            if (enabled('cal_price_bg')) css.push('.price:not(.disc):not(.surch){background:' + cssColor('cal_price_bg', '#111111') + '!important}');
            if (enabled('cal_price_color')) css.push('.price:not(.disc):not(.surch){color:' + cssColor('cal_price_color', '#ffffff') + '!important}');
            if (enabled('cal_price_size')) css.push('.price:not(.disc):not(.surch){font-size:' + cssNumber('cal_price_size', 8) + 'px!important}');
            if (enabled('cal_disc_color')) css.push('.price.disc{background:' + cssColor('cal_disc_color', '#16a34a') + '!important}');
            if (enabled('cal_surch_color')) css.push('.price.surch{background:' + cssColor('cal_surch_color', '#dc2626') + '!important}');
            if (enabled('cal_price_lbl_color')) css.push('.vstrb-price-mode-label{color:' + cssColor('cal_price_lbl_color', '#555555') + '!important}');
            if (enabled('cal_price_lbl_size')) css.push('.vstrb-price-mode-label{font-size:' + cssNumber('cal_price_lbl_size', 11) + 'px!important}');
            if (enabled('cal_price_lbl_weight')) css.push('.vstrb-price-mode-label{font-weight:bold!important}');
            if (enabled('cal_price_lbl_italic')) css.push('.vstrb-price-mode-label{font-style:italic!important}');

            liveStyle.textContent = css.join('\n');
        }

        var timer;
        function queueUpdate() {
            window.clearTimeout(timer);
            timer = window.setTimeout(updatePreview, 40);
        }

        form.addEventListener('input', queueUpdate);
        form.addEventListener('change', queueUpdate);
        document.querySelectorAll('[data-vstrb-preview-width]').forEach(function (button) {
            button.addEventListener('click', function () {
                document.querySelectorAll('[data-vstrb-preview-width]').forEach(function (item) {
                    item.classList.toggle('is-active', item === button);
                });
                frame.classList.toggle('is-mobile', button.dataset.vstrbPreviewWidth === 'mobile');
            });
        });
        updatePreview();
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initStylePreview);
    } else {
        initStylePreview();
    }
})();

(function () {
    'use strict';

    function initPageWizard() {
        var form = document.querySelector('.vstrb-page-wizard');
        if (!form) return;
        var steps = Array.prototype.slice.call(form.querySelectorAll('[data-vstrb-page-step]'));
        var progress = Array.prototype.slice.call(form.querySelectorAll('[data-vstrb-page-progress]'));
        var previous = form.querySelector('[data-vstrb-page-prev]');
        var next = form.querySelector('[data-vstrb-page-next]');
        var create = form.querySelector('[data-vstrb-page-create]');
        var unit = form.querySelector('[data-vstrb-page-unit]');
        var title = form.querySelector('[data-vstrb-page-title]');
        var current = 0;
        var suggestedTitle = '';

        function showStep(index) {
            current = Math.max(0, Math.min(index, steps.length - 1));
            steps.forEach(function (step, stepIndex) { step.hidden = stepIndex !== current; });
            progress.forEach(function (item, stepIndex) {
                item.classList.toggle('is-active', stepIndex === current);
                item.classList.toggle('is-complete', stepIndex < current);
            });
            previous.hidden = current === 0;
            next.hidden = current === steps.length - 1;
            create.hidden = current !== steps.length - 1;
        }

        function validateStep() {
            var invalid = steps[current].querySelector(':invalid');
            if (!invalid) return true;
            invalid.reportValidity();
            invalid.focus();
            return false;
        }

        function suggestTitle() {
            if (!unit || !title) return;
            var option = unit.options[unit.selectedIndex];
            var value = option ? (option.dataset.title || '') : '';
            if (!title.value || title.value === suggestedTitle) title.value = value;
            suggestedTitle = value;
        }

        previous.addEventListener('click', function () { showStep(current - 1); });
        next.addEventListener('click', function () { if (validateStep()) showStep(current + 1); });
        if (unit) unit.addEventListener('change', suggestTitle);
        form.addEventListener('submit', function (event) {
            if (validateStep()) return;
            event.preventDefault();
        });
        suggestTitle();
        showStep(0);
    }

    if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', initPageWizard);
    else initPageWizard();
})();

(function () {
    'use strict';
    function initNotificationBuilder() {
        var builder = document.getElementById('vstrb-notification-builder');
        if (!builder) return;

        function reindexNames(root, oldType, newType, oldRecipient, newRecipient) {
            root.querySelectorAll('[name]').forEach(function (field) {
                var name = field.name.replace('vstrb_notification_types[' + oldType + ']', 'vstrb_notification_types[' + newType + ']');
                if (oldRecipient !== null) name = name.replace('[recipients][' + oldRecipient + ']', '[recipients][' + newRecipient + ']');
                field.name = name;
            });
        }

        function resetRecipient(row) {
            row.querySelectorAll('input').forEach(function (field) {
                if (field.type === 'number') field.value = field.name.indexOf('escalate_after_hours') !== -1 ? '24' : '1';
                else field.value = '';
            });
            row.querySelectorAll('option').forEach(function (option) { option.selected = ['unit', 'dates', 'guests'].indexOf(option.value) !== -1; });
        }

		function resetType(type) {
			type.querySelector('input[name$="[label]"]').value = '';
			type.querySelector('input[type="color"]').value = '#2271b1';
			type.style.setProperty('--vstrb-task-color', '#2271b1');
			type.querySelector('input[type="checkbox"]').checked = false;
			var rows = type.querySelectorAll('[data-vstrb-recipient]');
			rows.forEach(function (row, index) { if (index > 0) row.remove(); else resetRecipient(row); });
		}

        builder.addEventListener('click', function (event) {
            var button = event.target.closest('button');
            if (!button) return;
			if (button.matches('[data-vstrb-move-up]')) {
				var movingUp = button.closest('[data-vstrb-recipient]');
				if (movingUp.previousElementSibling) movingUp.parentNode.insertBefore(movingUp, movingUp.previousElementSibling);
			} else if (button.matches('[data-vstrb-move-down]')) {
				var movingDown = button.closest('[data-vstrb-recipient]');
				if (movingDown.nextElementSibling) movingDown.parentNode.insertBefore(movingDown.nextElementSibling, movingDown);
			} else if (button.matches('[data-vstrb-remove-recipient]')) {
				var recipient = button.closest('[data-vstrb-recipient]');
				var recipients = recipient.closest('[data-vstrb-recipients]');
				if (recipients.querySelectorAll('[data-vstrb-recipient]').length === 1) resetRecipient(recipient);
				else recipient.remove();
            } else if (button.matches('[data-vstrb-remove-type]')) {
				var currentType = button.closest('[data-vstrb-type]');
				if (builder.querySelectorAll('[data-vstrb-type]').length === 1) resetType(currentType);
				else currentType.remove();
            } else if (button.matches('[data-vstrb-add-recipient]')) {
                var type = button.closest('[data-vstrb-type]');
                var list = type.querySelector('[data-vstrb-recipients]');
                var source = list.querySelector('[data-vstrb-recipient]');
                if (!source) return;
                var row = source.cloneNode(true);
                var oldType = type.dataset.typeIndex;
                var oldRecipient = (source.querySelector('[name]') || {}).name.match(/\[recipients\]\[(\d+)\]/)[1];
                var next = parseInt(list.dataset.nextRecipient || '0', 10);
                reindexNames(row, oldType, oldType, oldRecipient, next);
                resetRecipient(row);
                list.dataset.nextRecipient = String(next + 1);
                list.appendChild(row);
            } else if (button.matches('[data-vstrb-add-type]')) {
                var sourceType = builder.querySelector('[data-vstrb-type]');
                if (!sourceType) return;
                var type = sourceType.cloneNode(true);
                var oldType = sourceType.dataset.typeIndex;
                var nextType = parseInt(builder.dataset.nextType || '0', 10);
                reindexNames(type, oldType, nextType, null, null);
                type.dataset.typeIndex = String(nextType);
                type.querySelectorAll('[data-vstrb-recipient]').forEach(function (row, index) {
                    if (index > 0) row.remove(); else { resetRecipient(row); reindexNames(row, nextType, nextType, 0, 0); }
                });
                type.querySelector('input[type="hidden"]').value = 'task-' + (nextType + 1);
				resetType(type);
                type.querySelector('[data-vstrb-recipients]').dataset.nextRecipient = '1';
                builder.dataset.nextType = String(nextType + 1);
                builder.querySelector('[data-vstrb-types]').appendChild(type);
            }
        });
        builder.addEventListener('input', function (event) {
            if (event.target.type === 'color') event.target.closest('[data-vstrb-type]').style.setProperty('--vstrb-task-color', event.target.value);
        });
		builder.addEventListener('change', function (event) {
			if (event.target.matches('select[name$="[event]"]')) {
				var type = event.target.closest('[data-vstrb-type]');
				var checkbox = type.querySelector('input[name$="[require_confirmation]"]');
				var scheduled = event.target.value === 'arrival' || event.target.value === 'departure';
				checkbox.disabled = !scheduled;
				if (!scheduled) checkbox.checked = false;
			}
		});
		builder.querySelectorAll('select[name$="[event]"]').forEach(function (select) {
			select.dispatchEvent(new Event('change', { bubbles: true }));
		});
    }
    if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', initNotificationBuilder);
    else initNotificationBuilder();
})();

(function () {
    'use strict';

    function initApartmentWizardLink() {
        var link = document.getElementById('vstrb-add-with-wizard');
        var regularButton = document.querySelector('.wrap .page-title-action');
        if (!link || !regularButton || !regularButton.parentNode) return;
        regularButton.replaceWith(link);
        link.hidden = false;
    }

    function initApartmentWizard() {
        var basicBox = document.getElementById('vstrb_unit_basic');
        if (!basicBox) return;
		var basicInside = basicBox.querySelector('.inside');
		var staySection = basicBox.querySelector('[data-vstrb-wizard-section="stay"]');
		var availabilitySection = basicBox.querySelector('[data-vstrb-wizard-section="availability"]');
		if (basicInside && staySection && availabilitySection) {
			basicInside.insertBefore(staySection, availabilitySection);
		}

        var launch = basicBox.querySelector('.vstrb-unit-wizard-launch');
        var wizard = basicBox.querySelector('.vstrb-unit-wizard');
        var actions = basicBox.querySelector('.vstrb-unit-wizard__actions');
        var sections = Array.prototype.slice.call(basicBox.querySelectorAll('[data-vstrb-wizard-section]'));
        var stepButtons = Array.prototype.slice.call(basicBox.querySelectorAll('[data-vstrb-wizard-go]'));
        var advancedBox = document.getElementById('vstrb_unit_advanced');
        var wizardName = document.getElementById('vstrb-wizard-apartment-name');
        var wizardComplete = basicBox.querySelector('[data-vstrb-wizard-complete]');
        if (!launch || !wizard || !actions || !sections.length || !stepButtons.length) return;

        var stepKeys = stepButtons.map(function (button) { return button.dataset.vstrbWizardGo; });
        var currentStep = 0;
        var wizardValidationPassed = false;
        var advancedDisplay = advancedBox ? advancedBox.style.display : '';
        var advancedWasClosed = advancedBox ? advancedBox.classList.contains('closed') : false;

        function editorTitle() {
            if (wizardName) return wizardName.value;
            var classicTitle = document.getElementById('title');
            if (classicTitle) return classicTitle.value;
            if (window.wp && window.wp.data && window.wp.data.select('core/editor')) {
                return window.wp.data.select('core/editor').getEditedPostAttribute('title') || '';
            }
            return '';
        }

        function updateEditorTitle(value) {
            if (wizardName && wizardName.value !== value) wizardName.value = value;
            var classicTitle = document.getElementById('title');
            if (classicTitle) {
                classicTitle.value = value;
                classicTitle.dispatchEvent(new Event('input', { bubbles: true }));
                classicTitle.dispatchEvent(new Event('change', { bubbles: true }));
            } else if (window.wp && window.wp.data && window.wp.data.dispatch('core/editor')) {
                window.wp.data.dispatch('core/editor').editPost({ title: value });
            }
        }

        function updatePricingMode() {
            var modeSelect = basicBox.querySelector('[name="_vstrb_price_mode"]');
            if (!modeSelect) return;
            basicBox.querySelectorAll('[data-vstrb-price-field]').forEach(function (field) {
                field.hidden = field.dataset.vstrbPriceField !== modeSelect.value;
            });
        }

        function initPricingModeChooser() {
            var modeSelect = basicBox.querySelector('[name="_vstrb_price_mode"]');
            if (!modeSelect) return;
            modeSelect.addEventListener('change', updatePricingMode);
            updatePricingMode();
        }

        function initCurrencyAdder() {
            var list = basicBox.querySelector('[data-vstrb-currency-list]');
            var addButton = basicBox.querySelector('[data-vstrb-add-currency]');
            var input = basicBox.querySelector('[data-vstrb-new-currency]');
            var hidden = basicBox.querySelector('[name="vstrb_wizard_currencies"]');
            var error = basicBox.querySelector('[data-vstrb-currency-error]');
            if (!list || !addButton || !input || !hidden) return;

            addButton.addEventListener('click', function () {
                var code = input.value.trim().toUpperCase();
                var currencies = hidden.value.split(',').filter(Boolean);
                if (!/^[A-Z]{3}$/.test(code) || currencies.indexOf(code) !== -1) {
                    if (error) error.hidden = false;
                    input.focus();
                    return;
                }
                var source = list.querySelector('.vstrb-currency-pricing');
                if (!source) return;
                var oldCode = source.dataset.currency;
                var panel = source.cloneNode(true);
                panel.dataset.currency = code;
                var heading = panel.querySelector('h4');
                if (heading) heading.textContent = heading.textContent.replace(oldCode, code);
                panel.querySelectorAll('[name]').forEach(function (field) {
                    field.name = field.name.replace(new RegExp('_' + oldCode + '$'), '_' + code);
                    field.value = '';
                });
                list.appendChild(panel);
                currencies.push(code);
                hidden.value = currencies.join(',');
                list.dataset.currencies = hidden.value;
                input.value = '';
                if (error) error.hidden = true;
                updatePricingMode();
                panel.scrollIntoView({ behavior: 'smooth', block: 'center' });
            });
        }

        function hiddenField(name, value) {
            var field = document.createElement('input');
            field.type = 'hidden';
            field.name = name;
            field.value = value;
            return field;
        }

        function initCatalogAdders() {
            document.querySelectorAll('[data-vstrb-catalog-add]').forEach(function (box) {
                var type = box.dataset.vstrbCatalogAdd;
                var button = box.querySelector('[data-vstrb-add-catalog-item]');
                var nameInput = box.querySelector('[data-vstrb-item-name]');
                var list = box.querySelector('[data-vstrb-new-items]');
                var error = box.querySelector('[data-vstrb-item-error]');
                var index = 0;
                if (!button || !nameInput || !list) return;
                button.addEventListener('click', function () {
                    var name = nameInput.value.trim();
                    if (!name) {
                        if (error) error.hidden = false;
                        nameInput.focus();
                        return;
                    }
                    var item = document.createElement('span');
                    item.className = 'vstrb-wizard-new-item';
                    item.appendChild(document.createTextNode(name));
                    var prefix = type === 'service' ? 'vstrb_new_services' : (type === 'amenity' ? 'vstrb_new_amenities' : 'vstrb_new_contact_fields');
                    item.appendChild(hiddenField(prefix + '[' + index + '][name]', name));
                    if (type === 'service') {
                        item.appendChild(hiddenField(prefix + '[' + index + '][pricing_type]', box.querySelector('[data-vstrb-item-type]').value));
                        item.appendChild(hiddenField(prefix + '[' + index + '][price]', box.querySelector('[data-vstrb-item-price]').value || '0'));
                    } else if (type === 'amenity') {
                        item.appendChild(hiddenField(prefix + '[' + index + '][category]', box.querySelector('[data-vstrb-item-category]').value));
                    }
                    var remove = document.createElement('button');
                    remove.type = 'button';
                    remove.className = 'button-link';
                    remove.textContent = '×';
                    remove.addEventListener('click', function () { item.remove(); });
                    item.appendChild(remove);
                    list.appendChild(item);
                    index += 1;
                    nameInput.value = '';
                    if (error) error.hidden = true;
                });
            });
        }

        function validationErrors() {
            var summary = wizard.querySelector('[data-vstrb-validation-summary]');
            var errors = [];
            var value = function (name) {
                var field = basicBox.querySelector('[name="' + name + '"]');
                return field ? field.value.trim() : '';
            };
            if (!editorTitle().trim()) errors.push({ step: 'stay', message: summary.dataset.errorTitle });
            var capacity = Number(value('_vstrb_capacity'));
            if (!Number.isInteger(capacity) || capacity < 1) errors.push({ step: 'stay', message: summary.dataset.errorCapacity });
            if (!/^([01]\d|2[0-3]):[0-5]\d$/.test(value('_vstrb_checkin')) || !/^([01]\d|2[0-3]):[0-5]\d$/.test(value('_vstrb_checkout'))) {
                errors.push({ step: 'stay', message: summary.dataset.errorTimes });
            }
            var minStay = parseInt(value('_vstrb_min_stay'), 10);
            var maxStay = parseInt(value('_vstrb_max_stay'), 10);
            if ((minStay > 0 && maxStay > 0 && maxStay < minStay) || minStay < 0 || maxStay < 0) {
                errors.push({ step: 'stay', message: summary.dataset.errorStay });
            }
            if (!basicBox.querySelector('[name="vstrb_available_months[]"]:checked')) {
                errors.push({ step: 'availability', message: summary.dataset.errorMonths });
            }
            var mode = value('_vstrb_price_mode');
            var prefixes = {
                per_unit_night: '_vstrb_price_per_unit_night_',
                per_person_night: '_vstrb_price_per_person_night_',
                per_stay: '_vstrb_price_per_stay_',
                per_night: '_vstrb_price_per_night_',
                per_person: '_vstrb_price_per_person_'
            };
            var missingPrice = false;
            basicBox.querySelectorAll('.vstrb-currency-pricing').forEach(function (panel) {
                var price = panel.querySelector('[name="' + prefixes[mode] + panel.dataset.currency + '"]');
                if (!price || !Number.isFinite(Number(price.value)) || Number(price.value) <= 0) missingPrice = true;
            });
            if (missingPrice) errors.push({ step: 'pricing', message: summary.dataset.errorPrice });
            var negative = Array.prototype.some.call(basicBox.querySelectorAll('.vstrb-currency-pricing [data-vstrb-price-field]:not([hidden]) input[type="number"], .vstrb-price-advanced input[type="number"]'), function (field) {
                return field.value !== '' && Number(field.value) < 0;
            });
            negative = negative || Array.prototype.some.call(basicBox.querySelectorAll('[data-vstrb-item-price], [name^="vstrb_new_services"][name$="[price]"]'), function (field) {
                return field.value !== '' && Number(field.value) < 0;
            });
            if (negative) errors.push({ step: 'pricing', message: summary.dataset.errorNegative });
            var discountNights = Number(value('_vstrb_basic_discount_min_nights'));
            var discountPercent = Number(value('_vstrb_basic_discount_percent'));
            var hasBasicDiscount = discountNights !== 0 || discountPercent !== 0;
            if (hasBasicDiscount && (!Number.isInteger(discountNights) || discountNights < 2 || !Number.isFinite(discountPercent) || discountPercent <= 0 || discountPercent > 100)) {
                errors.push({ step: 'pricing', message: summary.dataset.errorDiscount });
            }
            var pendingCurrency = basicBox.querySelector('[data-vstrb-new-currency]');
            if (pendingCurrency && pendingCurrency.value.trim()) errors.push({ step: 'pricing', message: summary.dataset.errorPending });
            document.querySelectorAll('[data-vstrb-catalog-add]').forEach(function (box) {
                var pendingName = box.querySelector('[data-vstrb-item-name]');
                if (pendingName && pendingName.value.trim()) {
                    var catalogStep = { service: 'services', amenity: 'amenities', contact: 'advanced' };
                    errors.push({ step: catalogStep[box.dataset.vstrbCatalogAdd] || 'advanced', message: summary.dataset.errorPending });
                }
            });
            return errors;
        }

        function renderValidation(errors, showSuccess) {
            var summary = wizard.querySelector('[data-vstrb-validation-summary]');
            var list = summary.querySelector('ul');
            var heading = summary.querySelector('strong');
            list.innerHTML = '';
            stepButtons.forEach(function (button) { button.classList.remove('has-error'); });
            errors.forEach(function (error) {
                var item = document.createElement('li');
                item.textContent = error.message;
                list.appendChild(item);
                var button = wizard.querySelector('[data-vstrb-wizard-go="' + error.step + '"]');
                if (button) button.classList.add('has-error');
            });
            summary.classList.toggle('is-valid', !errors.length);
            summary.classList.toggle('is-visible', errors.length > 0 || showSuccess);
            heading.textContent = errors.length ? summary.dataset.errorHeading : summary.dataset.successHeading;
        }

        function scrollToWizard() {
            var top = basicBox.getBoundingClientRect().top + window.pageYOffset - 42;
            window.scrollTo({ top: Math.max(0, top), behavior: 'smooth' });
        }

        function showStep(index, shouldScroll) {
            currentStep = Math.max(0, Math.min(index, stepKeys.length - 1));
            var key = stepKeys[currentStep];
            var currentButton = stepButtons[currentStep];

            sections.forEach(function (section) {
                section.hidden = section.dataset.vstrbWizardSection !== key;
            });
            stepButtons.forEach(function (button, buttonIndex) {
                button.classList.toggle('is-active', buttonIndex === currentStep);
                button.classList.toggle('is-complete', buttonIndex < currentStep);
                if (buttonIndex === currentStep) button.setAttribute('aria-current', 'step');
                else button.removeAttribute('aria-current');
            });

            wizard.querySelector('[data-vstrb-wizard-title]').textContent = currentButton.dataset.title || '';
            wizard.querySelector('[data-vstrb-wizard-description]').textContent = currentButton.dataset.description || '';
            wizard.querySelector('[data-vstrb-wizard-help]').textContent = currentButton.dataset.description || '';
            actions.querySelector('[data-vstrb-wizard-previous]').disabled = currentStep === 0;
            actions.querySelector('[data-vstrb-wizard-next]').hidden = currentStep === stepKeys.length - 1;
            actions.querySelector('[data-vstrb-wizard-save]').hidden = currentStep !== stepKeys.length - 1;

            if (advancedBox) {
                advancedBox.style.display = key === 'advanced' ? '' : 'none';
                advancedBox.classList.toggle('vstrb-wizard-advanced-active', key === 'advanced');
                if (key === 'advanced') {
                    advancedBox.classList.remove('closed');
                    var inside = advancedBox.querySelector('.inside');
                    if (inside) inside.style.display = '';
                }
            }
            if (key === 'advanced') renderValidation(validationErrors(), true);
            if (shouldScroll) scrollToWizard();
        }

        function startWizard() {
            basicBox.classList.add('vstrb-wizard-active');
            if (wizardName) wizardName.value = editorTitle() || wizardName.value;
            launch.hidden = true;
            wizard.hidden = false;
            actions.hidden = false;
            showStep(0, true);
        }

        function exitWizard() {
            basicBox.classList.remove('vstrb-wizard-active');
            launch.hidden = false;
            wizard.hidden = true;
            actions.hidden = true;
            sections.forEach(function (section) { section.hidden = false; });
            if (advancedBox) {
                advancedBox.style.display = advancedDisplay;
                advancedBox.classList.remove('vstrb-wizard-advanced-active');
                advancedBox.classList.toggle('closed', advancedWasClosed);
            }
        }

        launch.querySelector('[data-vstrb-wizard-start]').addEventListener('click', startWizard);
        wizard.querySelector('[data-vstrb-wizard-exit]').addEventListener('click', exitWizard);
        actions.querySelector('[data-vstrb-wizard-previous]').addEventListener('click', function () {
            showStep(currentStep - 1, true);
        });
        actions.querySelector('[data-vstrb-wizard-next]').addEventListener('click', function () {
			var currentErrors = validationErrors().filter(function (error) { return error.step === stepKeys[currentStep]; });
			if (currentErrors.length) {
				renderValidation(currentErrors, false);
				return;
			}
            renderValidation([], false);
            showStep(currentStep + 1, true);
        });
        actions.querySelector('[data-vstrb-wizard-save]').addEventListener('click', function () {
			var errors = validationErrors();
			renderValidation(errors, true);
			if (errors.length) {
				var firstStep = stepKeys.indexOf(errors[0].step);
				if (firstStep >= 0) showStep(firstStep, true);
				return;
			}
			wizardValidationPassed = true;
            if (wizardComplete) wizardComplete.value = '1';
            var saveButton = document.getElementById('publish') ||
                document.querySelector('.editor-post-publish-button') ||
                document.querySelector('.editor-post-publish-panel__toggle');
            if (saveButton) saveButton.click();
        });
        stepButtons.forEach(function (button, index) {
            button.addEventListener('click', function () { showStep(index, true); });
        });
        if (wizardName) {
            wizardName.addEventListener('input', function () { updateEditorTitle(wizardName.value); });
        }
		initPricingModeChooser();
		initCurrencyAdder();
		initCatalogAdders();
		var postForm = document.getElementById('post');
		if (postForm) {
			postForm.addEventListener('input', function () { wizardValidationPassed = false; });
			postForm.addEventListener('submit', function (event) {
				if (!basicBox.classList.contains('vstrb-wizard-active') || wizardValidationPassed) return;
				var errors = validationErrors();
				if (!errors.length) {
					if (wizardComplete) wizardComplete.value = '1';
					return;
				}
				event.preventDefault();
				renderValidation(errors, true);
				var firstStep = stepKeys.indexOf(errors[0].step);
				if (firstStep >= 0) showStep(firstStep, true);
			});
		}
		document.addEventListener('click', function (event) {
			var publishButton = event.target.closest('#publish, .editor-post-publish-button, .editor-post-publish-panel__toggle');
			if (!publishButton || !basicBox.classList.contains('vstrb-wizard-active') || wizardValidationPassed) return;
			var errors = validationErrors();
			if (!errors.length) return;
			event.preventDefault();
			event.stopImmediatePropagation();
			renderValidation(errors, true);
			var firstStep = stepKeys.indexOf(errors[0].step);
			if (firstStep >= 0) showStep(firstStep, true);
		}, true);

        if (launch.dataset.vstrbWizardAutostart === '1') {
            window.setTimeout(startWizard, 0);
        }
    }

    function init() {
        initApartmentWizardLink();
        initApartmentWizard();
    }

    if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);
    else init();
})();
