jQuery(function ($) {
// state: array of nodes (ordered)
let vf_nodes = []; // each node: {type: 'delay'|'email', data:{...}, id:uid}
let editingNodeId = null;

// utilities
const uid = () => 'n' + Math.random().toString(36).substr(2, 9);

// render canvas
function renderCanvas() {
    const $c = $('#vf-canvas');
    $c.find('.vf-card, .vf-connector').remove();
    // start badge already present
    for (let i = 0; i < vf_nodes.length; i++) {
    const node = vf_nodes[i];
    const $card = $(renderCard(node, i + 1));
    $c.append($card);
    $c.append('<div class="vf-connector" data-idx="' + i + '"></div>');
    }
    // make sortable (vertical within canvas)
    $c.sortable({
    items: '.vf-card',
    axis: 'y',
    placeholder: 'vf-card-placeholder',
    update: function (e, ui) {
        // rebuild vf_nodes order
        const newNodes = [];
        $c.find('.vf-card').each(function () {
        const nid = $(this).data('id');
        const node = vf_nodes.find(n => n.id === nid);
        if (node) newNodes.push(node);
        });
        vf_nodes = newNodes;
        renderCanvas();
    }
    });
}

function renderCard(node, index) {
    if (node.type === 'delay') {
    return `
    <div class="vf-card" data-id="${node.id}">
        <div class="vf-card-header">
        <div class="vf-card-title">Delay</div>
        <div class="vf-card-type">Delay</div>
        </div>
        <div class="vf-card-body">
        <div class="vf-delay-row">
            <input type="number" class="vf-delay-num" value="${node.data.delay || 1}" min="0">
            <select class="vf-delay-unit">
            <option value="minutes" ${node.data.unit==='minutes'?'selected':''}>Minutes</option>
            <option value="hours" ${node.data.unit==='hours'?'selected':''}>Hours</option>
            <option value="days" ${node.data.unit==='days'?'selected':''}>Days</option>
            </select>
            <span class="vf-meta">after previous step</span>
        </div>
        </div>
        <div class="vf-actions">
        <button class="vf-save-delay" title="Save delay">Save Delay 💾</button>
        <button class="vf-remove" title="Remove"><i class="dashicons dashicons-trash"></i></button>
        </div>
    </div>
    `;
    } else {
    const subj = node.data.subject ? escapeHtml(node.data.subject) : 'Email';
    const preview = node.data.html ? node.data.html.replace(/(<([^>]+)>)/gi, "").substr(0, 120) : '';
    return `
    <div class="vf-card" data-id="${node.id}">
        <div class="vf-card-header">
        <div>
            <div class="vf-card-title">${subj}</div>
            <div class="vf-meta">${escapeHtml(node.data.preview || preview)}</div>
        </div>
        <div class="vf-card-type">Email</div>
        </div>
        <div class="vf-card-body">
        <div class="vf-meta">Subject: ${escapeHtml(node.data.subject || '')}</div>
        </div>
        <div class="vf-actions">
        <button class="vf-edit-email" title="Edit email"><i class="dashicons dashicons-edit"></i></button>
        <button class="vf-remove" title="Remove"><i class="dashicons dashicons-trash"></i></button>
        </div>
    </div>
    `;
    }
}

function escapeHtml(t) {
    return String(t || '').replace(/[&<>"']/g, function (m) {
    return {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#39;'
    } [m];
    });
}

// Add nodes
$('#vf-add-delay').on('click', function () {
    vf_nodes.push({
    id: uid(),
    type: 'delay',
    data: {
        delay: 1,
        unit: 'hours'
    }
    });
    renderCanvas();
});
$('#vf-add-email').on('click', function () {
    vf_nodes.push({
    id: uid(),
    type: 'email',
    data: {
        subject: '',
        html: '',
        preview: ''
    }
    });
    renderCanvas();
    // open editor on last email for convenience
    setTimeout(() => {
    const last = vf_nodes[vf_nodes.length - 1];
    openEmailEditor(last.id);
    }, 80);
});

// click handlers - delegate
$('#vf-canvas').on('click', '.vf-remove', function () {
    const id = $(this).closest('.vf-card').data('id');
    if (!confirm('Remove this step?')) return;
    vf_nodes = vf_nodes.filter(n => n.id !== id);
    renderCanvas();
});

$('#vf-canvas').on('click', '.vf-save-delay', function () {
    const $card = $(this).closest('.vf-card');
    const id = $card.data('id');
    const d = parseInt($card.find('.vf-delay-num').val() || 0);
    const unit = $card.find('.vf-delay-unit').val();
    const node = vf_nodes.find(n => n.id === id);
    if (node && node.type === 'delay') {
    node.data.delay = d;
    node.data.unit = unit;
    $(this).prop('disabled', true).text('✓').delay(800).queue(function (next) {
        $(this).prop('disabled', false).text('💾');
        next();
    });
    }
});

// edit email
$('#vf-canvas').on('click', '.vf-edit-email', function () {
    const id = $(this).closest('.vf-card').data('id');
    openEmailEditor(id);
});

// modal logic
function openEmailEditor(nodeId) {
    const node = vf_nodes.find(n => n.id === nodeId);
    if (!node) return;
    editingNodeId = nodeId;
    $('#vf-modal-subject').val(node.data.subject || '');
    
    // $('#vf-editor').html(node.data.html || '<p></p>');

    var content = node.data.html;
    var ed = tinyMCE.get('vf_email_editor');
    if (ed && !ed.isHidden()) {
        ed.setContent(content);
    } else {
        $('#vf_email_editor').val(content);
    }



    $('#vf-email-modal').attr('aria-hidden', 'false');
    // focus cursor
    // setTimeout(() => $('#vf-editor').focus(), 80);
}

$('#vf-modal-cancel').on('click', function () {
    $('#vf-email-modal').attr('aria-hidden', 'true');
    editingNodeId = null;
});

$('#vf-modal-save').on('click', function () {
    const subj = $('#vf-modal-subject').val();
    
    // const html = $('#vf-editor').html();
    const html = getVFEmailContent();


    const preview = stripTags(html).substr(0, 200);
    const node = vf_nodes.find(n => n.id === editingNodeId);
    if (node && node.type === 'email') {
    node.data.subject = subj;
    node.data.html = html;
    node.data.preview = preview;
    }
    editingNodeId = null;
    $('#vf-email-modal').attr('aria-hidden', 'true');
    renderCanvas();
});

function getVFEmailContent(){
    if ( tinyMCE.get('vf_email_editor') ) {
        return tinyMCE.get('vf_email_editor').getContent();
    } else {
        return $('#vf_email_editor').val(); // textarea raw value
    }
}


// toolbar commands
// $('.vf-editor-toolbar').on('click', 'button', function () {
//     const cmd = $(this).data('cmd');
//     if (cmd === 'createLink') {
//     const url = prompt('Enter URL');
//     if (url) document.execCommand('createLink', false, url);
//     } else if (cmd === 'insertImage') {
//     const url = prompt('Image URL');
//     if (url) document.execCommand('insertImage', false, url);
//     } else if (cmd === 'viewHtml') {
//     const cur = $('#vf-editor');
//     const html = cur.html();
//     const newHtml = prompt('Edit raw HTML', html);
//     if (newHtml !== null) cur.html(newHtml);
//     } else {
//     document.execCommand(cmd, false, null);
//     }
// });

function stripTags(html) {
    return html.replace(/<\/?[^>]+(>|$)/g, "");
}

// Save workflow -> serialize nodes to JSON and send AJAX
$('#vf-save-workflow').on('click', function () {
    const form_id = $('#vf-form-id').val();
    const name = $('#vf-workflow-name').val().trim();
    var selectemail = $('#vf-email-field-select').val();
    
    if (!form_id) return alert('Please select a form.');
    if (!name) return alert('Give this workflow a name.');
    if (!selectemail) return alert('Please select an email.');
    // ensure at least one node
    if (vf_nodes.length === 0) return alert('Add at least one step (Delay or Email).');

    // build simplified JSON: array with type + data
    const payload = vf_nodes.map(n => {
    if (n.type === 'delay') return {
        type: 'delay',
        delay: parseInt(n.data.delay || 0),
        delay_unit: n.data.unit || 'hours'
    };
    return {
        type: 'email',
        subject: n.data.subject || '',
        html: n.data.html || ''
    };
    });

    const data = new FormData();
    data.append('action', 'vform_save_automation');
    data.append('form_id', form_id);
    data.append('sequence_name', name);
    data.append('selectemail', selectemail);
    data.append('emails', JSON.stringify(payload));
    data.append('automation_id', $('#automation_id').val() || '');

    fetch(ajaxurl, {
        method: 'POST',
        body: data
    })
    .then(r => r.text())
    .then(txt => {
        alert(txt);
        location.reload();
    })
    .catch(e => alert('Save failed'));
});

// load automation for edit
$('.edit-automation').on('click', function () {
    const id = $(this).data('id');
    const data = new FormData();
    data.append('action', 'vform_get_automation');
    data.append('id', id);
    fetch(ajaxurl, {
        method: 'POST',
        body: data
    })
    .then(r => r.json())
    .then(res => {

        $('.vform-automation-main').css('display','flex');
        $('#vf-dashboard-panel').css('display','none');
        $('.vform-automation-header').css('display','none');

        if (!res || !res.emails) return alert('Load failed');
        $('#vf-form-id').val(res.form_id);
        $('#vf-workflow-name').val(res.sequence_name);
        $('#automation_id').val(res.id || '');
        vf_nodes = [];
        // res.emails is expected array as saved above
        res.emails.forEach(step => {
            if (step.type === 'delay') vf_nodes.push({
                id: uid(),
                type: 'delay',
                data: {
                delay: step.delay,
                unit: step.delay_unit || (step.delay_unit ? step.delay_unit : 'hours')
                }
            });
            else if (step.type === 'email') vf_nodes.push({
                id: uid(),
                type: 'email',
                data: {
                subject: step.subject,
                html: step.html,
                preview: (step.html ? stripTags(step.html).substr(0, 120) : '')
                }
            });
        });
        renderCanvas();
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });

        showemailpart(res.form_id,res.useremail);

    });
});

