document.querySelectorAll('.ugfx-rich-form').forEach(form => {
  const surface = form.querySelector('[data-editor-surface]');
  const target = form.querySelector('[data-editor-target]');
  if (!surface || !target) return;
  const sync = () => { target.value = surface.innerHTML.trim(); };
  form.querySelectorAll('[data-editor-cmd]').forEach(btn => {
    btn.addEventListener('click', () => {
      const cmd = btn.getAttribute('data-editor-cmd');
      let value = btn.getAttribute('data-editor-value') || null;
      if (cmd === 'createLink') {
        value = window.prompt('Paste the full link URL');
        if (!value) return;
      }
      surface.focus();
      document.execCommand(cmd, false, value);
      sync();
    });
  });
  surface.addEventListener('input', sync);
  form.addEventListener('submit', sync);
  sync();
});
