import { Node as TipTapNode, mergeAttributes } from "@tiptap/core"
import { SIGNATURES } from "@/lib/compose-context"

/** Menus/popovers Radix default z-50 ; compose sheet content uses z-61+. */
export const COMPOSE_PORTAL_Z = "z-[100]"

export const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/

export const SignatureBlock = TipTapNode.create({
  name: "signatureBlock",
  group: "block",
  content: "block+",
  defining: true,
  isolating: true,

  parseHTML() {
    return [{ tag: 'div[id="ultimail-signature"]' }]
  },

  renderHTML({ HTMLAttributes }) {
    return ["div", mergeAttributes(HTMLAttributes, { id: "ultimail-signature" }), 0]
  },
})

const SIG_REGEX = /<div id="ultimail-signature">[\s\S]*<\/div>/

export function stripSignature(html: string) {
  return html.replace(SIG_REGEX, "")
}

export function insertSignatureHtml(html: string, sigId: string | null) {
  const sig = sigId ? SIGNATURES.find((s) => s.id === sigId) : null
  const clean = stripSignature(html)
  if (!sig) return clean
  return clean + `<div id="ultimail-signature"><p>--</p>${sig.html}</div>`
}
