(function () {
    function mountSetupWizard() {
        if (!window.bookwellabSetupWizardData || !document.querySelector('#bw-setup-wizard-app')) {
            return;
        }

        const { createApp, ref, reactive } = Vue;
        const setupData = window.bookwellabSetupWizardData;
        const defaults = setupData.defaults || {};
        const generalDefaults = defaults.general || {};
        const ui = setupData.ui || {
            header: { title: '', subtitle: '' },
            steps: [],
            labels: {},
            placeholders: {},
            options: {}
        };

        const app = createApp({
            setup() {
                const i18n = setupData.i18n || {};
                const activeStep = ref(0);
                const loading = ref(false);
                const validationErrors = reactive({
                    company_name: false,
                    company_phone: false,
                    service_name: false,
                    service_price: false,
                    service_duration: false,
                    staff_name: false,
                    staff_email: false
                });
                const currencies = reactive(defaults.currencies || {});
                const countries = reactive(defaults.countries || {});
                const phone_codes = reactive(defaults.phone_codes || []);
                const days = setupData.days || {};

                const form = reactive({
                    settings: {
                        company_name: defaults.blog_name || '',
                        company_phone: generalDefaults.company_phone || '',
                        company_address: generalDefaults.company_address || '',
                        date_format: generalDefaults.date_format || 'Y-m-d',
                        time_format: generalDefaults.time_format || 'h:i a',
                        currency_code: generalDefaults.currency_code || 'USD',
                        currency_position: generalDefaults.currency_position || 'before',
                        default_status: 'approved',
                        default_payment_status: generalDefaults.default_payment_status || 'pending',
                        default_country: generalDefaults.default_country || 'us',
                        default_phone_code: generalDefaults.default_phone_code || '+1'
                    },
                    service: {
                        bw_service_name: '',
                        bw_service_price: 20,
                        bw_service_duration_val: 60,
                        bw_service_duration_unit: 'm',
                        bw_service_description: ''
                    },
                    staff: {
                        bw_staff_name: defaults.admin_name || '',
                        bw_staff_email: defaults.admin_email || '',
                        bw_staff_phone: '',
                        bw_staff_position: 'Main Specialist',
                        shifts: {
                            monday: { bw_start_time: '09:00', bw_end_time: '18:00', bw_is_off: 0, bw_breaks: [] },
                            tuesday: { bw_start_time: '09:00', bw_end_time: '18:00', bw_is_off: 0, bw_breaks: [] },
                            wednesday: { bw_start_time: '09:00', bw_end_time: '18:00', bw_is_off: 0, bw_breaks: [] },
                            thursday: { bw_start_time: '09:00', bw_end_time: '18:00', bw_is_off: 0, bw_breaks: [] },
                            friday: { bw_start_time: '09:00', bw_end_time: '18:00', bw_is_off: 0, bw_breaks: [] },
                            saturday: { bw_start_time: '09:00', bw_end_time: '18:00', bw_is_off: 1, bw_breaks: [] },
                            sunday: { bw_start_time: '09:00', bw_end_time: '18:00', bw_is_off: 1, bw_breaks: [] }
                        }
                    }
                });

                const getServiceDurationMax = () => {
                    return form.service.bw_service_duration_unit === 'h' ? 12 : 60;
                };

                const clampServiceDuration = () => {
                    const max = getServiceDurationMax();
                    let durationVal = parseInt(form.service.bw_service_duration_val, 10);
                    if (Number.isNaN(durationVal) || durationVal < 1) {
                        durationVal = 1;
                    }
                    if (durationVal > max) {
                        durationVal = max;
                    }
                    form.service.bw_service_duration_val = durationVal;
                };

                const next = () => {
                    if (activeStep.value === 0) {
                        validationErrors.company_name = !form.settings.company_name;
                        validationErrors.company_phone = !form.settings.company_phone;
                        if (validationErrors.company_name || validationErrors.company_phone) {
                            ElementPlus.ElMessage.warning(i18n.company_required || 'Company name and phone are required.');
                            return;
                        }
                    }
                    if (activeStep.value === 1) {
                        clampServiceDuration();
                        const durationVal = parseInt(form.service.bw_service_duration_val, 10);
                        validationErrors.service_name = !form.service.bw_service_name;
                        validationErrors.service_price = !(parseFloat(form.service.bw_service_price) > 0);
                        validationErrors.service_duration = !(durationVal > 0 && durationVal <= getServiceDurationMax());
                        if (validationErrors.service_name || validationErrors.service_price || validationErrors.service_duration) {
                            ElementPlus.ElMessage.warning(i18n.service_required || 'Please fill all required service fields.');
                            return;
                        }
                    }
                    if (activeStep.value === 2) {
                        validationErrors.staff_name = !form.staff.bw_staff_name;
                        validationErrors.staff_email = !form.staff.bw_staff_email;
                        if (validationErrors.staff_name || validationErrors.staff_email) {
                            ElementPlus.ElMessage.warning(i18n.staff_required || 'Name and email are required.');
                            return;
                        }
                    }
                    activeStep.value++;
                };

                const prev = () => {
                    activeStep.value--;
                };

                const finish = () => {
                    loading.value = true;
                    const formData = new FormData();
                    formData.append('action', 'bookwellab_finish_setup');
                    formData.append('_wpnonce', setupData.nonce || '');
                    formData.append('setup_data', JSON.stringify(form));

                    jQuery.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function (response) {
                            if (response.success) {
                                ElementPlus.ElNotification({
                                    title: i18n.success || 'Success',
                                    message: response.data.msg,
                                    type: 'success'
                                });
                                window.location.href = response.data.redirect;
                            } else {
                                ElementPlus.ElMessage.error(response.data.msg || i18n.setup_failed || 'Setup failed.');
                                loading.value = false;
                            }
                        },
                        error: function () {
                            ElementPlus.ElMessage.error(i18n.server_error || 'Server error occurred.');
                            loading.value = false;
                        }
                    });
                };

                const skipSetup = () => {
                    const isConfirmed = window.confirm(i18n.skip_setup_msg || 'Are you sure you want to skip the setup?');
                    if (!isConfirmed) {
                        return;
                    }
                    loading.value = true;
                    jQuery.ajax({
                        url: ajaxurl,
                        type: 'POST',
                        data: {
                            action: 'bookwellab_skip_setup',
                            _wpnonce: setupData.nonce || ''
                        },
                        success: function (response) {
                            if (response.success) {
                                window.location.href = response.data.redirect;
                            } else {
                                ElementPlus.ElMessage.error(response.data.msg);
                                loading.value = false;
                            }
                        },
                        error: function () {
                            ElementPlus.ElMessage.error(i18n.server_error || 'Server error occurred.');
                            loading.value = false;
                        }
                    });
                };

                const bwab_onDefaultCountryChange = (iso) => {
                    const isoLower = String(iso || '').toLowerCase();
                    const match = phone_codes.find(function (item) {
                        return String(item.iso || '').toLowerCase() === isoLower;
                    });
                    if (match) {
                        form.settings.default_country = isoLower;
                        form.settings.default_phone_code = match.code;
                    }
                };

                const bwab_addShiftBreak = (dayKey) => {
                    if (!form.staff.shifts[dayKey].bw_breaks) {
                        form.staff.shifts[dayKey].bw_breaks = [];
                    }
                    form.staff.shifts[dayKey].bw_breaks.push({ start: '12:00', end: '13:00' });
                };

                const bwab_removeShiftBreak = (dayKey, breakIndex) => {
                    if (form.staff.shifts[dayKey].bw_breaks) {
                        form.staff.shifts[dayKey].bw_breaks.splice(breakIndex, 1);
                    }
                };

                return {
                    ui: ui,
                    activeStep: activeStep,
                    form: form,
                    currencies: currencies,
                    countries: countries,
                    phone_codes: phone_codes,
                    days: days,
                    validationErrors: validationErrors,
                    next: next,
                    prev: prev,
                    finish: finish,
                    skipSetup: skipSetup,
                    bwab_onDefaultCountryChange: bwab_onDefaultCountryChange,
                    getServiceDurationMax: getServiceDurationMax,
                    clampServiceDuration: clampServiceDuration,
                    bwab_addShiftBreak: bwab_addShiftBreak,
                    bwab_removeShiftBreak: bwab_removeShiftBreak,
                    loading: loading
                };
            }
        });

        if (typeof Vue === 'undefined' || typeof ElementPlus === 'undefined') {
            console.error('BookWellNow setup wizard: Vue or Element Plus failed to load.');
            return;
        }

        app.use(ElementPlus);
        if (typeof ElementPlusIconsVue !== 'undefined') {
            for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
                app.component(key, component);
            }
        }
        app.mount('#bw-setup-wizard-app');
    }

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