llmApp.directive("contenteditable", function () {
  return {
    require: "ngModel",
    link: function (scope, element, attrs, ngModel) {
      // Render the model value into the view
      ngModel.$render = function () {
        element.html(ngModel.$viewValue || "");
      };

      // Listen for paste event to strip HTML
      element.on("paste", function (e) {
        e.preventDefault();
        const clipboardData = (e.originalEvent || e).clipboardData;
        if (!clipboardData) return;
        const text = clipboardData.getData("text/plain");
        const selection = window.getSelection();
        if (!selection.rangeCount) return;
        const range = selection.getRangeAt(0);
        range.deleteContents();
        const textNode = document.createTextNode(text);
        range.insertNode(textNode);

        // Move cursor to the end of the inserted text
        range.setStartAfter(textNode);
        range.collapse(true);
        selection.removeAllRanges();
        selection.addRange(range);
      });

      // Listen for change events to update the model
      element.on("blur keyup change", function () {
        scope.$apply(function () {
          ngModel.$setViewValue(element.html());
        });
      });
    },
  };
});
