import { __ } from '@/utils/i18n';

/**
 * Default form options structure
 */
export const formDefaults = {
    store_submissions: true,
    send_email: true,
    use_global_email_delivery: true,
    use_global_recipient: true,
    use_global_from_name: true,
    use_global_from_email: true,
    email_recipient: '',
    email_subject: '',
    email_from_name: '',
    email_from_address: '',
    honeypot: true,
    throttle: {
        max_requests: 3,
        per_seconds: 10,
    },
    success_message: __(
        'Thanks! Your message has been sent.',
        'formatrica'
    ),
    error_message: __(
        'Something went wrong. Please fix the errors and try again.',
        'formatrica'
    ),
    ip_storage: 'anonymous',
    delete_submissions_after_days_enabled: false,
    delete_submissions_after_days: 90,
    captcha: {
        provider: 'none',
        site_key: '',
        secret_key: '',
        secret_key_set: false,
        remove_secret_key: false,
    },
    email_delivery: {
        provider: 'wordpress',
        sendgrid: {
            api_key: '',
        },
        mailgun: {
            api_key: '',
            domain: '',
            region: 'us',
        },
        postmark: {
            api_token: '',
        },
        brevo: {
            api_key: '',
        },
        amazon_ses: {
            access_key: '',
            secret_key: '',
            region: 'us-east-1',
        },
        mailpit: {
            host: '127.0.0.1',
            port: 1025,
        },
        smtp2go: {
            api_key: '',
        },
        smtp: {
            host: '',
            port: 587,
            encryption: 'tls',
            username: '',
            password: '',
            password_set: false,
        },
    },
    custom_css: '',
    theme: {
        preset: 'classic',
        brand_color: '',
        mode: 'auto',
    },
    layout: {
        mode: 'single',
    },
    submit_action: {
        type: 'same_page',
        url: '',
    },
    wrapper_class: '',
    // Headless API submissions (Pro api.headless). Key input is write-only.
    headless_submission_enabled: false,
    headless_api_key: '',
    headless_api_key_set: false,
    headless_allowed_ips: [],
    webhooks: {
        enabled: false,
        endpoint: '',
        secret: '',
        secret_set: false,
        remove_secret: false,
    },
    integrations: {
        zapier: {
            enabled: false,
            webhook_url: '',
        },
        make: {
            enabled: false,
            webhook_url: '',
            // Make API-key auth (Pro P-WH2). Write-only: '' means keep stored.
            api_key: '',
            api_key_set: false,
            remove_api_key: false,
        },
        twilio: {
            enabled: false,
            account_sid: '',
            api_key_sid: '',
            // Write-only secret: '' means keep the stored encrypted key.
            api_key_secret: '',
            api_key_secret_set: false,
            remove_api_key_secret: false,
            sender_mode: 'number',
            from_number: '',
            messaging_service_sid: '',
            recipient_number: '',
            message_template: '',
            region: 'us1',
        },
        slack: {
            enabled: false,
            webhook_url: '',
            message_template: '',
        },
        wordpress_post: {
            enabled: false,
            post_type: 'post',
            post_status: 'pending',
            author_mode: 'current_user',
            fixed_author_id: 0,
            map: {
                title: '',
                content: '',
                excerpt: '',
                featured_image: '',
            },
            taxonomies: [],
            meta: [],
        },
        mailchimp: {
            enabled: false,
            api_key: '',
            api_key_set: false,
            remove_api_key: false,
            list_id: '',
            double_opt_in: false,
            email_field: '',
            first_name_field: '',
            last_name_field: '',
            tags_input: '',
        },
        brevo: {
            enabled: false,
            api_key: '',
            api_key_set: false,
            remove_api_key: false,
            list_id: '',
            email_field: '',
            first_name_field: '',
            last_name_field: '',
            tags_input: '',
        },
        salesforce: {
            enabled: false,
            org_id: '',
            lead_source: '',
            assignment_rule_id: '',
            debug_email: '',
            mappings: [],
        },
        hubspot: {
            enabled: false,
            access_token: '',
            access_token_set: false,
            remove_access_token: false,
            portal_id: '',
            form_guid: '',
            email_field: '',
            field_mappings: [],
            legal_consent: false,
            consent_text: '',
        },
        woocommerce: {
            enabled: false,
            product_mode: 'static',
            static_products: [],
            product_field: '',
            quantity_field: '',
            variation_field: '',
            price_field: '',
            order_status: 'wc-pending',
            create_customer: true,
            customer: {
                email_field: '',
                first_name_field: '',
                last_name_field: '',
                phone_field: '',
                company_field: '',
                billing: {
                    line1_field: '',
                    line2_field: '',
                    city_field: '',
                    state_field: '',
                    postcode_field: '',
                    country_field: '',
                },
                shipping: {
                    use_billing: true,
                    line1_field: '',
                    line2_field: '',
                    city_field: '',
                    state_field: '',
                    postcode_field: '',
                    country_field: '',
                },
            },
            metadata: [],
        },
    },
    // Wave 5 Pro feature option blocks — MUST be present so the per-form settings
    // tabs (Save & Resume, Payments, Email submitter/template) bind to a real
    // object. The server sanitizer is the allow-list.
    drafts: {
        enabled: false,
        resume_email_field: '',
        expiry_days: 14,
        resume_button_label: '',
        resume_email_subject: '',
        resume_email_intro: '',
        delete_after_final_submit: true,
    },
    submitter_email: {
        enabled: false,
        recipient_email_field: '',
        subject: __('Thank you for your submission', 'formatrica'),
        body: __(
            'Thank you for submitting {{form_title}}.\n\nWe received your message and will get back to you soon.',
            'formatrica'
        ),
        use_global_from_email: true,
        from_email: '',
        use_global_from_name: true,
        from_name: '',
        reply_to_email: '',
    },
    email_template: {
        show_title: true,
        show_metadata: true,
        font_stack: 'system',
        use_global_accent: true,
        accent_color: '',
        intro_text: '',
        footer_text: '',
    },
    payments: {
        enabled: false,
        provider: 'stripe',
        mode: 'test',
        currency: 'USD',
        amount_mode: 'fixed',
        fixed_amount: '',
        price_field_key: '',
        calculation_field_name: '',
        description: '',
        cancel_redirect: '',
    },
};

/**
 * Deep merge utility that merges source into target
 * Arrays are replaced, not merged
 * Objects are recursively merged
 * @param {Object} target - Target object
 * @param {Object} source - Source object
 * @returns {Object} Merged object
 */
export function deepMerge(target, source) {
    const output = { ...target };

    if (!isObject(target) || !isObject(source)) {
        return output;
    }

    Object.keys(source).forEach((key) => {
        const sourceValue = source[key];
        const targetValue = target[key];

        if (Array.isArray(sourceValue)) {
            // Arrays are replaced, not merged
            output[key] = sourceValue;
        } else if (isObject(sourceValue)) {
            // Recursively merge objects
            output[key] = deepMerge(targetValue || {}, sourceValue);
        } else {
            // Primitive values are replaced
            output[key] = sourceValue;
        }
    });

    return output;
}

/**
 * Check if value is a plain object
 * @param {*} value
 * @returns {boolean}
 */
function isObject(value) {
    return value !== null && typeof value === 'object' && !Array.isArray(value);
}

/**
 * Create a fresh copy of form defaults
 * @returns {Object}
 */
export function createFormDefaults() {
    return JSON.parse(JSON.stringify(formDefaults));
}