function showemailpart(formId,useremail){
    if (!formId) return;

    $.ajax({
      url: ajaxurl,
      method: 'POST',
      data: {
        action: 'vf_get_form_fields',
        form_id: formId
      },
      beforeSend: function () {
        $('#vf-email-field-select').html('<option>Loading...</option>');
      },
      success: function (response) {
        // console.log(response);

        if (response.success) {

            let fields = Array.isArray(response.data)
            ? response.data
            : Object.values(response.data);

            let options = '<option value="">— select email field —</option>';

            if (fields.length > 0) {
            fields.forEach(field => {
                options += `<option value="${field}">${field}</option>`;
            });
            } else {
            options = '<option>No fields found</option>';
            }

            $('#vf-email-field-select').html(options);

            $('#vf-email-field-select').val(useremail);

                    
        } else {
          $('#vf-email-field-select').html('<option>No fields found</option>');
        }
      },
      error: function () {
        $('#vf-email-field-select').html('<option>Error loading fields</option>');
      }
    });
}

// delete automation
$('.delete-automation').on('click', function () {
    if (!confirm('Delete this workflow?')) return;
    const id = $(this).data('id');
    const data = new FormData();
    data.append('action', 'vform_delete_automation');
    data.append('id', id);
    fetch(ajaxurl, {
        method: 'POST',
        body: data
    })
    .then(() => location.reload());
});

