jQuery(function ($) {
  let fieldId = 0;
  let rowId = 0;
  let currentFieldType = null;
 renderFormFromJSON(wpefb_admin_ajax_object.form_options);

  const proConfig = (wpefb_admin_ajax_object && wpefb_admin_ajax_object.pro) ? wpefb_admin_ajax_object.pro : {};
  const isProEnabled = !!proConfig.enabled;
  const lockedFieldTypes = Array.isArray(proConfig.locked_field_types) ? proConfig.locked_field_types : [];
  const upgradeUrl = String(proConfig.upgrade_url || '').trim();
  const pricingUrl = String(proConfig.pricing_url || '').trim();
  const proLogoUrl = String(proConfig.logo_url || '').trim();

  function isInternalProPage(url) {
    return String(url || '').indexOf('page=wpefb_pro') !== -1;
  }

  function isLockedFieldType(type) {
    return lockedFieldTypes.includes(String(type || ''));
  }

  function getProUpsellModal() {
    let $modal = $('#wefb-pro-upsell-modal');

    if ($modal.length) {
      return $modal;
    }

    const upgradeButton = upgradeUrl
      ? `<a class="button button-primary wefb-pro-modal-upgrade" href="${upgradeUrl}" ${isInternalProPage(upgradeUrl) ? '' : 'target="_blank" rel="noopener noreferrer"'}>${isInternalProPage(upgradeUrl) ? 'See Pro Features' : 'Upgrade to Pro'}</a>`
      : '';

    const logoHtml = proLogoUrl
      ? `<div class="wefb-pro-modal-brand"><img src="${proLogoUrl}" alt="Vedrixa Forms" class="wefb-pro-modal-logo"></div>`
      : '';

    const modalHtml = `
      <div id="wefb-pro-upsell-modal" class="wefb-pro-modal" role="dialog" aria-modal="true" aria-labelledby="wefb-pro-modal-title">
        <div class="wefb-pro-modal-overlay"></div>
        <div class="wefb-pro-modal-dialog">
          <button type="button" class="wefb-pro-modal-close" aria-label="Close">&times;</button>
          ${logoHtml}
          <h3 id="wefb-pro-modal-title" class="wefb-pro-modal-title"></h3>
          <p class="wefb-pro-modal-message"></p>
          <div class="wefb-pro-modal-actions">
            <button type="button" class="button wefb-pro-modal-dismiss">Maybe Later</button>
            ${upgradeButton}
          </div>
        </div>
      </div>
    `;

    $('body').append(modalHtml);
    $modal = $('#wefb-pro-upsell-modal');

    $modal.on('click', '.wefb-pro-modal-close, .wefb-pro-modal-dismiss, .wefb-pro-modal-overlay', function () {
      hideProUpsellModal();
    });

    $(document).on('keydown.wefbProModal', function (event) {
      if (event.key === 'Escape') {
        hideProUpsellModal();
      }
    });

    return $modal;
  }

  function hideProUpsellModal() {
    $('#wefb-pro-upsell-modal').removeClass('is-open');
    $('body').removeClass('wefb-pro-modal-open');
  }

  function showProFieldAlert(type) {
    const label = formatFieldTypeLabel(type);
    const $modal = getProUpsellModal();

    $modal.find('.wefb-pro-modal-title').text(`${label} is a Pro field`);
    const destination = pricingUrl ? 'See what is included in Pro and compare plans.' : `Unlock ${label} and other advanced fields in Vedrixa Forms Pro.`;
    $modal.find('.wefb-pro-modal-message').text(destination);

    $('body').addClass('wefb-pro-modal-open');
    $modal.addClass('is-open');
  }

  function redirectToProPage(type) {
    if (upgradeUrl) {
      window.location.href = upgradeUrl;
      return;
    }

    showProFieldAlert(type);
  }

  function lockPaletteFieldItem($item) {
    const type = String($item.data('type') || '');

    if (!type || !isLockedFieldType(type)) {
      return;
    }

    $item.addClass('is-pro-locked');
    $item.attr('aria-disabled', 'true');

    if (!$item.find('.wefb-pro-badge').length) {
      $item.append('<span class="wefb-pro-badge">Pro</span>');
    }
  }

  function applyProFieldAvailability() {
    if (isProEnabled || !lockedFieldTypes.length) {
      return;
    }

    $('.field-item').each(function () {
      const $item = $(this);
      lockPaletteFieldItem($item);
    });
  }

  function generateRuntimeFieldId() {
    fieldId += 1;
    return 'wefb_f_' + Date.now() + '_' + fieldId;
  }

  function formatFieldTypeLabel(type) {
    const raw = String(type || '').trim();
    if (!raw) return 'Field';
    return raw.replace(/_/g, ' ').replace(/\b\w/g, ch => ch.toUpperCase());
  }

  function getFieldDisplayLabel(label, name, type) {
    const safeLabel = String(label || '').trim();
    if (safeLabel) return safeLabel;
    const safeName = String(name || '').trim();
    if (safeName) return safeName.replace(/_/g, ' ');
    return formatFieldTypeLabel(type);
  }

  function buildFieldCardHtml(label, type, name) {
    const displayLabel = getFieldDisplayLabel(label, name, type);
    const typeLabel = formatFieldTypeLabel(type);
    return `
      <span class="field-title">${displayLabel}</span>
      <span class="field-bottom-row">
        <span class="field-type-badge">${typeLabel}</span>
        <span class="field-actions">
          <button class="field-settings" title="Field Settings" aria-label="Field Settings">
            <span class="dashicons dashicons-admin-generic"></span>
          </button>
          <button class="remove-field" title="Remove" aria-label="Remove Field">
            <span class="dashicons dashicons-trash"></span>
          </button>
        </span>
      </span>
    `;
  }
 
 
  function createColumn() {
    return $('<div class="column empty" data-field-id=""></div>');
  }

    
    function createSection() {
  const $section = $('<div class="section" data-row-id="' + rowId++ + '"></div>');      
        const $controls = $(`
  <div class="section-controls">
    <button class="remove-row" title="Delete Row" aria-label="Delete Row">
      <span class="dashicons dashicons-trash"></span>
    </button>
    <button class="section-settings" title="Row Settings" aria-label="Row Settings">
      <span class="dashicons dashicons-admin-generic"></span>
    </button>
  </div>
`);

  const $columns = $('<div class="columns"></div>');
  
  $columns.append(createColumn());
  $section.append($controls).append($columns);
  setTimeout(initColumnSortable, 50);
  return $section;
}

$('#wefb-canvas').on('click', '.add-column', function () {
  const $columns = $(this).closest('.section').find('.columns');
  if ($columns.children().length < 4) {
    $columns.append(createColumn());
    setTimeout(initColumnSortable, 50);
  }
});

$('#wefb-canvas').on('click', '.remove-row', function () {
  if (confirm('Are you sure you want to delete this row?')) {
    $(this).closest('.section').remove();
  }
});

//$('#wefb-canvas').on('click', '.section-settings', function () {
//  const $section = $(this).closest('.section');
//  
//  // Toggle settings UI (insert if missing)
//  if ($section.find('.section-settings-panel').length === 0) {
//    const $panel = $(`
//      <div class="section-settings-panel">
//        <label>Column Count:</label>
//        <select class="section-column-count">
//          <option value="1">1 Column</option>
//          <option value="2">2 Columns</option>
//          <option value="3">3 Columns</option>
//          <option value="4">4 Columns</option>
//        </select>
//      </div>
//    `);
//    $section.append($panel);
//  } else {
//    $section.find('.section-settings-panel').toggle();
//  }
//});




//$('#wefb-canvas').on('change', '.section-column-count', function () {
//  const $section = $(this).closest('.section');
//  const $columns = $section.find('.columns');
//  const newCount = parseInt($(this).val());
//
//  const currentFields = $columns.find('.field-rendered').toArray();
//
//  $columns.empty();
//  for (let i = 0; i < newCount; i++) {
//    const $col = $('<div class="column empty"></div>');
//    if (currentFields[i]) {
//      $col.html(currentFields[i]).removeClass('empty');
//    }
//    $columns.append($col);
//  }
//
//  initColumnSortable();
//});


$('#wefb-canvas').on('click', '.section-settings', function () {
  const $section = $(this).closest('.section');

  if ($section.find('.section-settings-panel').length === 0) {
    const $panel = $(`
      <div class="section-settings-panel">
        
        <div class="layout-options">
          ${[1, 2, 3, 4].map(cols => `
            <label class="layout-option" data-cols="${cols}">
              <input type="radio" name="column_layout_${$section.data('id')}" value="${cols}">
              <div class="layout-box">
                ${'<div class="col-box"></div>'.repeat(cols)}
              </div>
            </label>
          `).join('')}
        </div>
      </div>
    `);

    //$section.append($panel);
    $panel.insertBefore($section.find('.columns').first());


    // Layout change logic
    $panel.find('input[type="radio"]').on('change', function () {
      const newCount = parseInt($(this).val());
      const $columns = $section.find('.columns');

      const currentFields = $columns.find('.field-rendered').toArray(); // keep current fields

      $columns.empty();
      for (let i = 0; i < newCount; i++) {
        const $col = $('<div class="column empty" data-id="col-' + Date.now() + '-' + i + '"></div>');
        if (currentFields[i]) {
          $col.html(currentFields[i]).removeClass('empty');
        }
        $columns.append($col);
      }

      initColumnSortable();
    });
  } else {
    $section.find('.section-settings-panel').toggle();
  }
});




//  $('#add-row').on('click', function () {
//    $('#wefb-canvas').append(createSection());
//  });
  
  $('#wefb-canvas').on('click', '#add-row', function () {
    $(this).closest('#wefb-canvas').find('.add-row-button-wrapper').before(createSection());
    initColumnSortable();
  });

  $('#wefb-canvas').on('click', '.add-column', function () {
    const $columns = $(this).closest('.section').find('.columns');
    if ($columns.children().length < 4) {
      $columns.append(createColumn());
    }
  });

  $('#wefb-canvas').on('click', '.remove-column', function () {
    const $columns = $(this).closest('.section').find('.columns');
    if ($columns.children().length > 1) {
      $columns.children().last().remove();
    }
  });

  // Make palette items draggable
  
    $(document).ready(function () {
     initFieldPalette();
     applyProFieldAvailability();
   });

  
  $('.field-item').on('click', function (event) {
  const type = $(this).data('type');

  if (isLockedFieldType(type) && !isProEnabled) {
    event.preventDefault();
    redirectToProPage(type);
    return;
  }
  const label = type.charAt(0).toUpperCase() + type.slice(1);

  // Get first available empty column
  let placed = false;
  $('#wefb-canvas .section').each(function () {
    if (placed) return;
    $(this).find('.column').each(function () {
      if ($(this).find('.field-rendered').length === 0) {
        const $field = $(`
            <div class="field-rendered" data-type="${type}" data-id="${generateRuntimeFieldId()}" data-label="${label}">
              ${buildFieldCardHtml(label, type, '')}
            </div>
          `);    
        $(this).html($field).removeClass('empty');
        placed = true;
        return false;
      }
    });
  });

  if (!placed) alert('No empty column available. Please add a row or column first.');
});

  

  // Make columns droppable
  $(document).on('mouseenter', '.column', function () {
    if (!$(this).hasClass('ui-droppable')) {
      $(this).droppable({
        accept: '.field-item',
        hoverClass: 'drop-hover',
        drop: function (event, ui) {
          const $this = $(this);
          if ($this.find('.field-rendered').length === 0) {
            const type = ui.draggable.data('type');
            if (isLockedFieldType(type) && !isProEnabled) {
              return;
            }
            const label = type.charAt(0).toUpperCase() + type.slice(1);
            const $field = $(`
                <div class="field-rendered" data-type="${type}" data-id="${generateRuntimeFieldId()}" data-label="${label}">
              ${buildFieldCardHtml(label, type, '')}
            </div>
              `);
            $this.html($field).removeClass('empty');
          } else {
            alert('This column already contains a field.');
          }
        }
      });
    }
  });
  
  $('#wefb-canvas').sortable({
    items: '.section',
    handle: '.section-controls',
    placeholder: 'section-placeholder',
    forcePlaceholderSize: true
  });
  
  $('#wefb-canvas').on('click', '.remove-field', function (e) {
    e.stopPropagation();
    const $col = $(this).closest('.column');
    $(this).closest('.field-rendered').remove();
    $col.addClass('empty');
  });


function initFieldPalette() {
  $('#field-palette .field-item').draggable({
    helper: 'clone',
    revert: 'invalid',
    start: function (event, ui) {
      const type = $(this).data('type');
      if (isLockedFieldType(type) && !isProEnabled) {
        showProFieldAlert(type);
        return false;
      }
      ui.helper.css('z-index', 9999);
    }
  });
}


function initColumnSortable() {
  $('.columns .column').sortable({
    connectWith: '.columns .column',
    items: '.field-rendered',
    placeholder: 'field-placeholder',
    forcePlaceholderSize: true,
    receive: function (event, ui) {
      const $target = $(this);

      // If already has a field, reject it
      if ($target.find('.field-rendered').length > 1) {
        $(ui.sender).sortable('cancel');
        alert('Each column can hold only one field.');
      } else {
        $target.removeClass('empty');
      }
    },
    remove: function () {
      if ($(this).children().length === 0) {
        $(this).addClass('empty');
      }
    }
  });
}

function showConditionalFieldOptions(type) {
  const current = String(type || '').toLowerCase();
  $('.field-setting-conditional').hide();
  $('.field-setting-conditional').each(function () {
    const rawTypes = String($(this).data('types') || '').toLowerCase().trim();
    const types = rawTypes ? rawTypes.split(/\s+/) : [];
    if (types.includes(current)) {
      $(this).show();
    }
  });
}

function refreshRadioDefaultOptions(optionsArray, selectedValue) {
  const $select = $('#field-settings-form select[name="radio_default_value"]');
  const baseLabel = $('#field-settings-form select[name="radio_default_value"] option:first').text() || 'None';
  const current = selectedValue !== undefined ? selectedValue : $select.val();
  $select.empty().append('<option value="">' + baseLabel + '</option>');
  if (Array.isArray(optionsArray)) {
    optionsArray.forEach(opt => {
      if (!opt || typeof opt !== 'object') return;
      const value = opt.value || '';
      const label = opt.label || value;
      const isSelected = current && current === value ? ' selected' : '';
      $select.append('<option value="' + value.replace(/"/g, '&quot;') + '"' + isSelected + '>' + label + '</option>');
    });
  }
  if (!current) {
    $select.val('');
  }
}

function makeReferenceName(value) {
  return String(value || '')
    .toLowerCase()
    .replace(/\s+/g, '_')
    .replace(/[^a-z0-9_]/g, '')
    .replace(/_+/g, '_')
    .replace(/^_+|_+$/g, '')
    .slice(0, 40);
}

function isReferenceNameTaken(name, currentId) {
  let taken = false;
  const target = String(name || '').trim().toLowerCase();
  if (!target) return false;

  $('.field-rendered').each(function () {
    const $item = $(this);
    const itemId = String($item.data('id'));
    const itemName = String($item.attr('data-name') || '').trim().toLowerCase();
    if (!itemName) return;
    if (itemId !== String(currentId) && itemName === target) {
      taken = true;
      return false;
    }
  });

  return taken;
}

function updateTextFieldPreview($form) {
  const type = String(currentFieldType || '').toLowerCase();
  const supportedTypes = ['text', 'email', 'number', 'first_name', 'last_name', 'user_name', 'user_email', 'nickname', 'user_url', 'user_pass', 'confirm_pass', 'mobile_number', 'phone_number', 'repeatable_text'];
  if (!supportedTypes.includes(type)) return;
  const label = ($form.find('[name="label"]').val() || '').trim();
  const placeholder = ($form.find('[name="placeholder"]').val() || '').trim();
  const required = $form.find('[name="required"]').is(':checked');
  const previewTypeMap = {
    email: 'email',
    number: 'number',
    user_pass: 'password',
    confirm_pass: 'password',
    user_url: 'url'
  };
  const previewLabelMap = {
    first_name: 'First Name',
    last_name: 'Last Name',
    user_name: 'Username',
    user_email: 'User Email',
    user_url: 'User URL',
    user_pass: 'Password',
    confirm_pass: 'Confirm Password',
    mobile_number: 'Mobile Number',
    phone_number: 'Phone Number',
    repeatable_text: 'Repeatable Text'
  };
  const previewPlaceholderMap = {
    email: 'you@example.com',
    number: '123',
    user_url: 'https://example.com',
    user_pass: 'Enter password',
    confirm_pass: 'Confirm password',
    mobile_number: 'Enter mobile number',
    phone_number: 'Enter phone number'
  };
  const previewLabel = label || previewLabelMap[type] || 'Text';
  const requiredSuffix = required ? ' *' : '';
  const inputType = previewTypeMap[type] || 'text';

  $form.find('.wefb-text-preview-label').text(previewLabel + requiredSuffix);
  $form.find('.wefb-text-preview-input')
    .attr('type', inputType)
    .attr('placeholder', placeholder || previewPlaceholderMap[type] || 'Type here...');
}

function updateTextareaFieldPreview($form) {
  const type = String(currentFieldType || '').toLowerCase();
  if (!['textarea', 'description'].includes(type)) return;
  const label = ($form.find('[name="label"]').val() || '').trim();
  const placeholder = ($form.find('[name="placeholder"]').val() || '').trim();
  const required = $form.find('[name="required"]').is(':checked');
  const rows = parseInt(($form.find('[name="rows"]').val() || '4'), 10);
  const safeRows = Number.isFinite(rows) && rows > 1 ? rows : 4;
  const previewLabel = label || (type === 'description' ? 'Description' : 'Textarea');
  const requiredSuffix = required ? ' *' : '';

  $form.find('.wefb-textarea-preview-label').text(previewLabel + requiredSuffix);
  $form.find('.wefb-textarea-preview-input').attr('placeholder', placeholder || 'Type here...');
  $form.find('.wefb-textarea-preview-input').attr('rows', safeRows);
}

function updateCheckboxFieldPreview($form) {
  if (currentFieldType !== 'checkbox') return;
  const label = ($form.find('[name="label"]').val() || '').trim();
  const required = $form.find('[name="required"]').is(':checked');
  const previewLabel = label || 'Checkbox';
  const requiredSuffix = required ? ' *' : '';
  const $optionsWrap = $form.find('.wefb-checkbox-preview-options');
  const options = [];

  $form.find('.option-list[data-option-type="checkbox"] .option-item').each(function () {
    const optionLabel = ($(this).find('.option-label').val() || '').trim();
    if (optionLabel) {
      options.push(optionLabel);
    }
  });

  $form.find('.wefb-checkbox-preview-label').text(previewLabel + requiredSuffix);
  $optionsWrap.empty();

  if (!options.length) {
    $optionsWrap.append('<label class="wefb-checkbox-preview-option"><input type="checkbox" disabled> Option 1</label>');
    return;
  }

  options.forEach(function (opt) {
    $optionsWrap.append('<label class="wefb-checkbox-preview-option"><input type="checkbox" disabled> ' + opt + '</label>');
  });
}

function updateRadioFieldPreview($form) {
  if (currentFieldType !== 'radio') return;
  const label = ($form.find('[name="label"]').val() || '').trim();
  const required = $form.find('[name="required"]').is(':checked');
  const defaultValue = ($form.find('[name="radio_default_value"]').val() || '').trim();
  const previewLabel = label || 'Radio';
  const requiredSuffix = required ? ' *' : '';
  const $optionsWrap = $form.find('.wefb-radio-preview-options');
  const options = [];

  $form.find('.option-list[data-option-type="radio"] .option-item').each(function () {
    const optionLabel = ($(this).find('.option-label').val() || '').trim();
    const optionValue = ($(this).find('.option-value').val() || '').trim() || optionLabel;
    if (optionLabel) {
      options.push({ label: optionLabel, value: optionValue });
    }
  });

  $form.find('.wefb-radio-preview-label').text(previewLabel + requiredSuffix);
  $optionsWrap.empty();

  if (!options.length) {
    $optionsWrap.append('<label class="wefb-radio-preview-option"><input type="radio" disabled> Option 1</label>');
    return;
  }

  options.forEach(function (opt) {
    const checked = defaultValue && opt.value === defaultValue ? ' checked' : '';
    $optionsWrap.append('<label class="wefb-radio-preview-option"><input type="radio" disabled' + checked + '> ' + opt.label + '</label>');
  });
}

function updateSpecialFieldPreview($form) {
  const type = String(currentFieldType || '').toLowerCase();
  const label = ($form.find('[name="label"]').val() || '').trim();
  const required = $form.find('[name="required"]').is(':checked');
  const placeholder = ($form.find('[name="placeholder"]').val() || '').trim();
  const defaultValue = ($form.find('[name="default_value"]').val() || '').trim().toLowerCase();
  const requiredSuffix = required ? ' *' : '';

  if (type === 'date' || type === 'datepicker') {
    $form.find('.wefb-date-preview-label').text((label || 'Date') + requiredSuffix);
    $form.find('.wefb-date-preview-input').attr('placeholder', placeholder || 'Select date');
    return;
  }

  if (type === 'country') {
    $form.find('.wefb-country-preview-label').text((label || 'Country') + requiredSuffix);
    $form.find('.wefb-country-preview-select').val(($form.find('[name="default_value"]').val() || '').trim());
    return;
  }

  if (type === 'timezone') {
    $form.find('.wefb-timezone-preview-label').text((label || 'Timezone') + requiredSuffix);
    $form.find('.wefb-timezone-preview-select').val(($form.find('[name="default_value"]').val() || '').trim());
    return;
  }

  if (type === 'language') {
    $form.find('.wefb-language-preview-label').text((label || 'Language') + requiredSuffix);
    const $select = $form.find('.wefb-language-preview-select');
    if ($select.length) {
      const valueMap = {
        english: 'en',
        spanish: 'es',
        french: 'fr',
        german: 'de',
        hindi: 'hi'
      };
      const normalized = valueMap[defaultValue] || defaultValue;
      $select.val(normalized);
    }
    return;
  }

  if (['file', 'file_upload', 'fileupload', 'image', 'user_avatar'].includes(type)) {
    $form.find('.wefb-file-preview-label').text((label || 'File Upload') + requiredSuffix);
    $form.find('.wefb-file-preview-input').attr('accept', ($form.find('[name="accept"]').val() || '').trim());
    return;
  }

  if (type === 'term_checkbox') {
    $form.find('.wefb-terms-preview-label').text((label || 'Terms Checkbox') + requiredSuffix);
    const termsText = ($form.find('[name="term_and_condition"]').val() || '').trim() || 'I agree to the terms and conditions';
    $form.find('.wefb-terms-preview-option').html('<input type="checkbox" disabled> ' + termsText);
  }
}

function makeOptionValue(label) {
  const base = String(label || '').trim();
  if (!base) return '';
  return base
    .toLowerCase()
    .replace(/\s+/g, '_')
    .replace(/[^a-z0-9_]/g, '')
    .replace(/_+/g, '_')
    .replace(/^_+|_+$/g, '');
}

function updateSelectFieldPreview($form) {
  if (!['dropdown', 'select', 'multi_dropdown'].includes(String(currentFieldType || ''))) return;

  const fieldLabel = ($form.find('[name="label"]').val() || '').trim();
  const placeholder = ($form.find('[name="placeholder"]').val() || '').trim();
  const required = $form.find('[name="required"]').is(':checked');
  const defaultValue = ($form.find('[name="default_value"]').val() || '').trim();
  const fieldType = String(currentFieldType || '');
  const isMulti = fieldType === 'multi_dropdown';
  const $previewLabel = $form.find('.wefb-dropdown-preview-label');
  const $previewSelect = $form.find('.wefb-dropdown-preview-select');
  const rows = [];

  $form.find('.option-list[data-option-type="dropdown"] .option-item').each(function () {
    const label = ($(this).find('.option-label').val() || '').trim();
    const value = ($(this).find('.option-value').val() || '').trim() || makeOptionValue(label);
    if (!label) return;
    rows.push({ label, value });
  });

  const marker = required ? ' *' : '';
  const fallbackLabel = isMulti ? 'Multi Dropdown' : 'Dropdown';
  $previewLabel.text((fieldLabel || fallbackLabel) + marker);

  $previewSelect.prop('multiple', isMulti);
  $previewSelect.prop('disabled', true);
  $previewSelect.empty();

  if (!isMulti) {
    const prompt = placeholder || 'Select an option';
    $previewSelect.append('<option value="" selected>' + prompt + '</option>');
  }

  if (!rows.length) {
    $previewSelect.append('<option value="">No options yet</option>');
    return;
  }

  rows.forEach(function (row) {
    const defaultValues = isMulti ? defaultValue.split(',').map(v => String(v || '').trim()).filter(Boolean) : [defaultValue];
    const selected = defaultValues.includes(row.value) ? ' selected' : '';
    $previewSelect.append('<option value="' + row.value.replace(/"/g, '&quot;') + '"' + selected + '>' + row.label + '</option>');
  });
}

function buildOptionItemHtml(type, label, value) {
  const safeType = String(type || 'dropdown');
  const safeLabel = String(label || '');
  const safeValue = String(value || '');
  return (
    '<div class="option-item">' +
      '<input type="text" name="' + safeType + '_option_label[]" placeholder="label" class="option-label">' +
      '<input type="text" name="' + safeType + '_option_value[]" placeholder="value" class="option-value">' +
      '<button type="button" class="remove-option" aria-label="Remove option"><span class="dashicons dashicons-no-alt"></span></button>' +
    '</div>'
  );
}

function ensureAtLeastOneOptionRow($form, optionType) {
  const $list = $form.find('.option-list[data-option-type="' + optionType + '"]');
  if (!$list.length) return;
  if ($list.find('.option-item').length === 0) {
    const $item = $(buildOptionItemHtml(optionType, '', ''));
    $list.append($item);
  }
}

function populateConditionalFieldOptions(currentFieldId,selected) {
  const $select = $('#field-settings-form select[name="conditional_field"]');
  $select.empty().append('<option value="">-- Select Field --</option>');
  const selectedValue = String(selected || '');
  const currentValue = String(currentFieldId || '');

  $('.field-rendered').each(function () {
    const id = $(this).data('id');
    const name = $(this).attr('data-name');
    const label = $(this).attr('data-label') || $(this).text();
   let sel = '';
    if (String(id) !== currentValue) {
        if (String(id) === selectedValue)
        {
            sel='selected="selected"';
        }
      $select.append(`<option value="${id}" ${sel}>${label} (${name})</option>`);
    }
  });
}

function generateFormJSON(formId) {
  const rows = [];

  $('#wefb-canvas .form-row').each(function () {
    const row = {
      row_id: $(this).attr('data-id'),
      columns: []
    };

    $(this).find('.column').each(function () {
      const $field = $(this).find('.field-rendered');
      if ($field.length) {
        const fieldData = {
          id: $field.data('id'),
          type: $field.data('type'),
          label: $field.data('label'),
          name: $field.data('name'),
          placeholder: $field.data('placeholder'),
          required: $field.data('required'),
          default_value: $field.data('default-value'),
          css_class: $field.data('css-class'),
          max_length: $field.data('max-length'),
          options_dropdown: $field.data('options-dropdown'),
          options_radio: $field.data('options-radio'),
          paragraph_text: $field.data('paragraph-text'),
          columns: $field.data('columns'),
          rows: $field.data('rows'),
          heading_text: $field.data('heading-text'),
          heading_tag: $field.data('heading-tag'),
          conditional: {
            enabled: $field.data('conditional-enabled'),
            field: $field.data('conditional-field'),
            operator: $field.data('conditional-operator'),
            value: $field.data('conditional-value')
          }
        };

        row.columns.push({
          col_id: $(this).attr('data-id'),
          field: fieldData
        });
      }
    });

    rows.push(row);
  });

  const formStructure = {
    form_id: formId,
    created_at: new Date().toISOString(),
    layout: rows
  };

  return JSON.stringify(formStructure);
}


  
  $(document).ready(function () {
  const $canvas = $('#wefb-canvas');
  const $addRowButtonWrapper = $canvas.find('.add-row-button-wrapper');
  // Insert the first default section before the plus icon
  if ($canvas.find('.section').length === 0) {
    $addRowButtonWrapper.before(createSection());
  }
  initColumnSortable();
});


$('#field-settings-form').on('change', '#enable_conditional_logic', function () {
  if ($(this).is(':checked')) {
    $('.conditional-logic-settings').show();
  } else {
    $('.conditional-logic-settings').hide();
  }
});


$('#wefb-canvas').on('click', '.field-settings', function () {
  const $field = $(this).closest('.field-rendered');
  const fieldId = $field.data('id');
  const fieldType = String($field.data('type')).toLowerCase();
  const defaultValue = $field.attr('data-default-value') || '';
  currentFieldType = fieldType;

  // Set basic info
  $('#field-settings-form [name="field-id"]').val(fieldId);
  $('#field-settings-form [name="label"]').val($field.attr('data-label') || '');
  $('#field-settings-form [name="name"]').val($field.attr('data-name') || '');
  $('#field-settings-form [name="placeholder"]').val($field.attr('data-placeholder') || '');
  $('#field-settings-form [name="required"]').prop('checked', $field.attr('data-required') === 'true');

  // Extended metadata
  $('#field-settings-form [name="default_value"]').val(defaultValue);
  $('#field-settings-form [name="css_class"]').val($field.attr('data-css-class') || '');
  if (['dropdown', 'select', 'multi_dropdown'].includes(fieldType)) {
    $('#field-settings-form [name="max_length"]').val('');
  } else {
    $('#field-settings-form [name="max_length"]').val($field.attr('data-max-length') || '');
  }

  // Handle options for radio, checkbox, and dropdown/select fields
  const storedOptions = $field.attr('data-options');
  let rawDropdown = '';
  let rawRadio = '';
  // Clear any existing option items in the settings form
  $('#field-settings-form .option-list').each(function () {
    $(this).find('.option-item').remove();
  });

  if (storedOptions) {
    try {
      const options = JSON.parse(storedOptions);
      // Determine which option-list to populate
      let optionTarget = null;
      if (['select', 'multi_dropdown', 'dropdown'].includes(fieldType)) optionTarget = 'dropdown';
      else if (fieldType === 'radio') optionTarget = 'radio';
      else if (fieldType === 'checkbox') optionTarget = 'checkbox';

      if (optionTarget) {
        const $list = $('#field-settings-form .option-list[data-option-type="' + optionTarget + '"]');
        options.forEach(opt => {
          const $item = $(buildOptionItemHtml(optionTarget, '', ''));
          $item.find('.option-label').val(opt.label || '');
          $item.find('.option-value').val(opt.value || opt.label || '');
          $list.append($item);
        });
        if (fieldType === 'radio') {
          refreshRadioDefaultOptions(options, defaultValue);
        }
      }
    } catch (e) {
      console.error('Error parsing options:', e);
    }
  } else {
    // No structured options stored; try to populate from legacy raw attributes if present
    rawDropdown = $field.attr('data-options-dropdown') || '';
    rawRadio = $field.attr('data-options-radio') || '';
    if (rawDropdown) {
      const $list = $('#field-settings-form .option-list[data-option-type="dropdown"]');
      rawDropdown.split('\n').filter(Boolean).forEach(line => {
        const $item = $(buildOptionItemHtml('dropdown', '', ''));
        $item.find('.option-label').val(line.trim());
        $item.find('.option-value').val(line.trim());
        $list.append($item);
      });
    }
    if (rawRadio) {
      const $list = $('#field-settings-form .option-list[data-option-type="radio"]');
      rawRadio.split('\n').filter(Boolean).forEach(line => {
        const $item = $(buildOptionItemHtml('radio', '', ''));
        $item.find('.option-label').val(line.trim());
        $item.find('.option-value').val(line.trim());
        $list.append($item);
      });
      if (fieldType === 'radio') {
        const fallbackOptions = rawRadio.split('\n').filter(Boolean).map(line => ({ label: line.trim(), value: line.trim() }));
        refreshRadioDefaultOptions(fallbackOptions, defaultValue);
      }
    }
  }

  if (fieldType === 'radio' && !storedOptions && !rawRadio) {
    refreshRadioDefaultOptions([], defaultValue);
  }
  if (['dropdown', 'select', 'multi_dropdown'].includes(fieldType)) {
    ensureAtLeastOneOptionRow($('#field-settings-form'), 'dropdown');
  }
  if (fieldType === 'radio') {
    ensureAtLeastOneOptionRow($('#field-settings-form'), 'radio');
  }
  if (fieldType === 'checkbox') {
    ensureAtLeastOneOptionRow($('#field-settings-form'), 'checkbox');
  }

  $('#field-settings-form [name="paragraph_text"]').val($field.attr('data-paragraph-text') || '');
  $('#field-settings-form [name="accept"]').val($field.attr('data-accept') || '');
  $('#field-settings-form [name="term_and_condition"]').val($field.attr('data-term-and-condition') || '');
  $('#field-settings-form [name="columns"]').val($field.attr('data-columns') || '');
  $('#field-settings-form [name="rows"]').val($field.attr('data-rows') || '');
  $('#field-settings-form [name="heading_text"]').val($field.attr('data-heading-text') || '');
  $('#field-settings-form [name="heading_tag"]').val($field.attr('data-heading-tag') || 'h3');
  $('#field-settings-form [name="password_min_length"]').val($field.attr('data-password-min-length') || '8');
  $('#field-settings-form [name="password_require_uppercase"]').prop('checked', $field.attr('data-password-require-uppercase') === 'true');
  $('#field-settings-form [name="password_require_lowercase"]').prop('checked', $field.attr('data-password-require-lowercase') !== 'false');
  $('#field-settings-form [name="password_require_number"]').prop('checked', $field.attr('data-password-require-number') === 'true');
  $('#field-settings-form [name="password_require_special"]').prop('checked', $field.attr('data-password-require-special') === 'true');
  $('#field-settings-form [name="password_show_strength"]').prop('checked', $field.attr('data-password-show-strength') !== 'false');

  // Conditional logic
  const logicEnabled = $field.attr('data-conditional-enabled') === 'true';
  $('#enable_conditional_logic').prop('checked', logicEnabled);
  $('.conditional-logic-settings').toggle(logicEnabled);

  $('#field-settings-form [name="conditional_field"]').val($field.attr('data-conditional-field') || '');
  $('#field-settings-form [name="conditional_operator"]').val($field.attr('data-conditional-operator') || '');
  $('#field-settings-form [name="conditional_value"]').val($field.attr('data-conditional-value') || '');
 
  // Field type setup
  showConditionalFieldOptions(fieldType); // Use the fieldType variable from above
  populateConditionalFieldOptions(fieldId,$field.attr('data-conditional-field'));
  const currentName = String($field.attr('data-name') || '').trim();
  $('#field-settings-form').attr('data-auto-name', currentName ? '0' : '1');
  updateTextFieldPreview($('#field-settings-form'));
  updateTextareaFieldPreview($('#field-settings-form'));
  updateCheckboxFieldPreview($('#field-settings-form'));
  updateRadioFieldPreview($('#field-settings-form'));
  updateSpecialFieldPreview($('#field-settings-form'));
  updateSelectFieldPreview($('#field-settings-form'));

  $('#field-palette').hide();
  $('#wefb-builder').addClass('wef-settings-open');
  $('#field-settings-panel').show();
});

$('#field-settings-form').on('input', '[name="label"]', function () {
  const $form = $('#field-settings-form');
  if (['text', 'email', 'number', 'first_name', 'last_name', 'user_name', 'user_email', 'nickname', 'user_url', 'user_pass', 'confirm_pass', 'mobile_number', 'phone_number', 'repeatable_text'].includes(String(currentFieldType || '').toLowerCase())) {
    const autoName = $form.attr('data-auto-name') === '1';
    if (autoName) {
      const generated = makeReferenceName($(this).val());
      $form.find('[name="name"]').val(generated);
    }
    updateTextFieldPreview($form);
  }
  if (['textarea', 'description'].includes(String(currentFieldType || '').toLowerCase())) {
    updateTextareaFieldPreview($form);
  }
  if (currentFieldType === 'checkbox') {
    updateCheckboxFieldPreview($form);
  }
  if (currentFieldType === 'radio') {
    updateRadioFieldPreview($form);
  }
  updateSpecialFieldPreview($form);
  if (['dropdown', 'select', 'multi_dropdown'].includes(String(currentFieldType || ''))) {
    updateSelectFieldPreview($form);
  }
});

$('#field-settings-form').on('input', '[name="name"]', function () {
  const $form = $('#field-settings-form');
  $form.attr('data-auto-name', '0');
});

$('#field-settings-form').on('input change', '[name="placeholder"], [name="required"]', function () {
  updateTextFieldPreview($('#field-settings-form'));
  updateTextareaFieldPreview($('#field-settings-form'));
  updateCheckboxFieldPreview($('#field-settings-form'));
  updateRadioFieldPreview($('#field-settings-form'));
  updateSpecialFieldPreview($('#field-settings-form'));
  updateSelectFieldPreview($('#field-settings-form'));
});

$('#field-settings-form').on('input change', '[name="default_value"]', function () {
  updateSelectFieldPreview($('#field-settings-form'));
  updateSpecialFieldPreview($('#field-settings-form'));
});

$('#field-settings-form').on('input change', '[name="radio_default_value"]', function () {
  updateRadioFieldPreview($('#field-settings-form'));
});

$('#field-settings-form').on('input change', '[name="rows"]', function () {
  updateTextareaFieldPreview($('#field-settings-form'));
});

$('#field-settings-form').on('input change', '[name="accept"], [name="term_and_condition"]', function () {
  updateSpecialFieldPreview($('#field-settings-form'));
});


$('#field-settings-form').on('submit', function (e) {
  e.preventDefault();

  const $form = $(this);
  const id = $form.find('[name="field-id"]').val();
  const $field = $('.field-rendered[data-id="' + id + '"]');
  const type = String($field.data('type') || '').toLowerCase();

  if (!validateFieldSettingsForm($form, $field, type)) {
    return;
  }

  const label = $form.find('[name="label"]').val();
  const name = $form.find('[name="name"]').val();
  const placeholder = $form.find('[name="placeholder"]').val();
  const required = $form.find('[name="required"]').is(':checked');
  const defaultValue =
    type === 'radio'
      ? ($form.find('[name="radio_default_value"]').val() || '')
      : $form.find('[name="default_value"]').val();
  const cssClass = $form.find('[name="css_class"]').val();
  let maxLength = $form.find('[name="max_length"]').val();
  if (['dropdown', 'select', 'multi_dropdown'].includes(type)) {
    maxLength = '';
  }

  // Collect options from option-list inputs (preferred)
  const dropdownTypes = ['dropdown', 'select', 'multi_dropdown'];
  let options = [];
  let optionTargetKey = null;
  if (dropdownTypes.includes(String($field.data('type')).toLowerCase())) optionTargetKey = 'dropdown';
  else if (String($field.data('type')).toLowerCase() === 'radio') optionTargetKey = 'radio';
  else if (String($field.data('type')).toLowerCase() === 'checkbox') optionTargetKey = 'checkbox';

  if (optionTargetKey) {
    $form.find('.option-list[data-option-type="' + optionTargetKey + '"] .option-item').each(function () {
      const label = $(this).find('.option-label').val() || '';
      const value = $(this).find('.option-value').val() || label;
      if (label.trim()) options.push({ label: label.trim(), value: value.trim() });
    });
  }

  // Fallback: check legacy textarea-style inputs (if present)
  const optionsDropdown = $form.find('[name="options_dropdown"]').val();
  const optionsRadio = $form.find('[name="options_radio"]').val();
  const paragraphText = $form.find('[name="paragraph_text"]').val();
  const accept = $form.find('[name="accept"]').val();
  const multiple = $form.find('[name="wpefb_pro_upload_multiple"]').is(':checked');
  const maxFileSizeKb = $form.find('[name="wpefb_pro_max_file_size_kb"]').val();
  const termAndCondition = $form.find('[name="term_and_condition"]').val();
  const columns = $form.find('[name="columns"]').val();
  const rows = $form.find('[name="rows"]').val();
  const headingText = $form.find('[name="heading_text"]').val();
  const headingTag = $form.find('[name="heading_tag"]').val();
  const passwordMinLength = $form.find('[name="password_min_length"]').val();
  const passwordRequireUppercase = $form.find('[name="password_require_uppercase"]').is(':checked');
  const passwordRequireLowercase = $form.find('[name="password_require_lowercase"]').is(':checked');
  const passwordRequireNumber = $form.find('[name="password_require_number"]').is(':checked');
  const passwordRequireSpecial = $form.find('[name="password_require_special"]').is(':checked');
  const passwordShowStrength = $form.find('[name="password_show_strength"]').is(':checked');

  // Conditional logic
  const logicEnabled = $form.find('#enable_conditional_logic').is(':checked');
  const logicField = $form.find('[name="conditional_field"]').val();
  const logicOperator = $form.find('[name="conditional_operator"]').val();
  const logicValue = $form.find('[name="conditional_value"]').val();

  // Update field display
  $field.html(buildFieldCardHtml(label, type, name));

  // If option items weren't collected from the settings DOM, fall back to legacy textarea fields
  if (typeof options === 'undefined' || (Array.isArray(options) && options.length === 0)) {
    const dropdownTypesFallback = ['dropdown', 'select', 'multi_dropdown'];
    if (dropdownTypesFallback.includes(type) && optionsDropdown) {
      options = optionsDropdown.split('\n').filter(opt => opt.trim()).map(opt => ({ label: opt.trim(), value: opt.trim() }));
    } else if ((type === 'radio' || type === 'checkbox') && optionsRadio) {
      options = optionsRadio.split('\n').filter(opt => opt.trim()).map(opt => ({ label: opt.trim(), value: opt.trim() }));
    }
    if (typeof options === 'undefined') options = [];
  }

  // Save all as data-* attributes
  $field.attr({
    'data-id': id,
    'data-type': type, // Important: preserve the field type
    'data-label': label,
    'data-name': name,
    'data-placeholder': placeholder,
    'data-required': required,
    'data-default-value': defaultValue,
    'data-css-class': cssClass,
    'data-max-length': maxLength,
    'data-options': JSON.stringify(options), // Store processed options
    'data-options-dropdown': optionsDropdown, // Keep original for editing
    'data-options-radio': optionsRadio, // Keep original for editing
    'data-paragraph-text': paragraphText,
    'data-accept': accept,
    'data-multiple': multiple,
    'data-max-file-size-kb': maxFileSizeKb,
    'data-term-and-condition': termAndCondition,
    'data-columns': columns,
    'data-rows': rows,
    'data-heading-text': headingText,
    'data-heading-tag': headingTag,
    'data-password-min-length': passwordMinLength,
    'data-password-require-uppercase': passwordRequireUppercase,
    'data-password-require-lowercase': passwordRequireLowercase,
    'data-password-require-number': passwordRequireNumber,
    'data-password-require-special': passwordRequireSpecial,
    'data-password-show-strength': passwordShowStrength,
    'data-repeatable-add-label': $field.attr('data-repeatable-add-label') || '',
    'data-repeatable-min-rows': $field.attr('data-repeatable-min-rows') || '',
    'data-repeatable-max-rows': $field.attr('data-repeatable-max-rows') || '',
    'data-conditional-enabled': logicEnabled,
    'data-conditional-field': logicField,
    'data-conditional-operator': logicOperator,
    'data-conditional-value': logicValue,
    'data-usermeta-key': $field.attr('data-usermeta-key') || ''
  });

  // Reset UI
  $form.trigger('reset');
  $('#field-settings-panel').hide();
  $('#wefb-builder').removeClass('wef-settings-open');
  $('#field-palette').show();
  currentFieldType = null;
});

function validateFieldSettingsForm($form, $field, fieldType) {
  clearFieldSettingsErrors($form);

  let isValid = true;
  const label = ($form.find('[name="label"]').val() || '').trim();
  const name = ($form.find('[name="name"]').val() || '').trim();

  if (!label) {
    setFieldError($form.find('[name="label"]'), wpefb_admin_error_object.required_field || 'This is a required field.');
    isValid = false;
  }

  if (!name) {
    setFieldError($form.find('[name="name"]'), wpefb_admin_error_object.required_field || 'This is a required field.');
    isValid = false;
  } else {
    const isValidName = /^[A-Za-z0-9_]{1,40}$/.test(name);
    if (!isValidName) {
      setFieldError($form.find('[name="name"]'), 'Reference Name allows only letters, numbers, underscores (max 40).');
      isValid = false;
    } else if (isReferenceNameTaken(name, $field.data('id'))) {
      setFieldError($form.find('[name="name"]'), 'Reference Name must be unique across fields.');
      isValid = false;
    }
  }

  const maxLength = ($form.find('[name="max_length"]').val() || '').trim();
  if (maxLength && (isNaN(Number(maxLength)) || Number(maxLength) < 1)) {
    setFieldError($form.find('[name="max_length"]'), 'Maximum Length must be a number greater than 0.');
    isValid = false;
  }

  if (['textarea', 'description'].includes(fieldType)) {
    const columns = ($form.find('[name="columns"]').val() || '').trim();
    const rows = ($form.find('[name="rows"]').val() || '').trim();
    if (columns && (isNaN(Number(columns)) || Number(columns) < 2)) {
      setFieldError($form.find('[name="columns"]'), 'Columns must be at least 2.');
      isValid = false;
    }
    if (rows && (isNaN(Number(rows)) || Number(rows) < 2)) {
      setFieldError($form.find('[name="rows"]'), 'Rows must be at least 2.');
      isValid = false;
    }
  }

  if (fieldType === 'paragraph') {
    const paragraph = ($form.find('[name="paragraph_text"]').val() || '').trim();
    if (!paragraph) {
      setFieldError($form.find('[name="paragraph_text"]'), wpefb_admin_error_object.required_field || 'This is a required field.');
      isValid = false;
    }
  }

  if (['dropdown', 'select', 'multi_dropdown', 'radio', 'checkbox'].includes(fieldType)) {
    const optionType = (fieldType === 'dropdown' || fieldType === 'select' || fieldType === 'multi_dropdown') ? 'dropdown' : fieldType;
    const $list = $form.find('.option-list[data-option-type="' + optionType + '"]');
    const $items = $list.find('.option-item');
    let validCount = 0;
    const optionValues = [];

    $items.each(function () {
      const $item = $(this);
      const labelVal = ($item.find('.option-label').val() || '').trim();
      const valueVal = ($item.find('.option-value').val() || '').trim();

      if (!labelVal && !valueVal) {
        return;
      }
      if (!labelVal) {
        setOptionItemError($item, 'Option label is required.');
        isValid = false;
        return;
      }
      optionValues.push((valueVal || makeOptionValue(labelVal) || labelVal).trim());
      validCount++;
    });

    if (validCount === 0) {
      setOptionListError($list, 'Add at least one option.');
      isValid = false;
    }

    if (isValid && ['dropdown', 'select', 'multi_dropdown'].includes(fieldType)) {
      const rawDefault = ($form.find('[name="default_value"]').val() || '').trim();
      if (rawDefault) {
        const defaults = fieldType === 'multi_dropdown'
          ? rawDefault.split(',').map(v => String(v || '').trim()).filter(Boolean)
          : [rawDefault];
        const missing = defaults.filter(v => !optionValues.includes(v));
        if (missing.length) {
          setFieldError($form.find('[name="default_value"]'), 'Default value must match existing option value(s).');
          isValid = false;
        }
      }
    }
  }

  if (fieldType === 'user_pass') {
    const minLengthVal = ($form.find('[name="password_min_length"]').val() || '').trim();
    if (!minLengthVal || isNaN(Number(minLengthVal)) || Number(minLengthVal) < 4) {
      setFieldError($form.find('[name="password_min_length"]'), 'Password minimum length must be 4 or greater.');
      isValid = false;
    }
  }

  if (fieldType === 'term_checkbox') {
    const terms = ($form.find('[name="term_and_condition"]').val() || '').trim();
    if (!terms) {
      setFieldError($form.find('[name="term_and_condition"]'), 'Terms text is required.');
      isValid = false;
    }
  }

  if ($form.find('#enable_conditional_logic').is(':checked')) {
    const conditionalField = ($form.find('[name="conditional_field"]').val() || '').trim();
    const conditionalOperator = ($form.find('[name="conditional_operator"]').val() || '').trim();
    const conditionalValue = ($form.find('[name="conditional_value"]').val() || '').trim();

    if (!conditionalField) {
      setFieldError($form.find('[name="conditional_field"]'), 'Please select a trigger field.');
      isValid = false;
    }
    if (!conditionalOperator) {
      setFieldError($form.find('[name="conditional_operator"]'), 'Please select an operator.');
      isValid = false;
    }
    if (!conditionalValue) {
      setFieldError($form.find('[name="conditional_value"]'), 'Please enter a trigger value.');
      isValid = false;
    }
  }

  if (!isValid) {
    showFieldSettingsSummary($form, 'Please fix field settings errors before saving.');
  }

  return isValid;
}

function clearFieldSettingsErrors($form) {
  $form.find('.wefb-setting-error').remove();
  $form.find('.wefb-option-item-invalid').removeClass('wefb-option-item-invalid');
  $form.find('.wefb-setting-error-input').removeClass('wefb-setting-error-input');
  $form.find('.wefb-setting-summary').remove();
}

function setFieldError($input, message) {
  if (!$input || !$input.length) {
    return;
  }
  $input.addClass('wefb-setting-error-input');
  if ($input.next('.wefb-setting-error').length) {
    $input.next('.wefb-setting-error').text(message);
    return;
  }
  $('<div class="wefb-setting-error"></div>').text(message).insertAfter($input);
}

function setOptionItemError($item, message) {
  if (!$item || !$item.length) return;
  $item.addClass('wefb-option-item-invalid');
  if ($item.next('.wefb-setting-error.wefb-option-item-error').length) {
    $item.next('.wefb-setting-error.wefb-option-item-error').text(message);
    return;
  }
  $('<div class="wefb-setting-error wefb-option-item-error"></div>').text(message).insertAfter($item);
}

function setOptionListError($list, message) {
  if (!$list || !$list.length) return;
  if ($list.next('.wefb-setting-error.wefb-option-list-error').length) {
    $list.next('.wefb-setting-error.wefb-option-list-error').text(message);
    return;
  }
  $('<div class="wefb-setting-error wefb-option-list-error"></div>').text(message).insertAfter($list);
}

function showFieldSettingsSummary($form, message) {
  if ($form.find('.wefb-setting-summary').length) {
    $form.find('.wefb-setting-summary').text(message);
    return;
  }
  $('<div class="wefb-setting-summary"></div>').text(message).prependTo($form);
}


$('#cancel-settings').on('click', function () {
  $('#field-settings-form').trigger('reset');
  $('#field-settings-panel').hide();
  $('#wefb-builder').removeClass('wef-settings-open');
  $('#field-palette').show();
   $('#wefb-canvas').show();
   currentFieldType = null;
});


//$('#wefb-canvas').on('click', '.field-settings', function () {
//  const $field = $(this).closest('.field-rendered');
//  const type = $field.data('type');
//  const id = $field.data('id');
//
//  const fieldSettings = {
//    name: $field.attr('data-name') || '',
//    label: $field.text().trim(),
//    placeholder: $field.attr('data-placeholder') || '',
//    required: $field.attr('data-required') === 'true'
//  };
//
//  $('.wefb-field-palette').html(`
//    <div class="field-settings-form" data-id="${id}">
//      <h3>Field Settings</h3>
//      <label>Label:<br><input type="text" name="label" value="${fieldSettings.label}" /></label><br>
//      <label>Name:<br><input type="text" name="name" value="${fieldSettings.name}" /></label><br>
//      <label>Placeholder:<br><input type="text" name="placeholder" value="${fieldSettings.placeholder}" /></label><br>
//      <label><input type="checkbox" name="required" ${fieldSettings.required ? 'checked' : ''} /> Required</label><br>
//      <button class="save-field-settings">Save</button>
//      <button class="cancel-field-settings">Cancel</button>
//    </div>
//  `);
//});


//$('.wefb-field-palette').on('click', '.save-field-settings', function () {
//  const $form = $(this).closest('.field-settings-form');
//  const id = $form.data('id');
//  const $field = $(`.field-rendered[data-id="${id}"]`);
//
//  const label = $form.find('input[name="label"]').val();
//  const name = $form.find('input[name="name"]').val();
//  const placeholder = $form.find('input[name="placeholder"]').val();
//  const required = $form.find('input[name="required"]').is(':checked');
//
//  $field.text(label).append(`
//    <button class="field-settings">⚙️</button>
//    <button class="remove-field">×</button>
//  `);
//  $field.attr('data-name', name);
//  $field.attr('data-placeholder', placeholder);
//  $field.attr('data-required', required);
//
//  restorePalette();
//});

//$('.wefb-field-palette').on('click', '.cancel-field-settings', function () {
//  restorePalette();
//});

//function restorePalette() {
//  $('.wefb-field-palette').html(`
//    <div class="field-item" data-type="text">Text</div>
//    <div class="field-item" data-type="email">Email</div>
//    <div class="field-item" data-type="password">Password</div>
//    <!-- add other field types -->
//  `);
//    
//    initColumnSortable();
//}


 // Sortable
  $('.option-list').sortable({
    handle: '.option-label, .option-value',
    items: '.option-item',
    placeholder: 'sortable-placeholder'
  });

  // Add Option
  $('.wefb-field-settings-form').on('click', '.add-option', function () {
    const type = $(this).data('target');
    const $list = $('.option-list[data-option-type="' + type + '"]');

    const $template = $(buildOptionItemHtml(type, '', ''));

    $list.append($template);
    if (type === 'dropdown') {
      updateSelectFieldPreview($('#field-settings-form'));
    }
    if (type === 'checkbox') {
      updateCheckboxFieldPreview($('#field-settings-form'));
    }
    if (type === 'radio') {
      const optionsArray = [];
      $list.find('.option-item').each(function () {
        const label = $(this).find('.option-label').val() || '';
        const value = $(this).find('.option-value').val() || label;
        if (label.trim()) optionsArray.push({ label: label.trim(), value: value.trim() });
      });
      refreshRadioDefaultOptions(optionsArray);
      updateRadioFieldPreview($('#field-settings-form'));
    }
  });

  // Remove Option
  $('.wefb-field-settings-form').on('click', '.remove-option', function () {
    const wasDropdown = $(this).closest('.option-list').attr('data-option-type') === 'dropdown';
    const wasCheckbox = $(this).closest('.option-list').attr('data-option-type') === 'checkbox';
    $(this).closest('.option-item').remove();
    if (wasDropdown) {
      updateSelectFieldPreview($('#field-settings-form'));
    }
    if (wasCheckbox) {
      updateCheckboxFieldPreview($('#field-settings-form'));
    }
    if (currentFieldType === 'radio') {
      const $list = $('.option-list[data-option-type="radio"]');
      const optionsArray = [];
      $list.find('.option-item').each(function () {
        const label = $(this).find('.option-label').val() || '';
        const value = $(this).find('.option-value').val() || label;
        if (label.trim()) optionsArray.push({ label: label.trim(), value: value.trim() });
      });
      refreshRadioDefaultOptions(optionsArray);
      updateRadioFieldPreview($('#field-settings-form'));
    }
  });

  // Keep radio default selector in sync when option labels/values change
  $('.wefb-field-settings-form').on('input', '.option-list[data-option-type="radio"] .option-label, .option-list[data-option-type="radio"] .option-value', function () {
    if (currentFieldType !== 'radio') return;
    const $list = $('.option-list[data-option-type="radio"]');
    const optionsArray = [];
    $list.find('.option-item').each(function () {
      const label = $(this).find('.option-label').val() || '';
      const value = $(this).find('.option-value').val() || label;
      if (label.trim()) optionsArray.push({ label: label.trim(), value: value.trim() });
    });
    refreshRadioDefaultOptions(optionsArray);
    updateRadioFieldPreview($('#field-settings-form'));
  });

  $('.wefb-field-settings-form').on('input', '.option-list[data-option-type="dropdown"] .option-label', function () {
    const $item = $(this).closest('.option-item');
    const $value = $item.find('.option-value');
    if (!($value.val() || '').trim()) {
      $value.val(makeOptionValue($(this).val()));
    }
    updateSelectFieldPreview($('#field-settings-form'));
  });

  $('.wefb-field-settings-form').on('input', '.option-list[data-option-type="dropdown"] .option-value', function () {
    updateSelectFieldPreview($('#field-settings-form'));
  });

  $('.wefb-field-settings-form').on('input', '.option-list[data-option-type="checkbox"] .option-label, .option-list[data-option-type="checkbox"] .option-value', function () {
    updateCheckboxFieldPreview($('#field-settings-form'));
  });
  
  
  function hasRequiredEmailField(structureJSON) {
    const sections = Array.isArray(structureJSON && structureJSON.sections) ? structureJSON.sections : [];
    for (const section of sections) {
      const fields = Array.isArray(section && section.fields) ? section.fields : [];
      for (const field of fields) {
        const type = String((field && field.type) || '').toLowerCase();
        if (type === 'email' || type === 'user_email') {
          return true;
        }
      }
    }
    return false;
  }

  function showBuilderNotice(type, message) {
    const safeType = type === 'success' ? 'success' : 'error';
    const $existing = $('.wefb-builder-notice');

    if ($existing.length) {
      $existing.remove();
    }

    const $notice = $(`
      <div class="notice notice-${safeType} is-dismissible wefb-builder-notice">
        <p></p>
        <button type="button" class="notice-dismiss">
          <span class="screen-reader-text">Dismiss this notice.</span>
        </button>
      </div>
    `);

    $notice.find('p').text(message || '');
    $notice.find('.notice-dismiss').on('click', function () {
      $notice.remove();
    });

    $('#advrf_fb_app').before($notice);

    const noticeTop = Math.max($notice.offset().top - 48, 0);
    $('html, body').animate({ scrollTop: noticeTop }, 180);
  }

  function saveForm(closeAfterSave = false) {
    const formId = $('#wefb_form_id').val(); // dynamic form ID
    const structureJSON = getFormStructureJSON();

    if (!hasRequiredEmailField(structureJSON)) {
      alert('Please add at least one Email field before saving this form.');
      return;
    }

    $.post(
      wpefb_admin_ajax_object.ajax_url,
      {
        action: 'wefb_save_form_structure',
        nonce: wpefb_admin_ajax_object.nonce,
        form_id: formId,
        form_options: JSON.stringify(structureJSON),
      },
      function (response) {
        if (response && response.success) {
          showBuilderNotice('success', 'Form saved successfully.');
          if (closeAfterSave && wpefb_admin_ajax_object.dashboard_url) {
            window.location = wpefb_admin_ajax_object.dashboard_url;
          }
        } else {
          const message = response && response.data && response.data.message ? response.data.message : 'Failed to save the form.';
          showBuilderNotice('error', message);
        }
      }
    ).fail(function () {
      showBuilderNotice('error', 'Failed to save the form.');
    });
  }

  $('#advrforms-form-save-btn').on('click', function () {
    saveForm(false);
  });

  $('#advrforms-form-save-close-btn').on('click', function () {
    saveForm(true);
  });
  
  
  function getFormStructureJSON() {
        const structure = { sections: [] };

        $('#wefb-canvas .section').each(function () {
          const $section = $(this);
          const columnsCount = $section.find('.columns > .column').length;
          let sectionConditionalLogic = null;
          const rawSectionConditionalJson = $section.attr('data-conditional-json');
          if (rawSectionConditionalJson) {
            try {
              sectionConditionalLogic = JSON.parse(rawSectionConditionalJson);
            } catch (error) {
              sectionConditionalLogic = null;
            }
          }

          const sectionData = { columns: columnsCount, fields: [] };
          if (sectionConditionalLogic) {
            sectionData.conditional_logic = sectionConditionalLogic;
          }

          $section.find('.columns > .column .field-rendered').each(function () {
            const $field = $(this);

            const fieldData = {
              id: $field.data('id') || '',
              type: $field.data('type') || '',
              label: $field.attr('data-label') || '',
              name: $field.attr('data-name') || '',
              placeholder: $field.attr('data-placeholder') || '',
              required: $field.attr('data-required') === 'true',
              css_class: $field.attr('data-css-class') || '',
              default_value: $field.attr('data-default-value') || '',
              accept: $field.attr('data-accept') || '',
              multiple: $field.attr('data-multiple') === 'true',
              max_file_size_kb: parseInt($field.attr('data-max-file-size-kb')) || null,
              term_and_condition: $field.attr('data-term-and-condition') || '',
              max_length: parseInt($field.attr('data-max-length')) || null,
              columns: parseInt($field.attr('data-columns')) || null,
              rows: parseInt($field.attr('data-rows')) || null,
              heading_tag: $field.attr('data-heading-tag') || '',
              paragraph_text: $field.attr('data-paragraph-text') || '',
              password_min_length: parseInt($field.attr('data-password-min-length')) || 8,
              password_require_uppercase: $field.attr('data-password-require-uppercase') === 'true',
              password_require_lowercase: $field.attr('data-password-require-lowercase') !== 'false',
              password_require_number: $field.attr('data-password-require-number') === 'true',
              password_require_special: $field.attr('data-password-require-special') === 'true',
              password_show_strength: $field.attr('data-password-show-strength') !== 'false',
              repeatable_add_label: $field.attr('data-repeatable-add-label') || '',
              repeatable_min_rows: parseInt($field.attr('data-repeatable-min-rows')) || null,
              repeatable_max_rows: parseInt($field.attr('data-repeatable-max-rows')) || null,
              options: [], // Initialize options array
              visibility: parseInt($field.attr('data-visibility')) || 1,
              conditional_logic: (function () {
                const rawConditionalJson = $field.attr('data-conditional-json');
                if (rawConditionalJson) {
                  try {
                    return JSON.parse(rawConditionalJson);
                  } catch (error) {
                  }
                }

                return {
                  enabled: $field.attr('data-conditional-enabled') === 'true',
                  field: $field.attr('data-conditional-field') || '',
                  operator: $field.attr('data-conditional-operator') || '',
                  value: $field.attr('data-conditional-value') || ''
                };
              })(),
              section_conditional_logic: sectionConditionalLogic,
              usermeta_key: $field.attr('data-usermeta-key') || ''
            };

            // Parse options for radio, checkbox, and dropdown/select fields
            const ftype = String($field.data('type')).toLowerCase();
            const dropdownTypesLocal = ['dropdown', 'select', 'multi_dropdown'];
            const optionEnabledTypes = ['radio', 'checkbox', 'gender', 'language'];
            if (optionEnabledTypes.includes(ftype) || dropdownTypesLocal.includes(ftype)) {
              try {
                const storedOptions = $field.attr('data-options');
                if (storedOptions) {
                  fieldData.options = JSON.parse(storedOptions);
                } else {
                  // Fallback to raw options if the processed ones aren't available
                  const radioOptions = $field.attr('data-options-radio');
                  const dropdownOptions = $field.attr('data-options-dropdown');
                  
                  if (radioOptions) {
                    fieldData.options = radioOptions.split('\n').filter(opt => opt.trim()).map(opt => ({
                      label: opt.trim(),
                      value: opt.trim()
                    }));
                  } else if (dropdownOptions) {
                    fieldData.options = dropdownOptions.split('\n').filter(opt => opt.trim()).map(opt => ({
                      label: opt.trim(),
                      value: opt.trim()
                    }));
                  } else {
                    fieldData.options = [];
                  }
                }
              } catch (e) {
                console.error('Error parsing options:', e);
                fieldData.options = [];
              }
            }
            

            sectionData.fields.push(fieldData);
          });

          structure.sections.push(sectionData);
        });

        return structure;
  }


function renderFormFromJSON_old(data) {
  const $canvas = $('#wefb-canvas');
  //$canvas.empty();

   // If `data` is a string, parse it
    if (typeof data === 'string') {
      data = JSON.parse(data);
    }

    if (!data || !Array.isArray(data.sections)) {
      //console.error('Invalid form data structure:', data);
      return;
    }
  
  data.sections.forEach(section => {
    const $section = $('<div class="section"></div>');
    const $columnsWrapper = $('<div class="columns"></div>');

    for (let i = 0; i < section.columns; i++) {
      $columnsWrapper.append('<div class="column empty"></div>');
    }

    $section.append($columnsWrapper);
    $canvas.find('.add-row-button-wrapper').before($section);
    //$canvas.append($section);

    // Distribute fields across columns
    const usedIds = new Set();
    section.fields.forEach((field, index) => {
      const candidateId = String(field && field.id ? field.id : '').trim();
      const runtimeId = (candidateId && !usedIds.has(candidateId)) ? candidateId : generateRuntimeFieldId();
      usedIds.add(runtimeId);
      const $field = $(`
        <div class="field-rendered" data-id="${runtimeId}" data-type="${field.type}">
          ${buildFieldCardHtml(field.label, field.type, field.name)}
        </div>
      `);

      // Add attributes
  $field.attr('data-label', field.label || '');
  $field.attr('data-name', field.name || '');
  $field.attr('data-placeholder', field.placeholder || '');
  $field.attr('data-required', field.required ? 'true' : 'false');
  $field.attr('data-css-class', field.css_class || '');
  $field.attr('data-default-value', field.default_value || '');
  $field.attr('data-accept', field.accept || '');
  $field.attr('data-multiple', field.multiple ? 'true' : 'false');
  $field.attr('data-max-file-size-kb', field.max_file_size_kb || '');
  $field.attr('data-term-and-condition', field.term_and_condition || '');
  $field.attr('data-max-length', field.max_length || '');
  $field.attr('data-columns', field.columns || '');
  $field.attr('data-rows', field.rows || '');
  $field.attr('data-heading-tag', field.heading_tag || '');
  $field.attr('data-paragraph-text', field.paragraph_text || '');
  $field.attr('data-password-min-length', field.password_min_length || 8);
  $field.attr('data-password-require-uppercase', field.password_require_uppercase ? 'true' : 'false');
  $field.attr('data-password-require-lowercase', field.password_require_lowercase === false ? 'false' : 'true');
  $field.attr('data-password-require-number', field.password_require_number ? 'true' : 'false');
  $field.attr('data-password-require-special', field.password_require_special ? 'true' : 'false');
  $field.attr('data-password-show-strength', field.password_show_strength === false ? 'false' : 'true');
  $field.attr('data-repeatable-add-label', field.repeatable_add_label || '');
  $field.attr('data-repeatable-min-rows', field.repeatable_min_rows || '');
  $field.attr('data-repeatable-max-rows', field.repeatable_max_rows || '');
  $field.attr('data-visibility', field.visibility || 1);
  $field.attr('data-usermeta-key', field.usermeta_key || '');

      if (field.options && field.options.length) {
        $field.attr('data-options', JSON.stringify(field.options));
      }

      if (field.conditional_logic) {
        $field.attr('data-conditional-json', JSON.stringify(field.conditional_logic));
        $field.attr('data-conditional-enabled', field.conditional_logic.enabled ? 'true' : 'false');
        $field.attr('data-conditional-field', field.conditional_logic.field || '');
        $field.attr('data-conditional-operator', field.conditional_logic.operator || '');
        $field.attr('data-conditional-value', field.conditional_logic.value || '');
      }

      // Find the target column (rotate distribution)
      const $column = $columnsWrapper.find('.column').eq(index % section.columns);
      $column.append($field).removeClass('empty');
    });
  });
  
 

  initColumnSortable(); // re-initialize sorting etc.
}

function renderFormFromJSON(data) {
  const $canvas = $('#wefb-canvas');
  const usedIds = new Set();
  //$canvas.empty(); // Optionally clear canvas

  // If passed as string, parse JSON
  if (typeof data === 'string') {
    try {
      data = JSON.parse(data);
    } catch (e) {
      console.error('Invalid JSON data', e);
      return;
    }
  }

  if (!data || !Array.isArray(data.sections)) {
    console.error('Invalid data format. No sections found.');
    return;
  }

  data.sections.forEach((section, sectionIndex) => {
    const $section = $('<div class="section"></div>');
    const $columnsWrapper = $('<div class="columns"></div>');

    if (section.conditional_logic) {
      $section.attr('data-conditional-json', JSON.stringify(section.conditional_logic));
    }

    // Add section settings & delete buttons
    // Add section controls (as per your design)
    const $controls = $(`
      <div class="section-controls">
        <button class="remove-row" title="Delete Row" aria-label="Delete Row">
          <span class="dashicons dashicons-trash"></span>
        </button>
        <button class="section-settings" title="Row Settings" aria-label="Row Settings">
          <span class="dashicons dashicons-admin-generic"></span>
        </button>
      </div>
    `);
      $section.append($controls);   
    

    // Create columns
    for (let i = 0; i < section.columns; i++) {
      $columnsWrapper.append('<div class="column empty"></div>');
    }

    $section.append($columnsWrapper);
    $canvas.find('.add-row-button-wrapper').before($section);

    // Place fields into columns
    section.fields.forEach((field, index) => {
      const candidateId = String(field && field.id ? field.id : '').trim();
      const runtimeId = (candidateId && !usedIds.has(candidateId)) ? candidateId : generateRuntimeFieldId();
      usedIds.add(runtimeId);
      const $field = $(`
        <div class="field-rendered" data-id="${runtimeId}" data-type="${field.type}">
          ${buildFieldCardHtml(field.label, field.type, field.name)}
        </div>
      `);

      // Store field data attributes
  $field.attr('data-label', field.label || '');
  $field.attr('data-name', field.name || '');
  $field.attr('data-placeholder', field.placeholder || '');
  $field.attr('data-required', field.required ? 'true' : 'false');
  $field.attr('data-css-class', field.css_class || '');
  $field.attr('data-default-value', field.default_value || '');
  $field.attr('data-accept', field.accept || '');
  $field.attr('data-multiple', field.multiple ? 'true' : 'false');
  $field.attr('data-max-file-size-kb', field.max_file_size_kb || '');
  $field.attr('data-term-and-condition', field.term_and_condition || '');
  $field.attr('data-max-length', field.max_length || '');
  $field.attr('data-columns', field.columns || '');
  $field.attr('data-rows', field.rows || '');
  $field.attr('data-heading-tag', field.heading_tag || '');
  $field.attr('data-paragraph-text', field.paragraph_text || '');
  $field.attr('data-password-min-length', field.password_min_length || 8);
  $field.attr('data-password-require-uppercase', field.password_require_uppercase ? 'true' : 'false');
  $field.attr('data-password-require-lowercase', field.password_require_lowercase === false ? 'false' : 'true');
  $field.attr('data-password-require-number', field.password_require_number ? 'true' : 'false');
  $field.attr('data-password-require-special', field.password_require_special ? 'true' : 'false');
  $field.attr('data-password-show-strength', field.password_show_strength === false ? 'false' : 'true');
  $field.attr('data-repeatable-add-label', field.repeatable_add_label || '');
  $field.attr('data-repeatable-min-rows', field.repeatable_min_rows || '');
  $field.attr('data-repeatable-max-rows', field.repeatable_max_rows || '');
  $field.attr('data-visibility', field.visibility || 1);
  $field.attr('data-usermeta-key', field.usermeta_key || '');

      // Options (dropdown, radio, checkbox)
      if (field.options && Array.isArray(field.options)) {
        $field.attr('data-options', JSON.stringify(field.options));
      }

      // Conditional logic
      if (field.conditional_logic) {
        $field.attr('data-conditional-json', JSON.stringify(field.conditional_logic));
        $field.attr('data-conditional-enabled', field.conditional_logic.enabled ? 'true' : 'false');
        $field.attr('data-conditional-field', field.conditional_logic.field || '');
        $field.attr('data-conditional-operator', field.conditional_logic.operator || '');
        $field.attr('data-conditional-value', field.conditional_logic.value || '');
      }

      // Distribute across columns
      const $targetCol = $columnsWrapper.find('.column').eq(index % section.columns);
      $targetCol.append($field).removeClass('empty');
    });
  });

  initColumnSortable(); // Enable drag & drop if required
}


  
});
