frappe.ui.form.on('Lead', {
    refresh(frm) {
        // Only show the button if the Lead has been saved and has an email
        if (!frm.doc.__islocal && frm.doc.email_id) {
            frm.add_custom_button(__('Add to Email Campaign'), () => {
                open_email_campaign_dialog(frm);
            }, __('Action'));
        } else if (!frm.doc.email_id) {
            // Optional: give user visual feedback
            frm.dashboard.set_headline(__('This Lead has no email address — cannot add to Email Campaign.'));
        }
    }
});

function open_email_campaign_dialog(frm) {
    frappe.prompt([
        {
            fieldname: 'campaign_name',
            label: 'Campaign',
            fieldtype: 'Link',
            options: 'Campaign',
            reqd: 1
        },
        {
            fieldname: 'start_date',
            label: 'Start Date',
            fieldtype: 'Date',
            default: frappe.datetime.get_today(),
            reqd: 1
        }
    ],
    (values) => {
        frappe.call({
            method: 'rangeldigital.utilities.lead.lead_api.add_lead_to_campaign',
            args: {
                lead_name: frm.doc.name,
                campaign_name: values.campaign_name,
                start_date: values.start_date
            },
            freeze: true,
            freeze_message: __('Creating Email Campaign...'),
            callback: (r) => {
                if (r.message && r.message.status === 'success') {
                    frappe.show_alert({
                        message: __('Email Campaign created successfully'),
                        indicator: 'green'
                    });
                } else {
                    frappe.msgprint(__('Something went wrong. Please try again.'));
                }
            },
            error: (err) => {
                if (err && err.message) {
                    frappe.msgprint(err.message);
                } else {
                    frappe.msgprint(__('Unexpected error. Check the console.'));
                    console.error(err);
                }
            }
        });
    },
    __('New Email Campaign'),
    __('Create')
    );
}