// new workflow button clears canvas
$('#vf-new-workflow').on('click', function () {
    $('.vform-automation-main').css('display','flex');
    $('#vf-dashboard-panel').css('display','none');
    $('.vform-automation-header').css('display','none');
    
    $('#automation_id').val('');
    $('#vf-form-id').val('');
    $('#vf-workflow-name').val('');
    vf_nodes = [];
    renderCanvas();
});

// clear workflow
$('#vf-clear-workflow').on('click', function () {
    if (!confirm('Exit current workflow?')) return;

    $('.vform-automation-main').css('display','none');
    $('#vf-dashboard-panel').css('display','block');
    $('.vform-automation-header').css('display','block');

    vf_nodes = [];
    renderCanvas();
});

// init
renderCanvas();


 $('#vf-form-id').on('change', function () {
    const formId = $(this).val();
    if (!formId) return;

    $.ajax({
      url: ajaxurl,
      method: 'POST',
      data: {
        action: 'vf_get_form_fields',
        form_id: formId
      },
      beforeSend: function () {
        $('#vf-email-field-select').html('<option>Loading...</option>');
      },
      success: function (response) {
        // console.log(response);

        if (response.success) {

            let fields = Array.isArray(response.data)
            ? response.data
            : Object.values(response.data);

            let options = '<option value="">— select email field —</option>';

            if (fields.length > 0) {
            fields.forEach(field => {
                options += `<option value="${field}">${field}</option>`;
            });
            } else {
            options = '<option>No fields found</option>';
            }

            $('#vf-email-field-select').html(options);
                    
        } else {
          $('#vf-email-field-select').html('<option>No fields found</option>');
        }
      },
      error: function () {
        $('#vf-email-field-select').html('<option>Error loading fields</option>');
      }
    });
  });
  
});