console.log("Quilljs laden...");


(function registerOnce() {
  if (window.__hmQuillV2Registered) return;
  window.__hmQuillV2Registered = true;

  const Image = Quill.import("formats/image");
  Image.className = "hm-img-fluid";
  Quill.register(Image, true);

  const Inline = Quill.import("blots/inline");
  class CustomBlot extends Inline {
    static blotName = "custom";
    static tagName = "span";
    static className = "ql-custom";
  }
  Quill.register(CustomBlot, true);
})();

const Delta = Quill.import("delta");


window.__hmQuillInstances = window.__hmQuillInstances || new Map(); 


function isWhitespace(ch) {
  return ch === " " || ch === "\t" || ch === "\n";
}

function getInsertIndex(quill) {
  let index = (quill.getSelection() || {}).index;
  if (index === undefined || index < 0) index = quill.getLength();
  return index;
}

function uploadImageFileAndInsert(quill, fileOrBlob) {
  const formData = new FormData();
  formData.append("file", fileOrBlob);

  return $.ajax({
    url: "index.php?module=upload&event=uploadImageDirectly",
    type: "POST",
    data: formData,
    cache: false,
    contentType: false,
    processData: false
  }).done(function (data) {
    if (data && data !== "Nofile") {
      const index = getInsertIndex(quill);
      const url = "index.php?module=upload&event=ShowImage&name=" + data;

      quill.insertEmbed(index, "image", url, "user");

      try {
        quill.formatText(index, 1, "max-width", "100%");
      } catch (_) {}

      setTimeout(() => {
        const r = quill.getSelection(true);
        if (r) quill.setSelection(r.index + 1, 0, "silent");
      }, 0);
    }
  });
}

function getImageFilesFromClipboard(dt) {
  const out = [];

  if (dt.files && dt.files.length) {
    for (const f of Array.from(dt.files)) {
      if (f && f.type && f.type.startsWith("image/")) out.push(f);
    }
    if (out.length) return out;
  }

  if (dt.items && dt.items.length) {
    for (const it of Array.from(dt.items)) {
      if (it && it.type && it.type.startsWith("image/")) {
        const f = it.getAsFile();
        if (f) out.push(f);
      }
    }
  }

  return out;
}


$(".editor").each(function () {
  const fieldID = $(this).attr("id");
  if (window.__hmQuillInstances.has(fieldID)) return;

  const quill = new Quill("#" + fieldID, {
    theme: "snow",
    placeholder: "Hier bitte Beschreibung eingeben",
    modules: {
      clipboard: { matchVisual: false },
      toolbar: "#toolbar-container-" + fieldID
    }
  });

  window.__hmQuillInstances.set(fieldID, quill);

  quill.clipboard.addMatcher(Node.TEXT_NODE, function (node, delta) {
    const regex = /((http|https|ftp|ftps)\:\/\/(\S*)?)/g;
    if (typeof node.data !== "string") return delta;

    const matches = node.data.match(regex);
    if (matches && matches.length > 0) {
      const ops = [];
      let str = node.data;

      matches.forEach(function (match) {
        const split = str.split(match);
        const beforeLink = split.shift();
        ops.push({ insert: beforeLink });
        ops.push({ insert: match, attributes: { link: match } });
        str = split.join(match);
      });

      ops.push({ insert: str });
      delta.ops = ops;
    }
    return delta;
  });

  quill.clipboard.addMatcher("img", (node, delta) => {
    const src = node.getAttribute("src") || "";

    if (src.startsWith("data:image/") || src.startsWith("file:")) {
      return new Delta(); 
    }

    if (src.startsWith("http://") || src.startsWith("https://") ||  src.startsWith("index.php")) {
      return new Delta().insert({ image: src });
    }

    return new Delta();
  });

  quill.root.addEventListener(
    "paste",
    function (e) {
      const dt = e.clipboardData;
      if (!dt) return;

      const imageFiles = getImageFilesFromClipboard(dt);
      if (!imageFiles.length) return;

      e.preventDefault();
      e.stopPropagation();

      (async () => {
        for (const file of imageFiles) {
          await uploadImageFileAndInsert(quill, file);
        }
      })().catch(console.error);
    },
    true
  );

  const value = $("#textarea_" + fieldID).val();
  const delta = quill.clipboard.convert({ html: value || "" });
  quill.setContents(delta, "silent");

  quill.on("text-change", function () {
    $("#textarea_" + fieldID).val(quill.root.innerHTML);
  });

  $("#editHTMLBtn_" + fieldID).on("click", function () {
    const color = $("#editHTMLBtn_" + fieldID).css("color");

    if (color === "rgb(0, 0, 255)") {
      $("#quill_" + fieldID).show();
      quill.root.innerHTML = $("#textarea_" + fieldID).val();
      $("#textarea_" + fieldID).css({ visibility: "hidden", height: "0px" });
      $("#editHTMLBtn_" + fieldID).css({ color: "#333333" });
    } else {
      $("#quill_" + fieldID).hide();
      $("#textarea_" + fieldID).css({ visibility: "visible", height: "200px" });
      $("#editHTMLBtn_" + fieldID).css({ color: "#0000ff" });
    }
  });

  quill.on("text-change", function (delta, oldDelta, source) {
    const regex = /https?:\/\/[^\s]+$/;

    if (
      delta.ops.length === 2 &&
      delta.ops[0].retain &&
      isWhitespace(delta.ops[1].insert)
    ) {
      const endRetain = delta.ops[0].retain;
      const text = quill.getText().substr(0, endRetain);
      const match = text.match(regex);

      if (match !== null) {
        const url = match[0];

        let ops = [];
        if (endRetain > url.length) ops.push({ retain: endRetain - url.length });

        ops = ops.concat([
          { delete: url.length },
          { insert: url, attributes: { link: url } }
        ]);

        quill.updateContents({ ops });
      }
    }
  });
});


function insertSnippet(id, fieldid) {
  $.get(
    "index.php?module=ticket&class=snippets&event=getSnippetContent&id=" + id,
    function (data) {
      const quill = window.__hmQuillInstances.get(fieldid);
      if (!quill) return;

      const index = getInsertIndex(quill);
      quill.clipboard.dangerouslyPasteHTML(index, data);
      $("#myBigIFrameModal").modal("hide");
    }
  );
}

$(".dialog_ticketlist").fancybox({
  type: "iframe",
  autoSize: false,
  autoResize: true,
  autoCenter: true,
  beforeLoad: function () {
    this.width = 1300;
    this.height = 600;
  }
});

$(".dialog_medium").fancybox({
  width: 800,
  height: 600,
  closeClick: false,
  autoResize: false,
  autoCenter: true,
  autoSize: false
});
