/**
 * Rentals & Bookings for WooCommerce & Dokan - Wizard Steps UI JavaScript
 *
 * Handles all step-specific UI interactions for the multi-step wizard.
 * Replaces broken wp_add_inline_script calls in step templates.
 * Uses vanilla JS (no jQuery dependency).
 *
 * @package WahraRentalsBookings
 * @since 1.0.3
 */

(function () {
    'use strict';

    /* ========================================
     * UTILITY HELPERS
     * ======================================== */

    function $(selector, context) {
        return (context || document).querySelector(selector);
    }
    function $$(selector, context) {
        return Array.from((context || document).querySelectorAll(selector));
    }
    function on(el, event, handler) {
        if (el) el.addEventListener(event, handler);
    }
    function onAll(selector, event, handler) {
        $$(selector).forEach(function (el) { on(el, event, handler); });
    }
    function delegate(parent, selector, event, handler) {
        if (!parent) return;
        parent.addEventListener(event, function (e) {
            var target = e.target.closest(selector);
            if (target && parent.contains(target)) {
                handler.call(target, e);
            }
        });
    }
    function slideToggle(el, show) {
        if (!el) return;
        if (show) {
            el.style.display = '';
            el.style.overflow = 'hidden';
            el.style.maxHeight = el.scrollHeight + 'px';
            setTimeout(function () { el.style.maxHeight = ''; el.style.overflow = ''; }, 300);
        } else {
            el.style.overflow = 'hidden';
            el.style.maxHeight = el.scrollHeight + 'px';
            requestAnimationFrame(function () {
                el.style.maxHeight = '0';
                setTimeout(function () { el.style.display = 'none'; el.style.overflow = ''; el.style.maxHeight = ''; }, 300);
            });
        }
    }
    function escapeHtml(text) {
        if (!text) return '';
        var d = document.createElement('div');
        d.textContent = text;
        return d.innerHTML;
    }

    /* ========================================
     * STEP 1: PLATFORM CATEGORY SELECTION
     * ======================================== */

    function initStep1() {
        if (!$('.wahrb-step-1')) return;

        onAll('.wahrb-offer-card', 'click', function () {
            $$('.wahrb-offer-card').forEach(function (c) { c.classList.remove('selected'); });
            this.classList.add('selected');
            var radio = this.querySelector('input[type="radio"]');
            if (radio) radio.checked = true;

            // Auto-set the hidden offer_type from the selected category's primary booking mode
            var mode = this.getAttribute('data-booking-mode');
            var offerTypeInput = document.getElementById('wahrb_offer_type');
            if (mode && offerTypeInput) {
                offerTypeInput.value = mode;
            }
        });
    }

    /* ========================================
     * STEP 2: PRODUCT / INVENTORY
     * ======================================== */

    function initStep2() {
        if (!$('.wahrb-step-2')) return;

        var productSelect = $('#product_id');
        if (productSelect) {
            on(productSelect, 'change', function () {
                var opt = this.options[this.selectedIndex];
                var nameInput = $('input[name="product_name"]');
                if (nameInput && opt && opt.value) {
                    nameInput.value = opt.getAttribute('data-name') || '';
                }
            });
        }
    }

    /* ========================================
     * STEP 3: AVAILABILITY
     * ======================================== */

    function initStep3() {
        if (!$('.wahrb-step-3')) return;

        // Day button toggle
        onAll('.wahrb-day-btn', 'click', function (e) {
            e.preventDefault();
            this.classList.toggle('active');
            var cb = this.querySelector('input[type="checkbox"]');
            if (cb) cb.checked = this.classList.contains('active');
        });

        // Quick select (all / weekdays / weekend)
        onAll('.wahrb-quick-btn', 'click', function (e) {
            e.preventDefault();
            var action = this.getAttribute('data-select');
            var weekdays = ['mon', 'tue', 'wed', 'thu', 'fri'];
            var weekend = ['sat', 'sun'];

            $$('.wahrb-day-btn').forEach(function (btn) {
                var val = btn.querySelector('input').value;
                var shouldSelect = false;
                if (action === 'all') shouldSelect = true;
                else if (action === 'weekdays') shouldSelect = weekdays.indexOf(val) !== -1;
                else if (action === 'weekend') shouldSelect = weekend.indexOf(val) !== -1;

                btn.classList.toggle('active', shouldSelect);
                btn.querySelector('input').checked = shouldSelect;
            });
        });

        // Min/max duration validation
        var minDur = $('#min_duration');
        var maxDur = $('#max_duration');
        function validateDuration(e) {
            var min = parseInt(minDur ? minDur.value : 1) || 1;
            var max = parseInt(maxDur ? maxDur.value : 30) || 30;
            if (min > max) {
                if (e.target.id === 'min_duration') e.target.value = max;
                else e.target.value = min;
            }
        }
        on(minDur, 'change', validateDuration);
        on(maxDur, 'change', validateDuration);

        // Stepper +/- buttons
        onAll('.stepper-btn', 'click', function (e) {
            e.preventDefault();
            var action = this.getAttribute('data-action');
            var targetId = this.getAttribute('data-target');
            var input = document.getElementById(targetId);
            if (!input) return;
            var val = parseInt(input.value) || 1;
            var min = parseInt(input.getAttribute('min')) || 1;
            var max = parseInt(input.getAttribute('max')) || 365;
            if (action === 'increase' && val < max) input.value = val + 1;
            else if (action === 'decrease' && val > min) input.value = val - 1;
            input.dispatchEvent(new Event('change'));
        });

        // Hours mode toggle (same / per_day)
        onAll('input[name="hours_mode"]', 'change', function () {
            var mode = this.value;
            $$('.wahrb-mode-option').forEach(function (opt) { opt.classList.remove('active'); });
            this.closest('.wahrb-mode-option').classList.add('active');

            var sameSection = $('.wahrb-same-hours-section');
            var perDaySection = $('.wahrb-per-day-hours-section');
            if (sameSection) sameSection.style.display = mode === 'same' ? '' : 'none';
            if (perDaySection) perDaySection.style.display = mode === 'per_day' ? '' : 'none';
        });

        // Day checkbox toggle for per-day hours
        $$('.wahrb-day-toggle input[type="checkbox"]').forEach(function (cb) {
            on(cb, 'change', function () {
                var row = this.closest('.wahrb-day-hours-row');
                if (!row) return;
                var enabled = this.checked;
                row.classList.toggle('disabled', !enabled);
                row.querySelectorAll('.wahrb-day-times input').forEach(function (inp) {
                    inp.disabled = !enabled;
                });
            });
        });

        // Slot duration button toggle
        onAll('.wahrb-slot-duration-btn', 'click', function () {
            $$('.wahrb-slot-duration-btn').forEach(function (b) { b.classList.remove('active'); });
            this.classList.add('active');
        });
    }

    /* ========================================
     * STEP 4: PRICING
     * ======================================== */

    function initStep4() {
        if (!$('.wahrb-step-4')) return;

        var cfg = window.wahrbStep4Config || {};
        var currencySymbol = cfg.currencySymbol || '';
        var priceUnits = cfg.priceUnits || {};
        var initialRuleCount = cfg.customRuleIndex || 0;
        var i18n = cfg.i18n || {};
        var customRuleIndex = initialRuleCount;
        var currentIconTarget = null;
        var newRuleIcon = '\uD83C\uDFF7\uFE0F'; // 🏷️

        // Price preview
        function updatePreview() {
            var priceInput = $('#base_price');
            var unitSelect = $('#price_unit');
            var preview = $('#price-preview');
            if (!priceInput || !preview) return;
            var price = parseFloat(priceInput.value) || 0;
            var unitKey = unitSelect ? unitSelect.value : 'day';
            var unitLabel = priceUnits[unitKey] || i18n.fallbackUnit || 'day';
            preview.textContent = currencySymbol + price.toFixed(2) + ' / ' + unitLabel;
        }
        on($('#base_price'), 'input', updatePreview);
        on($('#price_unit'), 'change', updatePreview);

        // Toggle quick rules
        onAll('.wahrb-rule-toggle', 'click', function () {
            var rule = this.closest('.wahrb-quick-rule');
            if (!rule) return;
            this.classList.toggle('on');
            rule.classList.toggle('active');
            var input = rule.querySelector('.rule-enabled-input');
            if (input) input.value = this.classList.contains('on') ? '1' : '0';
        });

        // Day chips for weekend rule
        delegate(document.body, '.wahrb-day-chip', 'click', function () {
            this.classList.toggle('selected');
            var day = this.getAttribute('data-day');
            var config = this.closest('.wahrb-rule-config');
            if (config) {
                var dayInput = config.querySelector('.day-input-' + day);
                if (dayInput) dayInput.disabled = !this.classList.contains('selected');
            }
        });

        // Icon picker
        delegate(document.body, '.wahrb-rule-icon-btn', 'click', function (e) {
            e.preventDefault();
            e.stopPropagation();
            currentIconTarget = this;
            var overlay = $('#icon-picker-overlay');
            if (overlay) overlay.classList.add('show');
        });

        onAll('.wahrb-icon-option', 'click', function () {
            var icon = this.getAttribute('data-icon');
            if (currentIconTarget) {
                if (currentIconTarget.id === 'new-rule-icon-btn') {
                    newRuleIcon = icon;
                } else {
                    var hiddenInput = currentIconTarget.parentElement.querySelector('.rule-icon-input');
                    if (hiddenInput) hiddenInput.value = icon;
                }
                currentIconTarget.textContent = icon;
            }
            var overlay = $('#icon-picker-overlay');
            if (overlay) overlay.classList.remove('show');
        });

        on($('#icon-picker-overlay'), 'click', function (e) {
            if (e.target === this) this.classList.remove('show');
        });

        // Custom rule modal
        on($('#open-custom-rule-modal'), 'click', function () {
            resetRuleModal();
            var title = $('#modal-title');
            if (title) title.textContent = i18n.newRule || 'New Rule';
            var editIdx = $('#edit-rule-index');
            if (editIdx) editIdx.value = '-1';
            var modal = $('#custom-rule-modal');
            if (modal) modal.classList.add('show');
        });

        function resetRuleModal() {
            var nameInput = $('#new-rule-name');
            var valInput = $('#new-rule-value');
            var typeSelect = $('#new-rule-type');
            var showClient = $('#new-rule-show-client');
            var iconBtn = $('#new-rule-icon-btn');
            if (nameInput) nameInput.value = '';
            if (valInput) valInput.value = '';
            if (typeSelect) { typeSelect.value = 'always'; typeSelect.dispatchEvent(new Event('change')); }
            if (showClient) showClient.checked = true;
            newRuleIcon = '\uD83C\uDFF7\uFE0F';
            if (iconBtn) iconBtn.textContent = '\uD83C\uDFF7\uFE0F';
            $$('.condition-field').forEach(function (f) { f.style.display = 'none'; });
            var dateStart = $('#rule-date-start');
            var dateEnd = $('#rule-date-end');
            var durVal = $('#rule-duration-value');
            if (dateStart) dateStart.value = '';
            if (dateEnd) dateEnd.value = '';
            if (durVal) durVal.value = '7';
            $$('.wahrb-weekday-chip').forEach(function (c) { c.classList.remove('selected'); });
            $$('.rule-weekday-check').forEach(function (cb) { cb.checked = false; });
        }

        // Weekday chip toggle
        delegate(document.body, '.wahrb-weekday-chip', 'click', function () {
            this.classList.toggle('selected');
            var cb = this.querySelector('input');
            if (cb) cb.checked = this.classList.contains('selected');
        });

        onAll('#close-custom-modal, #cancel-custom-rule', 'click', function () {
            var modal = $('#custom-rule-modal');
            if (modal) modal.classList.remove('show');
        });

        // Rule type change
        on($('#new-rule-type'), 'change', function () {
            var type = this.value;
            $$('.condition-field').forEach(function (f) { f.style.display = 'none'; });
            if (type === 'date_range') { var el = $('#condition-date-range'); if (el) el.style.display = ''; }
            else if (type === 'duration') { var el = $('#condition-duration'); if (el) el.style.display = ''; }
            else if (type === 'weekday') { var el = $('#condition-weekday'); if (el) el.style.display = ''; }
        });

        // Build conditions
        function getConditionsFromInputs(type) {
            var conditions = '';
            var label = '';
            var dayNames = cfg.dayNames || {};

            if (type === 'date_range') {
                var start = $('#rule-date-start') ? $('#rule-date-start').value : '';
                var end = $('#rule-date-end') ? $('#rule-date-end').value : '';
                if (start && end) {
                    conditions = start + '|' + end;
                    label = formatDate(start) + ' - ' + formatDate(end);
                }
            } else if (type === 'duration') {
                var days = parseInt($('#rule-duration-value') ? $('#rule-duration-value').value : '7') || 7;
                conditions = days.toString();
                label = days + '+ ' + (i18n.days || 'days');
            } else if (type === 'weekday') {
                var selectedDays = [];
                var selectedLabels = [];
                $$('.rule-weekday-check:checked').forEach(function (cb) {
                    var day = cb.value;
                    selectedDays.push(day);
                    selectedLabels.push(dayNames[day] || day);
                });
                conditions = selectedDays.join(',');
                label = selectedLabels.join(', ');
            }
            return { conditions: conditions, label: label };
        }

        function formatDate(dateStr) {
            if (!dateStr) return '';
            var d = new Date(dateStr);
            return d.toLocaleDateString(undefined, { day: '2-digit', month: 'short' });
        }

        function validateRuleForm() {
            var name = $('#new-rule-name') ? $('#new-rule-name').value.trim() : '';
            var value = $('#new-rule-value') ? $('#new-rule-value').value : '';
            var type = $('#new-rule-type') ? $('#new-rule-type').value : 'always';

            if (!name) {
                alert(i18n.enterRuleName || 'Please enter a rule name');
                if ($('#new-rule-name')) $('#new-rule-name').focus();
                return false;
            }
            if (value === '' || isNaN(parseInt(value))) {
                alert(i18n.enterValidPercent || 'Please enter a valid percentage');
                if ($('#new-rule-value')) $('#new-rule-value').focus();
                return false;
            }
            var intVal = parseInt(value);
            if (intVal < -100 || intVal > 500) {
                alert(i18n.percentRange || 'Percentage must be between -100% and +500%');
                if ($('#new-rule-value')) $('#new-rule-value').focus();
                return false;
            }
            if (type === 'date_range') {
                var s = $('#rule-date-start') ? $('#rule-date-start').value : '';
                var e = $('#rule-date-end') ? $('#rule-date-end').value : '';
                if (!s || !e) { alert(i18n.selectDates || 'Please select start and end dates'); return false; }
                if (new Date(s) > new Date(e)) { alert(i18n.dateOrder || 'Start date must be before end date'); return false; }
            } else if (type === 'duration') {
                var d = parseInt($('#rule-duration-value') ? $('#rule-duration-value').value : '0');
                if (!d || d < 1) { alert(i18n.validDuration || 'Please enter a valid minimum duration'); return false; }
            } else if (type === 'weekday') {
                if ($$('.rule-weekday-check:checked').length === 0) { alert(i18n.selectDay || 'Please select at least one day'); return false; }
            }
            return true;
        }

        // Save custom rule
        on($('#save-custom-rule'), 'click', function () {
            if (!validateRuleForm()) return;

            var name = $('#new-rule-name').value.trim();
            var value = parseInt($('#new-rule-value').value) || 0;
            var type = $('#new-rule-type').value;
            var showCustomer = $('#new-rule-show-client') && $('#new-rule-show-client').checked ? '1' : '0';
            var editIndex = parseInt($('#edit-rule-index') ? $('#edit-rule-index').value : '-1');
            var condData = getConditionsFromInputs(type);
            var badgeClass = value >= 0 ? 'positive' : 'negative';
            var badgeText = (value >= 0 ? '+' : '') + value + '%';
            var ruleIndex = editIndex >= 0 ? editIndex : customRuleIndex;

            var html = '<div class="wahrb-custom-rule-card" data-index="' + ruleIndex + '" '
                + 'data-name="' + escapeHtml(name) + '" '
                + 'data-icon="' + newRuleIcon + '" '
                + 'data-value="' + value + '" '
                + 'data-type="' + type + '" '
                + 'data-conditions="' + escapeHtml(condData.conditions) + '">'
                + '<span class="wahrb-edit-icon">\u270F\uFE0F</span>'
                + '<span class="icon">' + newRuleIcon + '</span>'
                + '<div class="info"><strong>' + escapeHtml(name) + '</strong><small>' + escapeHtml(condData.label) + '</small></div>'
                + '<span class="badge ' + badgeClass + '">' + badgeText + '</span>'
                + '<button type="button" class="wahrb-remove-btn" data-index="' + ruleIndex + '">\u00D7</button>'
                + '<input type="hidden" name="custom_rules[' + ruleIndex + '][name]" value="' + escapeHtml(name) + '">'
                + '<input type="hidden" name="custom_rules[' + ruleIndex + '][icon]" value="' + newRuleIcon + '">'
                + '<input type="hidden" name="custom_rules[' + ruleIndex + '][value]" value="' + value + '">'
                + '<input type="hidden" name="custom_rules[' + ruleIndex + '][type]" value="' + type + '">'
                + '<input type="hidden" name="custom_rules[' + ruleIndex + '][conditions]" value="' + escapeHtml(condData.conditions) + '">'
                + '<input type="hidden" name="custom_rules[' + ruleIndex + '][condition_label]" value="' + escapeHtml(condData.label) + '">'
                + '<input type="hidden" name="custom_rules[' + ruleIndex + '][show_client]" value="' + showCustomer + '">'
                + '</div>';

            if (editIndex >= 0) {
                var existing = document.querySelector('.wahrb-custom-rule-card[data-index="' + editIndex + '"]');
                if (existing) { existing.outerHTML = html; }
            } else {
                var placeholder = $('#empty-rules-placeholder');
                if (placeholder) placeholder.remove();
                var list = $('#custom-rules-list');
                if (list) list.insertAdjacentHTML('beforeend', html);
                customRuleIndex++;
            }
            var modal = $('#custom-rule-modal');
            if (modal) modal.classList.remove('show');
        });

        // Edit existing custom rule
        delegate(document.body, '.wahrb-custom-rule-card', 'click', function (e) {
            if (e.target.closest('.wahrb-remove-btn')) return;

            var card = this;
            var index = card.getAttribute('data-index');
            var nameVal = card.querySelector('input[name$="[name]"]');
            var iconVal = card.querySelector('input[name$="[icon]"]');
            var valueVal = card.querySelector('input[name$="[value]"]');
            var typeVal = card.querySelector('input[name$="[type]"]');
            var condVal = card.querySelector('input[name$="[conditions]"]');
            var showVal = card.querySelector('input[name$="[show_client]"]');

            resetRuleModal();
            var title = $('#modal-title');
            if (title) title.textContent = i18n.editRule || 'Edit Rule';
            var editIdx = $('#edit-rule-index');
            if (editIdx) editIdx.value = index;
            if ($('#new-rule-name') && nameVal) $('#new-rule-name').value = nameVal.value;
            if ($('#new-rule-value') && valueVal) $('#new-rule-value').value = valueVal.value;
            if ($('#new-rule-type') && typeVal) {
                $('#new-rule-type').value = typeVal.value;
                $('#new-rule-type').dispatchEvent(new Event('change'));
            }
            if ($('#new-rule-show-client') && showVal) $('#new-rule-show-client').checked = showVal.value === '1';
            newRuleIcon = (iconVal ? iconVal.value : '') || '\uD83C\uDFF7\uFE0F';
            if ($('#new-rule-icon-btn')) $('#new-rule-icon-btn').textContent = newRuleIcon;

            var conditions = condVal ? condVal.value : '';
            var ruleType = typeVal ? typeVal.value : 'always';
            if (ruleType === 'date_range' && conditions) {
                var dates = conditions.split('|');
                if (dates.length === 2) {
                    if ($('#rule-date-start')) $('#rule-date-start').value = dates[0];
                    if ($('#rule-date-end')) $('#rule-date-end').value = dates[1];
                }
            } else if (ruleType === 'duration' && conditions) {
                if ($('#rule-duration-value')) $('#rule-duration-value').value = conditions;
            } else if (ruleType === 'weekday' && conditions) {
                conditions.split(',').forEach(function (day) {
                    var chip = document.querySelector('.wahrb-weekday-chip[data-day="' + day + '"]');
                    if (chip) {
                        chip.classList.add('selected');
                        var cb = chip.querySelector('input');
                        if (cb) cb.checked = true;
                    }
                });
            }

            var modalEl = $('#custom-rule-modal');
            if (modalEl) modalEl.classList.add('show');
        });

        // Remove custom rule
        delegate(document.body, '.wahrb-remove-btn', 'click', function (e) {
            e.stopPropagation();
            var confirmMsg = i18n.deleteRule || 'Delete this rule?';
            if (confirm(confirmMsg)) {
                var card = this.closest('.wahrb-custom-rule-card');
                if (card) card.remove();
                var list = $('#custom-rules-list');
                if (list && !list.querySelector('.wahrb-custom-rule-card')) {
                    var emptyMsg = i18n.emptyRules || 'High season, group promo, holiday weekend surcharge...';
                    list.innerHTML = '<div class="wahrb-empty-rules" id="empty-rules-placeholder"><div class="emoji">\uD83D\uDCA1</div><p>' + escapeHtml(emptyMsg) + '</p></div>';
                }
            }
        });

        // Numeric input validation
        delegate(document.body, '.wahrb-numeric-input, input[type="number"]', 'input', function () {
            this.value = this.value.replace(/[^-0-9.]/g, '');
            if (this.value.indexOf('-') > 0) {
                this.value = this.value.replace(/-/g, '');
            }
        });

        delegate(document.body, 'input[type="number"]', 'blur', function () {
            var val = parseFloat(this.value);
            var min = parseFloat(this.getAttribute('min'));
            var max = parseFloat(this.getAttribute('max'));
            if (!isNaN(min) && val < min) this.value = min;
            if (!isNaN(max) && val > max) this.value = max;
        });
    }

    /* ========================================
     * STEP 5: PAYMENT
     * ======================================== */

    function initStep5() {
        if (!$('.wahrb-step-5')) return;

        var cfg = window.wahrbStep5Config || {};
        var currencySymbol = cfg.currencySymbol || '';

        // Toggle sections
        on($('#deposit_enabled'), 'change', function () {
            var opts = $('#deposit-options');
            if (opts) opts.style.display = this.checked ? '' : 'none';
        });
        on($('#security_enabled'), 'change', function () {
            var opts = $('#security-options');
            if (opts) opts.style.display = this.checked ? '' : 'none';
        });
        on($('#balance_enabled'), 'change', function () {
            var opts = $('#balance-options');
            if (opts) opts.style.display = this.checked ? '' : 'none';
        });

        // Deposit type suffix
        on($('#deposit_type'), 'change', function () {
            var suffix = $('#deposit-suffix');
            if (suffix) suffix.textContent = this.value === 'percent' ? '%' : currencySymbol;
        });

        // Payment method cards toggle
        onAll('.wahrb-payment-method-card input[type="checkbox"]', 'change', function () {
            var card = this.closest('.wahrb-payment-method-card');
            if (card) card.classList.toggle('active', this.checked);
            if (this.value === 'online') {
                var gw = $('#gateways-section');
                if (gw) gw.style.display = this.checked ? '' : 'none';
            }
        });

        // Security method cards toggle
        onAll('.wahrb-security-method input[type="checkbox"]', 'change', function () {
            var card = this.closest('.wahrb-security-method');
            if (card) card.classList.toggle('active', this.checked);
        });
    }

    /* ========================================
     * STEP 7: REVIEW & PUBLISH
     * ======================================== */

    function initStep7() {
        if (!$('.wahrb-step-7')) return;

        var cfg = window.wahrbStep7Config || {};
        var termsRequired = cfg.termsRequired !== false;

        function updatePublishButton() {
            var btn = $('#wahrb-publish-btn');
            var cb = $('#terms_accepted');
            if (!btn) return;
            if (termsRequired) {
                btn.disabled = !(cb && cb.checked);
            } else {
                btn.disabled = false;
            }
        }
        on($('#terms_accepted'), 'change', updatePublishButton);
        updatePublishButton();

        // Policy card toggle
        onAll('input[name="cancellation_policy"]', 'change', function () {
            $$('.wahrb-policy-card').forEach(function (c) { c.classList.remove('selected'); });
            var card = this.closest('.wahrb-policy-card');
            if (card) card.classList.add('selected');
            var customSettings = $('#wahrb-custom-policy-settings');
            if (customSettings) {
                customSettings.style.display = this.value === 'custom' ? 'block' : 'none';
            }
        });
    }

    /* ========================================
     * INIT ALL STEPS ON DOM READY
     * ======================================== */

    function init() {
        initStep1();
        initStep2();
        initStep3();
        initStep4();
        initStep5();
        initStep7();
    }

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