jQuery(document).ready(function ($) {
  function applyConditionalLogic($form) {
    $form.find('[data-conditional]').each(function () {
      const $fieldWrapper = $(this);
      const cond = $fieldWrapper.data('conditional');

      if (!cond || !cond.enabled || !cond.field || !cond.operator) return;

      const fieldKey = String(cond.field || '').trim();
      if (!fieldKey) return;

      const escapedField = (window.CSS && typeof window.CSS.escape === 'function')
        ? window.CSS.escape(fieldKey)
        : fieldKey.replace(/([ #;?%&,.+*~':"!^$[\]()=>|\/@])/g, '\\$1');

      const selector = [
        `[name="${escapedField}"]`,
        `[name="wefb_fields[${escapedField}]"]`,
        `[name="wefb_fields[${escapedField}][]"]`
      ].join(',');

      let $trigger = $form.find(selector);
      if (!$trigger.length) {
        const $triggerField = $form.find(`[data-id="${escapedField}"]`);
        if ($triggerField.length) {
          $trigger = $triggerField.find('input[name], select[name], textarea[name]');
        }
      }
      if (!$trigger.length) return;

      const evaluate = () => {
        let value = $trigger.val();

        if ($trigger.attr('type') === 'radio' || $trigger.attr('type') === 'checkbox') {
          value = $trigger.filter(':checked').val();
        }

        let show = false;

        switch (cond.operator) {
          case 'equals':
            show = value == cond.value;
            break;
          case 'not_equals':
            show = value != cond.value;
            break;
          case 'contains':
            show = (value || '').includes(cond.value);
            break;
          case 'not_contains':
            show = !(value || '').includes(cond.value);
            break;
        }

        $fieldWrapper.toggle(show);
      };

      // Initial check
      evaluate();

      // Bind
      $trigger.on('change keyup input', evaluate);
    });
  }

  $('.wefb-frontend-form-wrapper form').each(function () {
    applyConditionalLogic($(this));
  });
});
