const { createApp, ref, reactive, onMounted } = Vue;

const adjustColor = (col, amt) => {
    if (!col) return col;
    let usePound = false;
    if (col[0] === '#') {
        col = col.slice(1);
        usePound = true;
    }
    let num = parseInt(col, 16);
    let r = (num >> 16) + amt;
    if (r > 255) r = 255;
    else if (r < 0) r = 0;
    let b = ((num >> 8) & 0x00FF) + amt;
    if (b > 255) b = 255;
    else if (b < 0) b = 0;
    let g = (num & 0x0000FF) + amt;
    if (g > 255) g = 255;
    else if (g < 0) g = 0;
    const newColor = (g | (b << 8) | (r << 16)).toString(16).padStart(6, '0');
    return (usePound ? '#' : '') + newColor;
};

const hexToRgb = (hex) => {
    if (!hex) return '4, 67, 67';
    let normalized = hex.replace('#', '');
    if (normalized.length === 3) {
        normalized = normalized.split('').map((c) => c + c).join('');
    }
    const num = parseInt(normalized, 16);
    return `${(num >> 16) & 255}, ${(num >> 8) & 255}, ${num & 255}`;
};

const buildAppearanceCss = (appearance) => {
    const primaryColor = appearance.primary_color || '#044343';
    const primaryHover = adjustColor(primaryColor, -10);
    const primaryRgb = hexToRgb(primaryColor);

    let fontFamily = 'inherit';
    if (appearance.font_family) {
        const fontName = appearance.font_family.split(',')[0].replace(/['"]/g, '').trim();
        fontFamily = `'${fontName}', sans-serif`;
    }

    const titleColor = appearance.title_color || '#044343';
    const detailColor = appearance.detail_text_color || '#64748b';
    const titleFontSize = (appearance.title_font_size || 20) + 'px';
    const detailFontSize = (appearance.detail_text_size || 14) + 'px';
    const sidebarTitleColor = appearance.sidebar_title_color || '#ffffff';
    const sidebarTextColor = appearance.sidebar_text_color || '#ffffff';
    const sidebarTitleSize = (appearance.sidebar_title_size || 16) + 'px';
    const sidebarTextSize = (appearance.sidebar_text_size || 12) + 'px';
    const sectionTitleSize = (appearance.section_title_size || 24) + 'px';
    const subtitleColor = appearance.subtitle_color || titleColor;
    const subtitleSize = appearance.subtitle_size ? appearance.subtitle_size + 'px' : titleFontSize;
    const contentTextColor = appearance.content_text_color || detailColor;
    const contentTextSize = appearance.content_text_size ? appearance.content_text_size + 'px' : detailFontSize;
    const panelBgColor = appearance.panel_bg_color || '#f8f4f8';
    const borderColor = appearance.border_color || '#d4cdc9';
    const buttonTextColor = appearance.button_text_color || '#ffffff';
    const buttonFontSize = (appearance.button_font_size || 16) + 'px';
    const priceBadgeColor = appearance.price_badge_color || '#ffffff';

    return `
        #bookwellab_customer_panel_app {
            --bw-primary-color: ${primaryColor};
            --bw-primary-hover: ${primaryHover};
            --bw-primary-color-rgb: ${primaryRgb};
            --bw-font-family: ${fontFamily};
            --bw-button-font-family: ${fontFamily};
            --bw-title-color: ${titleColor};
            --bw-detail-color: ${detailColor};
            --bw-title-font-size: ${titleFontSize};
            --bw-detail-font-size: ${detailFontSize};
            --bw-sidebar-title-color: ${sidebarTitleColor};
            --bw-sidebar-text-color: ${sidebarTextColor};
            --bw-sidebar-title-size: ${sidebarTitleSize};
            --bw-sidebar-text-size: ${sidebarTextSize};
            --bw-section-title-size: ${sectionTitleSize};
            --bw-subtitle-color: ${subtitleColor};
            --bw-subtitle-size: ${subtitleSize};
            --bw-content-text-color: ${contentTextColor};
            --bw-content-text-size: ${contentTextSize};
            --bw-panel-bg-color: ${panelBgColor};
            --bw-border-color: ${borderColor};
            --bw-button-text-color: ${buttonTextColor};
            --bw-button-font-size: ${buttonFontSize};
            --bw-price-badge-color: ${priceBadgeColor};
            --bw-button-secondary-bg: ${buttonTextColor};
            --bw-button-secondary-text: ${primaryColor};
            --bw-button-secondary-border: ${primaryColor};
            --el-border-color: ${borderColor};
            --el-input-border-color: ${borderColor};
            --el-input-hover-border-color: ${primaryColor};
            --el-input-focus-border-color: ${primaryColor};
        }
        #bookwellab_customer_panel_app,
        #bookwellab_customer_panel_app .bw-cp-main,
        #bookwellab_customer_panel_app .bw-cp-table {
            font-family: var(--bw-font-family) !important;
        }
        #bookwellab_customer_panel_app .el-button--primary,
        #bookwellab_customer_panel_app .bw-cp-btn-primary {
            background-color: var(--bw-primary-color) !important;
            border-color: var(--bw-primary-color) !important;
            color: var(--bw-button-text-color) !important;
            font-family: var(--bw-button-font-family) !important;
            font-size: var(--bw-button-font-size) !important;
        }
        #bookwellab_customer_panel_app .el-button--primary:hover,
        #bookwellab_customer_panel_app .bw-cp-btn-primary:hover {
            background-color: var(--bw-primary-hover) !important;
            border-color: var(--bw-primary-hover) !important;
        }
        #bookwellab_customer_panel_app .el-form-item__label {
            color: var(--bw-subtitle-color) !important;
            font-size: var(--bw-subtitle-size) !important;
            font-weight: 600 !important;
        }
        #bookwellab_customer_panel_app .el-input__wrapper,
        #bookwellab_customer_panel_app .el-textarea__inner {
            border: 1px solid var(--bw-border-color) !important;
            box-shadow: none !important;
            background: #fff !important;
            border-radius: 4px !important;
        }
        #bookwellab_customer_panel_app .el-input__inner {
            color: var(--bw-content-text-color) !important;
            font-size: var(--bw-content-text-size) !important;
            border: 0 !important;
            outline: none !important;
            box-shadow: none !important;
            background: transparent !important;
            padding: 0 !important;
            margin: 0 !important;
            height: auto !important;
            min-height: 0 !important;
        }
        #bookwellab_customer_panel_app .el-textarea__inner {
            color: var(--bw-content-text-color) !important;
            font-size: var(--bw-content-text-size) !important;
        }
        #bookwellab_customer_panel_app .el-input__wrapper.is-focus,
        #bookwellab_customer_panel_app .el-input__wrapper:hover,
        #bookwellab_customer_panel_app .el-textarea__inner:focus,
        #bookwellab_customer_panel_app .el-textarea__inner:hover {
            border-color: var(--bw-primary-color) !important;
        }
        #bookwellab_customer_panel_app .bw-cp-form .el-input,
        #bookwellab_customer_panel_app .bw-cp-form .el-input__wrapper {
            width: 100% !important;
        }
        #bookwellab_customer_panel_app .bw-cp-form .el-form-item__content {
            width: 100%;
        }
        #bookwellab_customer_panel_app .bw-cp-table-row--head {
            color: var(--bw-subtitle-color) !important;
            font-size: var(--bw-subtitle-size) !important;
        }
        #bookwellab_customer_panel_app .bw-cp-table-row:not(.bw-cp-table-row--head) {
            color: var(--bw-content-text-color) !important;
            font-size: var(--bw-content-text-size) !important;
        }
        #bookwellab_customer_panel_app .bw-cp-table-expand {
            background: #fff !important;
        }
        #bookwellab_customer_panel_app .el-pagination.is-background .el-pager li.is-active {
            background-color: var(--bw-primary-color) !important;
            color: var(--bw-sidebar-title-color) !important;
        }
        #bookwellab_customer_panel_app .el-tag,
        #bookwellab_customer_panel_app .el-tag.el-tag--small {
            --el-tag-font-size: var(--bw-content-text-size);
            font-size: var(--bw-content-text-size) !important;
        }
        #bookwellab_customer_panel_app .el-tag.el-tag--success {
            --el-tag-bg-color: rgba(34, 197, 94, 0.12);
            --el-tag-border-color: rgba(34, 197, 94, 0.25);
            --el-tag-text-color: #15803d;
        }
        #bookwellab_customer_panel_app .el-tag.el-tag--warning {
            --el-tag-bg-color: rgba(245, 158, 11, 0.12);
            --el-tag-border-color: rgba(245, 158, 11, 0.25);
            --el-tag-text-color: #b45309;
        }
        #bookwellab_customer_panel_app .el-tag.el-tag--info {
            --el-tag-bg-color: rgba(var(--bw-primary-color-rgb), 0.08);
            --el-tag-border-color: rgba(var(--bw-primary-color-rgb), 0.18);
            --el-tag-text-color: var(--bw-primary-color);
        }
        #bookwellab_customer_panel_app .bw-cp-title {
            color: var(--bw-title-color) !important;
            font-size: var(--bw-section-title-size) !important;
        }
        #bookwellab_customer_panel_app .bw-cp-login-card h3 {
            color: var(--bw-title-color) !important;
            font-size: var(--bw-section-title-size) !important;
        }
        #bookwellab_customer_panel_app .bw-cp-login-card p,
        #bookwellab_customer_panel_app .bw-cp-empty {
            color: var(--bw-content-text-color) !important;
            font-size: var(--bw-content-text-size) !important;
        }
        #bookwellab_customer_panel_app .bw-cp-duration {
            color: var(--bw-detail-color) !important;
            font-size: var(--bw-content-text-size) !important;
        }
        #bookwellab_customer_panel_app .bw-cp-expand-label {
            color: var(--bw-detail-color) !important;
            font-size: var(--bw-detail-font-size) !important;
        }
        #bookwellab_customer_panel_app .bw-cp-expand-service {
            color: var(--bw-title-color) !important;
            font-size: var(--bw-title-font-size) !important;
        }
        #bookwellab_customer_panel_app .bw-cp-service-name,
        #bookwellab_customer_panel_app .bw-cp-service-date,
        #bookwellab_customer_panel_app .bw-cp-table-cell--id,
        #bookwellab_customer_panel_app .bw-cp-table-cell--payment {
            color: var(--bw-content-text-color) !important;
            font-size: var(--bw-content-text-size) !important;
        }
        #bookwellab_customer_panel_app .bw-cp-expand-price {
            color: var(--bw-primary-color) !important;
        }
        #bookwellab_customer_panel_app .el-date-editor .el-input__wrapper,
        #bookwellab_customer_panel_app .el-range-editor.el-input__wrapper {
            border: 1px solid var(--bw-border-color) !important;
            box-shadow: none !important;
            background: #fff !important;
        }
        #bookwellab_customer_panel_app .bw-cp-filters .el-input__wrapper,
        #bookwellab_customer_panel_app .bw-cp-filters .el-range-editor.el-input__wrapper {
            min-height: 40px;
        }
        #bookwellab_customer_panel_app .el-date-editor .el-input__wrapper.is-focus,
        #bookwellab_customer_panel_app .el-date-editor .el-input__wrapper:hover,
        #bookwellab_customer_panel_app .el-range-editor.el-input__wrapper.is-focus,
        #bookwellab_customer_panel_app .el-range-editor.el-input__wrapper:hover {
            border-color: var(--bw-primary-color) !important;
        }
        #bookwellab_customer_panel_app .el-pagination.is-background .el-pager li {
            color: var(--bw-content-text-color) !important;
            font-size: var(--bw-content-text-size) !important;
        }
        #bookwellab_customer_panel_app .el-button--danger.is-plain {
            color: #dc2626 !important;
            border-color: rgba(220, 38, 38, 0.35) !important;
            background: #fff !important;
            font-size: var(--bw-content-text-size) !important;
        }
        #bookwellab_customer_panel_app .el-button--danger.is-plain:hover {
            color: #fff !important;
            background: #dc2626 !important;
            border-color: #dc2626 !important;
        }
        #bookwellab_customer_panel_app .bw-cp-input-error .el-input__wrapper,
        #bookwellab_customer_panel_app .bw-cp-input-error .el-input__wrapper.is-focus,
        #bookwellab_customer_panel_app .bw-cp-input-error .el-input__wrapper:hover {
            border-color: #dc2626 !important;
            box-shadow: 0 0 0 1px #dc2626 !important;
        }
        .bw-cp-popconfirm {
            --bw-primary-color: ${primaryColor};
            --bw-font-family: ${fontFamily};
            --bw-border-color: ${borderColor};
            --bw-content-text-color: ${contentTextColor};
        }
        .bw-cp-popconfirm .el-popconfirm__action .el-button--primary {
            background-color: ${primaryColor} !important;
            border-color: ${primaryColor} !important;
            color: #fff !important;
        }
    `;
};

const injectAppearanceStyles = (appearance) => {
    const styleId = 'bookwellab-customer-panel-appearance';
    let style = document.getElementById(styleId);
    if (!style) {
        style = document.createElement('style');
        style.id = styleId;
        document.head.appendChild(style);
    }
    style.innerHTML = buildAppearanceCss(appearance || {});
};

createApp({
    setup() {
        const config = window.bookwellab_cp_obj || {};
        const labels = config.labels || {};
        const isLoggedIn = !!config.is_logged_in;
        const isCustomer = !!config.is_customer;
        const loginUrl = config.login_url || '#';
        const logoutUrl = config.logout_url || '#';
        const lostPasswordUrl = config.lost_password_url || '#';
        const bookingUrl = config.booking_url || '';
        const panelNonce = config.nonce || '';
        const authNonce = config.login_nonce || '';

        const buildAjaxParams = (action, nonce, payload = {}) => {
            const params = new URLSearchParams();
            params.append('action', action);
            params.append('_wpnonce', nonce || '');
            Object.keys(payload).forEach((key) => {
                params.append(key, payload[key] == null ? '' : String(payload[key]));
            });
            return params;
        };

        const loginForm = reactive({
            username: '',
            password: '',
            remember: false,
        });
        const loginErrors = reactive({
            username: false,
            password: false,
        });
        const loggingIn = ref(false);

        const showForgot = ref(false);
        const forgotForm = reactive({ user_login: '' });
        const forgotError = ref(false);
        const sendingForgot = ref(false);

        const openForgot = () => {
            showForgot.value = true;
            forgotError.value = false;
        };
        const closeForgot = () => {
            showForgot.value = false;
            forgotError.value = false;
        };

        const doLostPassword = async () => {
            forgotError.value = !(forgotForm.user_login || '').trim();
            if (forgotError.value) {
                return;
            }
            sendingForgot.value = true;
            try {
                const params = buildAjaxParams('bookwellab_cp_lost_password', authNonce, {
                    user_login: forgotForm.user_login || '',
                });
                const response = await axios.post(config.ajax_url, params);
                if (response.data && response.data.success) {
                    ElementPlus.ElMessage.success((response.data.data && response.data.data.msg) || (labels.forgot_success || ''));
                    forgotForm.user_login = '';
                    forgotError.value = false;
                    showForgot.value = false;
                } else {
                    forgotError.value = true;
                    ElementPlus.ElMessage.error((response.data && response.data.data && response.data.data.msg) || (labels.forgot_failed || 'Error'));
                }
            } catch (error) {
                forgotError.value = true;
                ElementPlus.ElMessage.error(labels.forgot_failed || 'Error');
            } finally {
                sendingForgot.value = false;
            }
        };

        const doLogin = async () => {
            loginErrors.username = !(loginForm.username || '').trim();
            loginErrors.password = !(loginForm.password || '').trim();
            if (loginErrors.username || loginErrors.password) {
                return;
            }
            loggingIn.value = true;
            try {
                const params = buildAjaxParams('bookwellab_cp_login', authNonce, {
                    username: loginForm.username || '',
                    password: loginForm.password || '',
                    remember: loginForm.remember ? '1' : '0',
                });
                const response = await axios.post(config.ajax_url, params);
                if (response.data && response.data.success) {
                    if (labels.login_success) {
                        ElementPlus.ElMessage.success(labels.login_success);
                    }
                    window.location.reload();
                } else {
                    ElementPlus.ElMessage.error((response.data && response.data.data && response.data.data.msg) || 'Error');
                    loggingIn.value = false;
                }
            } catch (error) {
                ElementPlus.ElMessage.error('Error');
                loggingIn.value = false;
            }
        };

        const activeTab = ref('my_appointments');
        const profile = reactive({ ...(config.profile || {}) });
        const profileForm = reactive({
            first_name: profile.first_name || '',
            last_name: profile.last_name || '',
            email: profile.email || '',
            phone: profile.phone || '',
        });

        const defaultAccountField = (key) => ({
            label: labels[key] || '',
            placeholder: '',
            error_message: '',
            required: key === 'first_name' || key === 'email',
            hidden: false,
        });
        const rawAccountFields = config.account_fields || {};
        const accountFields = reactive({
            first_name: { ...defaultAccountField('first_name'), ...(rawAccountFields.first_name || {}) },
            last_name: { ...defaultAccountField('last_name'), ...(rawAccountFields.last_name || {}) },
            email: { ...defaultAccountField('email'), ...(rawAccountFields.email || {}) },
            phone: { ...defaultAccountField('phone'), ...(rawAccountFields.phone || {}) },
        });
        const profileErrors = reactive({
            first_name: '',
            last_name: '',
            phone: '',
        });
        const passwordErrors = reactive({
            current_password: false,
            new_password: false,
            confirm_password: false,
        });
        const accountFieldLabel = (key) => {
            const field = accountFields[key] || {};
            return field.label || labels[key] || '';
        };
        const passwordForm = reactive({
            current_password: '',
            new_password: '',
            confirm_password: '',
        });
        const filters = reactive({
            date_range: [],
            search: '',
        });
        const appointments = ref([]);
        const loadingAppointments = ref(isLoggedIn);
        const savingProfile = ref(false);
        const savingPassword = ref(false);
        const currentPage = ref(1);
        const totalAppointments = ref(0);
        const perPage = 6;
        const expandedAppointmentId = ref(null);
        const mobileMenuOpen = ref(false);

        const setTab = (tab) => {
            activeTab.value = tab;
        };

        const toggleMobileMenu = () => {
            mobileMenuOpen.value = !mobileMenuOpen.value;
        };

        const closeMobileMenu = () => {
            mobileMenuOpen.value = false;
        };

        const statusTagType = (status) => {
            const value = String(status || '').toLowerCase();
            if (value === 'approved' || value === 'paid') return 'success';
            if (value === 'pending') return 'warning';
            if (value === 'cancelled' || value === 'canceled' || value === 'failed') return 'info';
            return 'info';
        };

        const toggleAppointmentExpand = (appointmentId) => {
            expandedAppointmentId.value = expandedAppointmentId.value === appointmentId ? null : appointmentId;
        };

        const shouldShowPagination = () => Number(totalAppointments.value || 0) > Number(perPage || 0);

        const loadAppointments = async (page = 1) => {
            if (!isLoggedIn) return;
            currentPage.value = page;
            loadingAppointments.value = true;
            expandedAppointmentId.value = null;
            try {
                const payload = {
                    page: String(page),
                    search: filters.search || '',
                };
                if (Array.isArray(filters.date_range) && filters.date_range.length === 2) {
                    payload.date_from = filters.date_range[0] || '';
                    payload.date_to = filters.date_range[1] || '';
                }
                const params = buildAjaxParams('bookwellab_cp_get_appointments', panelNonce, payload);

                const response = await axios.post(config.ajax_url, params);
                if (response.data && response.data.success) {
                    appointments.value = (response.data.data.items || []).filter((item) => item && item.id);
                    totalAppointments.value = response.data.data.total || 0;
                } else {
                    ElementPlus.ElMessage.error((response.data && response.data.data && response.data.data.msg) || 'Error');
                }
            } catch (error) {
                ElementPlus.ElMessage.error('Error loading appointments');
            } finally {
                loadingAppointments.value = false;
            }
        };

        const cancelAppointment = async (appointmentId) => {
            try {
                const params = buildAjaxParams('bookwellab_cp_cancel_appointment', panelNonce, {
                    appointment_id: String(appointmentId),
                });
                const response = await axios.post(config.ajax_url, params);
                if (response.data && response.data.success) {
                    ElementPlus.ElMessage.success(labels.cancelled_success || response.data.data.msg);
                    loadAppointments(currentPage.value);
                } else {
                    ElementPlus.ElMessage.error((response.data && response.data.data && response.data.data.msg) || 'Error');
                }
            } catch (error) {
                ElementPlus.ElMessage.error('Error');
            }
        };

        const validateProfile = () => {
            profileErrors.first_name = '';
            profileErrors.last_name = '';
            profileErrors.phone = '';
            let valid = true;

            const checks = ['first_name', 'last_name', 'phone'];
            checks.forEach((key) => {
                const field = accountFields[key] || {};
                if (field.hidden) {
                    return;
                }
                if (field.required && !(profileForm[key] || '').toString().trim()) {
                    profileErrors[key] = field.error_message
                        || ((accountFieldLabel(key) || key) + ' is required.');
                    valid = false;
                }
            });

            return valid;
        };

        const saveProfile = async () => {
            if (!validateProfile()) {
                return;
            }
            savingProfile.value = true;
            try {
                const params = buildAjaxParams('bookwellab_cp_update_profile', panelNonce, {
                    first_name: profileForm.first_name || '',
                    last_name: profileForm.last_name || '',
                    phone: profileForm.phone || '',
                    phone_code: profile.phone_code || '',
                });
                const response = await axios.post(config.ajax_url, params);
                if (response.data && response.data.success) {
                    Object.assign(profile, response.data.data.profile || {});
                    ElementPlus.ElMessage.success(labels.profile_updated || response.data.data.msg);
                } else {
                    ElementPlus.ElMessage.error((response.data && response.data.data && response.data.data.msg) || 'Error');
                }
            } catch (error) {
                ElementPlus.ElMessage.error('Error');
            } finally {
                savingProfile.value = false;
            }
        };

        const validatePassword = () => {
            passwordErrors.current_password = !(passwordForm.current_password || '').trim();
            passwordErrors.new_password = !(passwordForm.new_password || '').trim();
            passwordErrors.confirm_password = !(passwordForm.confirm_password || '').trim();
            return !passwordErrors.current_password
                && !passwordErrors.new_password
                && !passwordErrors.confirm_password;
        };

        const savePassword = async () => {
            if (!validatePassword()) {
                return;
            }
            savingPassword.value = true;
            try {
                const params = buildAjaxParams('bookwellab_cp_change_password', panelNonce, {
                    current_password: passwordForm.current_password || '',
                    new_password: passwordForm.new_password || '',
                    confirm_password: passwordForm.confirm_password || '',
                });
                const response = await axios.post(config.ajax_url, params);
                if (response.data && response.data.success) {
                    passwordForm.current_password = '';
                    passwordForm.new_password = '';
                    passwordForm.confirm_password = '';
                    ElementPlus.ElMessage.success(labels.password_updated || response.data.data.msg);
                } else {
                    ElementPlus.ElMessage.error((response.data && response.data.data && response.data.data.msg) || 'Error');
                }
            } catch (error) {
                ElementPlus.ElMessage.error('Error');
            } finally {
                savingPassword.value = false;
            }
        };

        onMounted(() => {
            injectAppearanceStyles(config.appearance || {});
            if (isLoggedIn) {
                loadAppointments(1);
            }
        });

        return {
            labels,
            isLoggedIn,
            isCustomer,
            loginUrl,
            logoutUrl,
            lostPasswordUrl,
            bookingUrl,
            loginForm,
            loginErrors,
            loggingIn,
            doLogin,
            showForgot,
            forgotForm,
            forgotError,
            sendingForgot,
            openForgot,
            closeForgot,
            doLostPassword,
            activeTab,
            profile,
            profileForm,
            accountFields,
            accountFieldLabel,
            profileErrors,
            passwordForm,
            passwordErrors,
            filters,
            appointments,
            loadingAppointments,
            savingProfile,
            savingPassword,
            currentPage,
            totalAppointments,
            perPage,
            expandedAppointmentId,
            mobileMenuOpen,
            setTab,
            toggleMobileMenu,
            closeMobileMenu,
            statusTagType,
            toggleAppointmentExpand,
            shouldShowPagination,
            loadAppointments,
            cancelAppointment,
            saveProfile,
            savePassword,
        };
    },
}).use(ElementPlus).mount('#bookwellab_customer_panel_app');
