import { Node as TipTapNode, mergeAttributes } from "@tiptap/core"
import { getSignatureHtmlById } from "@/lib/stores/mail-signatures-store"

/** 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, "")
}

/** Accepts signature library id or raw HTML. */
export function insertSignatureHtml(html: string, sigIdOrHtml: string | null) {
  const clean = stripSignature(html)
  if (!sigIdOrHtml) return clean

  const fromLibrary = getSignatureHtmlById(sigIdOrHtml)
  const sigHtml = fromLibrary ?? (sigIdOrHtml.trimStart().startsWith("<") ? sigIdOrHtml : null)
  if (!sigHtml?.trim()) return clean
  return `${clean}<div id="ultimail-signature"><p>--</p>${sigHtml}</div>`
}

export function resolveSignatureContent(sigIdOrHtml: string | null): string | null {
  if (!sigIdOrHtml) return null
  return getSignatureHtmlById(sigIdOrHtml) ?? (sigIdOrHtml.trimStart().startsWith("<") ? sigIdOrHtml : null)
}
