/**
 * Minified by jsDelivr using Terser v5.39.0.
 * Original file: /npm/@leolionart/just-chat@1.0.0/dist/just-chat.umd.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
!function(e,t){"object"==typeof exports&&typeof module<"u"?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e=typeof globalThis<"u"?globalThis:e||self).UniversalChatPopup={})}(this,(function(e){"use strict";var t=Object.defineProperty,n=(e,n,s)=>((e,n,s)=>n in e?t(e,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[n]=s)(e,"symbol"!=typeof n?n+"":n,s);class s extends HTMLElement{constructor(){super(),n(this,"shadow"),this.shadow=this.attachShadow({mode:"open"})}addStyles(e){const t=new CSSStyleSheet;t.replaceSync(e),this.shadow.adoptedStyleSheets=[t]}createElement(e,t,n){const s=document.createElement(e);return t&&(s.className=t),n&&(s.textContent=n),s}}function r(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}customElements.define("chat-launcher",class extends s{constructor(){super(),n(this,"styles","\n    .launcher {\n      width: 60px;\n      height: 60px;\n      border-radius: 50%;\n      background-color: var(--theme-color, #1E40AF);\n      cursor: pointer;\n      display: flex;\n      align-items: center;\n      justify-content: center;\n      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);\n      transition: transform 0.2s ease;\n      position: fixed;\n      bottom: 24px;\n      right: 24px;\n      z-index: 9999;\n    }\n\n    .launcher:hover {\n      transform: scale(1.05);\n    }\n\n    .launcher svg {\n      width: 28px;\n      height: 28px;\n      fill: white;\n    }\n  "),n(this,"isOpen",!1),this.addStyles(this.styles),this.render(),window.addEventListener("close",(()=>{const e=this.shadow.querySelector(".launcher");e&&(e.style.visibility="visible",e.style.opacity="1",e.style.pointerEvents="auto")})),window.addEventListener("toggleChat",(e=>{const t=e;this.isOpen=t.detail.isOpen;const n=this.shadow.querySelector(".launcher");n&&(n.style.visibility=this.isOpen?"hidden":"visible",n.style.opacity=this.isOpen?"0":"1",n.style.pointerEvents=this.isOpen?"none":"auto")}))}static get observedAttributes(){return["theme-color"]}attributeChangedCallback(e,t,n){t!==n&&"theme-color"===e&&this.render()}render(){this.shadow.innerHTML="";const e=this.createElement("button","launcher");e.innerHTML=this.getChatIcon(),e.addEventListener("click",(()=>this.toggleChat())),this.shadow.appendChild(e)}toggleChat(){this.isOpen=!this.isOpen;const e=new CustomEvent("toggleChat",{detail:{isOpen:this.isOpen},bubbles:!0,composed:!0});this.dispatchEvent(e),console.log("Chat toggle event dispatched:",this.isOpen)}getChatIcon(){return'\n      <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">\n        <path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/>\n      </svg>\n    '}});let i={async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null};function o(e){i=e}const a={exec:()=>null};function l(e,t=""){let n="string"==typeof e?e:e.source;const s={replace:(e,t)=>{let r="string"==typeof t?t:t.source;return r=r.replace(c.caret,"$1"),n=n.replace(e,r),s},getRegex:()=>new RegExp(n,t)};return s}const c={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/gi,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[\t ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`),hrRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,"i")},h=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,p=/(?:[*+-]|\d{1,9}[.)])/,u=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,d=l(u).replace(/bull/g,p).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),g=l(u).replace(/bull/g,p).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),b=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,m=/(?!\s*\])(?:\\.|[^\[\]\\])+/,f=l(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",m).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),k=l(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,p).getRegex(),x="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",w=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,y=l("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$))","i").replace("comment",w).replace("tag",x).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),v=l(b).replace("hr",h).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",x).getRegex(),S={blockquote:l(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",v).getRegex(),code:/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,def:f,fences:/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,hr:h,html:y,lheading:d,list:k,newline:/^(?:[ \t]*(?:\n|$))+/,paragraph:v,table:a,text:/^[^\n]+/},A=l("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",h).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3}\t)[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",x).getRegex(),C={...S,lheading:g,table:A,paragraph:l(b).replace("hr",h).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",A).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",x).getRegex()},$={...S,html:l("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:\"[^\"]*\"|'[^']*'|\\s[^'\"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))").replace("comment",w).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:a,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:l(b).replace("hr",h).replace("heading"," *#{1,6} *[^\n]").replace("lheading",d).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},E=/^( {2,}|\\)\n(?!\s*$)/,T=/[\p{P}\p{S}]/u,z=/[\s\p{P}\p{S}]/u,R=/[^\s\p{P}\p{S}]/u,M=l(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,z).getRegex(),I=/(?!~)[\p{P}\p{S}]/u,L=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,P=l(L,"u").replace(/punct/g,T).getRegex(),_=l(L,"u").replace(/punct/g,I).getRegex(),q="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",O=l(q,"gu").replace(/notPunctSpace/g,R).replace(/punctSpace/g,z).replace(/punct/g,T).getRegex(),B=l(q,"gu").replace(/notPunctSpace/g,/(?:[^\s\p{P}\p{S}]|~)/u).replace(/punctSpace/g,/(?!~)[\s\p{P}\p{S}]/u).replace(/punct/g,I).getRegex(),H=l("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,R).replace(/punctSpace/g,z).replace(/punct/g,T).getRegex(),D=l(/\\(punct)/,"gu").replace(/punct/g,T).getRegex(),Z=l(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),j=l(w).replace("(?:--\x3e|$)","--\x3e").getRegex(),N=l("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",j).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),F=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,U=l(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label",F).replace("href",/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Q=l(/^!?\[(label)\]\[(ref)\]/).replace("label",F).replace("ref",m).getRegex(),G=l(/^!?\[(ref)\](?:\[\])?/).replace("ref",m).getRegex(),K={_backpedal:a,anyPunctuation:D,autolink:Z,blockSkip:/\[[^[\]]*?\]\((?:\\.|[^\\\(\)]|\((?:\\.|[^\\\(\)])*\))*\)|`[^`]*?`|<[^<>]*?>/g,br:E,code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,del:a,emStrongLDelim:P,emStrongRDelimAst:O,emStrongRDelimUnd:H,escape:/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,link:U,nolink:G,punctuation:M,reflink:Q,reflinkSearch:l("reflink|nolink(?!\\()","g").replace("reflink",Q).replace("nolink",G).getRegex(),tag:N,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,url:a},V={...K,link:l(/^!?\[(label)\]\((.*?)\)/).replace("label",F).getRegex(),reflink:l(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",F).getRegex()},W={...K,emStrongRDelimAst:B,emStrongLDelim:_,url:l(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},J={...W,br:l(E).replace("{2,}","*").getRegex(),text:l(W.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},X={normal:S,gfm:C,pedantic:$},Y={normal:K,gfm:W,breaks:J,pedantic:V},ee={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},te=e=>ee[e];function ne(e,t){if(t){if(c.escapeTest.test(e))return e.replace(c.escapeReplace,te)}else if(c.escapeTestNoEncode.test(e))return e.replace(c.escapeReplaceNoEncode,te);return e}function se(e){try{e=encodeURI(e).replace(c.percentDecode,"%")}catch{return null}return e}function re(e,t){var n;const s=e.replace(c.findPipe,((e,t,n)=>{let s=!1,r=t;for(;--r>=0&&"\\"===n[r];)s=!s;return s?"|":" |"})).split(c.splitPipe);let r=0;if(s[0].trim()||s.shift(),s.length>0&&!(null!=(n=s.at(-1))&&n.trim())&&s.pop(),t)if(s.length>t)s.splice(t);else for(;s.length<t;)s.push("");for(;r<s.length;r++)s[r]=s[r].trim().replace(c.slashPipe,"|");return s}function ie(e,t,n){const s=e.length;if(0===s)return"";let r=0;for(;r<s&&e.charAt(s-r-1)===t;)r++;return e.slice(0,s-r)}function oe(e,t,n,s,r){const i=t.href,o=t.title||null,a=e[1].replace(r.other.outputLinkReplace,"$1");if("!"!==e[0].charAt(0)){s.state.inLink=!0;const e={type:"link",raw:n,href:i,title:o,text:a,tokens:s.inlineTokens(a)};return s.state.inLink=!1,e}return{type:"image",raw:n,href:i,title:o,text:a}}class ae{constructor(e){n(this,"options"),n(this,"rules"),n(this,"lexer"),this.options=e||i}space(e){const t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){const t=this.rules.block.code.exec(e);if(t){const e=t[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?e:ie(e,"\n")}}}fences(e){const t=this.rules.block.fences.exec(e);if(t){const e=t[0],n=function(e,t,n){const s=e.match(n.other.indentCodeCompensation);if(null===s)return t;const r=s[1];return t.split("\n").map((e=>{const t=e.match(n.other.beginningSpace);if(null===t)return e;const[s]=t;return s.length>=r.length?e.slice(r.length):e})).join("\n")}(e,t[3]||"",this.rules);return{type:"code",raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:n}}}heading(e){const t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(this.rules.other.endingHash.test(e)){const t=ie(e,"#");(this.options.pedantic||!t||this.rules.other.endingSpaceChar.test(t))&&(e=t.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){const t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:ie(t[0],"\n")}}blockquote(e){const t=this.rules.block.blockquote.exec(e);if(t){let e=ie(t[0],"\n").split("\n"),n="",s="";const r=[];for(;e.length>0;){let t=!1;const i=[];let o;for(o=0;o<e.length;o++)if(this.rules.other.blockquoteStart.test(e[o]))i.push(e[o]),t=!0;else{if(t)break;i.push(e[o])}e=e.slice(o);const a=i.join("\n"),l=a.replace(this.rules.other.blockquoteSetextReplace,"\n    $1").replace(this.rules.other.blockquoteSetextReplace2,"");n=n?`${n}\n${a}`:a,s=s?`${s}\n${l}`:l;const c=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(l,r,!0),this.lexer.state.top=c,0===e.length)break;const h=r.at(-1);if("code"===(null==h?void 0:h.type))break;if("blockquote"===(null==h?void 0:h.type)){const t=h,i=t.raw+"\n"+e.join("\n"),o=this.blockquote(i);r[r.length-1]=o,n=n.substring(0,n.length-t.raw.length)+o.raw,s=s.substring(0,s.length-t.text.length)+o.text;break}if("list"!==(null==h?void 0:h.type));else{const t=h,i=t.raw+"\n"+e.join("\n"),o=this.list(i);r[r.length-1]=o,n=n.substring(0,n.length-h.raw.length)+o.raw,s=s.substring(0,s.length-t.raw.length)+o.raw,e=i.substring(r.at(-1).raw.length).split("\n")}}return{type:"blockquote",raw:n,tokens:r,text:s}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim();const s=n.length>1,r={type:"list",raw:"",ordered:s,start:s?+n.slice(0,-1):"",loose:!1,items:[]};n=s?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=s?n:"[*+-]");const i=this.rules.other.listItemRegex(n);let o=!1;for(;e;){let n=!1,s="",a="";if(!(t=i.exec(e))||this.rules.block.hr.test(e))break;s=t[0],e=e.substring(s.length);let l=t[2].split("\n",1)[0].replace(this.rules.other.listReplaceTabs,(e=>" ".repeat(3*e.length))),c=e.split("\n",1)[0],h=!l.trim(),p=0;if(this.options.pedantic?(p=2,a=l.trimStart()):h?p=t[1].length+1:(p=t[2].search(this.rules.other.nonSpaceChar),p=p>4?1:p,a=l.slice(p),p+=t[1].length),h&&this.rules.other.blankLine.test(c)&&(s+=c+"\n",e=e.substring(c.length+1),n=!0),!n){const t=this.rules.other.nextBulletRegex(p),n=this.rules.other.hrRegex(p),r=this.rules.other.fencesBeginRegex(p),i=this.rules.other.headingBeginRegex(p),o=this.rules.other.htmlBeginRegex(p);for(;e;){const u=e.split("\n",1)[0];let d;if(c=u,this.options.pedantic?(c=c.replace(this.rules.other.listReplaceNesting,"  "),d=c):d=c.replace(this.rules.other.tabCharGlobal,"    "),r.test(c)||i.test(c)||o.test(c)||t.test(c)||n.test(c))break;if(d.search(this.rules.other.nonSpaceChar)>=p||!c.trim())a+="\n"+d.slice(p);else{if(h||l.replace(this.rules.other.tabCharGlobal,"    ").search(this.rules.other.nonSpaceChar)>=4||r.test(l)||i.test(l)||n.test(l))break;a+="\n"+c}!h&&!c.trim()&&(h=!0),s+=u+"\n",e=e.substring(u.length+1),l=d.slice(p)}}r.loose||(o?r.loose=!0:this.rules.other.doubleBlankLine.test(s)&&(o=!0));let u,d=null;this.options.gfm&&(d=this.rules.other.listIsTask.exec(a),d&&(u="[ ] "!==d[0],a=a.replace(this.rules.other.listReplaceTask,""))),r.items.push({type:"list_item",raw:s,task:!!d,checked:u,loose:!1,text:a,tokens:[]}),r.raw+=s}const a=r.items.at(-1);if(!a)return;a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd(),r.raw=r.raw.trimEnd();for(let e=0;e<r.items.length;e++)if(this.lexer.state.top=!1,r.items[e].tokens=this.lexer.blockTokens(r.items[e].text,[]),!r.loose){const t=r.items[e].tokens.filter((e=>"space"===e.type)),n=t.length>0&&t.some((e=>this.rules.other.anyLine.test(e.raw)));r.loose=n}if(r.loose)for(let e=0;e<r.items.length;e++)r.items[e].loose=!0;return r}}html(e){const t=this.rules.block.html.exec(e);if(t)return{type:"html",block:!0,raw:t[0],pre:"pre"===t[1]||"script"===t[1]||"style"===t[1],text:t[0]}}def(e){const t=this.rules.block.def.exec(e);if(t){const e=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),n=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",s=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:e,raw:t[0],href:n,title:s}}}table(e){var t;const n=this.rules.block.table.exec(e);if(!n||!this.rules.other.tableDelimiter.test(n[2]))return;const s=re(n[1]),r=n[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=null!=(t=n[3])&&t.trim()?n[3].replace(this.rules.other.tableRowBlankLine,"").split("\n"):[],o={type:"table",raw:n[0],header:[],align:[],rows:[]};if(s.length===r.length){for(const e of r)this.rules.other.tableAlignRight.test(e)?o.align.push("right"):this.rules.other.tableAlignCenter.test(e)?o.align.push("center"):this.rules.other.tableAlignLeft.test(e)?o.align.push("left"):o.align.push(null);for(let e=0;e<s.length;e++)o.header.push({text:s[e],tokens:this.lexer.inline(s[e]),header:!0,align:o.align[e]});for(const e of i)o.rows.push(re(e,o.header.length).map(((e,t)=>({text:e,tokens:this.lexer.inline(e),header:!1,align:o.align[t]}))));return o}}lheading(e){const t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:"="===t[2].charAt(0)?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){const t=this.rules.block.paragraph.exec(e);if(t){const e="\n"===t[1].charAt(t[1].length-1)?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:e,tokens:this.lexer.inline(e)}}}text(e){const t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){const t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){const t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){const t=this.rules.inline.link.exec(e);if(t){const e=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(e)){if(!this.rules.other.endAngleBracket.test(e))return;const t=ie(e.slice(0,-1),"\\");if((e.length-t.length)%2==0)return}else{const e=function(e,t){if(-1===e.indexOf(t[1]))return-1;let n=0;for(let s=0;s<e.length;s++)if("\\"===e[s])s++;else if(e[s]===t[0])n++;else if(e[s]===t[1]&&(n--,n<0))return s;return-1}(t[2],"()");if(e>-1){const n=(0===t[0].indexOf("!")?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let n=t[2],s="";if(this.options.pedantic){const e=this.rules.other.pedanticHrefTitle.exec(n);e&&(n=e[1],s=e[3])}else s=t[3]?t[3].slice(1,-1):"";return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(n=this.options.pedantic&&!this.rules.other.endAngleBracket.test(e)?n.slice(1):n.slice(1,-1)),oe(t,{href:n&&n.replace(this.rules.inline.anyPunctuation,"$1"),title:s&&s.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){const e=t[(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," ").toLowerCase()];if(!e){const e=n[0].charAt(0);return{type:"text",raw:e,text:e}}return oe(n,e,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!(!s||s[3]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!s[1]&&!s[2]||!n||this.rules.inline.punctuation.exec(n))){const n=[...s[0]].length-1;let r,i,o=n,a=0;const l="*"===s[0][0]?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(l.lastIndex=0,t=t.slice(-1*e.length+n);null!=(s=l.exec(t));){if(r=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!r)continue;if(i=[...r].length,s[3]||s[4]){o+=i;continue}if((s[5]||s[6])&&n%3&&!((n+i)%3)){a+=i;continue}if(o-=i,o>0)continue;i=Math.min(i,i+o+a);const t=[...s[0]][0].length,l=e.slice(0,n+s.index+t+i);if(Math.min(n,i)%2){const e=l.slice(1,-1);return{type:"em",raw:l,text:e,tokens:this.lexer.inlineTokens(e)}}const c=l.slice(2,-2);return{type:"strong",raw:l,text:c,tokens:this.lexer.inlineTokens(c)}}}}codespan(e){const t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(this.rules.other.newLineCharGlobal," ");const n=this.rules.other.nonSpaceChar.test(e),s=this.rules.other.startingSpaceChar.test(e)&&this.rules.other.endingSpaceChar.test(e);return n&&s&&(e=e.substring(1,e.length-1)),{type:"codespan",raw:t[0],text:e}}}br(e){const t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){const t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){const t=this.rules.inline.autolink.exec(e);if(t){let e,n;return"@"===t[2]?(e=t[1],n="mailto:"+e):(e=t[1],n=e),{type:"link",raw:t[0],text:e,href:n,tokens:[{type:"text",raw:e,text:e}]}}}url(e){var t;let n;if(n=this.rules.inline.url.exec(e)){let e,s;if("@"===n[2])e=n[0],s="mailto:"+e;else{let r;do{r=n[0],n[0]=(null==(t=this.rules.inline._backpedal.exec(n[0]))?void 0:t[0])??""}while(r!==n[0]);e=n[0],s="www."===n[1]?"http://"+n[0]:n[0]}return{type:"link",raw:n[0],text:e,href:s,tokens:[{type:"text",raw:e,text:e}]}}}inlineText(e){const t=this.rules.inline.text.exec(e);if(t){const e=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:e}}}}class le{constructor(e){n(this,"tokens"),n(this,"options"),n(this,"state"),n(this,"tokenizer"),n(this,"inlineQueue"),this.tokens=[],this.tokens.links=Object.create(null),this.options=e||i,this.options.tokenizer=this.options.tokenizer||new ae,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};const t={other:c,block:X.normal,inline:Y.normal};this.options.pedantic?(t.block=X.pedantic,t.inline=Y.pedantic):this.options.gfm&&(t.block=X.gfm,this.options.breaks?t.inline=Y.breaks:t.inline=Y.gfm),this.tokenizer.rules=t}static get rules(){return{block:X,inline:Y}}static lex(e,t){return new le(t).lex(e)}static lexInline(e,t){return new le(t).inlineTokens(e)}lex(e){e=e.replace(c.carriageReturn,"\n"),this.blockTokens(e,this.tokens);for(let e=0;e<this.inlineQueue.length;e++){const t=this.inlineQueue[e];this.inlineTokens(t.src,t.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){var s,r,i;for(this.options.pedantic&&(e=e.replace(c.tabCharGlobal,"    ").replace(c.spaceLine,""));e;){let o;if(null!=(r=null==(s=this.options.extensions)?void 0:s.block)&&r.some((n=>!!(o=n.call({lexer:this},e,t))&&(e=e.substring(o.raw.length),t.push(o),!0))))continue;if(o=this.tokenizer.space(e)){e=e.substring(o.raw.length);const n=t.at(-1);1===o.raw.length&&void 0!==n?n.raw+="\n":t.push(o);continue}if(o=this.tokenizer.code(e)){e=e.substring(o.raw.length);const n=t.at(-1);"paragraph"===(null==n?void 0:n.type)||"text"===(null==n?void 0:n.type)?(n.raw+="\n"+o.raw,n.text+="\n"+o.text,this.inlineQueue.at(-1).src=n.text):t.push(o);continue}if(o=this.tokenizer.fences(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.heading(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.hr(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.blockquote(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.list(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.html(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.def(e)){e=e.substring(o.raw.length);const n=t.at(-1);"paragraph"===(null==n?void 0:n.type)||"text"===(null==n?void 0:n.type)?(n.raw+="\n"+o.raw,n.text+="\n"+o.raw,this.inlineQueue.at(-1).src=n.text):this.tokens.links[o.tag]||(this.tokens.links[o.tag]={href:o.href,title:o.title});continue}if(o=this.tokenizer.table(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.lheading(e)){e=e.substring(o.raw.length),t.push(o);continue}let a=e;if(null!=(i=this.options.extensions)&&i.startBlock){let t=1/0;const n=e.slice(1);let s;this.options.extensions.startBlock.forEach((e=>{s=e.call({lexer:this},n),"number"==typeof s&&s>=0&&(t=Math.min(t,s))})),t<1/0&&t>=0&&(a=e.substring(0,t+1))}if(this.state.top&&(o=this.tokenizer.paragraph(a))){const s=t.at(-1);n&&"paragraph"===(null==s?void 0:s.type)?(s.raw+="\n"+o.raw,s.text+="\n"+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):t.push(o),n=a.length!==e.length,e=e.substring(o.raw.length)}else if(o=this.tokenizer.text(e)){e=e.substring(o.raw.length);const n=t.at(-1);"text"===(null==n?void 0:n.type)?(n.raw+="\n"+o.raw,n.text+="\n"+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=n.text):t.push(o)}else if(e){const t="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw new Error(t)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){var n,s,r;let i=e,o=null;if(this.tokens.links){const e=Object.keys(this.tokens.links);if(e.length>0)for(;null!=(o=this.tokenizer.rules.inline.reflinkSearch.exec(i));)e.includes(o[0].slice(o[0].lastIndexOf("[")+1,-1))&&(i=i.slice(0,o.index)+"["+"a".repeat(o[0].length-2)+"]"+i.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;null!=(o=this.tokenizer.rules.inline.anyPunctuation.exec(i));)i=i.slice(0,o.index)+"++"+i.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;null!=(o=this.tokenizer.rules.inline.blockSkip.exec(i));)i=i.slice(0,o.index)+"["+"a".repeat(o[0].length-2)+"]"+i.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);let a=!1,l="";for(;e;){let o;if(a||(l=""),a=!1,null!=(s=null==(n=this.options.extensions)?void 0:n.inline)&&s.some((n=>!!(o=n.call({lexer:this},e,t))&&(e=e.substring(o.raw.length),t.push(o),!0))))continue;if(o=this.tokenizer.escape(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.tag(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.link(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(o.raw.length);const n=t.at(-1);"text"===o.type&&"text"===(null==n?void 0:n.type)?(n.raw+=o.raw,n.text+=o.text):t.push(o);continue}if(o=this.tokenizer.emStrong(e,i,l)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.codespan(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.br(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.del(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.autolink(e)){e=e.substring(o.raw.length),t.push(o);continue}if(!this.state.inLink&&(o=this.tokenizer.url(e))){e=e.substring(o.raw.length),t.push(o);continue}let c=e;if(null!=(r=this.options.extensions)&&r.startInline){let t=1/0;const n=e.slice(1);let s;this.options.extensions.startInline.forEach((e=>{s=e.call({lexer:this},n),"number"==typeof s&&s>=0&&(t=Math.min(t,s))})),t<1/0&&t>=0&&(c=e.substring(0,t+1))}if(o=this.tokenizer.inlineText(c)){e=e.substring(o.raw.length),"_"!==o.raw.slice(-1)&&(l=o.raw.slice(-1)),a=!0;const n=t.at(-1);"text"===(null==n?void 0:n.type)?(n.raw+=o.raw,n.text+=o.text):t.push(o)}else if(e){const t="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw new Error(t)}}return t}}class ce{constructor(e){n(this,"options"),n(this,"parser"),this.options=e||i}space(e){return""}code({text:e,lang:t,escaped:n}){var s;const r=null==(s=(t||"").match(c.notSpaceStart))?void 0:s[0],i=e.replace(c.endingNewline,"")+"\n";return r?'<pre><code class="language-'+ne(r)+'">'+(n?i:ne(i,!0))+"</code></pre>\n":"<pre><code>"+(n?i:ne(i,!0))+"</code></pre>\n"}blockquote({tokens:e}){return`<blockquote>\n${this.parser.parse(e)}</blockquote>\n`}html({text:e}){return e}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>\n`}hr(e){return"<hr>\n"}list(e){const t=e.ordered,n=e.start;let s="";for(let t=0;t<e.items.length;t++){const n=e.items[t];s+=this.listitem(n)}const r=t?"ol":"ul";return"<"+r+(t&&1!==n?' start="'+n+'"':"")+">\n"+s+"</"+r+">\n"}listitem(e){var t;let n="";if(e.task){const s=this.checkbox({checked:!!e.checked});e.loose?"paragraph"===(null==(t=e.tokens[0])?void 0:t.type)?(e.tokens[0].text=s+" "+e.tokens[0].text,e.tokens[0].tokens&&e.tokens[0].tokens.length>0&&"text"===e.tokens[0].tokens[0].type&&(e.tokens[0].tokens[0].text=s+" "+ne(e.tokens[0].tokens[0].text),e.tokens[0].tokens[0].escaped=!0)):e.tokens.unshift({type:"text",raw:s+" ",text:s+" ",escaped:!0}):n+=s+" "}return n+=this.parser.parse(e.tokens,!!e.loose),`<li>${n}</li>\n`}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox">'}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>\n`}table(e){let t="",n="";for(let t=0;t<e.header.length;t++)n+=this.tablecell(e.header[t]);t+=this.tablerow({text:n});let s="";for(let t=0;t<e.rows.length;t++){const r=e.rows[t];n="";for(let e=0;e<r.length;e++)n+=this.tablecell(r[e]);s+=this.tablerow({text:n})}return s&&(s=`<tbody>${s}</tbody>`),"<table>\n<thead>\n"+t+"</thead>\n"+s+"</table>\n"}tablerow({text:e}){return`<tr>\n${e}</tr>\n`}tablecell(e){const t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>\n`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${ne(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){const s=this.parser.parseInline(n),r=se(e);if(null===r)return s;let i='<a href="'+(e=r)+'"';return t&&(i+=' title="'+ne(t)+'"'),i+=">"+s+"</a>",i}image({href:e,title:t,text:n}){const s=se(e);if(null===s)return ne(n);let r=`<img src="${e=s}" alt="${n}"`;return t&&(r+=` title="${ne(t)}"`),r+=">",r}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:ne(e.text)}}class he{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}}class pe{constructor(e){n(this,"options"),n(this,"renderer"),n(this,"textRenderer"),this.options=e||i,this.options.renderer=this.options.renderer||new ce,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new he}static parse(e,t){return new pe(t).parse(e)}static parseInline(e,t){return new pe(t).parseInline(e)}parse(e,t=!0){var n,s;let r="";for(let i=0;i<e.length;i++){const o=e[i];if(null!=(s=null==(n=this.options.extensions)?void 0:n.renderers)&&s[o.type]){const e=o,t=this.options.extensions.renderers[e.type].call({parser:this},e);if(!1!==t||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(e.type)){r+=t||"";continue}}const a=o;switch(a.type){case"space":r+=this.renderer.space(a);continue;case"hr":r+=this.renderer.hr(a);continue;case"heading":r+=this.renderer.heading(a);continue;case"code":r+=this.renderer.code(a);continue;case"table":r+=this.renderer.table(a);continue;case"blockquote":r+=this.renderer.blockquote(a);continue;case"list":r+=this.renderer.list(a);continue;case"html":r+=this.renderer.html(a);continue;case"paragraph":r+=this.renderer.paragraph(a);continue;case"text":{let n=a,s=this.renderer.text(n);for(;i+1<e.length&&"text"===e[i+1].type;)n=e[++i],s+="\n"+this.renderer.text(n);r+=t?this.renderer.paragraph({type:"paragraph",raw:s,text:s,tokens:[{type:"text",raw:s,text:s,escaped:!0}]}):s;continue}default:{const e='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(e),"";throw new Error(e)}}}return r}parseInline(e,t=this.renderer){var n,s;let r="";for(let i=0;i<e.length;i++){const o=e[i];if(null!=(s=null==(n=this.options.extensions)?void 0:n.renderers)&&s[o.type]){const e=this.options.extensions.renderers[o.type].call({parser:this},o);if(!1!==e||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(o.type)){r+=e||"";continue}}const a=o;switch(a.type){case"escape":case"text":r+=t.text(a);break;case"html":r+=t.html(a);break;case"link":r+=t.link(a);break;case"image":r+=t.image(a);break;case"strong":r+=t.strong(a);break;case"em":r+=t.em(a);break;case"codespan":r+=t.codespan(a);break;case"br":r+=t.br(a);break;case"del":r+=t.del(a);break;default:{const e='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(e),"";throw new Error(e)}}}return r}}class ue{constructor(e){n(this,"options"),n(this,"block"),this.options=e||i}preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}provideLexer(){return this.block?le.lex:le.lexInline}provideParser(){return this.block?pe.parse:pe.parseInline}}n(ue,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens"]));const de=new class{constructor(...e){n(this,"defaults",{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}),n(this,"options",this.setOptions),n(this,"parse",this.parseMarkdown(!0)),n(this,"parseInline",this.parseMarkdown(!1)),n(this,"Parser",pe),n(this,"Renderer",ce),n(this,"TextRenderer",he),n(this,"Lexer",le),n(this,"Tokenizer",ae),n(this,"Hooks",ue),this.use(...e)}walkTokens(e,t){var n,s;let r=[];for(const i of e)switch(r=r.concat(t.call(this,i)),i.type){case"table":{const e=i;for(const n of e.header)r=r.concat(this.walkTokens(n.tokens,t));for(const n of e.rows)for(const e of n)r=r.concat(this.walkTokens(e.tokens,t));break}case"list":{const e=i;r=r.concat(this.walkTokens(e.items,t));break}default:{const e=i;null!=(s=null==(n=this.defaults.extensions)?void 0:n.childTokens)&&s[e.type]?this.defaults.extensions.childTokens[e.type].forEach((n=>{const s=e[n].flat(1/0);r=r.concat(this.walkTokens(s,t))})):e.tokens&&(r=r.concat(this.walkTokens(e.tokens,t)))}}return r}use(...e){const t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach((e=>{const n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach((e=>{if(!e.name)throw new Error("extension name required");if("renderer"in e){const n=t.renderers[e.name];t.renderers[e.name]=n?function(...t){let s=e.renderer.apply(this,t);return!1===s&&(s=n.apply(this,t)),s}:e.renderer}if("tokenizer"in e){if(!e.level||"block"!==e.level&&"inline"!==e.level)throw new Error("extension level must be 'block' or 'inline'");const n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&("block"===e.level?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:"inline"===e.level&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}"childTokens"in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)})),n.extensions=t),e.renderer){const t=this.defaults.renderer||new ce(this.defaults);for(const n in e.renderer){if(!(n in t))throw new Error(`renderer '${n}' does not exist`);if(["options","parser"].includes(n))continue;const s=n,r=e.renderer[s],i=t[s];t[s]=(...e)=>{let n=r.apply(t,e);return!1===n&&(n=i.apply(t,e)),n||""}}n.renderer=t}if(e.tokenizer){const t=this.defaults.tokenizer||new ae(this.defaults);for(const n in e.tokenizer){if(!(n in t))throw new Error(`tokenizer '${n}' does not exist`);if(["options","rules","lexer"].includes(n))continue;const s=n,r=e.tokenizer[s],i=t[s];t[s]=(...e)=>{let n=r.apply(t,e);return!1===n&&(n=i.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){const t=this.defaults.hooks||new ue;for(const n in e.hooks){if(!(n in t))throw new Error(`hook '${n}' does not exist`);if(["options","block"].includes(n))continue;const s=n,r=e.hooks[s],i=t[s];ue.passThroughHooks.has(n)?t[s]=e=>{if(this.defaults.async)return Promise.resolve(r.call(t,e)).then((e=>i.call(t,e)));const n=r.call(t,e);return i.call(t,n)}:t[s]=(...e)=>{let n=r.apply(t,e);return!1===n&&(n=i.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){const t=this.defaults.walkTokens,s=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(s.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}})),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return le.lex(e,t??this.defaults)}parser(e,t){return pe.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{const s={...n},r={...this.defaults,...s},i=this.onError(!!r.silent,!!r.async);if(!0===this.defaults.async&&!1===s.async)return i(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof t>"u"||null===t)return i(new Error("marked(): input parameter is undefined or null"));if("string"!=typeof t)return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));r.hooks&&(r.hooks.options=r,r.hooks.block=e);const o=r.hooks?r.hooks.provideLexer():e?le.lex:le.lexInline,a=r.hooks?r.hooks.provideParser():e?pe.parse:pe.parseInline;if(r.async)return Promise.resolve(r.hooks?r.hooks.preprocess(t):t).then((e=>o(e,r))).then((e=>r.hooks?r.hooks.processAllTokens(e):e)).then((e=>r.walkTokens?Promise.all(this.walkTokens(e,r.walkTokens)).then((()=>e)):e)).then((e=>a(e,r))).then((e=>r.hooks?r.hooks.postprocess(e):e)).catch(i);try{r.hooks&&(t=r.hooks.preprocess(t));let e=o(t,r);r.hooks&&(e=r.hooks.processAllTokens(e)),r.walkTokens&&this.walkTokens(e,r.walkTokens);let n=a(e,r);return r.hooks&&(n=r.hooks.postprocess(n)),n}catch(e){return i(e)}}}onError(e,t){return n=>{if(n.message+="\nPlease report this to https://github.com/markedjs/marked.",e){const e="<p>An error occurred:</p><pre>"+ne(n.message+"",!0)+"</pre>";return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function ge(e,t){return de.parse(e,t)}ge.options=ge.setOptions=function(e){return de.setOptions(e),ge.defaults=de.defaults,o(ge.defaults),ge},ge.getDefaults=r,ge.defaults=i,ge.use=function(...e){return de.use(...e),ge.defaults=de.defaults,o(ge.defaults),ge},ge.walkTokens=function(e,t){return de.walkTokens(e,t)},ge.parseInline=de.parseInline,ge.Parser=pe,ge.parser=pe.parse,ge.Renderer=ce,ge.TextRenderer=he,ge.Lexer=le,ge.lexer=le.lex,ge.Tokenizer=ae,ge.Hooks=ue,ge.parse=ge,ge.options,ge.setOptions,ge.use,ge.walkTokens,ge.parseInline,pe.parse,le.lex;class be{constructor(e){n(this,"storageKey"),this.storageKey=`chat_history_${btoa(e)}`}getMessages(){try{const e=localStorage.getItem(this.storageKey);return e?JSON.parse(e):[]}catch(e){return console.error("Failed to load chat history:",e),[]}}addMessage(e){try{const t=this.getMessages();t.push(e),localStorage.setItem(this.storageKey,JSON.stringify(t))}catch(e){console.error("Failed to save message:",e)}}updateMessage(e,t){try{const n=this.getMessages(),s=n.findIndex((t=>t.id===e));-1!==s&&(n[s]={...n[s],...t},localStorage.setItem(this.storageKey,JSON.stringify(n)))}catch(e){console.error("Failed to update message:",e)}}clearHistory(){try{localStorage.removeItem(this.storageKey)}catch(e){console.error("Failed to clear history:",e)}}}class me{constructor(e){n(this,"url"),n(this,"controller",null),this.url=e}async sendMessage(e){this.controller&&this.controller.abort(),this.controller=new AbortController;try{const t=await fetch(this.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:this.controller.signal});if(!t.ok)throw new Error(`HTTP error! status: ${t.status}`);const n=await t.json();if(this.controller=null,Array.isArray(n)&&n.length>0)return{output:n[0].output};if(n.output)return{output:n.output};throw new Error("Invalid response format from webhook")}catch(e){throw e instanceof Error&&"AbortError"===e.name?new Error("Request cancelled"):e}}cancelRequest(){this.controller&&(this.controller.abort(),this.controller=null)}}customElements.define("link-preview",class extends s{constructor(){super(),n(this,"styles","\n    .preview-container {\n      display: flex;\n      border: 1px solid #ccc;\n      border-radius: 12px;\n      overflow: hidden;\n      margin-top: 12px;\n      padding: 12px;\n      box-sizing: border-box;\n      gap: 12px;\n      background: #fff;\n      text-decoration: none;\n      color: inherit;\n    }\n\n    .preview-image {\n      width: 80px;\n      height: 80px;\n      object-fit: cover;\n    }\n\n    .preview-content {\n      flex: 1;\n      display: flex;\n      flex-direction: column;\n      justify-content: center;\n    }\n\n    .preview-title {\n      font-weight: bold;\n    }\n\n    .preview-description {\n      font-size: 13px;\n      color: #666;\n    }\n    @media (prefers-color-scheme: dark) {\n        .preview-container {\n          background: #2c2c2c !important;\n          border-color: #444 !important;\n          color: #eee !important;\n        }\n        .preview-description {\n          color: #aaa !important;\n        }\n      }\n  "),this.addStyles(this.styles)}static get observedAttributes(){return["url","title","description","image"]}connectedCallback(){this.render()}render(){const e=this.getAttribute("url")||"",t=this.getAttribute("title")||"Link Preview",n=this.getAttribute("description")||"",s=this.getAttribute("image")||"",r=this.createElement("a","preview-container");r.href=e,r.target="_blank";const i=this.createElement("img","preview-image");i.src=s,i.alt=t;const o=this.createElement("div","preview-content"),a=this.createElement("div","preview-title",t),l=this.createElement("div","preview-description",n);o.appendChild(a),o.appendChild(l),r.appendChild(i),r.appendChild(o),this.shadow.innerHTML="",this.shadow.appendChild(r)}attributeChangedCallback(e,t){e!==t&&this.render()}}),ge.setOptions({});const fe=class e extends s{constructor(){super(),n(this,"styles",'\n    .chat-window {\n      position: fixed;\n      bottom: 80px;\n      right: 0;\n      width: 100%;\n      max-width: 420px;\n      height: calc(100vh - 100px);\n      max-height: 600px;\n      background: white;\n      border-radius: 12px;\n      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);\n      display: flex;\n      flex-direction: column;\n      overflow: hidden;\n      opacity: 0;\n      transform: translateY(20px);\n      transition: opacity 0.2s ease, transform 0.2s ease;\n      pointer-events: none;\n    }\n    .suggestion-button {\n          background: #fff;\n          border: 1px solid #e5e5e5;\n          border-radius: 20px;\n          padding: 10px 16px;\n          font-size: 15px;\n          font-weight: 500;\n          margin-bottom: 10px;\n          cursor: pointer;\n          text-align: left;\n          transition: background-color 0.2s;\n        }\n\n        .suggestion-button:hover {\n          background-color: #f0f0f0;\n        }\n\n        .suggestion-button::after {\n          content: \'➤\';\n          float: right;\n          opacity: 0.5;\n        }\n\n    @media (max-width: 480px) {\n      .chat-window {\n        position: fixed;\n        inset: 0;\n        width: 100%;\n        height: 100dvh;\n        max-height: none;\n        border-radius: 0;\n        transform: translateY(100%);\n        contain: layout style;\n        touch-action: manipulation;\n        overscroll-behavior: none;\n      }\n      \n      .chat-window.open {\n        transform: translateY(0);\n      }\n\n      .messages {\n        padding: 12px;\n        padding-bottom: 80px;\n      }\n\n      .input-area {\n        padding: 12px;\n        padding-bottom: calc(env(safe-area-inset-bottom) + 16px);\n        position: sticky;\n        bottom: 0;\n        z-index: 10;\n        background-color: inherit;\n      }\n\n    }\n\n    .chat-window.open {\n      opacity: 1;\n      transform: translateY(0);\n      pointer-events: all;\n    }\n\n    :host([position="bottom-left"]) .chat-window {\n      right: auto;\n      left: 0;\n    }\n\n    .header {\n      padding: 16px;\n      background-color: var(--theme-color, #1E40AF);\n      color: white;\n      display: flex;\n      justify-content: space-between;\n      align-items: center;\n    }\n\n    .header h2 {\n      margin: 0;\n      font-size: 16px;\n      font-weight: 500;\n    }\n\n    .header-actions {\n      display: flex;\n      gap: 12px;\n    }\n\n    .header button {\n      background: none;\n      border: none;\n      color: white;\n      cursor: pointer;\n      width: 44px;\n      height: 44px;\n      display: flex;\n      align-items: center;\n      justify-content: center;\n      font-size: 24px;\n      opacity: 0.9;\n      transition: opacity 0.2s;\n      border-radius: 8px;\n      background-color: rgba(255, 255, 255, 0.1);\n    }\n\n    .header button:hover {\n      opacity: 1;\n    }\n\n    .messages {\n      flex: 1;\n      overflow-y: auto;\n      padding: 16px;\n      display: flex;\n      flex-direction: column;\n      gap: 16px;\n      background-color: #f7f7f8;\n    }\n\n    .message {\n      max-width: 85%;\n      padding: 12px 16px;\n      border-radius: 16px;\n      font-size: 16px;\n      line-height: 1.5;\n      box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);\n    }\n\n    .message.user {\n      align-self: flex-end;\n      background-color: var(--theme-color, #1E40AF);\n      color: white;\n      border-bottom-right-radius: 4px;\n    }\n\n    .message.bot {\n      background-color: #f0f0f0;\n      align-self: flex-start;\n      border-bottom-left-radius: 0;\n    }\n\n    /* Add dark mode support for chat window */\n    :host([data-theme="dark"]) .chat-window,\n    [data-theme="dark"] .chat-window {\n      background: #18181b;\n      color: #f3f4f6;\n    }\n    :host([data-theme="dark"]) .messages,\n    [data-theme="dark"] .messages {\n      background-color: #18181b;\n    }\n    :host([data-theme="dark"]) .message.bot,\n    [data-theme="dark"] .message.bot {\n      background-color: #23232a;\n      color: #f3f4f6;\n    }\n    :host([data-theme="dark"]) .message.user,\n    [data-theme="dark"] .message.user {\n      background-color: #2563eb;\n      color: #fff;\n    }\n    :host([data-theme="dark"]) .input-area,\n    [data-theme="dark"] .input-area {\n      background-color: #23232a;\n      border-top: 1px solid #333843;\n    }\n    :host([data-theme="dark"]) .input-area input,\n    [data-theme="dark"] .input-area input {\n      background-color: #18181b;\n      color: #f3f4f6;\n      border: 1px solid #333843;\n    }\n    :host([data-theme="dark"]) .input-area button,\n    [data-theme="dark"] .input-area button {\n      background-color: #2563eb;\n      color: #fff;\n    }\n    :host([data-theme="dark"]) .suggestion-button,\n    [data-theme="dark"] .suggestion-button {\n      background: #23232a;\n      color: #f3f4f6;\n      border-color: #333843;\n    }\n    :host([data-theme="dark"]) .suggestion-button:hover,\n    [data-theme="dark"] .suggestion-button:hover {\n      background: #18181b;\n    }\n    :host([data-theme="dark"]) .message-status,\n    [data-theme="dark"] .message-status {\n      color: #cbd5e1;\n    }\n    :host([data-theme="dark"]) .cancel-button,\n    [data-theme="dark"] .cancel-button {\n      background: rgba(255,255,255,0.08);\n      color: #fff;\n    }\n    :host([data-theme="dark"]) .message.system,\n    [data-theme="dark"] .message.system {\n      background-color: #23232a;\n      color: #a1a1aa;\n    }\n    :host([data-theme="dark"]) .message.bot code,\n    [data-theme="dark"] .message.bot code {\n      background-color: #27272a;\n      color: #facc15;\n    }\n    :host([data-theme="dark"]) .message.bot pre,\n    [data-theme="dark"] .message.bot pre {\n      background-color: #23232a;\n      color: #f3f4f6;\n    }\n    :host([data-theme="dark"]) .message.bot a,\n    [data-theme="dark"] .message.bot a {\n      color: #60a5fa;\n    }\n    .message.bot h1,\n    .message.bot h2,\n    .message.bot h3,\n    .message.bot h4,\n    .message.bot h5,\n    .message.bot h6 {\n      margin: 8px 0;\n      line-height: 1.2;\n      font-size: 1em;\n    }\n\n    .message.bot h1 { font-size: 1.4em; }\n    .message.bot h2 { font-size: 1.3em; }\n    .message.bot h3 { font-size: 1.2em; }\n\n    .message.bot p {\n      margin: 8px 0;\n    }\n\n    .message.bot ul,\n    .message.bot ol {\n      margin: 8px 0;\n      padding-left: 20px;\n    }\n\n    .message.bot code {\n      background-color: #e8e8e8;\n      padding: 2px 4px;\n      border-radius: 4px;\n      font-family: monospace;\n      font-size: 0.9em;\n    }\n\n    .message.bot pre {\n      background-color: #e8e8e8;\n      padding: 8px;\n      border-radius: 4px;\n      overflow-x: auto;\n      margin: 8px 0;\n    }\n\n    .message.bot pre code {\n      background-color: transparent;\n      padding: 0;\n      border-radius: 0;\n    }\n\n    .message.bot a {\n      color: var(--theme-color, #1E40AF);\n      text-decoration: none;\n    }\n\n    .message.bot a:hover {\n      text-decoration: underline;\n    }\n\n    .message.bot blockquote {\n      border-left: 4px solid #ddd;\n      margin: 8px 0;\n      padding-left: 16px;\n      color: #666;\n    }\n\n    .message.bot table {\n      border-collapse: collapse;\n      margin: 8px 0;\n      width: 100%;\n      font-size: 0.9em;\n    }\n\n    .message.bot th,\n    .message.bot td {\n      border: 1px solid #ddd;\n      padding: 6px;\n    }\n\n    .message.bot th {\n      background-color: #e8e8e8;\n      font-weight: 600;\n    }\n\n    .message.bot img {\n      max-width: 100%;\n      height: auto;\n      border-radius: 4px;\n      margin: 8px 0;\n    }\n\n    .message.system {\n      align-self: center;\n      background-color: #f5f5f5;\n      color: #666;\n      font-style: italic;\n      font-size: 13px;\n    }\n\n    .message.error {\n      background-color: #fee2e2;\n      color: #991b1b;\n    }\n\n    .message-status {\n      font-size: 11px;\n      margin-top: 4px;\n      opacity: 0.8;\n    }\n\n    .cancel-button {\n      font-size: 12px;\n      padding: 2px 6px;\n      color:rgb(255, 255, 255);\n      background: rgba(0, 0, 0, 0.1);\n      border: none;\n      border-radius: 4px;\n      cursor: pointer;\n      margin-left: 8px;\n    }\n\n    .input-area {\n      padding: 16px;\n      background-color: white;\n      border-top: 1px solid #eee;\n      display: flex;\n      gap: 8px;\n      position: relative;\n      box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);\n    }\n\n    .input-area input {\n      flex: 1;\n      padding: 12px 16px;\n      border: 1px solid #e5e5e5;\n      border-radius: 24px;\n      font-size: 16px;\n      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);\n      transition: border-color 0.2s, box-shadow 0.2s;\n    }\n\n    .input-area input:focus {\n      outline: none;\n      border-color: var(--theme-color, #1E40AF);\n      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);\n    }\n\n    .input-area button {\n      background-color: var(--theme-color, #1E40AF);\n      color: white;\n      border: none;\n      border-radius: 20px;\n      padding: 8px 16px;\n      cursor: pointer;\n      font-size: 14px;\n      transition: opacity 0.2s;\n    }\n\n    .input-area button:hover {\n      opacity: 0.9;\n    }\n\n    .input-area button:disabled {\n      opacity: 0.5;\n      cursor: not-allowed;\n    }\n\n    @media (prefers-color-scheme: dark) {\n      .chat-window {\n        background: #18181b;\n        color: #f3f4f6;\n      }\n\n      .messages {\n        background-color: #18181b;\n      }\n\n      .message.bot {\n        background-color: #23232a;\n        color: #f3f4f6;\n      }\n\n      .message.user {\n        background-color: var(--theme-color, #4f8cff);\n        color: white;\n      }\n\n      .input-area {\n        background-color: #1f1f1f;\n        border-top: 1px solid #333;\n      }\n\n      .input-area input {\n        background-color: #2c2c2c;\n        color: #eee;\n        border: 1px solid #444;\n      }\n\n      .link-preview {\n        background-color: #2c2c2c !important;\n        border-color: #444 !important;\n        color: #eee !important;\n      }\n\n      .message.bot a {\n        color: #91bfff;\n      }\n    }\n  '),n(this,"isOpen",!1),n(this,"storage"),n(this,"webhook"),n(this,"sessionId"),n(this,"hasShownWelcomeMessage",!1);const e=this.getAttribute("webhook-url")||"";this.storage=new be(e),this.webhook=new me(e),this.sessionId=crypto.randomUUID(),this.addStyles(this.styles)}static get observedAttributes(){return["webhook-url","title","welcome-message","history-enabled","history-clear-button","position"]}connectedCallback(){const e=()=>{"dark"===document.documentElement.getAttribute("data-theme")?this.setAttribute("data-theme","dark"):this.removeAttribute("data-theme")};e();const t=new MutationObserver(e);t.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),this._themeObserver=t,this.render()}render(){const e=this.createElement("div","chat-window"),t=this.createElement("div","header"),n=this.createElement("h2","",this.getAttribute("title")||"Chat with us"),s=this.createElement("div","header-actions");if("false"!==this.getAttribute("history-enabled")&&"false"!==this.getAttribute("history-clear-button")){const e=this.createElement("button","","⌫");e.title="Clear history",e.addEventListener("click",(()=>this.clearHistory())),s.appendChild(e)}const r=this.createElement("button","","✕");r.addEventListener("click",(()=>this.close())),s.appendChild(r),t.appendChild(n),t.appendChild(s);const i=this.createElement("div","messages");"false"!==this.getAttribute("history-enabled")&&this.storage.getMessages().forEach((e=>this.renderMessage(e,i))),["Triển khai smarthome thế nào?","Tìm hiểu về lắp đặt điện mặt trời","Triển khai các dịch vụ xem phim, giải trí tại nhà thì cần những gì?","Làm thế nào để wifi trong nhà mạnh hơn?"].forEach((e=>{const t=this.createElement("button","suggestion-button",e);t.addEventListener("click",(()=>{this.sendMessage(e)})),i.appendChild(t)}));const o=this.createElement("div","input-area"),a=this.createElement("input");a.type="text",a.placeholder="Type your message...";const l=this.createElement("button","","Send"),c=()=>{const e=a.value.trim();e&&(this.sendMessage(e),a.value="")};l.addEventListener("click",c),a.addEventListener("keypress",(e=>{"Enter"===e.key&&!e.shiftKey&&(e.preventDefault(),c())})),o.appendChild(a),o.appendChild(l),e.appendChild(t),e.appendChild(i),e.appendChild(o),this.shadow.innerHTML="",this.shadow.appendChild(e);const h=this.getAttribute("welcome-message");h&&!this.hasShownWelcomeMessage&&this.isOpen&&(this.addSystemMessage(h),this.hasShownWelcomeMessage=!0)}async sendMessage(e){const t=crypto.randomUUID(),n=(new Date).toISOString(),s={id:t,text:e,sender:"user",timestamp:n,status:"sending"};this.storage.addMessage(s),this.renderMessage(s);const r=this.shadow.querySelector('[data-message-id="typing-indicator"]');r&&r.remove();const i={id:"typing-indicator",text:"Đang tra cứu thông tin ...",sender:"backend",timestamp:(new Date).toISOString()};this.renderMessage(i);try{const r=await this.webhook.sendMessage({message:e,timestamp:n,sessionId:this.sessionId,context:{url:window.location.href}});s.status="sent",this.storage.updateMessage(t,{status:"sent"}),this.updateMessageStatus(t,"sent");const i=this.shadow.querySelector('[data-message-id="typing-indicator"]');i&&i.remove();const o={id:crypto.randomUUID(),text:r.output,sender:"backend",timestamp:(new Date).toISOString()};this.storage.addMessage(o),this.renderMessage(o)}catch(e){const n=this.shadow.querySelector('[data-message-id="typing-indicator"]');n&&n.remove(),e instanceof Error&&"Request cancelled"===e.message?(s.status="cancelled",this.storage.updateMessage(t,{status:"cancelled"}),this.updateMessageStatus(t,"cancelled")):(s.status="error",this.storage.updateMessage(t,{status:"error"}),this.updateMessageStatus(t,"error"),this.addSystemMessage("Failed to send message. Please try again."))}}createMessageElement(e,t=!1){const n=this.createElement("div","message "+(t?"user":"bot"));if("Đang tra cứu thông tin ..."===e)n.classList.add("typing"),n.innerHTML='\n        <span>Đang tra cứu thông tin </span>\n        <svg width="24" height="6" viewBox="0 0 24 6" xmlns="http://www.w3.org/2000/svg" fill="#666">\n          <circle cx="3" cy="3" r="3">\n            <animate attributeName="opacity" values="0;1;0" dur="1s" repeatCount="indefinite" begin="0s" />\n          </circle>\n          <circle cx="12" cy="3" r="3">\n            <animate attributeName="opacity" values="0;1;0" dur="1s" repeatCount="indefinite" begin="0.2s" />\n          </circle>\n          <circle cx="21" cy="3" r="3">\n            <animate attributeName="opacity" values="0;1;0" dur="1s" repeatCount="indefinite" begin="0.4s" />\n          </circle>\n        </svg>\n      ';else if(n.textContent="",t)n.textContent=e;else{const t=e.replace(/(https?:\/\/[\S]+)/g,(e=>`[${e}](${e})`));n.innerHTML=ge.parse(t)}return n}renderMessage(e,t){const n=t||this.shadow.querySelector(".messages");if(!n)return;const s=this.createMessageElement(e.text,"user"===e.sender);if(s.dataset.messageId=e.id,"user"===e.sender&&e.status){const t=this.createElement("div","message-status");if(t.textContent=e.status,"sending"===e.status){const e=this.createElement("button","cancel-button","Cancel");e.addEventListener("click",(()=>{this.webhook.cancelRequest()})),t.appendChild(e)}s.appendChild(t)}n.appendChild(s),n.scrollTop=n.scrollHeight;const r=e.text.match(/(https?:\/\/[\S]+)/g)||[];r.length>0&&r.forEach((async e=>{const t=await this.fetchLinkPreview(e);if(t){const n=document.createElement("link-preview");n.setAttribute("url",e),n.setAttribute("title",t.title),n.setAttribute("description",t.description),n.setAttribute("image",t.image),s.appendChild(n)}}))}async fetchLinkPreview(t){if(e.linkPreviewCache.has(t))return e.linkPreviewCache.get(t)??null;try{const n=await fetch(`/url?url=${encodeURIComponent(t)}`);if(n.ok){const s=await n.json(),r=s.match(/<title[^>]*>([^<]+)<\/title>/),i=s.match(/<meta[^>]*name="description"[^>]*content="([^"]+)"/i),o=s.match(/<meta[^>]*property="og:image"[^>]*content="([^"]+)"/i),a={title:r?r[1]:t,description:i?i[1]:"",image:o?o[1]:""};return e.linkPreviewCache.set(t,a),a}}finally{return e.linkPreviewCache.set(t,null),null}}updateMessageStatus(e,t){const n=this.shadow.querySelector(`[data-message-id="${e}"]`);if(n){const e=n.querySelector(".message-status");e&&(e.textContent=t)}}clearHistory(){if(confirm("Are you sure you want to clear the chat history?")){this.storage.clearHistory();const e=this.shadow.querySelector(".messages");e&&(e.innerHTML=""),this.hasShownWelcomeMessage=!1}}addSystemMessage(e){const t={id:crypto.randomUUID(),text:e,sender:"system",timestamp:(new Date).toISOString()};"false"!==this.getAttribute("history-enabled")&&this.storage.addMessage(t),this.renderMessage(t)}close(){this.isOpen=!1,this.updateVisibility(),this.dispatchEvent(new CustomEvent("toggleChat",{detail:{isOpen:!1},bubbles:!0,composed:!0})),this.dispatchEvent(new CustomEvent("close"))}setOpen(e,t=!1){if(this.isOpen=e,this.updateVisibility(),e&&t&&this.focusInput(),e&&!this.hasShownWelcomeMessage){const e=this.getAttribute("welcome-message");e&&(this.addSystemMessage(e),this.hasShownWelcomeMessage=!0)}}updateVisibility(){const e=this.shadow.querySelector(".chat-window");e&&(this.isOpen?e.classList.add("open"):e.classList.remove("open"))}focusInput(){const e=this.shadow.querySelector(".input-area input");e&&(e.focus(),setTimeout((()=>{e.scrollIntoView({behavior:"smooth",block:"center"})}),300))}attributeChangedCallback(e,t,n){if(t!==n){if("webhook-url"===e){const e=n||"";this.storage=new be(e),this.webhook=new me(e)}this.render()}}};n(fe,"linkPreviewCache",new Map);let ke=fe;customElements.define("chat-window",ke);function xe(e){var t,n;const s=document.createElement("chat-widget");return s.setAttribute("webhook-url",e.webhookUrl),e.themeColor&&s.setAttribute("theme-color",e.themeColor),e.position&&s.setAttribute("position",e.position),e.title&&s.setAttribute("title",e.title),e.welcomeMessage&&s.setAttribute("welcome-message",e.welcomeMessage),void 0!==(null==(t=e.history)?void 0:t.enabled)&&s.setAttribute("history-enabled",String(e.history.enabled)),void 0!==(null==(n=e.history)?void 0:n.clearButton)&&s.setAttribute("history-clear-button",String(e.history.clearButton)),document.body.appendChild(s),s}if(customElements.define("chat-widget",class extends s{constructor(){super(),n(this,"styles",`\n    :host {\n      position: fixed;\n      z-index: 9999;\n      bottom: 20px;\n      right: 20px;\n      font-family: system-ui, -apple-system, sans-serif;\n    }\n\n    :host([position="bottom-left"]) {\n      right: auto;\n      left: 20px;\n    }\n\n    .chat-widget-container {\n      --theme-color: ${this.getAttribute("theme-color")||"#1E40AF"};\n    }\n  `),n(this,"window",null),console.info("[just-chat] Version:","1.0.0"),this.addStyles(this.styles),this.render()}static get observedAttributes(){return["webhook-url","theme-color","position","title","welcome-message","history-enabled","history-clear-button"]}render(){this.shadow.innerHTML="";const e=this.createElement("div","chat-widget-container"),t=this.getConfig(),n=document.createElement("chat-window");n.setAttribute("webhook-url",t.webhookUrl),n.setAttribute("theme-color",t.themeColor),n.setAttribute("title",t.title),n.setAttribute("welcome-message",t.welcomeMessage),n.setAttribute("history-enabled",String(t.historyEnabled)),n.setAttribute("history-clear-button",String(t.historyClearButton)),n.setAttribute("position",t.position),this.window=n;const s=document.createElement("chat-launcher");s.setAttribute("theme-color",t.themeColor),s.addEventListener("toggleChat",(e=>{console.log("Toggle chat event received");const{isOpen:t}=e.detail;console.log("Toggle state:",t),this.handleToggleChat(t)})),e.appendChild(n),e.appendChild(s),this.shadow.appendChild(e)}handleToggleChat(e){console.log("Handling toggle chat:",e),this.window?(console.log("Chat window found, setting open state"),this.window.setOpen(e,!0)):console.log("Chat window not found")}getConfig(){return{webhookUrl:this.getAttribute("webhook-url")||"",themeColor:this.getAttribute("theme-color")||"#1E40AF",position:this.getAttribute("position")||"bottom-right",title:this.getAttribute("title")||"Chat with us",welcomeMessage:this.getAttribute("welcome-message")||"",historyEnabled:"false"!==this.getAttribute("history-enabled"),historyClearButton:"false"!==this.getAttribute("history-clear-button")}}attributeChangedCallback(e,t,n){t!==n&&("theme-color"===e&&this.addStyles(`\n          :host {\n            position: fixed;\n            z-index: 9999;\n            bottom: 20px;\n            right: 20px;\n            font-family: system-ui, -apple-system, sans-serif;\n          }\n\n          :host([position="bottom-left"]) {\n            right: auto;\n            left: 20px;\n          }\n\n          .chat-widget-container {\n            --theme-color: ${n||"#1E40AF"};\n          }\n        `),this.render())}}),document.currentScript instanceof HTMLScriptElement){const e=document.currentScript;xe({webhookUrl:e.dataset.webhookUrl||"",themeColor:e.dataset.themeColor,position:e.dataset.position,title:e.dataset.title,welcomeMessage:e.dataset.welcomeMessage,history:{enabled:"false"!==e.dataset.historyEnabled,clearButton:"false"!==e.dataset.historyClearButton}})}e.initChatPopup=xe,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})}));
//# sourceMappingURL=/sm/706965e059c0f36138e1e63180da14ba256b9d01dde30380bcddb62cddc87e95.map