1import{S as e,r as t,a as n,b as r,g as o,c as i,d as a}from"./chunks/sk-gb-html-utils-BvG7VahS.min.js";var l=window.alert;var s={chrome:"Klik pÃ¥ lÃ¥se-ikonet i adresselinjen â Indstillinger for website â Mikrofon â Tillad",edge:"Klik pÃ¥ lÃ¥se-ikonet i adresselinjen â Tilladelser â Mikrofon â Tillad",firefox:"Klik pÃ¥ lÃ¥se-ikonet i adresselinjen â Tilladelser â Brug mikrofonen â Tillad",safari:"Safari-menu â Indstillinger â Websites â Mikrofon â Tillad"};function c(e){var t=document.getElementById("mic-guide-banner");t&&t.remove();var n,r=(n=navigator.userAgent).indexOf("Edg/")>-1?"edge":n.indexOf("Chrome")>-1?"chrome":n.indexOf("Firefox")>-1?"firefox":n.indexOf("Safari")>-1?"safari":"chrome",o=s[r]||s.chrome,i=document.createElement("div");i.id="mic-guide-banner",i.className="mic-guide-banner";var a=document.createElement("div");a.className="mic-guide-icon",a.setAttribute("aria-hidden","true");var l="http://www.w3.org/2000/svg",c=document.createElementNS(l,"svg");c.setAttribute("viewBox","0 0 24 24"),c.setAttribute("fill","none"),c.setAttribute("stroke","currentColor"),c.setAttribute("stroke-width","1.5"),c.setAttribute("width","24"),c.setAttribute("height","24");var d=document.createElementNS(l,"path");d.setAttribute("d","M12 17c-2.76 0-5-2.24-5-5V7c0-2.76 2.24-5 5-5s5 2.24 5 5v5c0 2.76-2.24 5-5 5z");var u=document.createElementNS(l,"path");u.setAttribute("d","M19 10v2a7 7 0 01-14 0v-2");var p=document.createElementNS(l,"line");p.setAttribute("x1","12"),p.setAttribute("y1","21"),p.setAttribute("x2","12"),p.setAttribute("y2","23"),c.appendChild(d),c.appendChild(u),c.appendChild(p),a.appendChild(c),i.appendChild(a);var m=document.createElement("div");m.className="mic-guide-text";var f=document.createElement("div");f.className="mic-guide-title",f.textContent="Mikrofonen er ikke aktiveret",m.appendChild(f);var g=document.createElement("div");g.className="mic-guide-desc",g.textContent=o,m.appendChild(g),i.appendChild(m);var h=document.createElement("button");h.className="mic-guide-close",h.setAttribute("aria-label","Luk"),h.textContent="Ã",h.addEventListener("click",function(){i.style.opacity="0",setTimeout(function(){i.remove()},200)}),i.appendChild(h),document.body.appendChild(i),setTimeout(function(){i.parentNode&&(i.style.opacity="0",setTimeout(function(){i.remove()},200))},12e3)}window.alert=function(e){var t=(e||"").toString().toLowerCase();t.indexOf("mikrofon")>-1||t.indexOf("microphone")>-1||t.indexOf("mic")>-1&&t.indexOf("fejl")>-1||t.indexOf("talegenkendelse")>-1||t.indexOf("speech recognition")>-1?c():l.call(window,e)};const d="skrivebord.tts.volume";function u(e,t=.6){let n=Number(e);return Number.isFinite(n)||(n=t),n>1&&n<=100&&(n/=100),Math.min(1,Math.max(0,n))}function p(){if("undefined"!=typeof window&&void 0!==window.__SKRIVEBORD_TTS_VOLUME__)return u(window.__SKRIVEBORD_TTS_VOLUME__);const e=function(){try{return window.localStorage.getItem(d)}catch(e){return null}}();return null!==e&&""!==e?u(e):.6}function m(){return Math.round(100*p())}function f(e){const t=u(e);if("undefined"!=typeof window){window.__SKRIVEBORD_TTS_VOLUME__=t;try{window.localStorage.setItem(d,String(t))}catch(e){}}return t}function g(e){if(!e)return.6;const t=p();return e.volume=t,t}function h(){try{const e=window.localStorage.getItem("ss_tts_voice");if("male"===e||"female"===e)return e}catch(e){}return"female"}let v=null,y=null;function w(e){if(!e)return null;const t=String(e).trim().toLowerCase().replace(/_/g,"-").split("-")[0];return/^[a-z]{2,3}$/.test(t)?t:null}const b=new Set(["dag","morgen","gÃ¥r","gaar","aften","nat","morges","aftes","fjor","weekend","weekenden","Ã¥r","Ã¥ret","uge","ugen","uger","mÃ¥ned","mÃ¥neden","mÃ¥neder","sommer","sommers","vinter","vinters","efterÃ¥r","efterÃ¥ret","forÃ¥r","forÃ¥ret","starten","slutningen","begyndelsen","midten","løbet","stedet","gang","gangen","forbindelse","forhold","øjeblikket","mellemtiden","nærheden","orden","tvivl","stand","alt","aftenen","januar","februar","marts","april","maj","juni","juli","august","september","oktober","november","december"]),k=new Set(["denne","dette","den","det","de","en","et","ét","hele","hvert","hver","sidste","første","næste"]),S=new Set(["skal","kan","vil","mÃ¥","maa","bør","kunne","skulle","ville","burde","har","havde","er","var","bliver","blev","fÃ¥r","fik","gør","gjorde","kommer","kom","ser","sÃ¥","saa","tager","tog","siger","sagde","ved","vidste","hedder","hed","ønsker","ønskede","behøver","sender","sendte","ringer","ringede","skriver","skrev","læser","læste","spørger","spurgte","svarer","svarede","betaler","betalte","mangler","finder","fandt","bruger","brugte","kender","kendte","mødes","mødtes","ses","arbejder","bor","boede","husker","glemmer","vælger","valgte","holder","holdt","giver","gav","tror","hÃ¥ber","hjælpe","sende","ringe","komme","se","give","finde","fortælle","kontakte","oplyse","bekræfte","svare","vente","betale","deltage","huske","glemme","Ã¥bne","lukke","læse","skrive","gøre","tage","fÃ¥","faa","være","blive","holde","bruge","vælge","undersøge","vurdere","behandle","godkende","afvise","sørge","modtager","behandler","godkender","afviser","kontakter","bekræfter","oplyser","undersøger","vurderer","forstÃ¥r","hører","mener","accepterer","ignorerer","lovede","nævnte","besluttede","nægtede","tildelte","anmodede","modtog","afgjorde","indsendte","overførte","indgik","til","om","med","fra","uden","ikke","alle","begge","selv","ogsÃ¥","nu","jo","bare","her","der","dog","vel","altsÃ¥","gerne","godt","snart","stadig","allerede","sammen","som","to","tre","fire","fem","seks"]),x=new Set(["er","var","bliver","blev","kan","kunne","skal","skulle","vil","ville","mÃ¥","maa","bør","burde","har","havde","fÃ¥r","fik","gør","gjorde","kommer","kom","gÃ¥r","gik","siger","sagde","tror","troede","hÃ¥ber","hÃ¥bede","ved","vidste","mener","mente","synes","syntes","ønsker","ønskede","gider","tør","behøver","plejer","sender","henter","venter","møder","besøger","hjælper","køber","leverer","afleverer","tilbyder","anbefaler","hvornÃ¥r","hvordan","hvorfor","hvad","hvem","som","at","hvis","nÃ¥r","naar","da","mens","fordi","inden","før","foer","efter","om"]),T=new Set(["kapitel","del","type","gruppe","klasse","model","bind","akt","fase","grad","niveau","afsnit","sektion","trin"]),L=/(?:^|[^\p{L}])(?:version|punkt|afsnit|kapitel|stk\.?|pkt\.?|ios|android|gpt-?\d*|v)\s*$/iu,E=/(?:^|[^\p{L}])(?:vejer|vejede|koster|kostede|mÃ¥ler|mÃ¥lte|sparer|betaler|pÃ¥|omkring|cirka|ca\.?)\s*$/iu,C=/(?:^|[^\p{L}])(?:frist|møde|dato|deadline|aflever|senest|inden|den|d\.|periode|kvartal|uge)[\p{L}]*[^\p{L}\n]+(?:[\p{L}'â\-]+[^\p{L}\n]+){0,2}$/iu,_=/^\s?(?:(?:kilo|kg|gram|g|kroner|kr\.?|procent|meter|m|liter|l|km|cm|mm|ml|dl|point|kalorier|Ã¥r|aar|mÃ¥ned|mÃ¥neder|maaned|maaneder|uge|uger|time|timer|minut|minutter|sekund|sekunder)(?=$|[^\p{L}\p{N}_])|%)/iu;function A(e,t,n){const r=n&&n.idRe,o=n&&n.dateRe;return e=(e=e.replace(/(^|[^\d.-])(\d+)\.(\d)(?!\d)(?!\.\d)/g,(e,n,i,a,l,s)=>{const c=s.slice(0,l+n.length);if(r&&r.test(c))return e;if(t.test(s.slice(l+e.length)))return n+i+","+a;const d=parseInt(i,10);return o&&d>=1&&d<=31&&"0"!==a&&o.test(c)?e:n+i+","+a})).replace(/(^|[^\d.-])(\d+)\.(\d{2})(?!\d)(?!\.\d)/g,(e,n,o,i,a,l)=>{if(r&&r.test(l.slice(0,a+n.length)))return e;if(t.test(l.slice(a+e.length)))return n+o+","+i;const s=parseInt(o,10),c=parseInt(i,10);return s<=23&&c<=59||c>=1&&c<=12&&(s<=31||/^(?:1[89]|2[01])\d{2}$/.test(o))?e:n+o+","+i})}const q=/(?:^|[^\p{L}])(?:version|punkt|abschnitt|kapitel|paragraph|absatz|ziffer|artikel|ios|android|gpt-?\d*|v)\.?\s*$/iu,M=/(?:^|[^\p{L}])(?:versjon|punkt|kapittel|avsnitt|paragraf|artikkel|ios|android|gpt-?\d*|v)\.?\s*$/iu,I=/(?:^|[^\p{L}])(?:version|punkt|kapitel|avsnitt|paragraf|artikel|ios|android|gpt-?\d*|v)\.?\s*$/iu,B=/(?:^|[^\p{L}])(?:version|article|section|point|chapitre|ios|android|gpt-?\d*|v)\.?\s*$/iu,H=/(?:^|[^\p{L}
1])(?:versión|version|artÃculo|punto|apartado|capÃtulo|sección|ios|android|gpt-?\d*|v)\.?\s*$/iu,K=/(?:^|[^\p{L}])(?:am|bis|der|den|zum|ab|frist|termin|datum|liefer\p{L}*)\s*$/iu,D=/(?:^|[^\p{L}])(?:den|frist(?:en)?|møte(?:t)?|dato(?:en)?|innen|senest)\s*$/iu,P=/(?:^|[^\p{L}])(?:den|frist(?:en)?|möte(?:t)?|datum(?:et)?|innan|senast)\s*$/iu,N=/^\s?(?:(?:kilo|kg|gram|g|kroner|kr\.?|prosent|meter|m|liter|l|km|cm|mm|ml|dl|Ã¥r|aar|mÃ¥ned|mÃ¥neder|uke|uker|time|timer|minutt|minutter|sekund|sekunder|poeng)(?=$|[^\p{L}\p{N}_])|%)/iu,j=/(\d\.?\s+)(Januar|Februar|Mars|April|Mai|Juni|Juli|August|September|Oktober|November|Desember)\b(?!\s+[A-ZÃÃÃ
])/g,R=/(\b(?:[Ii]|[Tt]il|[Ff]ra)\s+)(Januar|Februar|Juli|September|Oktober|November|Desember)\b(?!\s+[A-ZÃÃÃ
])/g;const F=/^\s?(?:(?:kilo|kg|gram|g|kronor|kr\.?|procent|meter|m|liter|l|km|cm|mm|ml|dl|Ã¥r|aar|mÃ¥nad|mÃ¥nader|vecka|veckor|timme|timmar|minut|minuter|sekund|sekunder|poäng)(?=$|[^\p{L}\p{N}_])|%)/iu;const O=/^\s?(?:(?:kilo|kg|gramm|g|euro|prozent|meter|m|liter|l|km|cm|mm|ml|dl|punkte?|kalorien|jahre?|monate?|wochen?|stunden?|minuten?|sekunden?)(?=$|[^\p{L}\p{N}_])|%)/iu;const U=/^\s?(?:(?:kilos?|kg|grammes?|g|euros?|centimes?|mètres?|m|litres?|l|km|cm|mm|ml|dl|points?|calories|ans?|mois|semaines?|heures?|minutes?|secondes?)(?=$|[^\p{L}\p{N}_'â])|%)/iu,$=/(?:remise|réduction|rabais|taux|augmentation|baisse|hausse|tva|intérêts?|croissance|inflation|bénéfice|chômage|commission|marge|rendement|probabilité|réussite|score)[^\p{L}\n]+(?:[\p{L}'â\-]+[^\p{L}\n]+){0,3}$/iu;const z=/^\s?(?:(?:kilos?|kg|gramos?|g|euros?|céntimos?|metros?|m|litros?|l|km|cm|mm|ml|dl|puntos?|calorÃas|años?|meses|semanas?|horas?|minutos?|segundos?)(?=$|[^\p{L}\p{N}_])|%)/iu,G=/(?:descuento|rebaja|interés|intereses|iva|aumento|subida|bajada|tasa|crecimiento|inflación|margen|ganancia|beneficio|rentabilidad|comisión|desempleo)[^\p{L}\n]+(?:[\p{L}'â\-]+[^\p{L}\n]+){0,3}$/iu,V=/(?:artÃculos|puntos|apartados|párrafos|ejercicios|apartamentos|números|capÃtulos|páginas|secciones|habitaciones)\s+$/iu;const W={da:function(e){let t=String(e||"");if(!t)return t;t=t.replace(/(\d\s?)[ºª](?=\s*[CFcf]\b)/g,"$1°"),t=t.replace(/(\d)\s?[ºª](?!\s*[CFcf]\b)\.?/g,"$1."),t=t.replace(/(^|[^\d.])(\d+)\.(\d)(?!\d)(?!\.\d)/g,(e,t,n,r,o,i)=>{if(L.test(i.slice(0,o+t.length)))return e;if(_.test(i.slice(o+e.length)))return t+n+","+r;const a=i.slice(0,o+t.length);if(E.test(a))return t+n+","+r;const l=parseInt(n,10);return(l>=1&&l<=31&&"0"!==r||/^(?:1[89]|2[01])\d{2}$/.test(n)&&"0"!==r)&&C.test(a)?e:t+n+","+r}),t=t.replace(/(^|[^\d.])(\d+)\.(\d{2})(?!\d)(?!\.\d)/g,(e,t,n,r,o,i)=>{if(L.test(i.slice(0,o+t.length)))return e;if(_.test(i.slice(o+e.length)))return t+n+","+r;const a=i.slice(0,o+t.length);if(E.test(a))return t+n+","+r;const l=parseInt(n,10),s=parseInt(r,10);if(l<=23&&s<=59)return e;return s>=1&&s<=12&&(l<=31||/^(?:1[89]|2[01])\d{2}$/.test(n))&&C.test(a)?e:t+n+","+r}),t=t.replace(/(^|[^\p{L}\p{N}_])([Hh])undred(?![\p{L}\p{N}_])/gu,(e,t,n)=>t+n+"undrede");const n=(e,t,n)=>{const r=e.toLocaleLowerCase("da-DK");if(/^\d/.test(e))return/^(?:1[89]|2[01])\d{2}$/.test(e);const o=t.match(/([\p{L}\d'â\-]+)[^\p{L}\d]*$/u);if(o&&T.has(o[1].toLocaleLowerCase("da-DK")))return!1;if(b.has(r))return!0;if(o&&x.has(o[1].toLocaleLowerCase("da-DK")))return!1;if(n&&o&&/r$/.test(o[1])){const e=t.slice(0,t.lastIndexOf(o[1]));if(/(?:^|[.!?â¦]\s*)$/.test(e))return!1}return!!k.has(r)||!S.has(r)};return t=t.replace(/([^.!?â¦\n][^\S\n])I(?=[^\S\n]+([\p{L}\d][\p{L}\d'â\-]*))/gu,(e,t,r,o,i)=>n(r,i.slice(0,o+t.length),!0)?t+"i":e),t=t.replace(/(\b(?:[Kk]l|[Cc]a|[Nn]r|[Dd])\.[^\S\n])I(?=[^\S\n]+([\p{L}\d][\p{L}\d'â\-]*))/gu,(e,t,r,o,i)=>n(r,i.slice(0,o+t.length),!1)?t+"i":e),t=t.replace(/(\d\.?\s+)(Januar|Februar|Marts|April|Maj|Juni|Juli|August|September|Oktober|November|December)\b(?!\s+[A-ZÃÃÃ
])/g,(e,t,n)=>t+n.toLocaleLowerCase("da-DK")),t=t.replace(/(\b(?:[Ii]|[Tt]il|[Ff]ra|[Ii]nden|[Ss]iden|[Pp]rimo|[Mm]edio|[Uu]ltimo)\s+)(Januar|Februar|Marts|Juli|September|Oktober|November|December)\b/g,(e,t,n)=>t+n.toLocaleLowerCase("da-DK")),t=t.replace(/(\bi\s+)(April|Maj|Juni|August)\b/g,(e,t,n)=>t+n.toLocaleLowerCase("da-DK")),t=t.replace(/(^|[.!?â¦]\s+)(I[^\S\n]+)(April|Maj|Juni|August)\b/g,(e,t,n,r)=>t+n+r.toLocaleLowerCase("da-DK")),t=t.replace(/(\b[Kk]l\.\s+)(Halv|Kvart)\b/g,(e,t,n)=>t+n.toLocaleLowerCase("da-DK")),t=t.replace(/(\d+\.\s+)(Sal|Etage|Klasse|Plads|Række|Afdeling)\b/g,(e,t,n)=>t+n.toLocaleLowerCase("da-DK")),t},no:function(e){let t=String(e||"");return t?(t=t.replace(/(\d)\s?[ºª](?!\s*[CFcf]\b)\.?/g,"$1."),t=A(t,N,{idRe:M,dateRe:D}),t=t.replace(j,(e,t,n)=>t+n.toLocaleLowerCase("nb-NO")),t=t.replace(R,(e,t,n)=>t+n.toLocaleLowerCase("nb-NO")),t):t},sv:function(e){let t=String(e||"");return t?A(t,F,{idRe:I,dateRe:P}):t},de:function(e){let t=String(e||"");return t?A(t,O,{idRe:q,dateRe:K}):t},fr:function(e){let t=String(e||"");return t?(t=A(t,U,{idRe:B}),t=t.replace(/(\d+(?:,\d+)?)\s+pour 100\b/g,(e,n,r)=>$.test(t.slice(0,r))?n+" pour cent":e),t):t},es:function(e){let t=String(e||"");return t?(t=t.replace(/(\d+)\s+coma\s+(\d+)/gi,(e,t,n,r,o)=>V.test(o.slice(0,r))||/^\s+y\s+\d/.test(o.slice(r+e.length))?e:t+","+n),t=A(t,z,{idRe:H}),t=t.replace(/(\d+(?:,\d+)?)\s+por 100\b/g,(e,n,r)=>G.test(t.slice(0,r))?n+" por ciento":e),t):t}};function J(e,t){const n=W[t];return n?n(e):String(e||"")}function Z(e){const t=e.suppressToast||!1;let n=e.lang;const r=e.service||"chat",o=e.tokenEndpoint||"undefined"!=typeof window&&window.__SS_STT_TOKEN_ENDPOINT||"/api/stt-token.php",i=e.onTranscript,a=e.onPartial||null,l=e.onAudioActivity||null,s=e.onError||null,c=e.onStateChange||null,d=e.button||null;function u(e,n){t||function(e,t=4e3){v||(v=document.createElement("div"),v.className="ss-stt-toast",v.setAttribute("role","alert"),v.setAttribute("aria-live","assertive"),document.body.appendChild(v)),v.textContent=e,v.classList.add("ss-stt-toast--visible"),clearTimeout(y),y=setTimeout(()=>{v.classList.remove("ss-stt-toast--visible")},t)}(e),s&&s(e,n||"unknown")}const p=e.idleAriaLabel||d&&d.getAttribute("aria-label")||"",m=e.ariaLabels||{};let f="idle",g=null,h=null,b=null,k=null,S=null,x=null,T=0,L=null,E=0,C=!1,_="",A=0;const q=l?function(e,t={}){const n=Number(t.minRms)>
10?Number(t.minRms):.012,r=Number(t.noiseMultiplier)>1?Number(t.noiseMultiplier):3,o=Number(t.hangoverMs)>=0?Number(t.hangoverMs):300,i=Number(t.emitIntervalMs)>0?Number(t.emitIntervalMs):100;let a=.003,l=0,s=0,c=!1;return{process:function(t,d=Date.now()){if(!t||!t.length)return!1;let u=0;for(let e=0;e<t.length;e++){const n=t[e]/32768;u+=n*n}const p=Math.sqrt(u/t.length),m=Math.max(n,Math.min(.08,a*r)),f=p>=m;f?l=d+o:a=Math.min(.025,.98*a+.02*p);const g=f||d<l;return"function"==typeof e&&(g&&(!c||d-s>=i)?(s=d,e(!0,{rms:p,threshold:m})):!g&&c&&e(!1,{rms:p,threshold:m})),c=g,g},reset:function(){a=.003,l=0,s=0,c=!1}}}(l):null;function M(e){if(!d)return;d.classList.add("ss-mic"),d.classList.remove("ss-mic--connecting","ss-mic--listening","ss-mic--recording","ss-mic--error","ss-mic--processing","ss-mic--done"),"connecting"===e?d.classList.add("ss-mic--connecting"):"listening"===e?d.classList.add("ss-mic--listening"):"error"===e&&d.classList.add("ss-mic--error");const t="listening"===e||"connecting"===e;d.setAttribute("aria-busy","connecting"===e?"true":"false"),d.setAttribute("aria-pressed",t?"true":"false");const n="connecting"===e?m.connecting||"Forbinder...":"listening"===e?m.listening||"Lytter...":"error"===e&&m.error||p;n&&d.setAttribute("aria-label",n)}function I(){clearTimeout(x),"listening"===f&&(x=setTimeout(()=>{"listening"===f&&(u("Ingen tale registreret â prøv igen","silence"),O())},3e4))}function B(e){f!==e&&(f=e,M(e),"listening"===e&&I(),"idle"!==e&&"error"!==e||clearTimeout(x),c&&c(e))}function H(){if(L&&(clearTimeout(L),L=null),h){try{h.disconnect()}catch{}h=null}if(b){try{b.disconnect()}catch{}b=null}if(k&&(k.getTracks().forEach(e=>e.stop()),k=null),g&&"closed"!==g.state)try{g.close()}catch{}if(g=null,S){try{S.readyState<=1&&S.close()}catch{}S=null}}function K(e){return!C&&e===E}function D(e){if(K(e)&&"connecting"===f){if(T<3){T++;return void(L=setTimeout(()=>{L=null,K(e)&&"connecting"===f&&R(e)},1e3*T))}T=0,u("Forbindelse til taletjeneste fejlede â prøv igen","service"),B("error"),setTimeout(()=>{K(e)&&B("idle")},1500)}}function P(e){if("undefined"!=typeof AbortSignal&&"function"==typeof AbortSignal.timeout)return{signal:AbortSignal.timeout(e),cleanup:null};if("undefined"!=typeof AbortController){const t=new AbortController,n=setTimeout(()=>t.abort(),e);return{signal:t.signal,cleanup:()=>clearTimeout(n)}}return{signal:null,cleanup:null}}async function N(){const e=/\/SkrivSikkertSTT-token(?:[/?#]|$)/.test(String(o))?null:void 0===n?function(){try{if("undefined"!=typeof window&&window.ChatI18n&&"function"==typeof window.ChatI18n.getLang){const e=w(window.ChatI18n.getLang());if(e)return e}}catch(e){}try{const e=w(localStorage.getItem("sb_ui_lang"));if(e)return e}catch(e){}try{const e=localStorage.getItem("ss_chat_lang");if(e){const t=JSON.parse(e),n=w(t&&t.code);if(n)return n}}catch(e){}try{if("undefined"!=typeof document){const e=w(document.documentElement.lang);if(e)return e}}catch(e){}return"da"}():n,t=w(e),i=e?"&lang="+encodeURIComponent(e):"",a="undefined"!=typeof location&&location.pathname?"&sp="+encodeURIComponent(location.pathname):"",l=String(o).includes("?")?"&":"?",s="service="+encodeURIComponent(r)+i+a,c=String(o)+l+s,d={};let u=!0;try{u=new URL(c,location.href).origin===location.origin}catch(e){}if(u)try{const e="undefined"!=typeof window?window._supabase:null;if(e&&e.auth&&"function"==typeof e.auth.getSession){const t=await Promise.race([e.auth.getSession(),new Promise(e=>setTimeout(()=>e(null),800))]),n=t&&t.data&&t.data.session&&t.data.session.access_token;n&&(d.headers={Authorization:"Bearer "+n})}}catch(e){}const p=P(8e3);let m;p.signal&&(d.signal=p.signal);try{m=await fetch(c,d)}finally{p.cleanup&&p.cleanup()}if(!m.ok&&d.headers&&(401===m.status||403===m.status)){const e=P(8e3),t={};e.signal&&(t.signal=e.signal);try{m=await fetch(c,t)}finally{e.cleanup&&e.cleanup()}}if(!m.ok){const e=new Error("Token fetch failed: "+m.status);throw e.sttPermanent=m.status>=400&&m.status<500,e}const f=await m.json();if(!f||"string"!=typeof f.url||""===f.url.trim()){const e=new Error("Token response invalid");throw e.sttPermanent=!0,e}return{url:f.url.trim(),lang:t}}async function j(e){const t=window.AudioContext||window.webkitAudioContext;try{g=new t({sampleRate:16e3})}catch{g=new t}"suspended"===g.state&&await g.resume();try{b=g.createMediaStreamSource(k)}catch(e){if(!e||"NotSupportedError"!==e.name)throw e;try{g.close()}catch{}g=new t,"suspended"===g.state&&await g.resume(),b=g.createMediaStreamSource(k)}const n=function(e,t){if(!e||!t||e===t)return null;const n=e/t;let r=0,o=null;return function(e){const t=null===o?0:1,i=e.length+t;if(i<2)return e.length&&(o=e[e.length-1]),new Int16Array(0);const a=n=>t&&0===n?o:e[n-t],l=i-1,s=r>l?0:Math.floor((l-r)/n)+1,c=new Int16Array(s);for(let e=0;e<s;e++){const t=Math.floor(r),o=r-t,i=a(t),s=t<l?a(t+1):i;c[e]=Math.round(i+(s-i)*o),r+=n}return r-=l,o=a(l),c}}(g.sampleRate,16e3);let r=[],o=0;const i=t=>{if(!t||0===t.length)return;if(r.push(t),o+=t.length,o<1024)return;const n=new Int16Array(o);let i=0;for(const e of r)n.set(e,i),i+=e.length;r=[],o=0,e.readyState===WebSocket.OPEN&&e.send(n.buffer)};if("function"==typeof g.audioWorklet?.addModule)await g.audioWorklet.addModule("/shared/js/pcm-worklet.js"),h=new AudioWorkletNode(g,"pcm-capture"),h.port.onmessage=t=>{if(e.readyState!==WebSocket.OPEN)return;if(!q&&!n)return void e.send(t.data);const r=new Int16Array(t.data);q&&q.process(r),n?i(n(r)):e.send(t.data)},b.connect(h),h.connect(g.destination);else{const t=g.createScriptProcessor(4096,1,1);t.onaudioprocess=t=>{if(e.readyState!==WebSocket.OPEN)return;const r=t.inputBuffer.getChannelData(0),o=new Int16Array(r.length);for(let e=0;e<r.length;e++){const t=Math.max(-1,Math.min(1,r[e]));o[e]=t<0?32768*t:32767*t}q&&q.process(o),n?i(n(o)):e.send(o.buffer)},b.connect(t),t.connect(g.destination),h=t}}async function R(e){B("connecting");try{if(k=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,sampleRate:16e3,echoCancellation:!0,noiseSuppression:!0}}),!K(e)||"connecting"!==f)return void H()}catch(t){if(H(),!K(e)||"connecting"!==f)return;return"NotAllowedError"===t.name||"SecurityError"===t.name?u("Giv mikrofontilladelse i din browser","permission"):"NotFoundError"===t.name?u("Ingen mikrofon fundet","no-device"):"NotReadableError"===t.name?u("Mikrofonen er optaget af et andet program","busy"):"OverconstrainedError"===t.name?u("Mikrofon understøtter ikke de krævede indstillinger","device"):u("Mikrofon kunne ikke startes","device"),B("error"),void setTimeout(()=>{K(e)&&B("idle")},1500)}let t;try{t=await N()}catch(t){if(H(),!K(e)||"connecting"!==f)return;return t&&t.sttPermanent?(T=0,u("Forbindelse til taletjeneste fejlede â prøv igen","service"),B("error"),void setTimeout(()=>{K(e)&&B("idle")},1500)):void D(e)}if(K(e)&&"connecting"===f)try{const n=await async function(e,t,n){return new Promise((r,o)=>{const l=new WebSocket(e);let s=!1;const c=setTimeout(()=>{d(new Error("WebSocket connect timeout"));try{l.close()}catch{}},8e3);function d(e){s||(s=!0,clearTimeout(c),o(e))}l.onopen=()=>{S=l},l.onmessage=e=>{try{const o=JSON.parse(e.data);switch(o.type){case"ready":if(!K(t)){try{l.close()}catch{}return void d(new Error("WebSocket cancelled"))}if(s)return;s=!0,clearTimeout(c),r(l);break;case"partial":o.text&&a&&(I(),a(J(o.text,n)));break;case"final":{if(!o.text)break;const e=J(o.text,n),t=Date.now();(e!==_||t-A>400)&&(_=e,A=t,I(),i&&i(e));break}case"error":u("Taletjeneste fejl â prøv igen","service"),s||d(new Error(o.message||"WebSocket error"))}}catch{}},l.onerror=()=>d(new Error("WebSocket error")),l.onclose=()=>{s?"listening"!==f||C||(H(),K(t)&&(B("connecting"),D(t))):d(new Error("WebSocket closed before ready"))}})}(t.url,e,t.lang);
1if(!K(e)||"connecting"!==f)return void H();if(await j(n),!K(e)||"connecting"!==f)return void H();T=0,B("listening")}catch{H(),K(e)&&"connecting"===f&&D(e)}else H()}async function F(){if("listening"!==f&&"connecting"!==f&&!C){if(E++,T=0,_="",q&&q.reset(),!navigator.mediaDevices||"function"!=typeof navigator.mediaDevices.getUserMedia){const e=E;return u("Din browser understøtter ikke diktering","unsupported"),B("error"),void setTimeout(()=>{K(e)&&B("idle")},1500)}await R(E)}}function O(){"idle"!==f&&(E++,B("idle"),H())}return{start:F,stop:O,toggle:function(){"listening"===f||"connecting"===f?O():F()},destroy:function(){C=!0,E++,H(),f="idle",M("idle")},isActive:function(){return"listening"===f||"connecting"===f},setLang:function(e){n=e}}}const Y="[SS STT webkit]",Q="da-DK",X="da";let ee=!1,te=null,ne=null;function re(){return"undefined"==typeof window?null:window.SpeechRecognition||window.webkitSpeechRecognition||null}const oe=new Set;function ie(e){oe.forEach(t=>{if(t!==e)try{t.isActive()&&t.stop()}catch(e){}})}function ae(e){if(!e.onPartial||e.onAudioActivity)return Z(e);let t="";return Z({...e,onPartial(n){t=n||"",e.onPartial(n)},onTranscript(n){t="",e.onTranscript&&e.onTranscript(n)},onError(n,r){t="",e.onError&&e.onError(n,r)},onStateChange(n){const r="idle"===n?t:"";"idle"!==n&&"error"!==n&&"connecting"!==n||(t=""),r&&e.onTranscript&&e.onTranscript(r),e.onStateChange&&e.onStateChange(n)}})}function le(e){const t=e.onAudioActivity||ee||function(){try{return"undefined"!=typeof navigator&&/Android/i.test(navigator.userAgent||"")}catch(e){return!1}}()||!re()?ae(e):function(e){const t=e.suppressToast||!1,n=e.onTranscript,r=e.onPartial||null,o=e.onError||null,i=e.onStateChange||null,a=e.button||null,l=e.idleAriaLabel||a&&a.getAttribute("aria-label")||"",s=e.ariaLabels||{};let c=e.lang,d=null,u="idle",p=!1,m=null,f=!1,g=!1,h=0,v=0,y=0,w=null,b=null,k=!1,S=null;function x(e,n){t||function(e,t=4e3){te||(te=document.createElement("div"),te.className="ss-stt-toast",te.setAttribute("role","alert"),te.setAttribute("aria-live","assertive"),document.body.appendChild(te)),te.textContent=e,te.classList.add("ss-stt-toast--visible"),clearTimeout(ne),ne=setTimeout(()=>{te.classList.remove("ss-stt-toast--visible")},t)}(e),o&&o(e,n||"unknown")}function T(e){if(!a)return;a.classList.add("ss-mic"),a.classList.remove("ss-mic--connecting","ss-mic--listening","ss-mic--recording","ss-mic--error","ss-mic--processing","ss-mic--done"),"connecting"===e?a.classList.add("ss-mic--connecting"):"listening"===e?a.classList.add("ss-mic--listening"):"error"===e&&a.classList.add("ss-mic--error");const t="listening"===e||"connecting"===e;a.setAttribute("aria-busy","connecting"===e?"true":"false"),a.setAttribute("aria-pressed",t?"true":"false");const n="connecting"===e?s.connecting||"Forbinder...":"listening"===e?s.listening||"Lytter...":"error"===e&&s.error||l;n&&a.setAttribute("aria-label",n)}function L(){clearTimeout(w),"listening"===u&&(w=setTimeout(()=>{"listening"===u&&(x("Ingen tale registreret â prøv igen","silence"),K())},3e4))}function E(e){u!==e&&(u=e,T(e),"listening"===e&&L(),"idle"!==e&&"error"!==e||clearTimeout(w),i&&i(e))}function C(e,t){return!p&&!d&&m===e&&t===y}function _(){clearTimeout(w),clearTimeout(b),clearTimeout(S),S=null,k=!1;const e=m;if(m=null,y++,e)try{"function"==typeof e.abort?e.abort():e.stop()}catch(e){console.warn(Y,"abort failed:",e)}}function A(e,t){f=!1,g=!1,_(),x(e,t),E("error");const n=y;b=setTimeout(()=>{p||d||n!==y||"error"!==u||E("idle")},1500)}function q(){if(p||d)return;const t=f||"connecting"===u||"listening"===u;if(ee=!0,console.warn(Y,"Web Speech failed â falling back to WebSocket STT"),f=!1,g=!1,_(),r)try{r("")}catch(e){}d=ae({...e,lang:c}),t&&d.start()}function M(e,t){const o=new e;o.continuous=!0,o.interimResults=!0,o.maxAlternatives=1,o.lang=Q,o.onstart=()=>{C(o,t)&&f&&E("listening")};let i=0;return o.onresult=e=>{if(!C(o,t)||!f&&!k)return;let a="";for(let t=Math.max(e.resultIndex,i);t<e.results.length;t+=1){const r=e.results[t],o=String(r?.[0]?.transcript||"").trim();if(r.isFinal){if(i=t+1,!o)continue;L(),n&&n(J(o,X))}else o&&(a+=`${a?" ":""}${o}`)}a&&(L(),r&&r(J(a,X)))},o.onerror=e=>{if(!C(o,t))return;const n=String(e?.error||"unknown");console.warn(Y,"recognition error:",n),k?H():"no-speech"!==n&&"aborted"!==n&&("not-allowed"!==n&&"service-not-allowed"!==n?"audio-capture"!==n?q():A("Ingen mikrofon fundet","no-device"):A("Giv mikrofontilladelse i din browser","permission"))},o.onend=()=>
1{if(C(o,t))if(k)H();else{if(g&&f){const e=Date.now()-h;return v=e<1e3?v+1:0,v>=3?(console.warn(Y,"recognition ended repeatedly"),void q()):(m=null,void I(y))}m=null,"idle"!==u&&"error"!==u&&E("idle")}},o}function I(e){const t=re();if(!t)return void q();let n;try{n=M(t,e)}catch(e){return console.warn(Y,"could not create recognition:",e),void q()}m=n,h=Date.now();try{n.start()}catch(e){console.warn(Y,"could not start recognition:",e),e&&"NotAllowedError"===e.name?A("Giv mikrofontilladelse i din browser","permission"):q()}}function B(){p||k||"listening"===u||"connecting"===u||(clearTimeout(b),y++,f=!0,g=!0,v=0,E("connecting"),I(y))}function H(){clearTimeout(S),S=null,k=!1,clearTimeout(w),m=null,y++,E("idle")}function K(){if("idle"===u||k)return;f=!1,g=!1,clearTimeout(w);const e=m;if(e){k=!0;try{e.stop()}catch(e){return console.warn(Y,"stop failed:",e),k=!1,_(),void E("idle")}S=setTimeout(()=>{k&&H()},2e3)}else E("idle")}return{start(){if(d)return d.start();B()},stop(){if(d)return d.stop();K()},toggle(){if(d)return d.toggle();"listening"===u||"connecting"===u?K():B()},destroy(){d?d.destroy():(p=!0,f=!1,g=!1,_(),u="idle",T("idle"))},isActive:()=>d?d.isActive():"listening"===u||"connecting"===u,setLang(e){c=e,d&&d.setLang(e)}}}(e);let n=!1;const r={start(){if(!n&&!t.isActive())return ie(r),t.start()},stop(){if(!n)return t.stop()},toggle(){if(!n)return t.isActive()||ie(r),t.toggle()},destroy(){if(!n)return n=!0,oe.delete(r),t.destroy()},isActive:()=>!n&&t.isActive(),setLang(e){if(!n)return t.setLang(e)}};return oe.add(r),r}function se(){let e=null;function t(){const t=e;if(e=null,t){if("quill"===t.kind){try{t.quill.deleteText(t.index,t.length,"silent"),"function"==typeof t.quill.setSelection&&t.quill.setSelection(t.index,0,"silent")}catch(e){}return t.index}if(t.el){t.el.value=t.prefix+t.suffix;try{t.el.setSelectionRange(t.start,t.start)}catch(e){}}}}return{renderInQuill:function(n,r,o){const i=String(o||"").trim();if(i&&n){!e||"quill"===e.kind&&e.quill===n||t();try{if(e){const t=e,r=t.lead+i;n.deleteText(t.index,t.length,"silent"),n.insertText(t.index,r,"silent"),"function"==typeof n.setSelection&&n.setSelection(t.index+r.length,0,"silent"),t.length=r.length}else{const t="function"==typeof r?r():r,o=t>0&&"function"==typeof n.getText?n.getText(t-1,1):"",a=o&&!/\s/.test(o)?" ":"",l=a+i;n.insertText(t,l,"silent"),"function"==typeof n.setSelection&&n.setSelection(t+l.length,0,"silent"),e={kind:"quill",quill:n,index:t,length:l.length,lead:a}}}catch(t){e=null}}else t()},renderInField:function(n,r){const o=String(r||"").trim();if(!o||!n)return void t();if(!e||"field"===e.kind&&e.el===n||t(),!e){const t=String(n.value||""),r="number"==typeof n.selectionStart?n.selectionStart:t.length,i="number"==typeof n.selectionEnd?n.selectionEnd:r;e={kind:"field",el:n,prefix:t.slice(0,r),suffix:t.slice(i),start:r,needsSpace:!(!(r>0)||/\s$/.test(t.slice(0,r))||/^\s/.test(o))}}const i=e,a=i.needsSpace?" ":"",l=i.prefix+a+o+i.suffix,s=i.start+a.length+o.length;i.el.value=l;try{i.el.setSelectionRange(s,s)}catch(e){}},remove:t,isShowing:()=>!!e}}const ce={da:{"empty.title":"Skriv noget tekst først","empty.body":"Skriv eller indsæt tekst i editoren, sÃ¥ kan jeg hjælpe dig.","empty.ret_grammatik":"Ret grammatik","toolbar.ret_grammatik":"Ret grammatik","tab.korrektur":"Korrektur","toolbar.back_texts":"Tekster","ai.card.header":"Spørg AI","nav.overview":"Overblik","nav.newText":"Ny tekst","nav.improve":"Forbedre","nav.translate":"Oversæt","nav.chat":"Chat","nav.readAloud":"Oplæsning","nav.notes":"Noter","nav.jobSearch":"Jobsøgning","nav.more":"Mere","dropdown.guides":"Guides","dropdown.membership":"Medlemskab","dropdown.contact":"Kontakt","dropdown.darkMode":"Mørk tilstand","dropdown.lightMode":"Lys tilstand","dropdown.langSwitch":"English","dropdown.logout":"Log ud","nav.mobileNavigation":"Mobilnavigation","nav.moreOptions":"Flere indstillinger","controls.stt":"Tale-til-tekst","controls.paste":"Indsæt","controls.upload":"Upload dokumenter","controls.deleteAll":"Slet alt","format.undo":"Fortryd","format.redo":"Gentag","format.bold":"Fed","format.italic":"Kursiv","format.list":"Liste","format.readAloud":"Læs højt","tts.readAloud":"Læs højt","tts.stopReading":"Stop oplæsning","tts.cancelReading":"Annuller oplæsning","format.copyText":"Kopier tekst","format.download":"Download","format.compare":"Sammenlign før/efter","format.newText":"Ny tekst","format.originalText":"Oprindelig tekst","counter.chars":"tegn","sidebar.seeCorrections":"Se rettelser","sidebar.tone":"Tone","sidebar.improveText":"Forbedre teksten","sidebar.corrected":"Rettet","sidebar.comma":"Komma","sidebar.deleted":"Slettet","sidebar.ready":"Jeg er klar!","sidebar.working":"Arbejder...","sidebar.textCorrect":"Teksten er korrekt!","sidebar.errors":"Fejl","wm.kladde_ready":"Din kladde er klar","sidebar.refiningText":"Jeg finpudser teksten â uden at ændre budskabet.","improve.investigating":"Jeg undersøger","improve.tone":"Tone","improve.structure":"Struktur","improve.clarity":"Klarhed","style.moreParagraphs":"Flere afsnit","style.moreParagraphsDesc":"Din tekst bliver nemmere at overskue med afsnit og overskrifter.","style.bulletPoints":"Punktopstilling","style.bulletPointsDesc":"Din tekst bliver lavet om til en overskuelig liste.","style.shorterText":"Kortere tekst","style.shorterTextDesc":"Din tekst bliver forkortet men bevarer meningen.","style.longerText":"Længere tekst","style.longerTextDesc":"Din tekst bliver uddybet med flere detaljer.","style.responseCounter":"Tekst {current} ud af {total}","voice.professional":"Professionel","voice.informal":"Uformel","voice.formalAuthoritative":"Formel og autoritativ","voice.customPlaceholder":"Bestem selv...","voice.simplify":"Uformel","voice.simplifyDesc":"Afslappet og venlig","voice.elaborate":"Personlig","voice.elaborateDesc":"Varm og personlig","voice.convencing":"Neutral","voice.convencingDesc":"Klar og direkte","voice.concise":"Høflig","voice.conciseDesc":"Respektfuld og venlig","voice.professionalDesc":"Formel og autoritativ","tab.tone":"Tone","tab.better":"Bedre","tab.assistant":"Assistent","action.correctText":"Ret teksten","action.changeTone":"Ãndre tone
1n","action.examineText":"Undersøg teksten","action.makeMessageClear":"Gør budskabet klart","action.send":"Send","action.stop":"Stop","action.resume":"Genoptag","action.readAloud":"Læs op","action.copy":"Kopier","action.copyTitle":"Kopiér","action.edit":"Rediger","action.delete":"Slet","action.apply":"Anvend","action.applyChange":"Anvend ændringen","action.readAloudFull":"Læs hele teksten højt","action.continue":"Fortsæt","chat.whatToDo":"Hvad skal jeg gøre?","chat.chooseOrWrite":"Vælg et forslag eller skriv hvad du ønsker","chat.suggestions":"Forslag","chat.mine":"Mine","chat.help":"Hjælp","chat.humanize":"Humanisér","chat.aiCheck":"AI-tjek","chat.noShortcuts":"Du har ingen gemte genveje endnu.","chat.createShortcut":"Opret genvej","chat.askAssistant":"Spørg assistenten...","chat.dictate":"Dikter","chat.dictateAi":"Dikter til AI-assistent","chat.send":"Send","chat.newConversation":"Ny samtale","chat.error":"Beklager, der opstod en fejl. Prøv venligst igen.","chat.noResponse":"Ingen respons","chat.helpInstruction":"Forklar hvad du kan hjælpe med","chat.humanizeInstruction":"","chat.aiCheckInstruction":"","instruction.createShortcut":"Opret genvej","instruction.intro":"Lav en genvej til noget du ofte beder assistenten om. Næste gang skal du bare klikke på den.","instruction.nameLabel":"Hvad skal den hedde?","instruction.namePlaceholder":'F.eks. "Opsummer kort" eller "Gør formel"',"instruction.contentLabel":"Hvad skal assistenten gøre?","instruction.contentPlaceholder":'F.eks. "Skriv et kort resume på max 3 sætninger"',"instruction.hint":"Skriv som om du beder en kollega om hjælp.","instruction.ideas":"Idéer til genveje:","instruction.save":"Gem genvej","instruction.editShortcut":"Rediger genvej","instruction.saveChanges":"Gem ændringer","instruction.fillBothFields":"Udfyld begge felter","instruction.shortcutUpdated":"Genvej opdateret","instruction.shortcutSaved":"Genvej gemt","instruction.shortcutDeleted":"Genvej slettet","instruction.couldNotLoad":"Kunne ikke indlæse genveje","instruction.error":"Fejl","instruction.send":"Send","instruction.edit":"Rediger","instruction.delete":"Slet","instruction.noShortcutsYet":"Du har ingen gemte genveje endnu.","instruction.humanizeTitle":"Humanisér","instruction.humanizeContent":"","instruction.aiCheckTitle":"AI-tjek","instruction.aiCheckContent":"","instruction.expertReviewTitle":"Ekspertgennemgang","instruction.expertReviewContent":"","instruction.readerReactionTitle":"Læserreaktion","instruction.readerReactionContent":"","toast.saved":"Gemt","copy.copied":"Kopieret","copy.copy":"Kopier","grammar.light":"Let","grammar.standard":"Standard","grammar.max":"Maks","grammar.basicProofreading":"Grundlæggende korrekturlæsning","grammar.fullProofreading":"Fuld korrekturlæsning","grammar.dyslexia":"Anbefales til ordblinde","grammar.tooltipBasic":"Retter kun stavefejl og tegnsætning. Din tekst ændres mindst muligt.","grammar.tooltipStandard":"Retter stavefejl, grammatik og ordstilling. Anbefales til de fleste.","grammar.tooltipMax":"Forstår hvad du prøver at sige. Til dig der har brug for ekstra hjælp.","grammar.descBasic":"Retter kun stavefejl og tegnsætning.","grammar.descStandard":"Retter stavefejl, grammatik og ordstilling.","grammar.descMax":"Fuldender ufuldstændige sætninger.","grammar.helpLabel":"Læs mere om dette niveau","lang.danish":"Dansk","lang.english":"Engelsk","lang.german":"Tysk","lang.french":"Fransk","lang.spanish":"Spansk","lang.arabic":"Arabisk","lang.belarusian":"Hviderussisk","lang.bengali":"Bengalsk","lang.bosnian":"Bosnisk","lang.bulgarian":"Bulgarsk","lang.catalan":"Catalansk","lang.croatian":"Kroatisk","lang.czech":"Tjekkisk","lang.dutch":"Nederlandsk","lang.estonian":"Estisk","lang.finnish":"Finsk","lang.flemish":"Flamsk","lang.germanSwiss":"Tysk (Schweiz)","lang.greek":"Græsk","lang.hebrew":"Hebraisk","lang.hindi":"Hindi","lang.hungarian":"Ungarsk","lang.indonesian":"Indonesisk","lang.italian":"Italiensk","lang.japanese":"Japansk","lang.kannada":"Kannada","lang.korean":"Koreansk","lang.latvian":"Lettisk","lang.lithuanian":"Litauisk","lang.macedonian":"Makedonsk","lang.malay":"Malaysisk","lang.marathi":"Marathi","lang.norwegian":"Norsk","lang.persian":"Persisk","lang.polish":"Polsk","lang.portuguese":"Portugisisk","lang.romanian":"Rumænsk","lang.russian":"Russisk","lang.serbian":"Serbisk","lang.slovak":"Slovakisk","lang.slovenian":"Slovensk","lang.swedis
1h":"Svensk","lang.tagalog":"Tagalog","lang.tamil":"Tamil","lang.telugu":"Telugu","lang.turkish":"Tyrkisk","lang.ukrainian":"Ukrainsk","lang.urdu":"Urdu","lang.vietnamese":"Vietnamesisk","lang.writeLang":"Skriv sprog","wm.lang_label":"Sprog:","sidebarNav.logoutTokenError":"Kunne ikke finde log ud-token. Prøv igen.","sidebarNav.logoutError":"Log ud fejlede. Prøv igen senere.","membership.characters":"tegn","chatAction.copiedToClipboard":"Kopieret til udklipsholder","chatAction.couldNotCopy":"Kunne ikke kopiere","chatAction.applying":"Anvender ændringer...","chatAction.applyingShort":"Anvender...","chatAction.applyError":"Kunne ikke anvende ændringen","chatAction.undone":"Ãndring fortrudt","chatAction.changeApplied":"Ãndring anvendt","chatAction.noAIResponse":"Intet svar fra AI","chatAction.applied":"Anvendt","chatAction.undo":"Fortryd","loader.working":"Arbejder...","loader.rewriting":"Omskriver teksten...","loader.pleaseWait":"Vent venligst...","loader.cancel":"Annuller","loader.loading":"Indlæser...","loader.settingUp":"Ordner opsætningen...","loader.improvingText":"Forbedre teksten...","loader.correctingText":"Retter teksten...","loader.analyzingText":"Analyserer teksten...","analysis.defaultTextType":"Besked","analysis.defaultIssue":"Gør teksten mere præcis og forstÃ¥elig.","analysis.defaultButton":"Forbedre teksten","analysis.defaultCurrentStyle":"Uformel","analysis.defaultTargetStyle":"Professionel","undoRedo.undo":"Fortryd ændring","undoRedo.redo":"Gentag ændring","editor.placeholder":"Begynd at skriveâ¦","read.pause":"Pause","read.readAloud":"Læs op","read.loading":"Indlæser oplæsning","robot.ready":"Jeg er klar!","robot.refining":"Jeg finpudser teksten â uden at ændre budskabet.","robot.working":"Arbejder...","robot.textCorrect":"Teksten er korrekt!","robot.helpIntro":"Hej! Jeg er din skriveassistent. Indsæt en tekst, sÃ¥ hjælper jeg dig med at rette og forbedre den.","robot.howCanIHelp":"Hvordan kan jeg hjælpe?","robot.thinking":"Tænker...","robot.connecting":"Forbinder...","sidebarRobot.textChanged":"Teksten er ændret!","sidebarRobot.textChangedExplanation":'Jeg har opdateret teksten baseret pÃ¥ din instruktion: "{command}"',"sidebarRobot.changeText":"Ãndre tekst","sidebarRobot.editDescription":"Bed robotten om at omskrive eller rette den valgte tekst.","sidebarRobot.question":"SpørgsmÃ¥l","sidebarRobot.askDescription":"Stil et spørgsmÃ¥l eller bed om en forklaring til det valgte.","sidebarRobot.errorTryAgain":"Der opstod en fejl. Prøv venligst igen.","sidebarRobot.closeExplanation":"Luk forklaring","sidebarRobot.insertTextFirst":"Indsæt venligst noget tekst først.","stt.micError":"Fejl: Kan ikke finde mikrofonen.","stt.connectionFailed":"Forbindelse til talegenkendelse fejlede. Prøv igen senere.","tts.downloadDisabled":"Download er deaktiveret. Teksten overstiger {limit} tegn (aktuel: {current})","tts.downloadAudio":"Download lydfil","tts.noTextToConvert":"Ingen tekst at konvertere til tale","tts.textTooLong":"Teksten er for lang til download. Maksimum {limit} tegn tilladt (aktuel: {current})","tts.downloadFailed":"Download af lyd fejlede. Prøv igen.","tts.voiceMale":"Mads","tts.voiceFemale":"Sofia","download.noContent":"Intet indhold at eksportere.","download.pdfError":"Kunne ikke oprette PDF. Tjek konsollen for detaljer.","download.word":"Word","download.pdf":"PDF","download.textFile":"Tekstfil","download.audioFile":"Lydfil","crop.title":"Beskær billedet","crop.titleCounter":"Beskær billede {current} af {total}","crop.hint":"Træk i hjørnerne for at vælge det omrÃ¥de, der skal læses.","crop.cancel":"Annuller","crop.confirm":"Beskær","download.preparing":"Forbereder downloadâ¦","download.success":"Download klar!","download.error":"Download fejlede. Prøv igen.","style.changeError":"Kunne ikke ændre tekststil. Prøv igen.","style.improveError":"Kunne ikke forbedre teksten. Prøv igen.","file.ocrFailed":"OCR-udtræk fejlede","file.wordError":"Fejl ved behandling af Word-dokument","fileUpload.fileProcessingError":"Der opstod en fejl under behandling af filen.","fileUpload.uploadingText":"Uploader tekst...","fileUpload.stageDoc":"Læser dit dokument","fileUpload.stageImage":"Læser billedet","fileUpload.stageFiles":"Læser {n} filer","fileUpload.stageGather":"Samler det hele","fileUpload.uploadAria":"Upload dokument (PDF, billede eller Word)","fileUpload.internetError":"Der opstod en fejl. Tjek din internetforbindelse.","fileUpload.maxImagesError":"Du k
1an maksimalt uploade 5 billeder ad gangen.","fileUpload.maxDocumentsError":"Du kan kun uploade ét dokument ad gangen.","fileUpload.noTextExtracted":"Der blev ikke fundet noget tekst i filen.","fileUpload.pdfNativeFallback":"Aflæser PDF direkte...","fileUpload.pdfProcessingError":"Der opstod en fejl under behandling af PDF-filen.","fileUpload.formattingText":"Behandler tekst...","fileUpload.ocrFailed":"OCR-udtræk fejlede for denne side.","fileUpload.audioTooLarge":"Filen er for stor (maks 300 MB). Prøv at konvertere til MP3.","fileUpload.audioUnsupportedFormat":"Formatet understøttes ikke. Brug MP3, WAV, M4A, OGG eller FLAC.","fileUpload.audioDurationError":"Kunne ikke læse lydfilens længde. Prøv MP3 eller WAV.","fileUpload.audioTooLong":"Lydfilen er over 3 timer. Upload venligst en kortere fil.","fileUpload.audioTranscriptionFailed":"Transskriberingen fejlede. Prøv igen eller upload en anden fil.","fileUpload.audioMultiple":"Upload venligst én lydfil ad gangen.","fileUpload.audioTranscribing":"Transskriberer din lydfilâ¦","fileUpload.audioCleaningUp":"Rydder op i transskriptionâ¦","clipboard.ocrExtracting":"Læser tekst fra billedeâ¦","clipboard.ocrFailed":"Billedet kunne ikke omdannes til tekst.","explanation.processingError":"Der opstod en fejl ved behandling af forklaringer.","action.pause":"Pause","file.pdfPageLimit":"Du har uploadet over {limit} sider. Robotten læser kun de første {limit}.","file.pdfError":"Der opstod en fejl under behandling af PDF-filen.","file.processingError":"Der opstod en fejl under behandling af filen.","file.maxImages":"Du kan maksimalt uploade {limit} billeder ad gangen.","chatAI.helpIntro":"Jeg kan hjælpe dig med:","chatAI.helpRewrite":"Omskrive og forbedre dine noter","chatAI.helpSummarize":"Opsummere lange tekster","chatAI.helpFormality":"Gøre teksten mere formel eller uformel","chatAI.helpGrammar":"Rette grammatik og stavefejl","chatAI.helpBullets":"Strukturere indhold i punktform","chatAI.helpOutro":"Skriv eller dikter din note, og vælg derefter hvad jeg skal gøre med den.","chatAI.expansion":"Uddybning:","chatAI.expandedSimulated":"Her er en mere detaljeret version af din note med ekstra kontekst og forklaringer.","chatAI.simulatedResponse":"Dette er en simuleret AI-respons der viser hvordan funktionen vil virke nÃ¥r den er forbundet til en AI-model.","chatAI.writeNoteExpand":"Skriv først en note, sÃ¥ kan jeg uddybe den for dig.","chatAI.shortened":"Forkortet version:","chatAI.writeNoteShorten":"Skriv først en note, sÃ¥ kan jeg forkorte den for dig.","chatAI.writeNoteBullets":"Skriv først en note, sÃ¥ kan jeg omskrive den i punktform.","chatAI.noSpellingErrors":"Ingen stavefejl fundet (simuleret)","chatAI.writeNoteSpell":"Skriv først en note, sÃ¥ kan jeg rette stavefejl.","chatAI.result":"Resultat:","chatAI.simulatedFor":'(Simuleret AI-respons for: "',"chatAI.writeNoteHelp":'Skriv først en note, sÃ¥ kan jeg hjælpe dig med: "'},en:{"empty.title":"Write some text first","empty.body":"Write or paste text in the editor and I can help you.","empty.ret_grammatik":"Fix grammar","toolbar.ret_grammatik":"Fix grammar","tab.korrektur":"Corrections","toolbar.back_texts":"Texts","ai.card.header":"Ask AI","nav.overview":"Overview","nav.newText":"New text","nav.improve":"Improve","nav.translate":"Translate","nav.chat":"Chat","nav.readAloud":"Read aloud","nav.notes":"Notes","nav.jobSearch":"Job search","nav.more":"More","dropdown.guides":"Guides","dropdown.membership":"Membership","dropdown.contact":"Contact","dropdown.darkMode":"Dark mode","dropdown.lightMode":"Light mode","dropdown.langSwitch":"Dansk","dropdown.logout":"Log out","nav.mobileNavigation":"Mobile navigation","nav.moreOptions":"More options","controls.stt":"Speech to text","controls.paste":"Paste","controls.upload":"Upload documents","controls.deleteAll":"Delete all","format.undo":"Undo","format.redo":"Redo","format.bold":"Bold","format.italic":"Italic","format.list":"List","format.readAloud":"Read aloud","tts.readAloud":"Read aloud","tts.stopReading":"Stop reading","tts.cancelReading":"Cancel reading","format.copyText":"Copy text","format.download":"Download","format.compare":"Compare before/after","format.newText":"New text","format.originalText":"Original text","counter.chars":"characters","sidebar.seeCorrections":"See corrections","sidebar.tone":"Tone","sidebar.improveText":"Improve text","sidebar.corrected":"Corrected","sidebar.comma":"Comma","sidebar.deleted":"Deleted","sidebar.ready":"I'm ready!","sidebar.working":"Working...","sidebar.textCorrect":"Text is correct!","sidebar.errors":"Errors","wm.kladde_ready":"Your draft is ready","sidebar.refiningText":"I'm refining the text â without changing the message.","improve.investigating":"I'm investigating","improve.tone":"Tone","improve.structure":"Structure","improve.clarity":"Clarity","style.moreParagraphs":"More paragraphs","style.moreParagraphsDesc":"Your text becomes easier to overview with paragraphs and headings.","style.bulletPoints":"Bullet points","style.bulletPointsDesc":"Your text is turned into a clear list.","style.shorterText":"Shorter text","style.shorterTextDesc":"Your text is shortened but keeps the meaning.","style.longerText":"Longer text","style.longerTextDesc":"Your text is elaborated with more details.","style.responseCounter":"Text {current} of {total}","voice.professional":"Professional","voice.informal":"Informal","voice.formalAuthoritative":"Formal & authoritative","voice.customPlaceholder":"Decide yourself...","voice.simplify":"Informal","voice.simplifyDesc":"Relaxed & friendly","voice.elaborate":"Personal","voice.elaborateDesc":"Warm & personal","voice.convencing":"Neutral","voice.convencingDesc":"Clear & direct","voice.concise":"Polite","voice.conciseDesc":"Respectful & friendly","voice.professionalDesc":"Formal & authoritative","tab.tone":"Tone","tab.better":"Better","tab.assistant":"Assistant","action.correctText":"Correct text","action.changeTone":"Change tone","action.examineText":"Examine text","action.makeMessageClear":"Make the message clear","action.send":"Send","action.stop":"Stop","action.resume":"Resume","action.readAloud":"Read aloud","action.copy":"Copy","action.copyTitle":"Copy","action.edit":"Edit","action.delete":"Delete","action.apply":"Apply","action.applyChange":"Apply change","action.readAloudFull":"Read full text aloud","action.continue":"Continue","chat.whatToDo":"What should I do?","chat.chooseOrWrite":"Choose a suggestion or type what you want","chat.suggestions":"Suggestions","chat.mine":"My shortcuts","chat.help":"Help","chat.humanize":"Humanize","chat.aiCheck":"AI check","chat.noShortcuts":"You have no saved shortcuts yet.","chat.createShortcut":"Create shortcut","chat.askAssistant":"Ask the assistant...","chat.dictate":"Dictate","chat.dictateAi":"Dictate to AI assistant","chat.send":"Send","chat.newConversation":"New conversation","chat.error":"Sorry, an error occurred. Please try again.","chat.noResponse":"No response","chat.helpInstruction":"Explain what you can help with","chat.humanizeInstruction":"","chat.aiCheckInstruction":"","
1instruction.createShortcut":"Create shortcut","instruction.intro":"Create a shortcut for something you often ask the assistant. Next time you just click it.","instruction.nameLabel":"What should it be called?","instruction.namePlaceholder":'E.g. "Summarize briefly" or "Make formal"',"instruction.contentLabel":"What should the assistant do?","instruction.contentPlaceholder":'E.g. "Write a short summary in max 3 sentences"',"instruction.hint":"Write as if you are asking a colleague for help.","instruction.ideas":"Shortcut ideas:","instruction.save":"Save shortcut","instruction.editShortcut":"Edit shortcut","instruction.saveChanges":"Save changes","instruction.fillBothFields":"Fill in both fields","instruction.shortcutUpdated":"Shortcut updated","instruction.shortcutSaved":"Shortcut saved","instruction.shortcutDeleted":"Shortcut deleted","instruction.couldNotLoad":"Could not load shortcuts","instruction.error":"Error","instruction.send":"Send","instruction.edit":"Edit","instruction.delete":"Delete","instruction.noShortcutsYet":"You have no saved shortcuts yet.","instruction.humanizeTitle":"Humanize","instruction.humanizeContent":"","instruction.aiCheckTitle":"AI check","instruction.aiCheckContent":"","instruction.expertReviewTitle":"Expert review","instruction.expertReviewContent":"","instruction.readerReactionTitle":"Reader reaction","instruction.readerReactionContent":"","toast.saved":"Saved","copy.copied":"Copied","copy.copy":"Copy","grammar.light":"Light","grammar.standard":"Standard","grammar.max":"Max","grammar.basicProofreading":"Basic proofreading","grammar.fullProofreading":"Full proofreading","grammar.dyslexia":"Recommended for dyslexic users","grammar.tooltipBasic":"Only corrects spelling and punctuation. Your text is changed as little as possible.","grammar.tooltipStandard":"Corrects spelling, grammar, and word order. Recommended for most users.","grammar.tooltipMax":"Understands what you're trying to say. For those who need extra help.","grammar.descBasic":"Only corrects spelling and punctuation.","grammar.descStandard":"Corrects spelling, grammar, and word order.","grammar.descMax":"Completes incomplete sentences.","grammar.helpLabel":"Read more about this level","lang.danish":"Danish","lang.english":"English","lang.german":"German","lang.french":"French","lang.spanish":"Spanish","lang.arabic":"Arabic","lang.belarusian":"Belarusian","lang.bengali":"Bengali","lang.bosnian":"Bosnian","lang.bulgarian":"Bulgarian","lang.catalan":"Catalan","lang.croatian":"Croatian","lang.czech":"Czech","lang.dutch":"Dutch","lang.estonian":"Estonian","lang.finnish":"Finnish","lang.flemish":"Flemish","lang.germanSwiss":"German (Switzerland)","lang.greek":"Greek","lang.hebrew":"Hebrew","lang.hindi":"Hindi","lang.hungarian":"Hungarian","lang.indonesian":"Indonesian","lang.italian":"Italian","lang.japanese":"Japanese","lang.kannada":"Kannada","lang.korean":"Korean","lang.latvian":"Latvian","lang.lithuanian":"Lithuanian","lang.macedonian":"Macedonian","lang.malay":"Malay","lang.marathi":"Marathi","lang.norwegian":"Norwegian","lang.persian":"Persian","lang.polish":"Polish","lang.portuguese":"Portuguese","lang.romanian":"Romanian","lang.russian":"Russian","lang.serbian":"Serbian","lang.slovak":"Slovak","lang.slovenian":"Slovenian","lang.swedish":"Swedish","lang.tagalog":"Tagalog","lang.tamil":"Tamil","lang.telugu":"Telugu","lang.turkish":"Turkish","lang.ukrainian":"Ukrainian","lang.urdu":"Urdu","lang.vietnamese":"Vietnamese","lang.writeLang":"Type language","wm.lang_label":"Language:","sidebarNav.logoutTokenError":"Could not find logout token. Try again.","sidebarNav.logoutError":"Logout failed. Try again later.","membership.characters":"characters","chatAction.copiedToClipboard":"Copied to clipboard","chatAction.couldNotCopy":"Could not copy","chatAction.applying":"Applying changes...","chatAction.applyingShort":"Applying...","chatAction.applyError":"Could not apply the change","chatAction.undone":"Change undone","chatAction.changeApplied":"Change applied","chatAction.noAIResponse":"No response from AI","chatAction.applied":"Applied","chatAction.undo":"Undo","loader.working":"Working...","loader.rewriting":"Rewriting text...","loader.pleaseWait":"Please wait...","loader.cancel":"Cancel","loader.loading":"Loading...","loader.settingUp":"Setting up...","loader.improvingText":"Improving text...","loader.correctingText":"Correcting text...","loader.anal
1yzingText":"Analyzing text...","analysis.defaultTextType":"Message","analysis.defaultIssue":"Make the text more precise and understandable.","analysis.defaultButton":"Improve text","analysis.defaultCurrentStyle":"Informal","analysis.defaultTargetStyle":"Professional","undoRedo.undo":"Undo change","undoRedo.redo":"Redo change","editor.placeholder":"Start writingâ¦","read.pause":"Pause","read.readAloud":"Read aloud","read.loading":"Loading read aloud","robot.ready":"I'm ready!","robot.refining":"I'm refining the text â without changing the message.","robot.working":"Working...","robot.textCorrect":"Text is correct!","robot.helpIntro":"Hi! I'm your writing assistant. Paste a text and I'll help you correct and improve it.","robot.howCanIHelp":"How can I help?","robot.thinking":"Thinking...","robot.connecting":"Connecting...","sidebarRobot.textChanged":"Text changed!","sidebarRobot.textChangedExplanation":'I have updated the text based on your instruction: "{command}"',"sidebarRobot.changeText":"Change text","sidebarRobot.editDescription":"Ask the robot to rewrite or correct the selected text.","sidebarRobot.question":"Question","sidebarRobot.askDescription":"Ask a question or request an explanation for the selection.","sidebarRobot.errorTryAgain":"An error occurred. Please try again.","sidebarRobot.closeExplanation":"Close explanation","sidebarRobot.insertTextFirst":"Please insert some text first.","stt.micError":"Error: Cannot find microphone.","stt.connectionFailed":"Connection to speech recognition service failed. Please try again later.","tts.downloadDisabled":"Download is disabled. Text exceeds {limit} characters (current: {current})","tts.downloadAudio":"Download audio file","tts.noTextToConvert":"No text content to convert to speech","tts.textTooLong":"Text is too long for download. Maximum {limit} characters allowed (current: {current})","tts.downloadFailed":"Failed to download audio. Please try again.","tts.voiceMale":"Mads","tts.voiceFemale":"Sofia","download.noContent":"No content to export.","download.pdfError":"Unable to create PDF. Please check the console for details.","download.word":"Word","download.pdf":"PDF","download.textFile":"Text file","download.audioFile":"Sound file","crop.title":"Crop the image","crop.titleCounter":"Crop image {current} of {total}","crop.hint":"Drag the corners to choose the area you want read.","crop.cancel":"Cancel","crop.confirm":"Crop","download.preparing":"Preparing downloadâ¦","download.success":"Download ready!","download.error":"Download failed. Please try again.","style.changeError":"Failed to change text style. Please try again.","style.improveError":"Failed to improve text. Please try again.","file.ocrFailed":"OCR extraction failed","file.wordError":"Error processing Word document","fileUpload.fileProcessingError":"An error occurred while processing the file.","fileUpload.uploadingText":"Uploading text...","fileUpload.stageDoc":"Reading your document","fileUpload.stageImage":"Reading the image","fileUpload.stageFiles":"Reading {n} files","fileUpload.stageGather":"Putting it together","fileUpload.uploadAria":"Upload document (PDF, image, or Word)","fileUpload.internetError":"An error occurred. Please check your internet connection.","fileUpload.maxImagesError":"You can upload a maximum of 5 images at a time.","fileUpload.maxDocumentsError":"You can only upload one document at a time.","fileUpload.noTextExtracted":"No text could be extracted from the file.","fileUpload.pdfNativeFallback":"Reading PDF directly...","fileUpload.pdfProcessingError":"An error occurred while processing the PDF file.","fileUpload.formattingText":"Formatting text...","fileUpload.ocrFailed":"OCR extraction failed for this page.","fileUpload.audioTooLarge":"File is too large (max 300 MB). Try converting to MP3.","fileUpload.audioUnsupportedFormat":"Format not supported. Use MP3, WAV, M4A, OGG, or FLAC.","fileUpload.audioDurationError":"Could not read audio duration. Try MP3 or WAV.","fileUpload.audioTooLong":"Audio is over 3 hours. Please upload a shorter file.","fileUpload.audioTranscriptionFailed":"Transcription failed. Try again or upload another file.","fileUpload.audioMultiple":"Please upload one audio file at a time.","fileUpload.audioTranscribing":"Transcribing your audio fileâ¦","fileUpload.audioCleaningUp":"Cleaning up transcriptionâ¦","clipboard.ocrExtracting":"Extracting text from imageâ¦","clipboard.ocrFailed":"Could not extract text from image.","explanation.processingError":"An error occurred while processing explanations.","action.pause":"Pause","file.pdfPageLimit":"You uploaded over {limit} pages. The bot only reads the first {limit}.","file.pdfError":"An error occurred while processing the PDF file.","file.processingError":"An error occurred while processing the file.","file.maxImages":"You can upload a maximum of {limit} images at a time.","chatAI.helpIntro":"I can help you with:","chatAI.helpRewrite":"Rewrite and improve your notes","chatAI.helpSummarize":"Summarize long texts","chatAI.helpFormality":"Make the text more formal or informal","chatAI.helpGrammar":"Fix grammar and spelling errors","chatAI.helpBullets":"Structure content as bullet points","chatAI.helpOutro":"Write or dictate your note, then choose what I should do with it.","chatAI.expansion":"Expansion:","chatAI.expandedSimulated":"Here is a more detailed version of your note with extra context and explanations.","chatAI.simulatedResponse":"This is a simulated AI response showing how the feature will work when connected to an AI model.","chatAI.writeNoteExpand":"Write a note first, then I can expand on it for you.","chatAI.shortened":"Shortened version:","chatAI.writeNoteShorten":"Write a note first, then I can shorten it for you.","chatAI.writeNoteBullets":"Write a note first, then I can rewrite it as bullet points.","chatAI.noSpellingErrors":"No spelling errors found (simulated)","chatAI.writeNoteSpell":"Write a note first, then I can check
1spelling.","chatAI.result":"Result:","chatAI.simulatedFor":'(Simulated AI response for: "',"chatAI.writeNoteHelp":'Write a note first, then I can help you with: "'}},de="sb_ui_lang";let ue=localStorage.getItem(de)||"da";function pe(e,t){let n;if(!ce[ue]&&"undefined"!=typeof window&&"function"==typeof window.SKT)try{var r=window.SKT(e,t);r&&r!==e&&(n=r)}catch(e){}if(void 0===n){n=(ce[ue]||ce.da)[e],void 0===n&&(n=ce.da[e]||e),t&&Object.keys(t).forEach(e=>{n=n.replace(new RegExp("\\{"+e+"\\}","g"),t[e])})}return n}function me(){return ue}function fe(e){var t=(String(e||"").split("-")[0]||"da").toLowerCase();ue=t;try{localStorage.setItem(de,t)}catch(e){}document.documentElement.setAttribute("lang",t),document.documentElement.hasAttribute("data-rtl-ready")&&document.documentElement.setAttribute("dir","ar"===t?"rtl":"ltr");try{document.cookie="sb_ui_lang="+encodeURIComponent(t)+";path=/;max-age=31536000;SameSite=Lax"}catch(e){}he(),window.dispatchEvent(new CustomEvent("uilangchange",{detail:{lang:t}})),window.dispatchEvent(new CustomEvent("ss:lang-changed",{detail:{code:t,lang:t,isUI:!0}}))}function ge(e){let t=(ce[ue]||ce.da)[e];if(void 0===t&&(t=ce.da[e]),void 0!==t)return t;if("undefined"!=typeof window&&"function"==typeof window.SKT)try{const t=window.SKT(e);if(t&&t!==e)return t}catch(e){}return null}function he(){if(ce[ue]){var e=document.getElementById("grammar-bot-container")||document;e.querySelectorAll("[data-i18n]").forEach(e=>{const t=e.getAttribute("data-i18n");if(!t)return;const n=ge(t);null!==n&&(e.textContent=n)}),e.querySelectorAll("[data-i18n-placeholder]").forEach(e=>{const t=e.getAttribute("data-i18n-placeholder");if(!t)return;const n=ge(t);null!==n&&(e.placeholder=n)}),e.querySelectorAll("[data-i18n-title]").forEach(e=>{const t=e.getAttribute("data-i18n-title");if(!t)return;const n=ge(t);null!==n&&(e.title=n)}),e.querySelectorAll("[data-i18n-aria]").forEach(e=>{const t=e.getAttribute("data-i18n-aria");if(!t)return;const n=ge(t);null!==n&&e.setAttribute("aria-label",n)}),e.querySelectorAll("[data-i18n-html]").forEach(e=>{const t=e.getAttribute("data-i18n-html");if(!t)return;const n=ge(t);null!==n&&(e.innerHTML=n)}),e.querySelectorAll("[data-i18n-datalabel]").forEach(e=>{const t=e.getAttribute("data-i18n-datalabel");if(!t)return;const n=ge(t);null!==n&&e.setAttribute("data-label",n)}),e.querySelectorAll("[data-i18n-datatitle]").forEach(e=>{const t=e.getAttribute("data-i18n-datatitle");if(!t)return;const n=ge(t);null!==n&&e.setAttribute("data-title",n)}),function(){const e=document.querySelector(".ss-language-label-desktop"),t=document.querySelector(".ss-language-label-mobile"),n=pe("dropdown.langSwitch");e&&(e.textContent=n);t&&(t.textContent=n);const r="da"===ue;document.querySelectorAll(".ss-flag-en").forEach(e=>{e.style.display=r?"":"none"}),document.querySelectorAll(".ss-flag-dk").forEach(e=>{e.style.display=r?"none":""})}()}}"undefined"!=typeof window&&(window.__t=pe,window.__setUILang=fe,window.__getCurrentUILang=me,window.__toggleUILang=function(){fe("da"===ue?"en":"da")});const ve={request:"activeAbortController",tts:"activeTTSController"};function ye(e="request"){const t=new AbortController,n=ve[e];return n&&(window[n]=t),{signal:t.signal,abort(){t.abort(),n&&window[n]===t&&(window[n]=null)},clear(){n&&window[n]===t&&(window[n]=null)}}}function we(e="request"){const t=ve[e],n=t?window[t]:null;n&&(n.abort(),window[t]=null)}const be=()=>ye("request"),ke=()=>{const e=ve.request;window[e]&&(window[e]=null)},Se=()=>we("request"),xe=()=>function(e="request"){const t=ve[e];return t?window[t]?.signal:void 0}("request"),Te=()=>we("tts"),Le={success:{icon:e.CHECKMARK,class:"success"},info:{icon:e.INFO,class:"info"},warning:{icon:e.WARNING,class:"warning"},error:{icon:e.ERROR,class:"error"}};let Ee=null;function Ce(e,t){const n="object"==typeof t&&null!==t?t:{duration:t},r=void 0===n.duration?2e3:n.duration,o=n.type&&Le[n.type]?n.type:"success",{icon:i,class:a}=Le[o],l=document.getElementById("toastNotification"),s=document.getElementById("toastIcon"),c=document.getElementById("toastMessage");if(!l||!c)return;null!==Ee&&(clearTimeout(Ee),Ee=null),s&&(s.innerHTML=i);const d=Object.values(Le).map(e=>e.class);l.classList.remove(...d),l.classList.add(a),l.setAttribute("role","error"===o||"warning"===o?"alert":"status"),l.setAttribute("aria-live","error"===o||"warning"===o?"assertive":"polite"),c.textContent=e,l.classList.add("show");Ee=setTimeout(()=>{l.classList.remove("show"),Ee=null},r)}const _e="/robots/skrivebord/animations/robot-wave.json";function Ae(e=document.getElementById("gif"),t=_e){let n;if(n="string"==typeof e?document.querySelector(e):e,n){n.innerHTML="",n._lottieInstance&&n._lottieInstance.destroy();try{const e={container:n,renderer:"svg",loop:!0,autoplay:!0};"object"==typeof t&&null!==t?e.animationData=t:e.path=t;const r=lottie.loadAnimation(e);n._lottieInstance=r}catch(e){console.error("Error loading lottie animation:",e)}}}function qe(e,t=_e){if(e){e.innerHTML="";try{lottie.loadAnimation({container:e,renderer:"svg",loop:!0,autoplay:!0,path:t})}catch(e){console.error("Error loading lottie animation by address:",e)}}}function Me(e){if(e<=0)return 1;const t=Math.max(1,Math.ceil(e/6e3)),n=Math.max(1,Math.floor(e/1500));return Math.min(t,n)}function Ie(e){return/[.!?]["']?$/.test(e)}function Be(e,t,n=!1){if(n)return t;let r=-1;for(let n=t-1;n>=0;n--)if(Ie(e[n])){r=n+1;break}let o=-1;for(let n=t;n<e.length;n++)if(Ie(e[n])){o=n+1;break}return-1===r&&-1===o?t:-1===r?o:-1===o||t-r<=o-t?r:o}function He(e){return e?e.replace(/--/g,"-"):e}function Ke(e){try{const t="undefined"!=typeof window?window.marked:void 0!==t?t:null;
1if(!t||!t.parse){console.error("marked library not loaded");return e.split(/\n\n+/).filter(e=>e.trim()).map(e=>`<p>${e.trim().replace(/\n/g," ")}</p>`).join("")||`<p>${e}</p>`}let n=t.parse(e);const r=new DOMParser,o=r.parseFromString(n,"text/html").body;return o.querySelectorAll("h1, h2, h3, h4, h5, h6").forEach(e=>{const t=document.createElement("strong");t.innerHTML=e.innerHTML;const n=document.createElement("p");n.appendChild(t),n.style.marginTop="1em",n.style.marginBottom="0.5em",e.replaceWith(n)}),n=o.innerHTML,n=n.replace(/<p>\s*<\/p>/gi,""),n=n.replace(/(<p[^>]*>)([^<]+)(<\/p>)/gi,function(e,t,n,r){const o=n.replace(/\s+/g," ").trim();return o?t+o+r:""}),n=n.replace(/<p>\s*<\/p>/gi,""),n}catch(t){console.error("Error parsing markdown:",t);return e.split(/\n\n+/).filter(e=>e.trim()).map(e=>`<p>${e.trim().replace(/\n/g," ")}</p>`).join("")||`<p>${e}</p>`}}async function De(e,t,n,r){const o=function(e,t){if(1===t)return[e];const n=e.split(/\s+/).filter(e=>e.length>0);if(0===n.length)return[e];const r=1500,o=Math.min(6500,Math.max(r,Math.round(e.length/t))),i=[];let a=0;function l(t){if(t<=0)return 0;if(t>=n.length)return e.length;let r=0;for(let e=0;e<t;e++)r+=n[e].length+(e>0?1:0);return r}function s(e){let t=0;for(let r=0;r<n.length;r++){const o=t+(r>0?1:0),i=o+n[r].length;if(e<i)return e<o?Math.max(0,r-1):r;t=i}return n.length-1}for(let c=0;c<t;c++){if(c===t-1){const e=n.slice(a).join(" ");e.trim()&&i.push(e);break}const d=l(a),u=Math.min(d+o,e.length);let p=Math.min(s(u)+1,n.length),m=n.slice(a,p).join(" ");for(;m.length<r&&p<n.length;)p=Math.min(p+20,n.length),m=n.slice(a,p).join(" ");if(m.length>=r){const e=Be(n,p,!1);if(e>a){const t=n.slice(a,e).join(" ");t.length>=r&&(m=t,p=e)}}m.trim()?(i.push(m),a=p):a<n.length&&(i.push(n[a]),a++)}return i.filter(e=>e&&e.trim())}(e,Me(e.length)),i=new URLSearchParams;i.append("action","pdf_formater_parallel"),i.append("language",t),i.append("parts",JSON.stringify(o)),i.append("is_url","0"),r&&i.append("no_translate","1");const a=await fetch(n.ajax_url,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:i.toString()}),l=await a.json();if(l.success&&Array.isArray(l.data)){return`<div class="markdown-body">${He(Ke(l.data.map((e,t)=>t>0&&/^\*\*[^*]+\*\*\n/.test(e)?"\n\n"+e:e).join(" ")))}</div>`}throw new Error("Format failed")}async function Pe(e,t,n,r){if(!e)return null;const o=t();try{const t=function(e){return e?e.replace(/-/g,"--"):e}(e);return 1===Me(t.length)?await async function(e,t,n,r){const o=new FormData;o.append("action","pdf_formater"),o.append("language",t),o.append("text",e),o.append("is_url","0"),r&&o.append("no_translate","1");const i=await(await fetch(n.ajax_url,{method:"POST",body:o})).json();if(i.success)return`<div class="markdown-body">${He(Ke(i.data))}</div>`;throw new Error("Format failed")}(t,o,n,r):await De(t,o,n,r)}catch(e){return console.error("Text formatting error:",e),null}}async function Ne(e,t){const{text:n,aiFormat:r,preserveLanguage:o}=e,{deps:i,t:a,stageGather:l}=t,s=e=>{i.displayResponse?i.displayResponse(e,!0,!1,!0):function(e){window.quill1&&window.quill1.setText(e)}(e)},c=()=>{setTimeout(()=>{i.scrollAfterPaste&&i.scrollAfterPaste()},100),i.hideLoader&&i.hideLoader(".textarea-wrapper")};if(!r)return s(n),void c();!("function"==typeof l&&l())&&i.showLoader&&i.showLoader(".textarea-wrapper",a("fileUpload.formattingText"));const d=i.getLanguageFullName||(()=>"danish"),u=i.HGF_ajax_object||("undefined"!=typeof HGF_ajax_object?HGF_ajax_object:null);let p=null;try{p=await Pe(n,d,u,o)}catch(e){console.error("Formatting error:",e)}let m=null;if(p){const e=document.createElement("div");e.innerHTML=p,m=e.querySelector(".markdown-body")}if(m&&i.displayResponse)i.displayResponse(m.innerHTML,!0,!1,!0);else{s(function(e){return(e=(e=(e=(e=(e=(e=(e=e.replace(/\n{3,}/g,"\n\n")).replace(/[ââ]/g,"â¢")).replace(/(â¢|\d+\.)\s*/g,"\n$1 ")).replace(/(â¢|\d+\.)([^\s])/g,"$1 $2")).replace(/[ \t]+/g," ")).replace(/\n{3,}/g,"\n\n")).replace(/([.!?])([A-ZÃÃÃ
])/g,"$1\n$2")).trim()}(m?m.textContent||m.innerText||"":n))}c()}const je="sk-image-crop",Re="sk-image-crop-styles",Fe=["image/jpeg","image/jpg","image/png","image/webp","image/bmp","image/gif"];function Oe(e){const t=(e&&e.type?e.type:"").toLowerCase();return-1!==Fe.indexOf(t)}function Ue(e,t,n,r){return new Promise(function(o){!function(){if(document.getElementById(Re))return;const e=document.createElement("style");e.id=Re,e.textContent=["#"+je+"{position:fixed;inset:0;z-index:100000;display:flex;flex-direction:column;","align-items:center;justify-content:center;gap:18px;padding:20px;","background:rgba(12,11,10,.92);backdrop-filter:blur(2px);",'font-family:Inter,system-ui,-apple-system,"Segoe UI",sans-serif;color:#FAF5EF;',"overscroll-behavior:contain;touch-action:none;}","#"+je+" .sk-crop-head,#"+je+" .sk-crop-actions{position:relative;z-index:1;}","#"+je+" .sk-crop-head{text-align:center;max-width:min(680px,92vw);}","#"+je+" .sk-crop-title{margin:0;font-size:17px;font-weight:600;line-height:1.3;}","#"+je+" .sk-crop-hint{margin:6px 0 0;font-size:13.5px;line-height:1.4;color:rgba(250,245,239,.72);}","#"+je+" .sk-crop-stage{position:relative;display:block;line-height:0;","max-width:100%;flex:0 1 auto;min-height:0;}","#"+je+" .sk-crop-img{display:block;max-width:min(1100px,92vw);max-height:62vh;","width:auto;height:auto;user-select:none;-webkit-user-drag:none;}","#"+je+" .sk-crop-rect{position:absolute;box-sizing:border-box;
1cursor:move;","border:1px solid rgba(255,255,255,.9);box-shadow:0 0 0 9999px rgba(10,9,8,.62);touch-action:none;}","#"+je+' .sk-crop-rect::before{content:"";position:absolute;inset:0;',"border:1px solid rgba(20,18,16,.55);pointer-events:none;}","#"+je+" .sk-crop-handle{position:absolute;width:22px;height:22px;","border:3px solid #FFFEFB;background:transparent;touch-action:none;","filter:drop-shadow(0 0 1.5px rgba(20,18,16,.75));}","#"+je+' .sk-crop-handle[data-corner="nw"]{top:-2px;left:-2px;border-right:0;border-bottom:0;cursor:nwse-resize;}',"#"+je+' .sk-crop-handle[data-corner="ne"]{top:-2px;right:-2px;border-left:0;border-bottom:0;cursor:nesw-resize;}',"#"+je+' .sk-crop-handle[data-corner="sw"]{bottom:-2px;left:-2px;border-right:0;border-top:0;cursor:nesw-resize;}',"#"+je+' .sk-crop-handle[data-corner="se"]{bottom:-2px;right:-2px;border-left:0;border-top:0;cursor:nwse-resize;}',"#"+je+' .sk-crop-handle::after{content:"";position:absolute;top:50%;left:50%;',"width:28px;height:28px;transform:translate(-50%,-50%);}","#"+je+" .sk-crop-actions{display:flex;align-items:center;justify-content:center;gap:12px;flex-wrap:wrap;}","#"+je+" .sk-crop-btn{border:0;cursor:pointer;border-radius:999px;padding:12px 28px;","font-family:inherit;font-size:14px;font-weight:600;line-height:1;min-width:120px;}","#"+je+" .sk-crop-btn:focus-visible{outline:2px solid #A8C5B8;outline-offset:3px;}","#"+je+" .sk-crop-btn--ghost{background:rgba(250,245,239,.13);color:#FAF5EF;}","#"+je+" .sk-crop-btn--ghost:hover{background:rgba(250,245,239,.2);}","#"+je+" .sk-crop-btn--primary{background:#6E8A7E;color:#FFFEFB;}","#"+je+" .sk-crop-btn--primary:hover{background:#4A7A68;}","@media (max-width:600px){","#"+je+"{gap:14px;padding:14px;}","#"+je+" .sk-crop-img{max-height:54vh;}","#"+je+" .sk-crop-btn{padding:12px 22px;min-width:104px;}","}","@media (prefers-reduced-motion:reduce){#"+je+"{backdrop-filter:none;}}"].join(""),document.head.appendChild(e)}();const i=URL.createObjectURL(e),a=document.createElement("div");a.id=je,a.setAttribute("role","dialog"),a.setAttribute("aria-modal","true"),a.setAttribute("aria-labelledby",je+"-title");const l=document.createElement("div");l.className="sk-crop-head";const s=document.createElement("h2");s.className="sk-crop-title",s.id=je+"-title",s.textContent=r>1?t.titleCounter.replace("{current}",String(n+1)).replace("{total}",String(r)):t.title;const c=document.createElement("p");c.className="sk-crop-hint",c.textContent=t.hint,l.appendChild(s),l.appendChild(c);const d=document.createElement("div");d.className="sk-crop-stage";const u=document.createElement("img");u.className="sk-crop-img",u.alt="";const p=document.createElement("div");p.className="sk-crop-rect",["nw","ne","sw","se"].forEach(function(e){const t=document.createElement("div");t.className="sk-crop-handle",t.setAttribute("data-corner",e),p.appendChild(t)}),d.appendChild(u),d.appendChild(p);const m=document.createElement("div");m.className="sk-crop-actions";const f=document.createElement("button");f.type="button",f.className="sk-crop-btn sk-crop-btn--ghost",f.textContent=t.cancel;const g=document.createElement("button");g.type="button",g.className="sk-crop-btn sk-crop-btn--primary",g.textContent=t.confirm,m.appendChild(f),m.appendChild(g),a.appendChild(l),a.appendChild(d),a.appendChild(m);let h={x:0,y:0,w:0,h:0},v=0,y=0,w=!1;function b(){p.style.left=h.x+"px",p.style.top=h.y+"px",p.style.width=h.w+"px",p.style.height=h.h+"px"}function k(e){const t=u.getBoundingClientRect(),n=v,r=y;if(v=t.width,y=t.height,e&&n&&r){const e=v/n,t=y/r;h={x:h.x*e,y:h.y*t,w:h.w*e,h:h.h*t}}else h={x:0,y:0,w:v,h:y};b()}function S(){v&&k(!0)}let x=null;function T(e){const t=u.getBoundingClientRect();return{x:e.clientX-t.left,y:e.clientY-t.top}}function L(e){if(x){x=null;try{p.releasePointerCapture(e.pointerId)}catch(e){}}}function E(e){"Escape"===e.key?(e.preventDefault(),C(null)):"Enter"===e.key&&e.target!==f?(e.preventDefault(),_()):"Tab"===e.key&&(e.preventDefault(),(document.activeElement===g?f:g).focus())}function C(e){w||(w=!0,function(){window.removeEventListener("resize",S),window.removeEventListener("orientationchange",S),document.removeEventListener("keydown",E,!0);try{a.remove()}catch(e){}try{URL.revokeObjectURL(i)}catch(e){}}(),o(e))}function _(){if(w)return;if(!v||!y)return void C(e);
1const t=u.naturalWidth/v,n=u.naturalHeight/y,r=Math.round(h.x*t),o=Math.round(h.y*n),i=Math.round(h.w*t),a=Math.round(h.h*n);if(r<=0&&o<=0&&i>=u.naturalWidth-1&&a>=u.naturalHeight-1)C(e);else try{const t=document.createElement("canvas");t.width=Math.max(1,i),t.height=Math.max(1,a);const n=t.getContext("2d");n.fillStyle="#FFFFFF",n.fillRect(0,0,t.width,t.height),n.drawImage(u,r,o,i,a,0,0,t.width,t.height);const l=function(e){const t=(e||"").toLowerCase();return"image/jpeg"===t||"image/jpg"===t?"image/jpeg":"image/webp"===t?"image/webp":"image/png"}(e.type);t.toBlob(function(t){if(!t)return void C(e);let n;try{n=new File([t],e.name,{type:l,lastModified:Date.now()})}catch(r){n=t;try{n.name=e.name}catch(e){}}try{n.ssOriginalFile=e}catch(e){}C(n)},l,"image/png"===l?void 0:.92)}catch(t){console.error("Image crop failed, uploading the original:",t),C(e)}}f.addEventListener("click",function(){C(null)}),g.addEventListener("click",_),p.addEventListener("pointerdown",function(e){const t=e.target&&e.target.getAttribute?e.target.getAttribute("data-corner"):null;if(!t&&e.target!==p)return;e.preventDefault();const n=T(e);x={corner:t,startX:n.x,startY:n.y,origin:{x:h.x,y:h.y,w:h.w,h:h.h}};try{p.setPointerCapture(e.pointerId)}catch(e){}}),p.addEventListener("pointermove",function(e){if(!x)return;e.preventDefault();const t=T(e),n=t.x-x.startX,r=t.y-x.startY,o=x.origin;if(x.corner){const e="nw"===x.corner||"sw"===x.corner,t="nw"===x.corner||"ne"===x.corner,i=o.x+o.w,a=o.y+o.h;if(e){const e=Math.min(Math.max(0,o.x+n),i-32);h.x=e,h.w=i-e}else h.w=Math.min(Math.max(32,o.w+n),v-o.x);if(t){const e=Math.min(Math.max(0,o.y+r),a-32);h.y=e,h.h=a-e}else h.h=Math.min(Math.max(32,o.h+r),y-o.y)}else h.x=Math.min(Math.max(0,o.x+n),v-o.w),h.y=Math.min(Math.max(0,o.y+r),y-o.h),h.w=o.w,h.h=o.h;b()}),p.addEventListener("pointerup",L),p.addEventListener("pointercancel",L),window.addEventListener("resize",S),window.addEventListener("orientationchange",S),document.addEventListener("keydown",E,!0),u.addEventListener("load",function(){k(!1);try{g.focus({preventScroll:!0})}catch(e){}}),u.addEventListener("error",function(){C(e)}),u.src=i,document.body.appendChild(a)})}function $e(){const e=document.querySelector(".skv2-doc-title")||document.getElementById("doc-title");return e&&e.value&&e.value.trim()?e.value.trim():""}function ze(e,t){var n=String(e||"").replace(/[\\/:*?"<>|]/g,"").replace(/\s+/g," ").trim();if(n||(n="SkrivSikkert dokument"),n=n.substring(0,100),t){var r="."+t;return n.toLowerCase().endsWith(r.toLowerCase())&&(n=n.slice(0,-r.length)),n+r}return n}function Ge(e){const t=new Blob(["\ufeff"+e],{type:"text/plain;charset=utf-8"});!function(e,t){const n=document.createElement("a");n.href=e,n.download=t||$e(),document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(e)}(URL.createObjectURL(t),ze($e(),"txt"))}async function Ve(e){if("undefined"==typeof pdfMake||"undefined"==typeof htmlToPdfmake)throw new Error("PDF libraries (pdfMake / htmlToPdfmake) not loaded");const t=window.quill1.root.innerHTML.trim();if(!t||"<p><br></p>"===t)throw new Error("No content to export");const n=function(e="Roboto"){return"Helvetica"===e?(pdfMake.fonts={Helvetica:{normal:"Helvetica",bold:"Helvetica-Bold",italics:"Helvetica-Oblique",bolditalics:"Helvetica-BoldOblique"},Times:{normal:"Times-Roman",bold:"Times-Bold",italics:"Times-Italic",bolditalics:"Times-BoldItalic"},Courier:{normal:"Courier",bold:"Courier-Bold",italics:"Courier-Oblique",bolditalics:"Courier-BoldOblique"}},"Helvetica"):"Roboto"}("Roboto"),r=e.replace(/[\u{1F600}-\u{1F64F}]|[\u{1F300}-\u{1F5FF}]|[\u{1F680}-\u{1F6FF}]|[\u{1F1E0}-\u{1F1FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]|[\u{1F900}-\u{1F9FF}]|[\u{1F018}-\u{1F270}]|[\u{238C}-\u{2454}]|[\u{20D0}-\u{20FF}]|[\u{FE00}-\u{FE0F}]|[\u{1F004}]|[\u{1F0CF}]|[\u{1F170}-\u{1F251}]/gu,"");const o={pageSize:"A4",pageMargins:[72,72,72,72],content:htmlToPdfmake(r,{window:window,customTag:function(e){const t=e&&e.element,n=e&&e.ret;if(t&&"BLOCKQUOTE"===String(t.nodeName).toUpperCase()){return{table:{widths:["*"],body:[[{stack:Array.isArray(n&&n.stack)?n.stack:[n],border:[!1,!1,!1,!1]}]]},layout:{hLineWidth:function(){return 0},vLineWidth:function(e){return 0===e?3:0},vLineColor:function(){return"#C7C2B8"},paddingLeft:function(){return 12},paddingRight:function(){return 8},paddingTop:function(){return 6},paddingBottom:function(){return 6}},margin:[0,6,0,8]}}return n}}),defaultStyle:{fontSize:12,lineHeight:1.4,font:n},styles:{header:{fontSize:18,bold:!0,margin:[0,0,0,10]}
1,subheader:{fontSize:16,bold:!0,margin:[0,10,0,5]},normal:{fontSize:12,margin:[0,0,0,5]}}};pdfMake.createPdf(o).download(ze($e(),"pdf"))}let We=0;function Je(e){const t=document.createElement("div");t.innerHTML=e;const n={ops:[]};function r(e,o,i){if(void 0===o&&(o=null),void 0===i&&(i=0),e.nodeType===Node.TEXT_NODE){if(e.textContent){const r={};let a=e.parentElement,l=!1,s=o;for(;a&&a!==t;){const e=a.tagName?.toLowerCase();if("li"===e){l=!0;const e=a.parentElement;if(e){const t=e.tagName.toLowerCase();"ul"===t?s="bullet":"ol"===t&&(s="ordered")}}switch(e){case"h1":r.header=1;break;case"h2":r.header=2;break;case"h3":r.header=3;break;case"h4":r.header=4;break;case"h5":r.header=5;break;case"h6":r.header=6;break;case"strong":case"b":r.bold=!0;break;case"em":case"i":r.italic=!0;break;case"u":r.underline=!0;break;case"strike":case"s":r.strike=!0}a=a.parentElement}l&&s&&(r.list=s,i>0&&(r.indent=i)),n.ops.push({insert:e.textContent,attributes:Object.keys(r).length>0?r:void 0})}}else if(e.nodeType===Node.ELEMENT_NODE){const t=e.tagName.toLowerCase();if("ul"===t||"ol"===t){const n="ul"===t?"bullet":"ordered",o="li"===(e.parentElement&&e.parentElement.tagName?e.parentElement.tagName.toLowerCase():"")?i+1:i;Array.from(e.children).forEach(e=>{"li"===e.tagName.toLowerCase()&&r(e,n,o)})}else if("li"===t){const t=parseInt(e.getAttribute("data-ss-indent")||"0",10),a=Math.max(i,Number.isFinite(t)?t:0);Array.from(e.childNodes).forEach(e=>{r(e,o,a)});const l={};o&&(l.list=o,a>0&&(l.indent=a)),n.ops.push({insert:"\n",attributes:Object.keys(l).length>0?l:void 0})}else if(["p","div","br","h1","h2","h3","h4","h5","h6","blockquote"].includes(t)){if(Array.from(e.childNodes).forEach(e=>{r(e,o,i)}),"br"!==t){const e={};if(["h1","h2","h3","h4","h5","h6"].includes(t)){const n=parseInt(t.charAt(1));e.header=n}else"blockquote"===t&&(e.blockquote=!0);n.ops.push({insert:"\n",attributes:Object.keys(e).length>0?e:void 0})}}else Array.from(e.childNodes).forEach(e=>{r(e,o,i)})}}return Array.from(t.childNodes).forEach(e=>{r(e)}),n}function Ze(e,t){if("undefined"==typeof docx)throw new Error("docx library not loaded");const n={text:e,font:"Calibri",color:"000000"};if(t.header)switch(n.bold=!0,t.header){case 1:n.size=32;break;case 2:n.size=28;break;case 3:n.size=26;break;case 4:n.size=24;break;case 5:default:n.size=22;break;case 6:n.size=20}else n.size=22,(t.bold||t.strong)&&(n.bold=!0);return t.italic&&(n.italics=!0),t.underline&&(n.underline={}),t.strike&&(n.strike=!0),t.script&&("super"===t.script?n.superScript=!0:"sub"===t.script&&(n.subScript=!0)),new docx.TextRun(n)}function Ye(e,t,n){if(void 0===n&&(n=!1),"undefined"==typeof docx)throw new Error("docx library not loaded");const r={children:e.length>0?e:[Ze(" ",{})],spacing:{after:300,before:0}};if(t.header)r.spacing={after:200,before:t.header<=2?400:200},r.heading=`Heading${t.header}`;else if(t.list){const e=Math.min(t.indent||0,4);r.spacing={after:0,before:0};const n=t.listInstance||0;"bullet"===t.list?r.numbering={reference:"bullet-numbering-"+n,level:e}:"ordered"===t.list&&(r.numbering={reference:"ordered-numbering-"+n,level:e})}else if(t.blockquote)r.spacing={after:300,before:300},r.indent={left:720},r.border={left:{style:docx.BorderStyle.SINGLE,size:18,space:12,color:"C7C2B8"}};else if(n&&(r.spacing.before=300),t.indent&&(r.indent={left:720*t.indent}),t.align){const e={left:docx.AlignmentType.LEFT,center:docx.AlignmentType.CENTER,right:docx.AlignmentType.RIGHT,justify:docx.AlignmentType.JUSTIFIED};r.alignment=e[t.align]}return new docx.Paragraph(r)}const Qe=["â¢","â","âª","â¢","â"],Xe=["DECIMAL","LOWER_LETTER","LOWER_ROMAN","DECIMAL","LOWER_LETTER"];function et(e){const t=[];for(let n=0;n<=4;n++)t.push({level:n,format:"bullet"===e?docx.LevelFormat.BULLET:docx.LevelFormat[Xe[n]],text:"bullet"===e?Qe[n]:"%"+(n+1)+".",alignment:docx.AlignmentType.LEFT,style:{paragraph:{indent:{left:720*(n+1),hanging:360}}}});return t}function tt(e){const t=Math.max(1,e),n=[];for(let e=0;e<t;e++)n.push({reference:"bullet-numbering-"+e,levels:et("bullet")}),n.push({reference:"ordered-numbering-"+e,levels:et("ordered")});return n}async function nt(){if("undefined"==typeof docx||"undefined"==typeof saveAs)throw new Error("DOCX libraries (docx / FileSaver) not loaded");const e=function(e){const t=document.createElement("div");return t.innerHTML=e,t.querySelectorAll('ham-dan.grammar-correction-removed, [class*="grammar-correction-removed"]').forEach(e
1=>{e.remove()}),t.querySelectorAll("ham-dan").forEach(e=>{const t=e.textContent,n=document.createTextNode(t);e.parentNode.replaceChild(n,e)}),t.querySelectorAll("mark").forEach(e=>{const t=e.textContent,n=document.createTextNode(t);e.parentNode.replaceChild(n,e)}),t.querySelectorAll("blockquote").forEach(e=>{Array.from(e.children).filter(e=>{const t=e.tagName?e.tagName.toLowerCase():"";return"p"===t||"div"===t}).forEach((t,n)=>{for(n>0&&e.insertBefore(document.createTextNode(" "),t);t.firstChild;)e.insertBefore(t.firstChild,t);t.remove()})}),t.querySelectorAll('li[class*="ql-indent-"]').forEach(e=>{const t=/ql-indent-(\d+)/.exec(e.className||"");t&&e.setAttribute("data-ss-indent",t[1])}),t.querySelectorAll("*").forEach(e=>{e.removeAttribute("style"),e.removeAttribute("class")}),t.querySelectorAll("h1, h2, h3, h4, h5, h6, strong").forEach(e=>{const t=e.nextElementSibling;t&&"P"===t.tagName&&(1===t.childNodes.length&&t.firstChild&&t.firstChild.nodeType===Node.ELEMENT_NODE&&"BR"===t.firstChild.tagName||"<br>"===t.innerHTML.trim().toLowerCase()||"<br/>"===t.innerHTML.trim().toLowerCase()||"<br />"===t.innerHTML.trim().toLowerCase())&&t.parentNode.removeChild(t)}),[...t.querySelectorAll("ol")].forEach(e=>{const t=document.createElement("ul");let n=!1;[...e.children].forEach(e=>{"bullet"===e.getAttribute("data-list")&&(e.removeAttribute("data-list"),t.appendChild(e.cloneNode(!0)),e.remove(),n=!0)}),n&&(0===e.children.length?e.replaceWith(t):e.parentNode.insertBefore(t,e))}),t.innerHTML}(window.quill1.root.innerHTML),t=function(e){const t=[];let n=[],r=!1,o={},i=-1;return We=0,e.ops.forEach((e,a)=>{if("string"==typeof e.insert){const a=e.insert,l=e.attributes||{},s=!!l.list;if(a.includes("\n")){const e=a.split("\n");e.forEach((a,c)=>{if(a&&n.push(Ze(a,l)),c<e.length-1){const e=r&&!s,a={...o,...l};a.list&&(r||(i++,We=i+1),a.listInstance=i),t.push(Ye(n,a,e)),n=[],r=s,o={}}})}else a&&(n.push(Ze(a,l)),o={...o,...l})}}),n.length>0&&t.push(Ye(n,o,!1)),0===t.length&&t.push(new docx.Paragraph({children:[Ze(" ",{})]})),t}(function(e){if("string"==typeof e){if("undefined"!=typeof document){const t=document.createElement("template");if(t&&t.content&&"function"==typeof t.content.querySelectorAll)return t.innerHTML=e,t.content.querySelectorAll('.grammar-correction-removed, [class*="grammar-correction-removed"]').forEach(e=>e.remove()),t.innerHTML}return e.replace(/<([a-z][\w:-]*)\b(?=[^>]*\bgrammar-correction-removed\b)[^>]*>[\s\S]*?<\/\1>/gi,"")}return{ops:e.ops.filter(e=>!(e.attributes&&e.attributes["grammar-removed"]))}}(Je(e))),n=new docx.Document({numbering:{config:tt(We)},sections:[{properties:{page:{margin:{top:720,right:720,bottom:720,left
1:720}}},children:t}]}),r=await docx.Packer.toBlob(n);saveAs(r,ze($e(),"docx"))}function rt(e,t){var n=document.getElementById("sk-download-toast");n&&n.remove();var r=document.createElement("div");r.id="sk-download-toast",r.className="sk-download-toast"+(t?" sk-download-toast--error":""),r.textContent=e,document.body.appendChild(r),requestAnimationFrame(function(){r.classList.add("sk-download-toast--visible")}),setTimeout(function(){r.classList.remove("sk-download-toast--visible"),setTimeout(function(){r.remove()},300)},t?3e3:2e3)}function ot(e){var r=e&&e.processQuillContentForCopy,o=e&&e.downloadAudioFile;const i=document.getElementById("downloadBtnQuill");if(!i)return void console.error("Download button not found");const a=document.createElement("div");a.id="downloadDropdown",a.className="ed-overflow-menu download-menu",a.setAttribute("role","menu"),a.setAttribute("aria-label",pe("format.download")||"Download"),a.setAttribute("aria-hidden","true"),a.hidden=!0;const l=[{format:"docx",i18nKey:"download.word",fallback:"Word",icon:'<path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/>'},{format:"pdf",i18nKey:"download.pdf",fallback:"PDF",icon:'<path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/><path d="M10 12H8v5h2a2 2 0 0 0 0-4H8"/>'},{format:"txt",i18nKey:"download.textFile",fallback:"Tekstfil",icon:'<path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/><line x1="9" y1="15" x2="15" y2="15"/>'}];"function"==typeof o&&l.push({format:"audio",i18nKey:"download.audioFile",fallback:"Lydfil",icon:'<path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/><circle cx="10" cy="17" r="1.5"/><path d="M11.5 17v-4.5l4-1"/>'}),l.forEach(e=>{const t=document.createElement("button");t.type="button",t.className="ed-overflow-item",t.setAttribute("role","menuitem"),t.setAttribute("data-format",e.format),t.setAttribute("data-i18n",e.i18nKey),t.setAttribute("tabindex","-1"),t.innerHTML='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round">'+e.icon+"</svg><span>"+(pe(e.i18nKey)||e.fallback)+"</span>",a.appendChild(t)}),document.body.appendChild(a);var s=null;function c(){var e=(s&&document.body.contains(s)?s:i).getBoundingClientRect();a.style.setProperty("position","fixed","important"),a.style.setProperty("right","auto","important"),a.style.setProperty("bottom","auto","important"),a.style.setProperty("left","0px","important"),a.style.setProperty("top","0px","important");var t=a.getBoundingClientRect(),n=e.left,r=e.bottom+6;n+t.width+8>window.innerWidth&&(n=e.right-t.width),n<8&&(n=8),r+t.height+8>window.innerHeight&&(r=e.top-t.height-6),r<8&&(r=8),a.style.setProperty("left",Math.round(n)+"px","important"),a.style.setProperty("top",Math.round(r)+"px","important")}function d(){return a.classList.contains("active")}function u(e){s=e||i,a.hidden=!1,a.setAttribute("aria-hidden","false"),a.classList.add("active"),i.setAttribute("aria-expanded","true"),c()}function p(e){var t=s||i;a.classList.remove("active"),a.setAttribute("aria-hidden","true"),a.hidden=!0,i.setAttribute("aria-expanded","false"),e&&t&&"function"==typeof t.focus&&t.focus(),s=null}function m(e){var t=a.querySelectorAll('[role="menuitem"]');0!==t.length&&t[Math.max(0,Math.min(e,t.length-1))].focus()}function f(){if(i)try{if("none"!==window.getComputedStyle(i).display)return i}catch(e){return i}return document.querySelector(".ed-overflow-toggle")||i}function g(){const e=f();if(!e||"1"===e.dataset.skDownloadBusy)return null;const t=e;t.dataset.skDownloadBusy="1";const n=t.disabled;t.disabled=!0;const r=t.innerHTML;t.innerHTML='<svg class="sk-dl-spin" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M21 12a9 9 0 11-6.219-8.56"/></svg>',t.setAttribute("aria-busy","true");const o=Date.now();return function(){const e=Math.max(0,320-(Date.now()-o));setTimeout(()=>{t.innerHTML=r,t.removeAttribute("aria-busy"),delete t.dataset.skDownloadBusy,t.disabled=n},e)}}function h(){return new Promise(e=>{"function"==typeof requestAnimationFrame?requestAnimationFrame(()=>setTimeout(e,0)):setTimeout(e,16)})}async function v(e){if(p(!0),"audio"===e){const e=g();try{await h(),"function"==typeof o&&await o()}finally{e&&e()}return}const i=g();try{await h();const o=function(e){const t=document.createElement("div");
1return t.innerHTML=e,t.querySelectorAll("*").forEach(e=>{e.removeAttribute("style")}),t.innerHTML}(t(n(function(e){const t=document.createElement("div");return t.innerHTML=e,["h1","h2","h3","h4","h5","h6"].forEach(e=>{t.querySelectorAll(e).forEach(e=>{const t=document.createElement("strong");t.innerHTML=e.innerHTML,e.parentNode.replaceChild(t,e)})}),t.querySelectorAll("strong").forEach(e=>{const t=e.nextElementSibling;t&&"P"===t.tagName&&(1===t.childNodes.length&&t.firstChild&&t.firstChild.nodeType===Node.ELEMENT_NODE&&"BR"===t.firstChild.tagName||"<br>"===t.innerHTML.trim().toLowerCase()||"<br/>"===t.innerHTML.trim().toLowerCase()||"<br />"===t.innerHTML.trim().toLowerCase())&&t.parentNode.removeChild(t)}),[...t.querySelectorAll("ol")].forEach(e=>{const t=document.createElement("ul");let n=!1;[...e.children].forEach(e=>{"bullet"===e.getAttribute("data-list")&&(e.removeAttribute("data-list"),t.appendChild(e.cloneNode(!0)),e.remove(),n=!0)}),n&&(0===e.children.length?e.replaceWith(t):e.parentNode.insertBefore(t,e))}),t.innerHTML}(window.quill1.root.innerHTML)))),i=r?function(e,t){const{text:n}=t(e);return n}(window.quill1,r):"";switch(rt(pe("download.preparing"),!1),e){case"txt":Ge(i);break;case"docx":await nt();break;case"pdf":await Ve(o)}rt(pe("download.success"),!1)}catch(e){rt(pe("download.error"),!0)}finally{i&&i()}}function y(){d()&&c()}i.addEventListener("click",()=>{d()?p(!0):(u(i),m(0))}),i.addEventListener("sk:download-menu-open",e=>{var t=e&&e.detail&&e.detail.anchor;d()?p(!1):(u(t||i),m(0))}),i.addEventListener("keydown",e=>{if("ArrowDown"===e.key||"Down"===e.key)e.preventDefault(),d()||u(i),m(0);else if("ArrowUp"===e.key||"Up"===e.key){e.preventDefault(),d()||u(i),m(a.querySelectorAll('[role="menuitem"]').length-1)}}),a.addEventListener("keydown",e=>{var t=Array.from(a.querySelectorAll('[role="menuitem"]')),n=t.indexOf(document.activeElement);"ArrowDown"===e.key||"Down"===e.key?(e.preventDefault(),m(n+1<t.length?n+1:0)):"ArrowUp"===e.key||"Up"===e.key?(e.preventDefault(),m(n-1>=0?n-1:t.length-1)):"Escape"===e.key?(e.preventDefault(),p(!0)):"Tab"===e.key?p(!1):"Home"===e.key?(e.preventDefault(),m(0)):"End"===e.key&&(e.preventDefault(),m(t.length-1))}),a.querySelectorAll('[role="menuitem"]').forEach(e=>{e.addEventListener("click",()=>{v(e.getAttribute("data-format"))})}),document.addEventListener("click",e=>{!d()||i.contains(e.target)||a.contains(e.target)||p(!1)}),i.addEventListener("keydown",e=>{"Escape"===e.key&&d()&&(e.preventDefault(),p(!0))}),window.addEventListener("scroll",y,!0),window.addEventListener("resize",y),window.addEventListener("uilangchange",()=>{a.querySelectorAll('[role="menuitem"]').forEach(e=>{var t=e.getAttribute("data-i18n");if(t){var n=e.querySelector("span");n&&(n.textContent=pe(t))}})})}const it={Dansk:"da",Engelsk:"en",Tysk:"ge",Fransk:"fr",Spansk:"es"},at={Arabisk:"ar-SA",Hviderussisk:"be",Bengalsk:"bn",Bosnisk:"bs",Bulgarsk:"bg",Catalansk:"ca",Kroatisk:"hr",Tjekkisk:"cs",Nederlandsk:"nl",Estisk:"et",Finsk:"fi",Flamsk:"nl-BE","Tysk (Schweiz)":"de-CH","Græsk":"el",Hebraisk:"he",Hindi:"hi",Ungarsk:"hu",Indonesisk:"id",Italiensk:"it",Japansk:"ja",Kannada:"kn",Koreansk:"ko",Lettisk:"lv",Litauisk:"lt",Makedonsk:"mk",Malaysisk:"ms",Marathi:"mr",Norsk:"no",Persisk:"fa",Polsk:"pl",Portugisisk:"pt","Rumænsk":"ro",Russisk:"ru",Serbisk:"sr",Slovakisk:"sk",Slovensk:"sl",Svensk:"sv",Tagalog:"tl",Tamil:"ta",Telugu:"te",Tyrkisk:"tr",Ukrainsk:"uk",Urdu:"ur",Vietnamesisk:"vi"},lt={...it,...at};let st="da",ct=null;const dt='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" style="margin-right: 8px;">\n <g clip-path="url(#clip0_custom_globe_1755061628572)">\n <circle cx="12" cy="12" r="10" stroke="#6B7280" stroke-width="2" fill="none"></circle>\n <path d="M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z" stroke="#6B7280" stroke-width="2" fill="none"></path>\n </g>\n <defs>\n <clipPath id="clip0_custom_globe_1755061628572">\n <rect width="24" height="24" fill="white"></rect>\n </clipPath>\n </defs>\n</svg>',ut='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">\n <circle cx="12" cy="12" r="10" stroke="#6B7280" stroke-width="2" fill="none"></circle>\n <path d="M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z" stroke="#6B7280" stroke-width="2" fill="none"></path>\n</svg>',pt={Arabisk:"Ø§ÙØ¹Ø±Ø¨ÙØ©",Hviderussisk:"ÐелаÑÑÑкаÑ",Bengalsk:"বাà¦à¦²à¦¾",Bosnisk:"Bosanski",Bulgarsk:"ÐÑлгаÑÑки",Catalansk:"Català ",Kroatisk:"Hrvatski",Tjekkisk:"ÄeÅ¡tina",Nederlandsk:"Nederlands",Estisk:"Eesti",Finsk:"Suomi",Flamsk:"Vlaams","Tysk (Schweiz)":"Deutsch (Schweiz)","Græsk":"Îλληνικά",Hebraisk:"×¢×ר×ת",Hindi:"हिनà¥à¤¦à¥",Ungarsk:"Magyar",Indonesisk:"Bahasa Indonesia",Italiensk:"Ital
1iano",Japansk:"æ¥æ¬èª",Kannada:"à²à²¨à³à²¨à²¡",Koreansk:"íêµì´",Lettisk:"LatvieÅ¡u",Litauisk:"Lietuvių",Makedonsk:"ÐакедонÑки",Malaysisk:"Bahasa Melayu",Marathi:"मराठà¥",Norsk:"Norsk",Persisk:"ÙØ§Ø±Ø³Û",Polsk:"Polski",Portugisisk:"Português","Rumænsk":"RomânÄ",Russisk:"Ð ÑÑÑкий",Serbisk:"СÑпÑки",Slovakisk:"SlovenÄina",Slovensk:"SlovenÅ¡Äina",Svensk:"Svenska",Tagalog:"Tagalog",Tamil:"தமிழà¯",Telugu:"à°¤à±à°²à±à°à±",Tyrkisk:"Türkçe",Ukrainsk:"УкÑаÑнÑÑка",Urdu:"اردÙ",Vietnamesisk:"Tiếng Viá»t"};function mt(e,t){try{if("function"==typeof window.SKT){const t=window.SKT(e);if(t&&t!==e)return t}}catch(e){}return t}function ft(e,t){const n=e.querySelector(".dk-extended"),r=e.querySelector(".dk-expand-btn");if(!n||!r)return;n.classList.toggle("dk-extended--open",t),r.classList.toggle("dk-expand-btn--open",t),r.setAttribute("aria-expanded",t?"true":"false");const o=r.querySelector(".dk-expand-label");o&&(o.textContent=t?mt("lang.show_fewer_langs","Vis færre sprog"):mt("lang.show_more_langs","Vis flere sprog"))}function gt(e){const t=e.querySelector(".dk-dropdown");if(!t||t.querySelector(".dk-search-wrap"))return;const n=t.querySelector(".dk-custom-language");n&&n.remove();const r=t.querySelector(".dk-dropdown-divider");r&&r.remove();const o=document.createElement("div");o.className="dk-search-wrap";const i=document.createElement("input");i.type="text",i.className="dk-lang-search",i.setAttribute("autocomplete","off"),i.setAttribute("spellcheck","false"),i.placeholder=mt("wm.lang_search","Søg sprog..."),o.appendChild(i);let a=t.querySelector(".dk-dropdown-list");a||(a=document.createElement("div"),a.className="dk-dropdown-list",t.querySelectorAll(":scope > .dk-dropdown-item").forEach(e=>a.appendChild(e)),t.appendChild(a)),a.setAttribute("role","listbox");const l=document.createElement("button");l.type="button",l.className="dk-expand-btn",l.setAttribute("aria-expanded","false"),l.innerHTML=`<span class="dk-expand-label">${mt("lang.show_more_langs","Vis flere sprog")}</span><svg class="dk-expand-icon" width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M4 6L8 10L12 6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,a.appendChild(l);const s=document.createElement("div");s.className="dk-extended",a.appendChild(s);const c=document.createElement("div");c.className="dk-dropdown-item dk-custom-row",c.style.display="none",c.innerHTML=`\n <div class="dk-language-dropdown-icon dk-globe-icon">${ut}</div>\n <span class="dk-dropdown-text dk-custom-row-label"></span>\n `,a.appendChild(c),t.insertBefore(o,t.firstChild)}function ht(){document.querySelectorAll(".dk-dropdown").forEach(e=>{if(e.closest(".lang-pill-wrap"))return;if(e.querySelector(".dk-search-only"))return;const t=e.querySelector(".dk-extended")||e.querySelector(".dk-dropdown-list")||e;Object.keys(at).forEach(e=>{t.appendChild(function(e){const t=document.createElement("div");t.className="dk-dropdown-item dk-search-only",t.setAttribute("data-lang",e);const n=pt[e]||e;return t.setAttribute("data-search",(e+" "+n).toLowerCase()),t.innerHTML=`\n <div class="dk-language-dropdown-icon dk-globe-icon">${ut}</div>\n <span class="dk-dropdown-text">${n}</span>\n `,t}(e))})})}function vt(e,t,n=!1){try{localStorage.setItem("grammarBot_lang",e),localStorage.setItem("grammarBot_langName",t),localStorage.setItem("grammarBot_isCustom",n?"1":"0")}catch(e){console.warn("Failed to save language:",e)}}function yt(){return st}function wt(e){const t=Object.entries(lt).find(([t,n])=>n===e)?.[0];return t||e||"da"}function bt(){document.querySelectorAll(".dk-dropdown").forEach(e=>{e.classList.remove("dk-show"),e.querySelectorAll(".dk-dropdown-item").forEach(e=>e.classList.remove("dk-keyboard-focus"))}),document.querySelectorAll(".dk-language-select").forEach(e=>{e.classList.remove("dk-active")})}function kt(e){return Array.from(e.querySelectorAll(".dk-dropdown-item")).filter(e=>!e.classList.contains("dk-disabled")&&"none"!==e.style.display&&null!==e.offsetParent)}function St(e,t){const n=kt(e);
1if(n.forEach(e=>e.classList.remove("dk-keyboard-focus")),t>=0&&t<n.length){const e=n[t];e.classList.add("dk-keyboard-focus"),e.scrollIntoView({block:"nearest",behavior:"smooth"})}}function xt(e){const t=kt(e).findIndex(e=>e.classList.contains("dk-keyboard-focus"));return t>=0?t:-1}function Tt(e){const t=document.querySelector(".dk-dropdown.dk-show");if(!t)return;const n=kt(t);if(0!==n.length){if("ArrowDown"===e.key){e.preventDefault();const r=xt(t);return void St(t,r<n.length-1?r+1:0)}if("ArrowUp"===e.key){e.preventDefault();const r=xt(t);return void St(t,r<=0?n.length-1:r-1)}if("Enter"===e.key){const r=xt(t);return void(r>=0&&n[r]&&(e.preventDefault(),_t(n[r])))}"Escape"===e.key&&(e.preventDefault(),bt())}}function Lt(){if(ct){const e=wt(st);ct(e&&"string"==typeof e?e:"dansk")}}function Et(e,t){const n=e.value.trim();if(!n)return;const r=t.querySelector(".dk-language-text");r.removeAttribute("data-i18n"),r.textContent=n;const o=t.querySelector(".dk-language-icon");o&&(o.innerHTML=dt),st=lt[n]||n.toLowerCase(),window.dispatchEvent(new CustomEvent("ss:lang-changed",{detail:{code:st}})),window.dispatchEvent(new CustomEvent("sk-language-changed",{detail:{lang:st}})),vt(st,n,!0),e.value="",bt(),Lt()}function Ct(e,t){const n=e.value.trim().toLowerCase(),r=t.querySelector(".dk-dropdown");if(!r)return;const o=r.querySelector(".dk-dropdown-list")||r,i=r.querySelector(".dk-extended"),a=r.querySelector(".dk-expand-btn"),l=r.querySelector(".dk-custom-row"),s=Array.from(o.querySelectorAll(".dk-dropdown-item")).filter(e=>!e.classList.contains("dk-custom-row"));if(!n)return s.forEach(e=>e.style.display=""),i&&i.classList.remove("dk-extended--search"),a&&(a.style.display=""),void(l&&(l.style.display="none"));let c=!1;if(s.forEach(e=>{const t=(e.getAttribute("data-search")||e.getAttribute("data-lang")||e.textContent||"").trim().toLowerCase().includes(n);e.style.display=t?"":"none",t&&(c=!0)}),i&&i.classList.add("dk-extended--search"),a&&(a.style.display="none"),l)if(c)l.style.display="none";else{const t=e.value.trim().charAt(0).toUpperCase()+e.value.trim().slice(1),n=l.querySelector(".dk-custom-row-label");n&&(n.textContent=mt("lang.use_custom",'Brug "{x}"').replace("{x}",t)),l.dataset.customName=t,l.style.display=""}}function _t(e){if(e.classList.contains("dk-disabled"))return;const t=e.closest(".dk-language-select"),n=t.querySelector(".dk-language-text"),r=e.getAttribute("data-lang"),o=e.closest(".dk-dropdown");o&&o.querySelectorAll(".dk-dropdown-item").forEach(e=>{e.classList.remove("dk-selected"),e.style.display="flex"}),e.classList.add("dk-selected");const i=e.querySelector(".dk-dropdown-text, [data-i18n]"),a=i&&i.getAttribute("data-i18n");a?(n.setAttribute("data-i18n",a),n.textContent=window.SKT?window.SKT(a):pe(a)):i?(n.removeAttribute("data-i18n"),n.textContent=i.textContent):(n.removeAttribute("data-i18n"),n.textContent=r);const l=t.querySelector(".dk-language-icon"),s=e.querySelector(".dk-language-dropdown-icon");if(l&&s){const e=s.querySelector("svg");if(e){const t=e.cloneNode(!0);l.innerHTML="",l.appendChild(t)}}st=lt[r]||r,window.dispatchEvent(new CustomEvent("ss:lang-changed",{detail:{code:st}})),window.dispatchEvent(new CustomEvent("sk-language-changed",{detail:{lang:st}})),vt(st,r,!1);const c=t.querySelector(".dk-custom-input");c&&(c.value=""),Lt(),bt()}function At(e){e.stopPropagation()}function qt(e){e.target.closest(".dk-language-select")||bt()}function Mt(e="da",t){ct=t,document.querySelectorAll(".dk-language-select").forEach(gt),ht();const n=function(){try{const e=localStorage.getItem("grammarBot_lang"),t=localStorage.getItem("grammarBot_langName"),n="1"===localStorage.getItem("grammarBot_isCustom");if(e&&t)return{langCode:e,langName:t,isCustom:n}}catch(e){console.warn("Failed to load language:",e)}return null}();n?(st=n.langCode,document.querySelectorAll(".dk-language-select").forEach(e=>{const t=e.querySelector(".dk-language-text"),r=e.querySelector(".dk-language-icon");if(t){let r=null;const o=e.querySelector(".dk-dropdown");o&&o.querySelectorAll(".dk-dropdown-item[data-lang]").forEach(e=>{e.getAttribute("data-lang")===n.langName&&(r=e.querySelector(".dk-dropdown-text, [data-i18n]"))});const i=r&&r.getAttribute("data-i18n");i?(t.setAttribute("data-i18n",i),t.textContent=window.SKT?window.SKT(i):pe(i)):r?(t.removeAttribute("data-i18n"),t.textContent=r.textContent):(t.removeAttribute("data-i18n"),t.textContent=n.langName)}if(n.isCustom&&r)r.innerHTML=dt;
1else if(!n.isCustom){const t=e.querySelector(".dk-dropdown");t&&t.querySelectorAll(".dk-dropdown-item").forEach(e=>{if(e.getAttribute("data-lang")===n.langName){if(e.classList.add("dk-selected"),r){const t=e.querySelector(".dk-language-dropdown-icon svg");t&&(r.innerHTML="",r.appendChild(t.cloneNode(!0)))}}else e.classList.remove("dk-selected")})}})):st=e,document.addEventListener("click",qt),document.addEventListener("keydown",Tt),document.querySelectorAll(".dk-language-select").forEach(e=>{e.addEventListener("click",t=>function(e,t){if(e.target.closest(".dk-lang-search"))return;if(e.target.closest(".dk-expand-btn"))return;e.stopPropagation();const n=t.querySelector(".dk-dropdown"),r=n.classList.contains("dk-show");if(bt(),!r){n.classList.add("dk-show"),t.classList.add("dk-active");const e=t.querySelector(".dk-lang-search");if(e){e.value="",ft(n,!1),Ct(e,t);try{e.focus()}catch(e){}}const r=kt(n).findIndex(e=>e.classList.contains("dk-selected"));St(n,r>=0?r:0)}}(t,e));const t=e.querySelector(".dk-lang-search");t&&(t.addEventListener("keypress",n=>function(e,t,n){if("Enter"!==e.key)return;e.preventDefault();const r=n.querySelector(".dk-dropdown");if(!r)return;const o=r.querySelector(".dk-custom-row");if(o&&"none"!==o.style.display)return void Et(t,n);const i=kt(r).filter(e=>!e.classList.contains("dk-custom-row"));i.length>0&&_t(i[0])}(n,t,e)),t.addEventListener("click",At),t.addEventListener("input",()=>Ct(t,e)));const n=e.querySelector(".dk-expand-btn");n&&n.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation();const n=e.querySelector(".dk-dropdown"),r=n&&n.querySelector(".dk-extended");ft(n,!(r&&r.classList.contains("dk-extended--open")))});const r=e.querySelector(".dk-custom-row");r&&t&&r.addEventListener("click",n=>{n.stopPropagation(),Et(t,e)})}),document.querySelectorAll(".dk-dropdown-item:not(.dk-custom-row):not(.lang-pill-option)").forEach(e=>{e.addEventListener("click",t=>{t.stopPropagation(),_t(e)})}),Lt(),n&&(window.dispatchEvent(new CustomEvent("ss:lang-changed",{detail:{code:st}})),window.dispatchEvent(new CustomEvent("sk-language-changed",{detail:{lang:st}})))}function It(){return{da:"danish",en:"english",ge:"german",fr:"french",es:"spanish",sv:"swedish",no:"norwegian",fi:"finnish",pl:"polish",it:"italian",pt:"portuguese",nl:"dutch",tr:"turkish",ru:"russian",ar:"arabic",ja:"japanese",ko:"korean"}[yt()]||"danish"}function Bt(){const e=(yt()||"da").toLowerCase(),t={da:"Danish",en:"English",ge:"German",fr:"French",es:"Spanish"};return t[e]?t[e]:"English"}const Ht=new class{constructor(){this.currentLevel=2,this.modeIcons={1:'<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 20 21" fill="none">
1<path d="M16.2314 10.0855C16.2314 5.18792 12.7389 1.2146 8.43404 1.2146C4.12918 1.2146 0.636719 5.18792 0.636719 10.0855C0.636719 14.9831 4.12918 18.9564 8.43404 18.9564" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"></path><path d="M6.16406 10.8381H11.4404" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"></path><path d="M4.9248 13.5538L8.8779 4.92114L12.6132 13.5538" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"></path><path d="M10.2764 15.5739L12.8978 19.5472L19.1625 12.3533" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"></path></svg>',2:'<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 20 21" fill="none"><path d="M16.2314 10.0855C16.2314 5.18792 12.7389 1.2146 8.43404 1.2146C4.12918 1.2146 0.636719 5.18792 0.636719 10.0855C0.636719 14.9831 4.12918 18.9564 8.43404 18.9564" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"></path><path d="M6.16406 10.8381H11.4404" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"></path><path d="M4.9248 13.5538L8.8779 4.92114L12.6132 13.5538" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"></path><path d="M10.2764 15.5739L12.8978 19.5472L19.1625 12.3533" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"></path></svg>',3:'<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 20 21" fill="none">
1<path d="M16.2314 10.0855C16.2314 5.18792 12.7389 1.2146 8.43404 1.2146C4.12918 1.2146 0.636719 5.18792 0.636719 10.0855C0.636719 14.9831 4.12918 18.9564 8.43404 18.9564" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"></path><path d="M6.16406 10.8381H11.4404" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"></path><path d="M4.9248 13.5538L8.8779 4.92114L12.6132 13.5538" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"></path><path d="M10.2764 15.5739L12.8978 19.5472L19.1625 12.3533" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"></path></svg>'}}getLevelSubtitles(){return{1:pe("grammar.basicProofreading"),2:pe("grammar.fullProofreading"),3:pe("grammar.dyslexia")}}getLevelTooltips(){return{1:pe("grammar.tooltipBasic"),2:pe("grammar.tooltipStandard"),3:pe("grammar.tooltipMax")}}getModeNames(){return{1:pe("grammar.light"),2:pe("grammar.standard"),3:pe("grammar.max")}}getModeDescriptions(){return{1:pe("grammar.descBasic"),2:pe("grammar.descStandard"),3:pe("grammar.descMax")}}getSliderHTML(){return`\n <div class="correction-level-container">\n \x3c!-- Help Icon - Top Right --\x3e\n <button class="level-help-btn" id="levelHelpBtn" aria-label="${pe("grammar.helpLabel")}" type="button">\n <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <circle cx="12" cy="12" r="10"></circle>\n <path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"></path>\n <line x1="12" y1="17" x2="12.01" y2="17"></line>\n </svg>\n </button>\n <div class="level-help-tooltip" id="levelTooltip">${pe("grammar.tooltipStandard")}</div>\n\n <div class="level-header">\n <div class="level-subtitle" id="levelSubtitle">${pe("grammar.fullProofreading")}</div>\n </div>\n\n <div class="level-slider-wrapper">\n <input type="range" class="level-slider" id="correctionLevelSlider"\n min="1" max="3" value="2" step="1">\n </div>\n\n <div class="level-labels">\n <span class="level-label" data-level="1">${pe("grammar.light")}</span>\n <span class="level-label" data-level="2">${pe("grammar.standard")}</span>\n <span class="level-label" data-level="3">${pe("grammar.max")}</span>\n </div>\n </div>\n `}getModeName(e){return this.getModeNames()[e]||pe("grammar.standard")}getModeDescription(e){return this.getModeDescriptions()[e]||pe("grammar.descStandard")}getModeIcon(e){return this.modeIcons[e]||this.modeIcons[2]}attachListeners(){const e=document.getElementById("correctionLevelSlider"),t=document.querySelectorAll(".level-label");e&&e.addEventListener("input",e=>{this.selectLevel(parseInt(e.target.value),!0)}),t.forEach(e=>{e.addEventListener("click",e=>{this.selectLevel(parseInt(e.currentTarget.dataset.level),!0)})})}selectLevel(e,t=!0){if(this.currentLevel=e,window.grammarModelDepth=e,t){const t=1===e?"basic":2===e?"plus":"max";console.log("Grammar Mode Slider - Saving to cookie:",t,"for level:",e),"function"==typeof window.setCookie&&window.setCookie("model_depth_choice",t,30)}this.updateSliderUI(e)}updateSliderUI(e){const t=document.getElementById("correctionLevelSlider"),n=document.querySelectorAll(".level-label"),r=document.getElementById("levelSubtitle"),o=document.getElementById("levelTooltip");t&&(t.value=e),n.forEach((t,n)=>{t.classList.toggle("active",n+1===e)});const i=this.getLevelSubtitles();r&&i[e]&&(r.textContent=i[e]);const a=this.getLevelTooltips();o&&a[e]&&(o.textContent=a[e])}getCurrentLevel(){return this.currentLevel}initializeFromCookie(){const e="function"==typeof window.getCookie?window.getCookie("model_depth_choice"):null,t=window.innerWidth<=767||/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);console.log("Grammar Mode Slider - Initializing from cookie:",e);let n=2;n=t?2:"basic"===e?1:"plus"===e?2:"max"===e?3:2,console.log("Grammar Mode Slider - Setting level to:",n),this.selectLevel(n,null===e)}getButtonHTML(e){const t=this.getModeNames(),n=this.getModeDescriptions(),r=this.modeIcons[e]||this.modeIcons[2];return`<span>${t[e]||t[2]}</span>${r}<span class="explanation-premium-plus-tooltip">${n[e]||n[2]}</span>`}getNextLevel(e){return 1===e?2:2===e?3:1}getPreviousLevel(e){return 3===e?2:2===e?1:3}};function Kt(e,t,n=30){const r=new Date;r.setTime(r.getTime()+24*n*60*60*1e3),document.cookie=`${e}=${t};expires=${r.toUTCString()};path=/`}function Dt(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}function Pt(e){if(Dt()){return e.replace(/:/g,";")}return e}function Nt(e){if(!Dt())return e;const t=document.createElement("div");t.innerHTML=e;const n=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,null,!1);let r;for(;r=n.nextNode();){r.textContent;r.textContent=r.textContent.replace(/:/g,";"),r.textContent}return t.innerHTML}function jt(e){e.match(/<([a-z0-9]+)[\s>]/gi);const t=document.createElement("div");t.innerHTML=e;t.querySelectorAll("p").forEach((e,t)=>
1{const n=e.innerHTML.trim(),r=e.textContent.trim();(" "===n||" "===n||" "===r&&n.includes(" "))&&(e.setAttribute("data-empty-line","true"),e.innerHTML="")}),t.querySelectorAll("br"),function(){const e=Array.from(t.childNodes);if(e.length>=2&&e[0].nodeType===Node.ELEMENT_NODE&&"STRONG"===e[0].tagName&&"P"===e[1].tagName){const n=e[1];1===n.childNodes.length&&"BR"===n.firstChild.tagName&&t.removeChild(n)}}();let n="",r=!1,o=0,i=[" ⢠"," - "," * "];const a={H1:{before:"\n\n",after:"\n\n",process:e=>e.toUpperCase()},H2:{before:"\n\n",after:"\n\n",process:e=>e},H3:{before:"\n\n",after:"\n\n",process:e=>e},H4:{before:"\n\n",after:"\n\n",process:e=>e},H5:{before:"\n\n",after:"\n\n",process:e=>e},H6:{before:"\n\n",after:"\n\n",process:e=>e},P:{before:e=>(e.hasAttribute("data-empty-line"),"\n"),after:e=>e.hasAttribute("data-empty-line")?"\n":"\n\n",process:e=>e},DIV:{before:"",after:"\n",process:e=>e},BLOCKQUOTE:{before:"\n\n> ",after:"\n\n",process:e=>e},UL:{before:"\n",after:"\n",process:e=>e,onEnter:()=>{r=!0,o++},onExit:()=>{r=o>1,o--}},OL:{before:"\n",after:"\n",process:e=>e,onEnter:()=>{r=!0,o++},onExit:()=>{r=o>1,o--}},LI:{before:e=>{if("OL"===e.parentNode.tagName){const t=Math.max(0,2*o),n=Array.from(e.parentNode.children).indexOf(e)+1;return`\n${" ".repeat(t)}${n}. `}{const e=2*(o-1),t=Math.max(0,e),n=Math.max(0,Math.min(o-1,i.length-1)),r=i[n];return`\n${" ".repeat(t)}${r}`}},after:"",process:e=>e},TR:{before:"",after:"\n",process:e=>e},TD:{before:"",after:"\t",process:e=>e},TH:{before:"",after:"\t",process:e=>e.toUpperCase()},TABLE:{before:"\n\n",after:"\n\n",process:e=>e},STRONG:{before:"",after:"",process:e=>e},B:{before:"",after:"",process:e=>e},EM:{before:"",after:"",process:e=>e},I:{before:"",after:"",process:e=>e},CODE:{before:" `",after:"` ",process:e=>e},PRE:{before:"\n```\n",after:"\n```\n",process:e=>e},SPAN:{before:"",after:"",process:e=>e},MARK:{before:"",after:"",process:e=>e},A:{before:"",after:"",process:e=>e}};return function e(t,o=0){if(t&&"SCRIPT"!==t.tagName&&"STYLE"!==t.tagName)if(t.nodeType===Node.ELEMENT_NODE){const r=t.tagName.toUpperCase(),i=a[r];if(i){if("function"==typeof i.before){const e=i.before(t);n+=e}else n+=i.before;if(i.onEnter&&i.onEnter(),/^H[1-6]$/.test(r)){const e=t.textContent.trim(),r=i.process(e);n+=r}else if("P"===r&&t.hasAttribute("data-empty-line"));else for(let n=0;n<t.childNodes.length;n++)e(t.childNodes[n],o+1);if(i.onExit&&i.onExit(),"function"==typeof i.after){const e=i.after(t);n+=e}else n+=i.after}else for(let n=0;n<t.childNodes.length;n++)e(t.childNodes[n],o+1)}else if(t.nodeType===Node.TEXT_NODE){const e=t.textContent;if(e){n+=e;const o=t.parentNode.tagName?t.parentNode.tagName.toUpperCase():"",i=["SPAN","STRONG","EM","B","I","MARK","A"].includes(o),a=t.nextSibling,l=a&&a.nodeType===Node.ELEMENT_NODE&&["SPAN","STRONG","EM","B","I","MARK","A"].includes(a.tagName.toUpperCase());!(r||i||l||["LI","H1","H2","H3","H4","H5","H6","CODE","PRE"].includes(o)||e.endsWith(" ")||e.endsWith("\n"))&&(n+=" ")}}}(t),(n.match(/__BR_PLACEHOLDER__/g)||[]).length,n=n.replace(/__BR_PLACEHOLDER__/g,"\n"),n.length,n=n.replace(/\n{3,}/g,"\n\n").replace(/ {2,}/g," ").replace(/\n([ ]*)(â¢|-|\*|\d+\.) {2,}/g,"\n$1$2 ").trim(),n.length,n}function Rt(e,r="unknown"){try{"function"==typeof t&&(e=t(e))}catch(e){}try{"function"==typeof n&&(e=n(e))}catch(e){}try{e=function(e){const t=document.createElement("div");return t.innerHTML=e,t.querySelectorAll('img.emoji, img[role="img"]').forEach(e=>{const t=e.getAttribute("alt");if(t&&/[\u{1F600}-\u{1F64F}\u{1F300}-\u{1F5FF}\u{1F680}-\u{1F6FF}\u{1F700}-\u{1F77F}\u{1F780}-\u{1F7FF}\u{1F800}-\u{1F8FF}\u{1F900}-\u{1F9FF}\u{1FA00}-\u{1FA6F}\u{1FA70}-\u{1FAFF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}]/u.test(t)){const n=document.createTextNode(t);e.parentNode.replaceChild(n,e)}}),t.innerHTML}(e)}catch(e){}try{e=function(e){const t=(new DOMParser).parseFromString(e,"text/html");[...t.querySelectorAll("ol")].forEach((e,t)=>{const n=document.createElement("ul");let r=!1;e.children.length,[...e.children].forEach((e,t)=>{"bullet"===e.getAttribute("data-list")&&(e.removeAttribute("data-list"),n.appendChild(e.cloneNode(!0)),e.remove(),r=!0)}),r&&(0===e.children.length?e.replaceWith(n):e.parentNode.insertBefore(n,e))});const n=t.body.innerHTML;return t.querySelectorAll("ol").length,t.querySelectorAll("ul").length,n}(e)}catch(e){}try{e=function(e){const t=document.createElement("div");return t.innerHTML=e,t.querySelectorAll("p").forEach((e,t)=>{("<br>"===e.innerHTML.trim()||"<br/>"===e.innerHTML.trim()||"<br />"===e.innerHTML.trim()||1===e.childNodes.length&&e.firstChild.nodeType===Node.ELEMENT_NODE&&"BR"===e.firstChild.tagName&&""===e.textContent.trim()||""===e.textContent.trim()&&""===e.innerHTML.trim())&&(e.innerHTML=" ")}),t.innerHTML}(e)}catch(e){}return e}async function Ft(e,t){if(navigator.clipboard?.write)try{return await navigator.clipboard.write([new ClipboardItem({"text/html":new Blob([e],{type:"text/html"}),"text/plain":new Blob([t],{type:"text/plain"})})]),!0}catch(e){}try{return await navigator.clipboard.writeText(t),!0}catch(e){return!1}}function Ot(e){if(!e)return"";let t=e.replace(/^%%\s*:?\s*/i,"").trim();return t=t.replace(/<[^>]*>/g,"").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),t=t.replace(/^#{1,6}\s+/gm,"").replace(/\*\*(.*?)\*\*/g,"$1").replace(/__(.*?)__/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/_(.*?)_/g,"$1").replace(/~~(.*?)~~/g,"$1").replace(/```[\s\S]*?```/g,"").replace(/`([^`]+)`/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/^[-*]{3,}$/gm,"").replace(/^>\s*/gm,"").replace(/^[\s]*[-*+]\s+/gm,"").replace(/^[\s]*\d+\.\s+/gm,"").replace(/\n\s*\n/g,"\n").replace(/[ \t]+/g," ").trim(),t=t.replace(/["'""'':]/g,""),t}function Ut(e,n){try{const r=n?n():window.getSelection();if(0===r.rangeCount||r.isCollapsed)return Ot(e);const o=r.getRangeAt(0).cloneContents(),i=document.createElement("div");i.appendChild(o);let a=i.innerHTML;t&&(a=t(a));const l=function(e){const t=document.createElement("div");t.innerHTML=e;const n=[],r=Array.from(t.childNodes);if(0===r.length)return(t.textContent||t.innerText||"").trim();
1return r.forEach(e=>{if(e.nodeType===Node.TEXT_NODE){const t=e.textContent.trim();t&&n.push(t)}else if(e.nodeType===Node.ELEMENT_NODE){const t=function(e){if(!e)return"";const t=e.cloneNode(!0);return(t.textContent||t.innerText||"").replace(/\s+/g," ").trim()}(e);t&&n.push(t)}}),n.join("\n").trim()}(a);return l||Ot(e)}catch(t){return Ot(e)}}"undefined"!=typeof module&&module.exports&&(module.exports=Ht),"undefined"!=typeof window&&(window.grammarModeSlider=Ht),"undefined"!=typeof window&&(window.selectGrammarMode=function(e,t=!0){window.grammarModeSlider?window.grammarModeSlider.selectLevel(e,t):(window.grammarModelDepth=e,t&&Kt("model_depth_choice",1===e?"basic":2===e?"plus":"max",30))},window.getCookie=function(e){const t=e+"=",n=document.cookie.split(";");for(let e=0;e<n.length;e++){let r=n[e].trim();if(0===r.indexOf(t))return r.substring(t.length)}return null},window.setCookie=Kt),document.addEventListener("DOMContentLoaded",function(){setTimeout(()=>{const e=document.getElementById("grammarModeContainer");e&&window.grammarModeSlider&&(e.innerHTML=window.grammarModeSlider.getSliderHTML(),window.grammarModeSlider.attachListeners(),window.grammarModeSlider.initializeFromCookie())},100)});function $t(e,t,n=1e3){let r=String(t||"").trim();for(;r.length>n;){let t=r.lastIndexOf(" ",n);t<Math.floor(.6*n)&&(t=n);const o=r.slice(0,t).trim();o&&e.push(o),r=r.slice(t).trim()}r&&e.push(r)}const zt=window.HGF_ajax_object?.ajax_url||window.ajaxurl||"/wp-admin/admin-ajax.php",Gt=["mads","lars","anders","sofie","freja","ida"];let Vt={isPlaying:!1,currentAudio:null,currentAudioUrl:null,isPaused:!1,currentTime:0,duration:0,playbackSpeed:1,isProcessing:!1,isSpeedPanelOpen:!1,allChunks:[],currentChunkIndex:0,currentPlayingChunkIndex:-1,currentPlayingChunkText:"",audioQueue:[],isFetching:!1,currentChunkRequest:null,isCancelled:!1,isWaitingForNextChunk:!1,chunkRetryCount:{},_currentLanguage:null,_SB_ajax_object:null},Wt=1,Jt=null,Zt="idle",Yt=!1,Qt="";const Xt=()=>Ut(Qt);let en=null,tn=0;function nn(){if(tn+=1,en){try{en.abort()}catch(e){}en=null}}async function rn(e,t,n){const r=function(e){return String(e||"").replace(/\s+/g," ").trim().split(" ").filter(Boolean).slice(0,80).join(" ")}(e);if(r.length<3)return t;if("undefined"!=typeof navigator&&!1===navigator.onLine)return t;const o=await async function(){try{if(window.SSGrammarAuth&&"function"==typeof window.SSGrammarAuth.getAuthToken){const e=await window.SSGrammarAuth.getAuthToken();if("string"==typeof e&&e)return e}if(window.SSAuth&&"function"==typeof window.SSAuth.token){const e=await window.SSAuth.token();if("string"==typeof e&&e)return e}if(window._supabase&&window._supabase.auth&&"function"==typeof window._supabase.auth.getSession){const e=await window._supabase.auth.getSession(),t=e&&e.data?e.data.session:null;return t&&t.access_token?t.access_token:""}}catch(e){}return""}();if(!o)return t;if("function"==typeof n&&!n())return t;const i="undefined"!=typeof AbortController?new AbortController:null;en=i;const a=i?setTimeout(function(){try{i.abort()}catch(e){}},12e3):null;try{const e=await fetch("/robots/skrivebord/php/tts/doc-lang-classify.php",{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json",Authorization:"Bearer "+o},body:JSON.stringify({text:r}),signal:i?i.signal:void 0}),n=await e.json().catch(function(){return null}),a=e.ok&&n&&!0===n.ok&&n.data?n.data.language:"";return"string"==typeof a&&a.trim()?"undefined"!=typeof TTSEngine&&TTSEngine&&"function"==typeof TTSEngine.normalizeLanguage?TTSEngine.normalizeLanguage(a,t):a.trim():t}catch(e){return t}finally{a&&clearTimeout(a),en===i&&(en=null)}}async function on(e,t,n,o){const i=Date.now();if(Vt.isCancelled)throw new Error("Request was cancelled");const a=t&&"string"==typeof t?t.trim():"English",l="male"===h()?"Male":"Female",s=function(){try{const e=window.localStorage.getItem("ss_tts_voice_variant")||"";if(Gt.includes(e))return e}catch(e){}return"male"===h()?"mads":"sofie"}(),c="undefined"!=typeof TTSEngine&&"function"==typeof TTSEngine.normalizeSpeechText?TTSEngine.normalizeSpeechText:function(e){return e},d=new FormData;d.append("action","hgf_important_secure_bots_text_to_speech"),d.append("nonce",window.HGF_ajax_object?.nonce||""),d.append("text",r(c(e.trim(),{lang:a}))),d.append("lang",a),d.append("gender",l),d.append("voice",s);const u=new AbortController;
1Vt.currentChunkRequest=u;const p="undefined"!=typeof TTSEngine&&TTSEngine.DEFAULT_TTS_FETCH_TIMEOUT_MS||15e3;let m=!1;const f=setTimeout(()=>{m=!0;try{u.abort()}catch(e){}},p);try{const e=await window.fetch(zt,{method:"POST",body:d,signal:u.signal});if(Vt.isCancelled)throw Vt.currentChunkRequest=null,new Error("Request was cancelled");if(!e.ok){const t=await e.text().catch(()=>"Unknown error");throw console.error("â WordPress AJAX error response:",t),new Error(`WordPress AJAX Error: ${e.status} - ${t}`)}const t=await e.blob(),n=Date.now()-i;if(0===t.size)throw Vt.currentChunkRequest=null,new Error("Received empty audio file");const r=URL.createObjectURL(t);return Vt.currentChunkRequest=null,{audioUrl:r,time:n}}catch(e){if(Vt.currentChunkRequest=null,m)throw new Error("TTS request timed out after "+p+"ms");if("AbortError"===e.name)throw new Error("Request aborted");throw e}finally{clearTimeout(f)}}async function an(e){if(Vt.isFetching||Vt.currentChunkIndex>=Vt.allChunks.length||Vt.isCancelled)return;Vt.isFetching=!0;const t=Vt.currentChunkIndex,n=Vt.allChunks[t];Vt.chunkRetryCount[t]||(Vt.chunkRetryCount[t]=0);try{const r=await on(n,e,0,Vt.allChunks.length);if(Vt.isCancelled)return void(Vt.isFetching=!1);Vt.chunkRetryCount[t]=0,Vt.audioQueue.push(r.audioUrl),Vt.currentChunkIndex++,Vt.isFetching=!1,Vt.currentChunkRequest=null,(!Vt.isPlaying||Vt.isWaitingForNextChunk)&&Vt.audioQueue.length>0&&!Vt.isCancelled&&(Vt.isProcessing=!1,ln())}catch(n){if(Vt.isFetching=!1,Vt.currentChunkRequest=null,Vt.isCancelled||"Request was cancelled"===n.message||"Request aborted"===n.message)return;Vt.chunkRetryCount[t]<1?(Vt.chunkRetryCount[t]++,console.warn(`â ï¸ [Chunk ${t+1}] Failed: ${n.message}`),await new Promise(e=>setTimeout(e,1e3)),Vt.isCancelled||await an(e)):(console.error(`â [Chunk ${t+1}] Failed after retry: ${n.message}`),console.error(` Skipping chunk ${t+1} and moving to next chunk...`),Vt.currentChunkIndex++,Vt.currentChunkIndex<Vt.allChunks.length&&!Vt.isCancelled&&an(e))}}function ln(){if(0===Vt.audioQueue.length)return Vt.currentChunkIndex<Vt.allChunks.length?(Vt.isWaitingForNextChunk=!0,Vt.isPlaying=!1,void(Zt="loading")):(Vt.isPlaying=!1,Vt.isWaitingForNextChunk=!1,Vt.isProcessing=!1,Vt.currentChunkRequest=null,Yt=!1,Vt.currentPlayingChunkIndex=-1,Vt.currentPlayingChunkText="",void(Zt="idle"));Vt.isWaitingForNextChunk=!1,Vt.isPlaying=!0;const e=Vt.audioQueue.shift(),t=Math.max(0,Vt.currentChunkIndex-Vt.audioQueue.length-1);if(Vt.currentPlayingChunkIndex=t,Vt.currentPlayingChunkText=Vt.allChunks[t]||"",Jt)try{Jt.pause(),Jt.onended=null,Jt.ontimeupdate=null,Jt.onerror=null}catch(e){}const n=new Audio(e);g(n),Jt=n,Vt.currentAudio=n,Vt.currentAudioUrl=e,n.playbackRate=Wt,Zt="playing";let r=!1;n.ontimeupdate=()=>{if(!r&&Vt.currentChunkIndex<Vt.allChunks.length&&!Vt.isFetching){(n.currentTime>=11||n.duration>0&&n.currentTime/n.duration>=.8)&&(r=!0,Vt._currentLanguage&&an(Vt._currentLanguage))}},n.onended=()=>{n.ontimeupdate=null,ln()},n.onerror=e=>{if(console.error("Audio playback error:",e),Vt.isPlaying=!1,Vt.isProcessing=!1,Vt.isFetching=!1,Vt.isWaitingForNextChunk=!1,Vt.currentChunkRequest){try{Vt.currentChunkRequest.abort()}catch(e){}Vt.currentChunkRequest=null}Zt="idle"},n.play().catch(e=>{if(console.error("Audio play error:",e),Vt.isPlaying=!1,Vt.isProcessing=!1,Vt.isFetching=!1,Vt.isWaitingForNextChunk=!1,Vt.currentChunkRequest){try{Vt.currentChunkRequest.abort()}catch(e){}Vt.currentChunkRequest=null}Zt="idle"})}async function sn(){if(!Qt.trim())return;if(Vt.isProcessing)return;const e=Xt();if(!e.trim())return;const t=Date.now();Vt.allChunks=[],Vt.currentChunkIndex=0,Vt.audioQueue=[],Vt.isPlaying=!1,Vt.isFetching=!1,Vt.isCancelled=!1,Vt.isWaitingForNextChunk=!1,Vt.currentPlayingChunkIndex=-1,Vt.currentPlayingChunkText="",Vt.chunkRetryCount={},Vt.isProcessing=!0,Vt.isPaused=!1,Yt=!0,Zt="loading";const n=function(){const e=function(e){if(!e)return"";const t=String(e).trim();if(!t)return"";if("undefined"!=typeof TTSEngine&&TTSEngine&&"function"==typeof TTSEngine.normalizeLanguage){const e="__unknown_tts_language__",n=TTSEngine.normalizeLanguage(t,e);if(n&&n!==e)return n}const n={da:"Danish",danish:"Danish",en:"English",english:"English",de:"German",ge:"German",german:"German",fr:"French",french:"French",es:"Spanish",spanish:"Spanish",sv:"Swedish",swedis
1h:"Swedish",no:"Norwegian",nb:"Norwegian",nn:"Norwegian",norwegian:"Norwegian",fi:"Finnish",finnish:"Finnish",pl:"Polish",polish:"Polish",it:"Italian",italian:"Italian",pt:"Portuguese",portuguese:"Portuguese",nl:"Dutch",dutch:"Dutch",tr:"Turkish",turkish:"Turkish",ru:"Russian",russian:"Russian",ar:"Arabic",arabic:"Arabic",ja:"Japanese",japanese:"Japanese",ko:"Korean",korean:"Korean"};return n[t.split("-")[0].toLowerCase()]||n[t.toLowerCase()]||""};try{if("undefined"!=typeof localStorage){const t=localStorage.getItem("ss_chat_lang");if(t){const n=JSON.parse(t),r=n&&e(n.ttsName);if(r)return r;const o=n&&e(n.code);if(o)return o}}}catch(e){}const t="undefined"!=typeof window?window:{},n=e(t.__CHAT_LANG_NAME);if(n)return n;return e(t.__CHAT_LANG)||Bt()}();Vt._currentLanguage=n;const r=++tn,o=await rn(e,n,function(){return r===tn&&!Vt.isCancelled});if(r!==tn||Vt.isCancelled)return;Vt._currentLanguage=o;const i="undefined"!=typeof TTSEngine&&"function"==typeof TTSEngine.normalizeSpeechText?TTSEngine.normalizeSpeechText:function(e){return e};Vt.allChunks=function(e,t=60){if(!e||""===e.trim())return[];const n=e.match(/[^.!?,;\n]+[.!?,;\n]+|[^.!?,;\n]+$/g)||[e],r=[];let o="";for(let e=0;e<n.length;e++){const i=n[e].trim();i&&(i.split(/\s+/).length,o=o?o+" "+i:i,(o.split(/\s+/).length>=t||o.length>=1e3)&&($t(r,o),o=""))}return o.trim()&&($t(r,o),o.split(/\s+/).length),r.forEach((e,t)=>{e.split(/\s+/).length}),r}(e).filter(e=>""!==i(String(e).trim(),{lang:o}).trim()),Vt.allChunks.length>0?an(o).then(()=>{}).catch(e=>{const n=Date.now()-t;console.error(`\nâ Error after ${n}ms: ${e.message}`),Vt.isProcessing=!1,Vt.isPlaying=!1,Yt=!1,Zt="idle"}):(Vt.isProcessing=!1,Vt.isPlaying=!1,Yt=!1,Zt="idle")}function cn(){Jt&&"playing"===Zt&&(Jt.pause(),Zt="paused",Vt.isPlaying=!1,Vt.isPaused=!0)}function dn(){Jt&&"paused"===Zt&&Jt.play().then(()=>{Zt="playing",Vt.isPlaying=!0,Vt.isPaused=!1,Jt.playbackRate=Wt}).catch(()=>pn())}function un(){if(nn(),Vt.isCancelled=!0,Vt.isFetching=!1,Vt.isWaitingForNextChunk=!1,Vt.currentChunkRequest&&Vt.currentChunkRequest.abort)try{Vt.currentChunkRequest.abort()}catch(e){}if(Vt.currentChunkRequest=null,Vt.audioQueue=[],Vt.allChunks=[],Vt.currentChunkIndex=0,Vt.currentPlayingChunkIndex=-1,Vt.currentPlayingChunkText="",Jt&&(Jt.pause(),Jt.currentTime=0,Jt.ontimeupdate=null,Jt=null),Vt.currentAudio=null,Vt.currentAudioUrl){try{URL.revokeObjectURL(Vt.currentAudioUrl)}catch(e){}Vt.currentAudioUrl=null}Vt.isPlaying=!1,Vt.isPaused=!1,Vt.isProcessing=!1,Vt.isCancelled=!1,pn()}function pn(){Zt="idle",Yt=!1}function mn(){if(nn(),Vt.isCancelled=!0,Vt.isFetching=!1,Vt.isWaitingForNextChunk=!1,Vt.currentChunkRequest&&Vt.currentChunkRequest.abort)try{Vt.currentChunkRequest.abort()}catch(e){}if(Vt.currentChunkRequest=null,Vt.audioQueue=[],Vt.allChunks=[],Vt.currentChunkIndex=0,Vt.currentPlayingChunkIndex=-1,Vt.currentPlayingChunkText="",Jt&&(Jt.pause(),Jt.currentTime=0,Jt.ontimeupdate=null,Jt=null),Vt.currentAudio=null,Vt.currentAudioUrl){try{URL.revokeObjectURL(Vt.currentAudioUrl)}catch(e){}Vt.currentAudioUrl=null}Vt.isPlaying=!1,Vt.isPaused=!1,Vt.isProcessing=!1,Vt.isCancelled=!1,Zt="idle",Yt=!1}function fn(){const e=window.quill1;if(!e)return;const t=e.getText().trim().length>0,n=document.getElementById("readBtn"),r=document.getElementById("copyBtn"),o=document.getElementById("downloadBtnQuill");n&&(n.disabled=!t),r&&(r.disabled=!t),o&&(o.disabled=!t)}function gn(e,t,n,r){const o=e.getSelection();if(!o)return;const i=e.getFormat(o);i.bold?t.classList.add("active"):t.classList.remove("active"),i.italic?n.classList.add("active"):n.classList.remove("active"),"bullet"===i.list?r.classList.add("active"):r.classList.remove("active")}"undefined"!=typeof window&&(window.handleSelectionTTS=function(){return async function(){if(!Yt||Vt.isPlaying||Vt.isPaused)switch(Xt(),Zt){case"loading":un();break;case"playing":cn();break;case"paused":dn();break;default:await sn()}else mn()}()},window.pauseSelectionTTS=function(){return cn()},window.resumeSelectionTTS=function(){return dn()},window.stopSelectionTTS=function(){return un()},window.setSelectionTTSpeed=function(e){return function(e){Wt=e,Vt.playbackSpeed=e,!Jt||"playing"!==Zt&&"paused"!==Zt||(Jt.playbackRate=e)}(e)},window.getSelectionTTSState=function(){return{...Vt}},window.getPlaybackSpeed=function(){return Wt},window.getIsSpeedPanelOpen=function(){return!1},window.cleanupSelectionTTS=mn,window.updateSelectionTTSSelectedText=function(e){Qt=e});const hn=new WeakSet;function vn(e={}){const t=e.window||globalThis.window,n=e.document||t.document,r=e.fetch||((...e)=>t.fetch(...e)),o=e.alert||((...e)=>t.alert(...e)),i=e.MutationObserver||t.MutationObserver,a=e.console||t.console;if(!n.getElementById("ss-sidebar-wrapper"))return!1;if(hn.has(n))return!1;hn.add(n);const l=n.querySelector(".new-korrektur");l&&l.classList.add("ss-has-sidebar");const s=n.getElementById("ss-profile-btn"),c=n.getElementById("ss-dropdown"),d=n.getElementById("ss-dropdown-backdrop"),u=n.getElementById("ss-mobile-more-btn"),p=n.getElementById("ss-mobile-menu");let m=!1;const f=n.createElement("div");f.className="ss-tooltip",n.body.appendChild(f);const g=n.querySelectorAll(".ss-nav-item[data-label], .ss-profile-btn");function h(e){if(m)return;if(c&&c.classList.contains("is-active"))return;const n=e.dataset.label||"Menu",r=e.getBoundingClientRect();let o=r.top+r.height/2;f.textContent=n;
1const i=t.innerHeight-18;o=Math.max(18,Math.min(i,o)),f.style.top=`${o}px`,e.classList.contains("is-active")?f.classList.add("is-active"):f.classList.remove("is-active"),f.classList.add("is-visible")}function v(){f.classList.remove("is-visible")}let y=null;function w(){c&&d&&s&&(c.classList.remove("is-active"),d.classList.remove("is-active"),s.setAttribute("aria-expanded","false"),m=!0,s.focus(),f.classList.remove("is-visible"),setTimeout(()=>{m=!1},200))}t.matchMedia("(hover: hover)").matches&&g.forEach(e=>{e.addEventListener("mouseenter",()=>{clearTimeout(y),y=setTimeout(()=>h(e),150)}),e.addEventListener("mouseleave",()=>{clearTimeout(y),v()}),e.addEventListener("focus",()=>h(e)),e.addEventListener("blur",v)}),c&&n.body.appendChild(c),d&&n.body.appendChild(d),s&&c&&d&&(s.addEventListener("click",e=>{e.stopPropagation(),c.classList.contains("is-active")?w():function(){if(!s||!c||!d)return;const e=s.getBoundingClientRect();c.style.left=`${e.right+8}px`,c.style.bottom=t.innerHeight-e.bottom+2+"px",c.classList.add("is-active"),d.classList.add("is-active"),s.setAttribute("aria-expanded","true"),f.classList.remove("is-visible");const n=c.querySelector("a, button");n&&n.focus()}()}),d.addEventListener("click",w),t.addEventListener("resize",()=>{if(!c.classList.contains("is-active"))return;const e=s.getBoundingClientRect();c.style.left=`${e.right+8}px`,c.style.bottom=t.innerHeight-e.bottom+2+"px"}),c.querySelectorAll("a").forEach(e=>{e.addEventListener("click",w)}));let b=!1;function k(){p&&u&&(p.classList.remove("is-active"),p.setAttribute("aria-hidden","true"),n.body.style.overflow="",n.body.style.paddingRight="",u.classList.remove("is-active"),u.focus())}if(u&&p){u.addEventListener("keydown",e=>{"Enter"!==e.key&&" "!==e.key||(b=!0)}),u.addEventListener("click",function(){if(!p||!u)return;p.classList.add("is-active"),p.setAttribute("aria-hidden","false");const e=t.innerWidth-n.documentElement.clientWidth;if(n.body.style.overflow="hidden",n.body.style.paddingRight=`${e}px`,u.classList.add("is-active"),b){const e=p.querySelector("a, button");e&&e.focus(),b=!1}}),p.addEventListener("click",e=>{e.target===p&&k()}),p.querySelectorAll("a").forEach(e=>{e.addEventListener("click",k)});const e=p.querySelector(".ss-mobile-menu-content");let r=0,o=0,i=!1;e&&(e.addEventListener("touchstart",t=>{e.scrollTop<=0&&(r=t.touches[0].clientY,o=r,i=!0,e.style.transition="none")},{passive:!0}),e.addEventListener("touchmove",t=>{if(!i)return;o=t.touches[0].clientY;const n=o-r;n>0&&(e.style.transform=`translateY(${n}px)`)},{passive:!0}),e.addEventListener("touchend",()=>{if(!i)return;i=!1;const t=o-r;e.style.transition="",t>100&&k(),e.style.transform=""}))}if(n.addEventListener("keydown",e=>{"Escape"===e.key&&(c&&c.classList.contains("is-active")&&w(),p&&p.classList.contains("is-active")&&k())}),c){const e=c.querySelectorAll("a, button"),t=e[0],r=e[e.length-1];c.addEventListener("keydown",e=>{"Tab"===e.key&&t&&r&&(e.shiftKey?n.activeElement===t&&(e.preventDefault(),r.focus()):n.activeElement===r&&(e.preventDefault(),t.focus()))})}const S=n.getElementById("ss-darkmode-btn"),x=n.getElementById("ss-mobile-darkmode-btn"),T=x?x.querySelector(".ss-darkmode-label"):null,L=S?S.querySelector(".ss-darkmode-label-desktop"):null;function E(){const e=n.documentElement.classList.contains("wp-dark-mode-active")||n.body.classList.contains("wp-dark-mode-active")?"function"==typeof t.__t?t.__t("dropdown.lightMode"):"Lys tilstand":"function"==typeof t.__t?t.__t("dropdown.darkMode"):"Mørk tilstand";T&&(T.textContent=e),L&&(L.textContent=e)}function C(e){e.preventDefault();const t=n.querySelector(".wp-dark-mode-switch");t&&t.click(),c&&c.classList.contains("is-active")&&w(),setTimeout(E,50)}E(),x&&x.addEventListener("click",C),S&&S.addEventListener("click",C);const _=new i(e=>{e.forEach(e=>{"class"===e.attributeName&&E()})});_.observe(n.documentElement,{attributes:!0,attributeFilter:["class"]}),_.observe(n.body,{attributes:!0,attributeFilter:["class"]});const A=n.getElementById("ss-language-btn"),q=n.getElementById("ss-mobile-language-btn");function M(e){e.preventDefault(),"function"==typeof t.__toggleUILang&&t.__toggleUILang(),c&&c.classList.contains("is-active")&&w(),p&&p.classList.contains("is-active")&&k()}if(A&&A.addEventListener("click",M),q&&q.addEventListener("click",M),p){const e=p.querySelector(".ss-mobile-menu-content");e&&e.addEventListener("keydown",t=>{if("Tab"!==t.key)return;const r=e.querySelectorAll("a, button"),o=r[0],i=r[r.length-1];o&&i&&(t.shiftKey&&n.activeElement===o?(t.preventDefault(),i.focus()):t.shiftKey||n.activeElement!==i||(t.preventDefault(),o.focus()))})}async function I(){try{const e=await r("/wp-login.php?action=logout",{credentials:"same-origin"}),n=(await e.text()).match(/_wpnonce=([a-zA-Z0-9]+)/);n&&n[1]?t.location.href=`/wp-login.php?action=logout&_wpnonce=${n[1]}&redirect_to=/`:o("function"==typeof t.__t?t.__t("sidebarNav.logoutTokenError"):"Kunne ikke finde log ud-token. Prøv igen.")}catch(e){a.error("Logout error:",e),o("function"==typeof t.__t?t.__t("sidebarNav.logoutError"):"Log ud fejlede. Prøv igen senere.")}}const B=n.getElementById("ss-logout-btn"),H=n.getElementById("ss-mobile-logout-btn");return B&&B.addEventListener("click",e=>{e.preventDefault(),w(),I()}),H&&H.addEventListener("click",e=>{e.preventDefault(),k(),I()}),!0}const{removeHamDanTags:yn,removeMarkTags:wn,stripCssAttributesFromHtml:bn,str
1ipCssAttributesFromHtmlPreserveGrammar:kn,sanitizeEditorPasteHtml:Sn,removeHyphens:xn,initializeViewportHeightFix:Tn,SVG_ICONS:Ln,escapeHTML:En,stripHTML:Cn,markdownToHTML:_n}=o,An=a;window.showToast=function(e,t){Ce(e,"string"==typeof t?{type:t}:t)},function(e={}){const t=e.window||globalThis.window,n=e.document||t.document;"loading"===n.readyState?n.addEventListener("DOMContentLoaded",()=>vn(e)):vn(e)}();let qn={};function Mn(e,t){const n=e.querySelector("svg path");n&&(n.style.fill=t?"var(--Text-Secondary, #ADB5BD)":"var(--Text-Muted, #6C757D)")}function In(){document.querySelectorAll(".response-navigation").forEach(e=>{const t=e.querySelector(".response-counter");if(!t)return;const[n,r]=function(e){const t=e.match(/\d+/g);return[t&&t[0]?parseInt(t[0],10):1,t&&t[1]?parseInt(t[1],10):1]}(t.textContent),o=e.querySelector(".prev-btn"),i=e.querySelector(".next-btn"),a=n<=1,l=n>=r;o&&(o.disabled=a,Mn(o,a),o.style.cursor=a?"not-allowed":"pointer"),i&&(i.disabled=l,Mn(i,l),i.style.cursor=l?"not-allowed":"pointer")})}function Bn(e){!function(e){try{"function"==typeof window.savePreApiSnapshot&&window.savePreApiSnapshot(`rewrite:${e}`)}catch(e){}const{originalContent:t,showLoader:n,hideLoader:r,displayResponse:o,onResponseGenerated:i,HGF_ajax_object:a}=window._rewriteSystem,l=n.bind(window.textAreaLoader),s=r.bind(window.textAreaLoader),c=wn(yn(quill1.root.innerHTML));window.quill1&&(window.userOriginalInput=window.quill1.root.innerHTML);l(".textarea-wrapper",pe("loader.rewriting"),!0),qn[0]||(qn[0]={responses:[c]});const d=wn(yn(window.convertBulletListToUl(bn(window.convertBulletListToUl(c))))),u=new FormData;switch(u.append("action","hgf_rewrite_grammer_bot"),u.append("current_text",d),u.append("language",It()),e){case"simplify":u.append("prompt_index","0");break;case"elaborate":u.append("prompt_index","1");break;case"convencing":u.append("prompt_index","2");break;case"concise":u.append("prompt_index","3");break;case"professional":u.append("prompt_index","4");break;default:u.append("prompt_index","5")}const p=document.getElementById("custom_rewrite_input");p?.value&&u.append("rewrite_prompt",p.value);for(var m of(u.append("nonce",a.nonce),u.entries()));fetch(a.ajax_url,{method:"POST",credentials:"same-origin",body:new URLSearchParams(u),signal:xe()}).then(e=>e.text()).then(e=>{try{return JSON.parse(e)}catch(e){throw console.error("Failed to parse response:",e),new Error("Invalid response format")}}).then(e=>{if(e.success){const t=e.data.replace(/\\/g,"");o(t),i(t),Pn(),qn[0].responses.push(t);const n=qn[0].responses.length;document.querySelectorAll(".response-counter").forEach(e=>{e.textContent=pe("style.responseCounter",{current:n,total:n})}),In(),Kn(n-1)}else console.error("Error:",e.data?.message||"Unknown error")}).catch(e=>{"AbortError"!==e.name&&console.error("Request failed:",e)}).finally(()=>{s(".textarea-wrapper")})}(e),window._rewriteSystem.dkHamdanCloseModal()}function Hn(e){const t=document.querySelectorAll(".response-counter");if(0===t.length)return;const n=t[0].textContent.match(/\d+/g),[r,o]=n?n.map(e=>parseInt(e)):[1,1];let i;if("next"===e&&r<o)i=r;else{if(!("prev"===e&&r>1))return;i=r-2}Kn(i)}function Kn(e){qn[0]||(qn[0]={responses:[window.lastCorrectedText||""]});const t=qn[0].responses;if(t&&0!==t.length&&t[e]){window._rewriteSystem.displayResponse(t[e],!1);document.querySelectorAll(".response-counter").forEach(n=>{n.textContent=pe("style.responseCounter",{current:e+1,total:t.length})}),In()}}function Dn(){document.querySelectorAll(".response-navigation").forEach(e=>{e.style.display="none"}),qn={};document.querySelectorAll(".response-counter").forEach(e=>{e.textContent=pe("style.responseCounter",{current:1,total:1})}),In()}function Pn(){document.querySelectorAll(".response-navigation").forEach(e=>{e.style.display="flex"})}function Nn(){return qn}function jn(e){const t=document.querySelector(".dk-hamdan-modal-container");t.style.display="block",t.style.position="fixed",t.style.top="50%",t.style.left="50%",t.style.transform="translate(-50%, -50%)",t.style.zIndex="1000";const n=document.createElement("div");n.className="dk-hamdan-modal-overlay",n.style.position="fixed",n.style.top="0",n.style.left="0",n.style.width="100vw",n.style.height="100vh",n.style.backgroundColor="rgba(0, 0, 0, 0.5)",n.style.zIndex="999",document.body.appendChild(n),document.getElementById("custom_rewrite_input").value="",n.addEventListener("click",Rn),function(e){const t=e.nextElementSibling;""!==e.value.trim()?t.style.display="inline":t.style.display="none"}(document.getElementById("custom_rewrite_input"))}function Rn(){const e=document.querySelector(".dk-hamdan-modal-container"),t=document.querySelector(".dk-hamdan-modal-overlay");e.style.display="none",t&&document.body.removeChild(t),window._rewriteSystem.manuallyCloseMicButton("micButton2")}function Fn(){}const On=1024;async function Un(e,t={}
1){const{maxDimension:n=On,applySharpening:r=!0,sharpenStrength:o=1}=t;return new Promise((t,i)=>{const a=new Image;if(a.onload=function(){try{const e=document.createElement("canvas"),i=e.getContext("2d"),{width:l,height:s}=function(e,t,n){if(e<=n&&t<=n)return{width:e,height:t};const r=e/t;return e>t?{width:n,height:Math.round(n/r)}:{width:Math.round(n*r),height:n}}(a.width,a.height,n);e.width=l,e.height=s,i.fillStyle="white",i.fillRect(0,0,l,s),i.drawImage(a,0,0,l,s);let c=i.getImageData(0,0,l,s);c=$n(c),r&&(c=zn(c,o)),i.putImageData(c,0,0);const d=e.toDataURL("image/png",.9);t({dataURL:d,width:l,height:s})}catch(e){i(new Error("Preprocessing failed: "+e.message))}},a.onerror=function(){i(new Error("Failed to load image"))},"string"==typeof e)a.src=e;else if(e instanceof Blob||e instanceof File){const t=new FileReader;t.onload=e=>a.src=e.target.result,t.onerror=()=>i(new Error("Failed to read file")),t.readAsDataURL(e)}else i(new Error("Invalid image source type"))})}function $n(e){const t=e.data,n=t.length/4,r=new Array(256).fill(0);for(let e=0;e<t.length;e+=4)r[t[e]]++;const o=Math.floor(.01*n);let i=0,a=255,l=0;for(let e=0;e<256;e++)if(l+=r[e],l>o){i=e;break}l=0;for(let e=255;e>=0;e--)if(l+=r[e],l>o){a=e;break}if(a===i)return e;const s=255/(a-i);for(let e=0;e<t.length;e+=4){let n=t[e];n=Math.max(0,Math.min(255,Math.round((n-i)*s))),t[e]=n,t[e+1]=n,t[e+2]=n}return e}function zn(e,t=1){const n=e.width,r=e.height,o=e.data,i=new Uint8ClampedArray(o),a=-t,l=[[0,a,0],[a,1+4*t,a],[0,a,0]];for(let e=1;e<r-1;e++)for(let t=1;t<n-1;t++){let r=0;for(let o=-1;o<=1;o++)for(let a=-1;a<=1;a++){r+=i[4*((e+o)*n+(t+a))]*l[o+1][a+1]}const a=4*(e*n+t),s=Math.max(0,Math.min(255,Math.round(r)));o[a]=s,o[a+1]=s,o[a+2]=s}return e}function Gn(){return"undefined"!=typeof window&&window.quill1&&window.quill1.root?window.quill1:null}function Vn(){const e=Gn();return e&&e.root&&e.root.innerHTML||""}function Wn(e){const t=Gn();if(!t||!t.root)return;const n=e&&e.trim()?e.trim():"";if(t.setContents([]),n){const e="undefined"!=typeof DOMPurify?DOMPurify.sanitize(n,{ADD_TAGS:["ham-dan"],KEEP_CONTENT:!0}):n;t.clipboard.dangerouslyPasteHTML(0,e,"api")}else t.clipboard.dangerouslyPasteHTML(0,"<p><br></p>","api")}let Jn={};async function Zn(e){const t=new FormData;t.append("action","hgf_korrektur_OCR"),t.append("imageData",e),t.append("nonce",HGF_ajax_object.nonce);const n=await fetch("undefined"!=typeof HGF_ajax_object?HGF_ajax_object.ajax_url:"",{method:"POST",credentials:"same-origin",body:t}),r=await n.json();if(!r.success)throw new Error(r.data?.message||pe("file.ocrFailed"));return r.data}async function Yn(e){try{if(e.type.toLowerCase().includes("image")&&(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)||e.type.toLowerCase().includes("heic")||e.type.toLowerCase().includes("heif")))try{e=await async function(e){try{const t=new FormData;t.append("image",e);const n=await fetch("/robots/skrivebord/grammar-api.php?action=image-convert",{method:"POST",body:t});if(!n.ok)throw new Error(`Server returned ${n.status}: ${n.statusText}`);const r=await n.blob();return new File([r],e.name.replace(/\.[^.]+$/,".jpg"),{type:"image/jpeg"})}catch(t){return console.error("Image compression error:",t),e}}(e)}catch(e){console.error("Compression error, continuing with original file:",e)}const{dataURL:t}=await Un(e);return{text:await Zn(t),selectedMethod:"AI",selectedConfidence:null}}catch(e){return console.error("Image OCR error:",e),{text:"",selectedMethod:"Error",selectedConfidence:0,error:e.message}}}async function Qn(e){return new Promise(t=>{const n=new FileReader;n.onload=function(n){n.target.result;try{const n=document.createElement("img");n.onload=function(){EXIF.getData(n,function(){const e=EXIF.getAllTags(this),n=Object.keys(e).length>0,r=e.Make||e.Model||e.DateTimeOriginal||e.Orientation;t(r||n)})},n.onerror=function(){console.error("Failed to load image for EXIF extraction"),t(!1)},n.src=URL.createObjectURL(e)}catch(e){console.error("Error checking EXIF data:",e),t(!1)}},n.onerror=function(){console.error("FileReader error during EXIF check"),t(!1)},n.readAsArrayBuffer(e)})}function Xn(e){return e.trim().replace(/\s+/g," ").length>50}async function er(e){const t=e.getViewport({scale:2}),n=document.createElement("canvas"),r=n.getContext("2d");return n.width=t.width,n.height=t.height,r.fillStyle="white",r.fillRect(0,0,n.width,n.height),await e.render({canvasContext:r,viewport:t}).promise,n.toDataURL("image/png",.9)}async function tr(e){const t=e.getViewport({scale:2}),n=document.createElement("canvas"),r=n.getContext("2d");return n.width=t.width,n.height=t.height,r.fillStyle="white",r.fillRect(0,0,n.width,n.height),await e.render({canvasContext:r,viewport:t}).promise,async function(e,t={}){try{const n=e.getContext("2d");let r=n.getImageData(0,0,e.width,e.height);
1return r=$n(r),!1!==t.applySharpening&&(r=zn(r,t.sharpenStrength||1)),n.putImageData(r,0,0),e.toDataURL("image/png",.9)}catch(e){throw new Error("PDF page preprocessing failed: "+e.message)}}(n)}async function nr(e){try{const{dataURL:t}=await Un(e);return await Zn(t)}catch(e){return console.error("Image OCR error:",e),""}}async function rr(e){try{const t=5e4;return new Promise((n,r)=>{const o=new FileReader;o.onload=async function(e){try{const r=e.target.result,o={styleMap:["p[style-name='Heading 1'] => h1:fresh","p[style-name='Heading 2'] => h2:fresh","p[style-name='Heading 3'] => h3:fresh","p[style-name='Title'] => h1:fresh","p[style-name='Subtitle'] => h2:fresh"]};let i=(await mammoth.convertToHtml({arrayBuffer:r},o)).value;const a=document.createElement("div");a.innerHTML=i;(a.textContent||a.innerText||"").length>t&&(i=function(e,t){const n=new DOMParser,r=n.parseFromString(e,"text/html").body;let o=0,i="";function a(e){if(o>=t)return!1;if(e.nodeType===Node.TEXT_NODE){const n=e.textContent,r=t-o;if(n.length<=r)return i+=n,o+=n.length,!0;{let e=n.substring(0,r);const t=e.lastIndexOf(" ");return t>.8*r&&(e=n.substring(0,t)),i+=e,o+=e.length,!1}}if(e.nodeType===Node.ELEMENT_NODE){const t=e.tagName.toLowerCase(),n=Array.from(e.attributes).map(e=>`${e.name}="${e.value}"`).join(" ");i+=`<${t}${n?" "+n:""}>`;let r=!0;for(const t of e.childNodes)if(r=a(t),!r)break;return["br","hr","img","input","meta","link"].includes(t)||(i+=`</${t}>`),r}return!0}for(const e of r.childNodes){if(!a(e))break}return i}(i,t)),n(i.trim())}catch(e){r(e)}},o.readAsArrayBuffer(e)})}catch(e){throw console.error("DOCX processing error:",e),new Error(pe("file.wordError"))}}function or(e){Jn=e||{};const t=document.getElementById("uploadImg"),n=document.getElementById("imageUpload");if(!t||!n)return void console.error("File upload elements not found");if(!t.getAttribute("aria-label")){var r="Upload dokument (PDF, billede eller Word)";try{var o=pe("fileUpload.uploadAria");o&&0!==o.indexOf("fileUpload.")&&(r=o)}catch(e){}t.setAttribute("aria-label",r),t.setAttribute("title",r)}n.setAttribute("multiple","true"),n.setAttribute("accept","image/*,.pdf,.docx,.txt,.jpg,.jpeg,.png,.mp3,.wav,.m4a,.ogg,.webm,.aac,.flac,application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,text/plain"),t.addEventListener("click",function(){n.click(),Jn.manuallyCloseMicButton&&Jn.manuallyCloseMicButton("micButton1")});let i=!1;var a=null,l=[".mp3",".wav",".m4a",".ogg",".webm",".aac",".flac"],s=["audio/mpeg","audio/mp3","audio/wav","audio/wave","audio/x-wav","audio/mp4","audio/x-m4a","audio/m4a","audio/aac","audio/ogg","audio/webm","video/webm","audio/flac","audio/x-flac"];function c(e){var t=(e&&e.name?e.name:"").toLowerCase(),n=t.lastIndexOf(".");return n>=0?t.slice(n):""}function d(e){var t=(e&&e.type?e.type:"").toLowerCase(),n=c(e);return s.includes(t)||l.includes(n)}async function u(e){if(e.size>314572800)Ce(pe("fileUpload.audioTooLarge"),{type:"error",duration:4e3});else if(d(e)){try{var n=await function(e){return new Promise(function(t,n){var r=new Audio;r.addEventListener("loadedmetadata",function(){t(r.duration),URL.revokeObjectURL(r.src)}),r.addEventListener("error",function(){URL.revokeObjectURL(r.src),n(new Error("Cannot read audio"))}),r.src=URL.createObjectURL(e)})}(e);if(!Number.isFinite(n)||n<=0)return void Ce(pe("fileUpload.audioDurationError"),{type:"error",duration:4e3});if(n>10800)return void Ce(pe("fileUpload.audioTooLong"),{type:"error",duration:4e3})}catch(e){return void Ce(pe("fileUpload.audioDurationError"),{type:"error",duration:4e3})}try{"function"==typeof window.setEditorRobotLoading&&window.setEditorRobotLoading(!0,pe("fileUpload.audioTranscribing")),t.disabled=!0;var r=await fetch("/api/stt-token.php?service=voice&lang="+encodeURIComponent(Jn.getCurrentLanguage?Jn.getCurrentLanguage():"da")+"&sp="+encodeURIComponent(location.pathname));if(!r.ok)throw new Error("Token fetch failed");var o=((await r.json()).url||"").match(/[?&]session=([^&]+)/),i=o?o[1]:"";if(!i)throw new Error("No session token");
1var a=Jn.getCurrentLanguage?Jn.getCurrentLanguage():"da",l=new FormData;l.append("audio",e),l.append("session",i),l.append("language",a);var s=await fetch("/robots/skrivebord/grammar-api.php?action=audio-transcribe",{method:"POST",body:l});if(!s.ok)throw new Error("Transcription HTTP "+s.status);var c=await s.json();if(!c.text||!c.text.trim())throw new Error("Empty transcript");var u=c.text;"function"==typeof window.setEditorRobotLoading&&window.setEditorRobotLoading(!0,pe("fileUpload.audioCleaningUp"));var p=await async function(e,t){try{var n="";if(window._supabase&&window._supabase.auth&&"function"==typeof window._supabase.auth.getSession){var r=await window._supabase.auth.getSession(),o=r&&r.data?r.data.session:null;n=o&&o.access_token?o.access_token:""}if(!n)return null;var i=await fetch("/robots/skrivebord/grammar-api.php?action=audio-transcript-cleanup",{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+n},body:JSON.stringify({text:e,language:t})});if(!i.ok)return null;var a=await i.json();return a&&a.ok&&a.data&&"string"==typeof a.data.content&&a.data.content.trim()?a.data.content:null}catch(e){return console.error("Transcript cleanup failed, using raw:",e),null}}(u,a),m=p||u;"function"==typeof window.setEditorRobotLoading&&window.setEditorRobotLoading(!1),Jn.handleClear&&Jn.handleClear(),Jn.displayResponse&&Jn.displayResponse(m,!0,!1,!0),setTimeout(function(){Jn.scrollAfterPaste&&Jn.scrollAfterPaste()},100)}catch(e){console.error("Audio transcription error:",e),"function"==typeof window.setEditorRobotLoading&&window.setEditorRobotLoading(!1),Ce(pe("fileUpload.audioTranscriptionFailed"),{type:"error",duration:4e3})}finally{t.disabled=!1}}else Ce(pe("fileUpload.audioUnsupportedFormat"),{type:"error",duration:4e3})}async function p(e){if(e.length&&!i){i=!0;var n=e.filter(d),r=e.filter(function(e){return!d(e)});if(n.length>0){if(n.length>1)return Ce(pe("fileUpload.audioMultiple"),{type:"error",duration:4e3}),void(i=!1);try{await u(n[0])}catch(e){throw i=!1,e}if(0===r.length)return void(i=!1)}if(!(0===r.length&&n.length>0)){var o=r.length>0?r:e,l=o.filter(Oe);if(l.length>5)return Ce(pe("fileUpload.fileProcessingError")+" "+pe("fileUpload.maxImagesError"),{type:"error",duration:5e3}),void(i=!1);if(l.length>0){var s=await async function(e,t){const n=Array.from(e||[]),r=n.filter(Oe);if(!r.length)return n;const o=t&&"function"==typeof t.t?t.t:null;function i(e,t){if(!o)return t;try{const n=o(e);return n&&n!==e?n:t}catch(e){return t}}const a={title:i("crop.title","Beskær billedet"),titleCounter:i("crop.titleCounter","Beskær billede {current} af {total}"),hint:i("crop.hint","Træk i hjørnerne for at vælge det omrÃ¥de, der skal læses."),cancel:i("crop.cancel","Annuller"),confirm:i("crop.confirm","Beskær")},l=new Map;for(let e=0;e<r.length;e++){const t=await Ue(r[e],a,e,r.length);if(null===t)return null;l.set(r[e],t)}return n.map(function(e){return l.has(e)?l.get(e):e})}(o,{t:pe});if(!s)return void(i=!1);o=s}if(Jn.showLoader&&Jn.showLoader(".textarea-wrapper",pe("fileUpload.uploadingText")),t.disabled=!0,a=null,window.ssStagedProgress&&window.ssStagedProgress.start)try{var p=document.querySelector(".sk-editor-ai-loading-lock"),m=p?p.querySelector(".calm-cancel-label"):null,f=p?p.querySelector(".loader-text"):null;if(p&&m&&f){var g=window.ssStagedProgress.makeBar();f.parentNode.insertBefore(g,f.nextSibling);for(var h=0,v=0;v<o.length;v++)h+=o[v].size||0;var y=1===o.length&&(o[0].type||"").toLowerCase().includes("image/"),w=o.length>1?String(pe("fileUpload.stageFiles")||"Læser {n} filer").replace("{n}",o.length):y?pe("fileUpload.stageImage")||"Læser billedet":pe("fileUpload.stageDoc")||"Læser dit dokument";a=window.ssStagedProgress.start({lineEl:m,barEl:g,readText:pe("fileUpload.uploadingText"),workText:w,gatherText:pe("fileUpload.stageGather")||"Samler det hele",estimateMs:Math.min(45e3,8e3+4e3*Math.round(h/1048576))})}}catch(e){a=null}try{const e=o.filter(e=>e.type.toLowerCase().includes("image/")),n=o.filter(e=>"application/pdf"===e.type.toLowerCase()),r=o.filter(e=>"application/vnd.openxmlformats-officedocument.wordprocessingml.document"===e.type.toLowerCase());if(e.length>5)throw new Error(pe("fileUpload.maxImagesError"));if(n.length>1||r.length>1)throw new Error(pe("fileUpload.maxDocumentsError"));let i="",l=!1,s=!1;if(e.length>0){l=!0;let t="";for(let n=0;n<e.length;n++){const r=e[n].ssOriginalFile||e[n],o=await Qn(r);let i="";if(o||e[n].type.toLowerCase().includes("heic")||e[n].type.toLowerCase().includes("heif")){i=(await Yn(e[n])).text}else i=await nr(e[n]);t+=i+"\n\n"}i+=t}if(n.length>0){const e=await async function(e){try{const t=await e.arrayBuffer(),n=await pdfjsLib.getDocument({data:t}).promise,r=Math.min(n.numPages,20);let o="",i=!1,a=0,l=0;for(let e=1;e<=r;e++){const t=await n.getPage(e),r=(await t.getTextContent()).items.map(e=>e.str).join(" ");if(Xn(r))o+=r+"\n\n";else{i=!0,a++;let n="";try{const e=await er(t);if(e&&(n=await Zn(e)),!n||!n.trim()){const e=await tr(t);e&&(n=await Zn(e))}n&&n.trim()&&(o+=n.trim()+"\n\n")}catch(t){console.error(`Error processing page ${e} with OCR:`,t)}n&&n.trim()||l++}}return o=o.replace(/\s+/g," ").replace(/([.!?])\s*(?=[A-ZÃÃÃ
])/g,"$1\n\n").trim(),o.length>24e3&&(o=o.substring(0,24e3)),{text:o.trim(),usedOCR:i,ocrPagesAttempted:a,ocrPagesFailed:l}}catch(e){throw console.error("Enhanced PDF processing error:",e),new Error(pe("fileUpload.pdfProcessingError"))}}(n[0]);if(i+=e.text,e.usedOCR&&(l=!0),e.usedOCR&&e.ocrPagesAttempted>0&&e.ocrPagesFailed===e.ocrPagesAttempted&&(s=!0),s&&!i.trim())try{!a&&Jn.showLoader&&Jn.showLoader(".textarea-wrapper",pe("fileUpload.pdfNativeFallback"));const e=await async function(e){const t=await e.arrayBuffer(),n=new Uint8Array(t);let r="";for(let e=0;e<n.length;e++)r+=String.fromCharCode(n[e]);const o="data:application/pdf;base64,"+btoa(r),i=new FormData;i.append("action","hgf_pdf_native_extract"),i.append("pdfData",o),i.append("nonce",HGF_ajax_object.nonce);const a={};if(window._supabase&&window._supabase.auth&&"function"==typeof window._supabase.auth.getSession){const e=await window._supabase.auth.getSession(),t=e&&e.data?e.data.session:null,n=t&&t.access_token?t.access_token:"";n&&(a.Authorization="Bearer "+n)}const l=await fetch("undefined"!=typeof HGF_ajax_object?HGF_ajax_object.ajax_url:"",{method:"POST",credentials:"same-origin",headers:a,body:i}),s=await l.json();if(!s.success)throw new Error(s.data?.message||pe("file.ocrFailed"));return s.data}(n[0]);e&&e.trim()&&(i=e.trim(),s=!1)}catch(e){console.error("PDF native extraction also failed:",e)}}if(r.length>0){const e=await rr(r[0]),t=document.createElement("div");t.innerHTML=e||"";const n=(t.textContent||"").trim().length;let o="";n<80&&(o=await async function(e){const t=document.createElement("div");t.innerHTML=e||"";const n=Array.from(t.querySelectorAll("img")).map(e=>e.getAttribute("src")||"").filter(e=>e.startsWith("data:image"));let r="";for(const e of n)try{const t=await Zn(e);t&&t.trim()&&(r+=t.trim()+"\n\n")}catch(e){console.error("DOCX image OCR error:",e)}return r.trim()}(e)),o?(i+=o,l=!0):i+=e}const d=o.filter(function(e){return"text/plain"===e.type.toLowerCase()||".txt"===c(e)});for(var b=0;b<d.length;b++){if(d[b].size>10485760)throw new Error(pe("fileUpload.fileTooLarge")||"Filen er for stor (maks 10 MB).");i+=await new Promise(function(e,t){var n=new FileReader;n.onload=function(){e(n.result||"")},n.onerror=function(){t(new Error("Cannot read text file"))},n.readAsText(d[b])})}if(!i)throw new Error(pe(l?"fileUpload.ocrFailed":"fileUpload.noTextExtracted"));{Jn.handleClear&&Jn.handleClear();const e=l||n.length>0,o=!e&&r.length>0;await Ne({text:i,aiFormat:e,asHtml:o,preserveLanguage:e},{deps:Jn,t:pe,stageGather:function(){if(!a)return!1;try{a.gather()}catch(e){}return!0}}),t.disabled=!1}}catch(e){console.error("Processing Error:",e);var k=e&&e.message?" "+e.message:"";Ce(pe("fileUpload.fileProcessingError")+k,{type:"error",duration:5e3}),t.disabled=!1,Jn.hideLoader&&Jn.hideLoader(".textarea-wrapper")}finally{if(a){try{a.stop()}catch(e){}a=null}i=!1}
1}}}n.addEventListener("change",async function(e){const t=Array.from(e.target.files||[]);t.length&&(i||p(t).catch(function(e){console.error("File picker error:",e)}).finally(()=>{e.target.value=""}))}),function(){const e=document.querySelector(".textarea-wrapper");e&&(e.addEventListener("dragover",t=>{t.preventDefault();t.dataTransfer.types&&Array.from(t.dataTransfer.types).includes("Files")&&!i?(t.dataTransfer.dropEffect="copy",e.classList.add("drop-active")):e.classList.remove("drop-active")}),e.addEventListener("dragleave",t=>{t.relatedTarget&&e.contains(t.relatedTarget)||e.classList.remove("drop-active")}),e.addEventListener("drop",t=>{if(t.preventDefault(),e.classList.remove("drop-active"),i)return;const n=Array.from(t.dataTransfer.files||[]);n.length&&p(n).catch(function(e){console.error("Drop handler error:",e)})}))}()}let ir="div";function ar(e){ir=function(e){e.substring(0,20);const t=document.createElement("div");t.innerHTML=e;const n=t.querySelectorAll(":scope > p").length;t.querySelectorAll(":scope > div").length;const r=t.querySelectorAll("p").length,o=t.querySelectorAll("div").length,i=t.querySelectorAll("div > p").length,a={includes_p:e.includes("<p>"),includes_P:e.includes("<P>"),indexOf_p:e.indexOf("<p")>=0,indexOf_P:e.indexOf("<P")>=0,regex_p:/\<p[\s>]/i.test(e),search_p:e.search(/<p/i)>=0,includes_div:e.includes("<div>"),includes_DIV:e.includes("<DIV>"),indexOf_div:e.indexOf("<div")>=0,indexOf_DIV:e.indexOf("<DIV")>=0,search_div:e.search(/<div/i)>=0};return r>0&&(n>0||i>0||r>o)&&(a.indexOf_p||a.regex_p||a.search_p)?"p":"div"}(e)}const{processQuillContentForCopy:lr,initQuillCopy:sr}=function({getPreferredFormat:e,convertDivsToParagraphs:t,convertParagraphsToDivs:r}){function o(o){const i=o.container.querySelector(".ql-editor");if(!i)return{html:"",text:""};let a=i.innerHTML;try{"function"==typeof n&&(a=n(a))}catch(e){}a=Rt(a,"full-content");const l=document.createElement("div");l.innerHTML=a,l.querySelectorAll("p").length,l.querySelectorAll("div").length;["h1","h2","h3","h4","h5","h6"].forEach(e=>{l.querySelectorAll(e).forEach(e=>{const t=e.nextElementSibling;if(t&&"P"===t.tagName){const e=1===t.childNodes.length&&t.firstChild&&t.firstChild.nodeType===Node.ELEMENT_NODE&&"BR"===t.firstChild.tagName,n="<br>"===t.innerHTML.trim()||"<br/>"===t.innerHTML.trim()||"<br />"===t.innerHTML.trim();(e||n)&&t.parentNode.removeChild(t)}})});l.querySelectorAll(".ql-ui").forEach(e=>{e.parentNode.removeChild(e)});l.querySelectorAll("*").forEach((e,t)=>{if(e.getAttribute("style"),e.style.backgroundColor="",e.style.fontSize="",e.style.fontFamily="",e.hasAttribute("style")){let t=e.getAttribute("style");t=t.replace(/background(-color)?:[^;]+;?/gi,""),t=t.replace(/font-size:[^;]+;?/gi,""),t=t.replace(/font-family:[^;]+;?/gi,""),t=t.replace(/color:[^;]+;?/gi,""),""===t.trim()?e.removeAttribute("style"):e.setAttribute("style",t),e.getAttribute("style")}}),l.style&&(l.style.backgroundColor,l.style.fontSize,l.style.fontFamily,l.style.color,l.style.backgroundColor="",l.style.fontSize="",l.style.fontFamily="",l.style.color=""),a=l.innerHTML;const s=e(),c=a.includes("<p"),d=a.includes("<div");"p"===s&&d?a=t(a):"div"===s&&c&&(a=r(a));let u=jt(a);return Dt()&&(a=Nt(a),u=Pt(u)),{html:a,text:u}}function i(n){const o=n.container;o&&o.addEventListener("copy",o=>{const i=window.getSelection();if(0===i.rangeCount||i.isCollapsed)return;const a=n.container.querySelector(".ql-editor"),l=i.getRangeAt(0);if(a.contains(l.commonAncestorContainer)||l.commonAncestorContainer===a)try{const n=l.cloneContents(),a=document.createElement("div");a.appendChild(n);let s=a.innerHTML;if(!s.trim()){const e=document.createRange();e.selectNodeContents(l.commonAncestorContainer);const t=e.cloneContents(),n=document.createElement("div");n.appendChild(t),s=n.innerHTML}const c=i.toString();if(!c||""===c.trim())return;s=Rt(s,"selection");const d=document.createElement("div");d.innerHTML=s;["h1","h2","h3","h4","h5","h6"].forEach(e=>{d.querySelectorAll(e).forEach(e=>{const t=e.nextElementSibling;if(t&&"P"===t.tagName){const e=1===t.childNodes.length&&t.firstChild&&t.firstChild.nodeType===Node.ELEMENT_NODE&&"BR"===t.firstChild.tagName,n="<br>"===t.innerHTML.trim()||"<br/>"===t.innerHTML.trim()||"<br />"===t.innerHTML.trim();(e||n)&&t.parentNode.removeChild(t)}})});
1d.querySelectorAll(".ql-ui").forEach(e=>{e.parentNode.removeChild(e)});const u=d.querySelectorAll("*");let p=0;if(u.forEach((e,t)=>{const n=e.getAttribute("style");if(e.style.backgroundColor="",e.style.fontSize="",e.style.fontFamily="",e.hasAttribute("style")){let t=e.getAttribute("style");t=t.replace(/background(-color)?:[^;]+;?/gi,""),t=t.replace(/font-size:[^;]+;?/gi,""),t=t.replace(/font-family:[^;]+;?/gi,""),t=t.replace(/color:[^;]+;?/gi,""),""===t.trim()?e.removeAttribute("style"):e.setAttribute("style",t);n!==(e.getAttribute("style")||"")&&p++}}),d.style){d.style.backgroundColor,d.style.fontSize,d.style.fontFamily,d.style.color;d.style.backgroundColor="",d.style.fontSize="",d.style.fontFamily="",d.style.color=""}let m=d.innerHTML;const f=e(),g=m.includes("<p"),h=m.includes("<div");"p"===f&&h?m=t(m):"div"===f&&g&&(m=r(m));let v=jt(m);Dt()&&(m=Nt(m),v=Pt(v)),o.clipboardData.setData("text/html",m),o.clipboardData.setData("text/plain",v),o.preventDefault()}catch(e){return}})}const a=async()=>{const{html:e,text:t}=o(window.quill1);let n=await Ft(e,t);if(!n){try{const t=document.createElement("div");t.setAttribute("contenteditable","true"),t.innerHTML=e,t.style.position="absolute",t.style.left="-9999px",t.style.top="-9999px",document.body.appendChild(t);const r=document.createRange();r.selectNodeContents(t);const o=window.getSelection();o.removeAllRanges(),o.addRange(r),n=document.execCommand("copy"),o.removeAllRanges(),document.body.removeChild(t)}catch(e){}if(!n)try{n=await navigator.clipboard.writeText(window.quill1.getText()).then(()=>!0).catch(()=>!1)}catch(e){}}n&&(l(!0),setTimeout(()=>l(!1),2e3))},l=e=>{const t=document.getElementById("copyBtn");t&&(t.innerHTML,t.innerHTML=e?'<svg class="check-icon" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">\n <polyline points="20 6 9 17 4 12"></polyline>\n </svg>':'<svg\n xmlns="http://www.w3.org/2000/svg"\n width="16"\n height="16"\n viewB
1ox="0 0 24 24"\n fill="none"\n stroke="currentColor"\n stroke-width="2"\n stroke-linecap="round"\n stroke-linejoin="round"\n >\n <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>\n <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>\n </svg>',t.innerHTML)};return{processQuillContentForCopy:o,setupQuillCopyHandler:i,handleQuillCopy:a,updateCopyButton:l,initQuillCopy:function(){try{i(window.quill1)}catch(e){}const e=document.getElementById("copyBtn");e&&e.addEventListener("click",a)}}}({getPreferredFormat:function(){return ir},convertDivsToParagraphs:function(e){const t=document.createElement("div");return t.innerHTML=e,t.querySelectorAll("div").forEach(e=>{const t=document.createElement("p");for(let n=0;n<e.attributes.length;n++){const r=e.attributes[n];t.setAttribute(r.name,r.value)}t.innerHTML=e.innerHTML,e.parentNode.replaceChild(t,e)}),t.innerHTML},convertParagraphsToDivs:function(e){const t=document.createElement("div");return t.innerHTML=e,t.querySelectorAll("p").forEach(e=>{const t=document.createElement("div");for(let n=0;n<e.attributes.length;n++){const r=e.attributes[n];t.setAttribute(r.name,r.value)}t.innerHTML=e.innerHTML,e.parentNode.replaceChild(t,e)}),t.innerHTML}});async function cr(e=!1,t=!0){const{stopSpeaking:n,manuallyCloseMicButton:r,resetNavText:o,handleClear:i,correctionSidebarLoader:a}=window;n(),r("micButton1"),o();try{let t=Boolean(e);const n=()=>{const e=window.quill1&&window.quill1.history;e&&"function"==typeof e.cutoff&&e.cutoff()},r=()=>{a.showReadyState(),i({skipEditor:!0}),t=!1};let o="";if(navigator.clipboard.read)try{const e=await navigator.clipboard.read();let i=!1;for(const o of e)if((!o.types.some(e=>e.startsWith("image/")&&!e.includes("docs"))||1!==o.types.length)&&o.types.includes("text/html")){const e=await o.getType("text/html"),a=await e.text();ar(a);const l=a.replace(/<img[^>]*>/gi,"").replace(/background-image\s*:\s*url\([^)]+\)/gi,"").replace(/<svg[^>]*>.*?<\/svg>/gis,"").replace(/<picture[^>]*>.*?<\/picture>/gis,"").replace(/data:image\/[^;]+;base64,[^\s'"]+/gi,"").replace(/<video[^>]*>.*?<\/video>/gis,"").replace(/<iframe[^>]*>.*?<\/iframe>/gis,"").replace(/<embed[^>]*>/gi,"").replace(/<object[^>]*>.*?<\/object>/gis,"");if(l.trim()){const e=Sn(l);if(ur(e)){if("function"==typeof An&&o.types.includes("text/plain")){const t=await o.getType("text/plain"),n=await t.text();if(n&&An(e,n,l))continue}if(t){r(),n();const t=window.quill1.clipboard.convert({html:e});window.quill1.setContents(t,"user"),n(),window.quill1.setSelection(Math.max(0,window.quill1.getLength()-1),0)}else{const t=0===window.quill1.getText().trim().length,n=window.quill1.getSelection(),r=n?n.index:window.quill1.getLength(),o=n?n.length:0;if(o>0&&window.quill1.deleteText(r,o),t){"<p><br></p>"===window.quill1.root.innerHTML&&window.quill1.setText(""),window.quill1.clipboard.dangerouslyPasteHTML(0,e,"user");const t=window.quill1.getLength();window.quill1.setSelection(t-1,0)}else{const t=n?n.index:window.quill1.getLength(),r=window.quill1.getLength();window.quill1.clipboard.dangerouslyPasteHTML(t,e,"user");const o=window.quill1.getLength(),i=t+(o-r);window.quill1.setSelection(i,0)}}window.quill1.focus(),i=!0;break}}}if(!i)for(const t of e)if((!t.types.some(e=>e.startsWith("image/")&&!e.includes("docs"))||1!==t.types.length)&&t.types.includes("text/plain")){const e=await t.getType("text/plain");o=await e.text();break}if(!i&&!o){let t=!1,n=!1;for(const r of e){const e=r.types.find(e=>e.startsWith("image/"));if(e){if(ea){n=!0;break}ea=!0,t=!1,ta=function(){t=!0},"function"==typeof window.setEditorRobotLoading&&window.setEditorRobotLoading(!0,pe("clipboard.ocrExtracting"));try{const n=await r.getType(e),i=new File([n],"clipboard-paste.png",{type:e}),a=await Yn(i);!t&&a&&a.text&&a.text.trim()&&(o=a.text.trim())}catch(e){t||console.error("Clipboard image OCR failed:",e)}finally{ta=null,ea=!1,"function"==typeof window.setEditorRobotLoading&&window.setEditorRobotLoading(!1)}break}}o||t||n||Ce(pe("clipboard.ocrFailed"),{type:"warning"})}}catch(e){console.error("navigator.clipboard.read failed:",e);try{o=await navigator.clipboard.readText()}catch(e){console.error("readText fallback failed:",e)}}else try{o=await navigator.clipboard.readText()}catch(e){console.error("readText fallback failed:",e)}if(o){if(o.trim())if(t)r(),n(),window.quill1.setText(o,"user"),n(),window.quill1.setSelection(o.length,0);else{if(0===window.quill1.getText().trim().length)"<p><br></p>"===window.quill1.root.innerHTML&&window.quill1.setText(""),window.quill1.insertText(0,o,"user"),window.quill1.setSelection(o.length,0);else{const e=window.quill1.getSelection(),t=e?e.index:window.quill1.getLength(),n=e?e.length:0;n>0&&window.quill1.deleteText(t,n),window.quill1.insertText(t,o,"user");const r=t+o.length;window.quill1.setSelection(r,0)}}window.quill1.focus()}window.quill1.getSelection()}catch(e){console.error("Clipboard handling failed:",e)}}function dr(){setTimeout(()=>{document.querySelector(".ql-container");const e=document.querySelector(".ql-editor");e&&(e.scrollTop=e.scrollHeight);const t=Math.max(document.body.scrollHeight,document.body.offsetHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight,document.documentElement.offsetHeight);window.scrollTo({top:t,behavior:"smooth"}),setTimeout(()=>{window.scrollTo({top:document.documentElement.scrollHeight,behavior:"smooth"})},100)},200)}function ur(e){if(!e||!e.trim())return!1;try{const t=(new DOMParser).parseFromString(e,"text/html"),n=t.body||t;return!!(n.textContent||"").replace(/\u00a0/g," ").trim()||Boolean(n.querySelector("table, hr"))}catch(t){return e.replace(/<script[^>]*>.*?<\/script>/gis,"").replace(/<style[^>]*>.*?<\/style>/gis,"").replace(/<[^>]+>/g,"").replace(/ /gi," ").trim().length>0}}const pr={micButton1:"inputText",micButton2:"custom_rewrite_input",chatMicBtn:"chat-custom-input"};let mr={},fr=null;var gr=null;function hr(){var e=gr;gr=null,window.quill1&&(window.quill1.root.style.removeProperty("--sk-stt
1-gap"),null!==e&&e<window.quill1.getLength()&&window.quill1.formatText(e,1,{sttgap:!1},"silent"))}function vr(){const e=window.quill1;if(!e)return 0;const t=e.getSelection();if(t)return t.index;const n=e.selection&&e.selection.savedRange;return n&&"number"==typeof n.index?n.index:null!==fr?fr:Math.max(0,e.getLength()-1)}const yr=se();function wr(){const e=yr.remove();"number"==typeof e&&(fr=e,document.dispatchEvent(new CustomEvent("skrivebord:stt-preview-change")))}function br(){try{const e=localStorage.getItem("sb_ui_lang");if(e)return String(e).split("-")[0].toLowerCase()}catch(e){}return"da"}function kr(e){const t=mr[e];t&&(t.stop(),delete mr[e]),Lr(e,!1,!1),"inputText"===pr[e]&&(hr(),fr=null)}const Sr="sk:mic-claim",xr="grammar-bot";function Tr(e){if(Object.keys(mr).forEach(t=>{t!==e&&(mr[t].stop(),delete mr[t],Lr(t,!1,!1))}),mr[e])return mr[e].stop(),delete mr[e],Lr(e,!1,!1),void("inputText"===pr[e]&&(fr=null));!function(){try{window.dispatchEvent(new CustomEvent(Sr,{detail:{owner:xr}}))}catch(e){}}(),Lr(e,!1,!0),mr[e]=le({button:document.getElementById(e),idleAriaLabel:document.getElementById(e)?.getAttribute("aria-label")||pe("controls.stt"),service:"chat",lang:"chatMicBtn"===e?br():null,onTranscript:function(t){if(!t||!t.trim())return;const n=pr[e],r=document.getElementById(n);if(r)if(wr(),"inputText"===r.id&&window.quill1){{hr();let e=vr();window.quill1.insertText(e,t+" ","user");const n=e+t.length+1;fr=n,window.quill1.setSelection(n,0),window.quill1.focus()}r.dispatchEvent(new Event("input",{bubbles:!0}))}else!function(e,t){var n=function(e){var t="string"==typeof e.value?e.value:"",n="number"==typeof e.selectionStart?e.selectionStart:t.length;return n<0&&(n=0),n>t.length&&(n=t.length),n}(e),r="string"==typeof e.value?e.value:"",o=r.slice(0,n),i=r.slice(n),a=(o&&!/\s$/.test(o)?" ":"")+t+(""!==i&&/^\s/.test(i)?"":" ");if("function"==typeof e.setRangeText)e.setRangeText(a,n,n,"end");else if(e.value=o+a+i,"function"==typeof e.setSelectionRange)try{e.setSelectionRange(n+a.length,n+a.length)}catch(e){}e.dispatchEvent(new Event("input",{bubbles:!0}))}(r,t)},onPartial:function(t){!function(e,t){const n=pr[e],r=document.getElementById(n);r&&("inputText"!==n?yr.renderInField(r,t):window.quill1&&(yr.renderInQuill(window.quill1,vr,t),document.dispatchEvent(new CustomEvent("skrivebord:stt-preview-change"))))}(e,t)},onError:function(t){console.error("STT error for "+e+":",t),wr(),delete mr[e],Lr(e,!1,!1),"inputText"===pr[e]&&(hr(),fr=null)},onStateChange:function(t){"listening"===t?(Lr(e,!0,!1),"inputText"===pr[e]&&window.quill1&&(window.quill1.focus(),null!==fr&&window.quill1.setSelection(fr,0))):"connecting"===t?Lr(e,!1,!0):"idle"!==t&&"error"!==t||("inputText"===pr[e]&&hr(),wr(),delete mr[e],Lr(e,!1,!1),"inputText"===pr[e]&&(fr=null))}}),mr[e].start()}function Lr(e,t,n=!1){document.querySelectorAll('[data-stt-proxy-for="'+e+'"]').forEach(function(r){if(r.classList.remove("ss-mic--connecting","ss-mic--listening","ss-mic--error"),n)r.classList.add("ss-mic--connecting"),r.setAttribute("aria-busy","true"),r.setAttribute("aria-pressed","true");else if(t)r.classList.add("ss-mic--listening"),r.setAttribute("aria-busy","false"),r.setAttribute("aria-pressed","true");else{var o=document.getElementById(e);o&&o.classList.contains("ss-mic--error")&&r.classList.add("ss-mic--error"),r.setAttribute("aria-busy","false"),r.setAttribute("aria-pressed","false")}});const r=document.getElementById(e),o=document.querySelector(`#${e} .lucide-mic`);if(r)if("chatMicBtn"===e){if(n&&o&&(o.style.display="none"),n)return}else{const e=r.querySelector(".loader");if(e&&e.remove(),r.classList.remove("ss-mic--connecting"),n)return void r.classList.add("ss-mic--connecting")}if(o){o.style.display="inline";o.querySelectorAll("path").forEach(e=>{e.setAttribute("stroke",t?"#28a745":"currentColor")}),t?o.classList.add("listening-glow"):o.classList.remove("listening-glow")}}"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener(Sr,function(e){e&&e.detail&&e.detail.owner===xr||Object.keys(mr).forEach(e=>kr(e))});const Er=new class{constructor(){this.activeLoaders=new Set}showHistoryLoader(e,t="loader1"){const n=document.getElementById(e)||document.querySelector(e);
1if(!n)return;this.hideHistoryLoader(e);const r=document.createElement("div");r.className=t,r.dataset.loaderId=e;const o=document.createElement("div");o.className="dotted-loader";for(let e=1;e<=8;e++){const e=document.createElement("div");e.className="dot",o.appendChild(e)}r.appendChild(o),n.appendChild(r),this.activeLoaders.add(e)}hideHistoryLoader(e){const t=document.getElementById(e)||document.querySelector(e);if(!t)return;t.querySelectorAll(".loader1, .loader2").forEach(t=>{t.dataset.loaderId===e&&t.remove()}),this.activeLoaders.delete(e)}showButtonLoading(e){const t="string"==typeof e?document.querySelector(e):e;t&&t.classList.add("loading")}hideButtonLoading(e){const t="string"==typeof e?document.querySelector(e):e;t&&t.classList.remove("loading")}hideAllLoaders(){this.activeLoaders.forEach(e=>{this.hideHistoryLoader(e)}),document.querySelectorAll(".button-container.loading").forEach(e=>{e.classList.remove("loading")})}hasActiveLoaders(){return this.activeLoaders.size>0}};"undefined"!=typeof module&&module.exports&&(module.exports=Er),"undefined"!=typeof window&&(window.historyLoader=Er);let Cr=!0;function _r(){const e=window.quill1;if(!e||!e.root)return;const t=document.querySelector(".word-count"),n=document.querySelector(".char-limit-warning"),r=document.querySelector(".word-counter-div"),o=e.getText().trim().length,i=document.getElementById("voiceChangeBtn"),a=document.getElementById("analyzeRequestBtn"),l=document.getElementById("chat-send-btn"),s=o>0;if(n&&(n.style.display="none"),t){const e=o.toLocaleString("da-DK");t.textContent=`${e} ${pe("membership.characters")}`}r&&(r.style.display=s?"flex":"none",r.style.flexDirection="row"),s?(Cr=!1,i&&(i.disabled=!1,i.style.cursor="pointer"),a&&(a.disabled=!1,a.style.cursor="pointer")):(Cr=!0,i&&(i.disabled=!0,i.style.cursor=""),a&&(a.disabled=!0,a.style.cursor="")),l&&(l.disabled=!1,l.style.cursor="pointer")}const Ar=new class{constructor(){this.activeLoaders=new Map,this.buttonTexts={}}setButtonLoading(e){const t=document.getElementById(e);if(!t)return;const n=t.querySelector("span");this.buttonTexts[e]||(this.buttonTexts[e]=n?n.textContent:t.innerHTML),t.disabled=!0,t.style.pointerEvents="none",t.style.cursor="not-allowed",t.classList.add("disabled-gen-btn"),n?n.textContent=pe("loader.pleaseWait"):t.textContent=pe("loader.pleaseWait")}resetButton(e){const t=document.getElementById(e);if(!t)return;const n=this.buttonTexts[e];if(!n)return;const r=t.querySelector("span");t.disabled=!1,t.style.pointerEvents="auto",t.style.cursor="pointer",t.classList.remove("disabled-gen-btn"),r?r.textContent=n:t.innerHTML=n,delete this.buttonTexts[e]}setAllButtonsLoading(){Cr=!0,this.setButtonLoading("voiceChangeBtn"),this.setButtonLoading("analyzeRequestBtn")}resetAllButtons(){Cr=!1,this.resetButton("voiceChangeBtn"),this.resetButton("analyzeRequestBtn")}showTextAreaLoader(e,t="Loading...",n=!1){const r=document.querySelector(e);if(r){if(this.hideTextAreaLoader(e),this.setAllButtonsLoading(),n&&(be(),window.quill1&&(window.editOriginalText=window.quill1.root.innerHTML)),"function"==typeof window.setEditorRobotLoading){window.setEditorRobotLoading(!0,"Loading..."===t?void 0:t);const r=document.querySelector(".sk-editor-ai-loading-lock");if(r&&(r.dataset.selector=e,n)){const t=document.createElement("button");t.className="text-area-cancel-btn",t.innerHTML=`<span>${pe("loader.cancel")}</span>`,t.onclick=()=>this.handleCancelRequest(e),r.appendChild(t)}}this.activeLoaders.set(e,{element:r,text:t,showCancel:n}),"function"==typeof window.updateClearRevertButtonState&&window.updateClearRevertButtonState()}}hideTextAreaLoader(e){if(!document.querySelector(e))return;this.resetAllButtons(),_r(),"function"==typeof window.setEditorRobotLoading&&window.setEditorRobotLoading(!1);const t=document.querySelector(".textarea-wrapper");(t||document.body).querySelectorAll(".loader-backdrop:not(.sk-editor-ai-loading-lock)").forEach(t=>{t.dataset.selector===e&&t.remove()}),t&&(t.style.overflowY="auto"),this.activeLoaders.delete(e),"function"==typeof window.updateClearRevertButtonState&&window.updateClearRevertButtonState()}updateLoaderText(e,t){const n=(document.querySelector(".textarea-wrapper")||document.body).querySelector('.loader-backdrop[data-selector="'+e+'"]');if(n){const r=n.querySelector(".loader-text");r&&(r.textContent=t,this.activeLoaders.has(e)&&(this.activeLoaders.get(e).text=t))}}isLoaderActive(e){return this.activeLoaders.has(e)}getCurrentText(e){const t=this.activeLoaders.get(e);return t?t.text:null}
1hideAllLoaders(){this.activeLoaders.forEach((e,t)=>{this.hideTextAreaLoader(t)})}getActiveLoaders(){return Array.from(this.activeLoaders.keys())}hasActiveLoaders(){return this.activeLoaders.size>0}handleCancelRequest(e){Se(),window.lastRequestCancelled=!0,window.userOriginalInput&&window.quill1&&(window.displayResponse(window.userOriginalInput,!1,!0,!0),window.userOriginalInput=null);if(!(window.trueOriginalText&&window.trueOriginalText.trim().length||window.editOriginalText&&window.editOriginalText.trim().length||window.preApiSnapshot&&window.preApiSnapshot.trim().length)){const e=document.getElementById("mainSwitcher");e&&(e.disabled=!0)}this.resetAllStateVariables(),this.hideTextAreaLoader(e),window.resetSidebarRobot&&window.resetSidebarRobot();!(null!==document.querySelector(".correction-content.has-explanations"))&&window.correctionSidebarLoader&&window.correctionSidebarLoader.showReadyState&&window.correctionSidebarLoader.showReadyState(),"function"==typeof window.resetSidebar&&window.resetSidebar(!0),this.resetAllButtons(),_r();const t=document.getElementById("actionBtn");if(t&&t.classList.contains("disabled-gen-btn")){const e=this.buttonTexts.actionBtn;if(e){const n=t.querySelector("span");n?n.textContent=e:t.innerHTML=e}t.disabled=!1,t.style.pointerEvents="auto",t.style.cursor="pointer",t.classList.remove("disabled-gen-btn"),delete this.buttonTexts.actionBtn}}resetAllStateVariables(){null!==document.querySelector(".correction-content.has-explanations")||("undefined"!=typeof window&&window.resetGrammarBotState?window.resetGrammarBotState():"undefined"!=typeof window&&(window.currentHtmlParts=[],window.editOriginalText=null,window.userOriginalInput=null,window.analysisState&&(window.analysisState.analysisData=null,window.analysisState.isAnalyzing=!1)))}};"undefined"!=typeof module&&module.exports&&(module.exports=Ar),"undefined"!=typeof window&&(window.textAreaLoader=Ar);const qr=new class{constructor(){this.cache=new Map,this.isPreloading=!1,this.preloadPromise=null}async preloadAnimations(e){return this.isPreloading?this.preloadPromise:(this.isPreloading=!0,this.preloadPromise=this._loadAllAnimations(e),await this.preloadPromise,this.cache)}async _loadAllAnimations(e){const t=Object.entries(e).map(async([e,t])=>{try{const n=await fetch(t);if(!n.ok)throw new Error(`HTTP ${n.status}`);const r=await n.json();this.cache.set(e,r)}catch(e){}});await Promise.all(t)}getCachedAnimation(e){return this.cache.get(e)}isCached(e){return this.cache.has(e)}};"undefined"!=typeof module&&module.exports&&(module.exports=qr),"undefined"!=typeof window&&(window.animationPreloader=qr);const Mr=new class{constructor(){this.activeLoaders=new Map,this.lottieLoadAnimation=null,this.animationUrls={ready:"/robots/skrivebord/animations/robot-wave.json",loading:"/robots/skrivebord/animations/robot-loading-loop-1.json",success:"/robots/skrivebord/animations/robot-comfirmed.json",analyzed:"/robots/skrivebord/animations/Robot-Ready-Loop.json"}}setLottieFunction(e){this.lottieLoadAnimation=e}async initializePreloader(){try{await qr.preloadAnimations(this.animationUrls)}catch(e){}}loadAnimationByState(e="ready",t="#gif"){if(!this.lottieLoadAnimation)return;const n="string"==typeof t?document.querySelector(t):t;if(!n)return;const r="string"==typeof t&&"#gif-sidebar-collapsed"===t||t&&"gif-sidebar-collapsed"===t.id,o=()=>{const t=n.querySelector(".sidebar-robot-gif-loader");n.innerHTML="",n._lottieInstance&&(n._lottieInstance.destroy(),n._lottieInstance=null);const r=document.createElement("div");r.className="gif-animation-slot",r.style.position="relative",r.style.width="100%",r.style.height="100%",n.appendChild(r);const o=qr.getCachedAnimation(e);if(o)this.lottieLoadAnimation(r,o);else{const t=this.animationUrls[e]||this.animationUrls.ready;this.lottieLoadAnimation(r,t)}t&&(t.style.position="absolute",t.style.inset="0",t.style.zIndex="2",n.appendChild(t))};r?(n.classList.add("loading-new"),setTimeout(()=>{o(),setTimeout(()=>n.classList.remove("loading-new"),100)},50)):o(),"analyzed"===e&&setTimeout(()=>{const e=n.querySelector("svg");e&&(e.style.marginBottom="0px",document.querySelector(".action-button").style.marginBottom="0px")},100)}reapplyButtonSelection(){setTimeout(()=>{if("function"==typeof window.selectGrammarMode){const e=window.grammarModelDepth||!1;window.selectGrammarMode(e,!1)}else{const e=window.grammarModelDepth||!1,t=document.querySelector(".grammar-basic-btn"),n=document.querySelector(".grammar-plus-btn");t&&n&&(e?(t.classList.remove("selected"),n.classList.add("selected")):(n.classList.remove("selected"),t.classList.add("selected")))}},50)}showCorrectionLoader(e,t="Analyzing..."){if(Cr=!0,"undefined"!=typeof window&&!1===window.toggleState)return;const n=document.querySelector(".improv-inner .correction-content");n&&(n.classList.contains("has-explanations")&&n.classList.remove("has-explanations"),n.style.justifyContent="center",n.innerHTML=`\n\n <div style="display:block" class="hamdan-speech-bubble">\n <div class="gradient-loader"></div>\n <span>${pe("loader.working")}</span>\n </div>\n <div style="display:block" class="hamdan-robot-container">\n <div id="gif"></div>\n </div>\n <div class="legend-section" id="legend-section">\n <div class="legend-item">\n <div class="legend-dot change"></div>
1\n <span class="legend-text">${pe("sidebar.corrected")}</span>\n </div>\n <div class="legend-item">\n <div class="legend-dot add"></div>\n <span class="legend-text">${pe("sidebar.comma")}</span>\n </div>\n <div class="legend-item">\n <div class="legend-dot remove"></div>\n <span class="legend-text">${pe("sidebar.deleted")}</span>\n </div>\n </div>\n <div class="correction-message" style="display: none">\n <span>${pe("sidebar.ready")}</span>\n </div>\n`,this.loadAnimationByState("loading","#gif"),this.activeLoaders.set(e,{element:n,text:t}))}hideCorrectionLoader(e){const t=document.querySelector(".gradient-loader");t&&t.remove();const n=document.querySelector(".improv-inner .hamdan-speech-bubble");n&&(n.textContent=pe("sidebar.ready"),this.loadAnimationByState("ready",".improv-inner #gif")),_r(),this.activeLoaders.delete(e);const r=document.querySelector(".improv-inner .correction-content");r&&(r.style.justifyContent="")}toggleSmartLoader(e){if("undefined"!=typeof window&&!1===window.toggleState)return;const t=document.querySelector(".correction-inner .demo-inner .hamdan-speech-bubble"),n=document.querySelector(".correction-inner-main .hamdan-speech-bubble");if(e){if(t){t.innerHTML=`\n <div class="gradient-loader"></div>\n <span>${pe("loader.working")}</span>\n `;const e=document.querySelector(".correction-inner .demo-inner #gif");e&&this.loadAnimationByState("loading",e)}if(n){n.innerHTML=`\n <div class="gradient-loader"></div>\n <span>${pe("loader.working")}</span>\n `;const e=document.querySelector(".correction-inner-main .hamdan-robot-container #gif");e&&this.loadAnimationByState("loading",e)}}else{if(t){t.textContent=pe("sidebar.refiningText");const e=document.querySelector(".correction-inner .demo-inner #gif");e&&this.loadAnimationByState("ready",e)}if(n){n.textContent=pe("sidebar.ready");const e=document.querySelector(".correction-inner-main .hamdan-robot-container #gif");e&&this.loadAnimationByState("ready",e)}}}showReadyState(){const e=document.querySelector(".improv-inner .correction-content");if(!e)return;e.classList.contains("has-explanations")&&e.classList.remove("has-explanations"),e.style.justifyContent="";const t=window.grammarModeSlider?window.grammarModeSlider.getSliderHTML():"";if(e.innerHTML=`\n<div class="grammar-mode-buttons" id="grammarModeContainer">\n ${t}\n</div>\n<div class="hamdan-speech-bubble">${pe("sidebar.ready")}</div>\n<div class="hamdan-robot-container">\n <div id="gif"></div>\n</div>\n<div class="legend-section" id="legend-section">\n <div class="legend-item">\n <div class="legend-dot change"></div>\n <span class="legend-text">${pe("sidebar.corrected")}</span>\n </div>\n <div class="legend-item">\n <div class="legend-dot add"></div>\n <span class="legend-text">${pe("sidebar.comma")}</span>\n </div>\n <div class="legend-item">\n <div class="legend-dot remove"></div>\n <span class="legend-text">${pe("sidebar.deleted")}</span>\n </div>\n</div>\n<div class="correction-message" style="display: none">\n <span>${pe("sidebar.ready")}</span>\n</div>\n`,window.grammarModeSlider){window.grammarModeSlider.attachListeners();const e=window.grammarModelDepth||2;window.grammarModeSlider.selectLevel(e,!1)}const n=e.querySelector("#gif");n&&this.loadAnimationByState("ready",n)}showPerfectState(){const e=document.querySelector(".improv-inner .correction-content");if(!e)return;e.classList.contains("has-explanations")||e.classList.add("has-explanations"),e.innerHTML=`\n <div class="explanation-header-wrapper">\n <div class="no-of-changes fade-in">
1\n <span class="no-of-changes-text">${pe("sidebar.errors")}</span>\n <span class="no-of-changes-count">0</span>\n </div>\n <div class="explanation-header-left">\n <span class="show-hide-underlines">\n <svg\n xmlns="http://www.w3.org/2000/svg"\n width="18"\n height="18"\n viewBox="0 0 24 24"\n fill="none"\n stroke="currentColor"\n stroke-width="2"\n stroke-linecap="round"\n stroke-linejoin="round"\n class="lucide lucide-eye"\n >\n <path d="M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"></path>\n <circle cx="12" cy="12" r="3"></circle>\n </svg>\n</span>\n\n <button class="explanation-premium-plus-btn">\n ${window.grammarModeSlider?window.grammarModeSlider.getButtonHTML(window.grammarModelDepth||2):`<span>${pe("grammar.standard")}</span><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 20 21" fill="none"><path d="M16.2314 10.0855C16.2314 5.18792 12.7389 1.2146 8.43404 1.2146C4.12918 1.2146 0.636719 5.18792 0.636719 10.0855C0.636719 14.9831 4.12918 18.9564 8.43404 18.9564" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"></path><path d="M6.16406 10.8381H11.4404" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"></path><path d="M4.9248 13.5538L8.8779 4.92114L12.6132 13.5538" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"></path><path d="M10.2764 15.5739L12.8978 19.5472L19.1625 12.3533" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"></path></svg><span class="explanation-premium-plus-tooltip">${pe("grammar.descStandard")}</span>`}\n </button>\n </div>\n </div>\n <div class="perfect-state-bot-container">\n <div style="display: block" class="hamdan-speech-bubble">
1\n <span>${pe("sidebar.textCorrect")}</span>\n </div>\n <div style="display: block" class="hamdan-robot-container">\n <div id="gif"></div>\n </div>\n\n <div class="correction-message" style="display: none">\n <span>${pe("sidebar.ready")}</span>\n </div>\n </div>\n`,this.loadAnimationByState("success","#gif"),document.querySelector(".correction-content").style.justifyContent="center";const t=e.querySelector(".explanation-premium-plus-btn");t&&window.grammarModeSlider&&(t.onclick=e=>{const t=window.grammarModelDepth||2,n=window.grammarModeSlider.getNextLevel(t);"function"==typeof window.selectGrammarMode&&window.selectGrammarMode(n,!0),e.currentTarget.innerHTML=window.grammarModeSlider.getButtonHTML(n)})}hasActiveLoaders(){return this.activeLoaders.size>0}hideAllLoaders(){this.activeLoaders.forEach((e,t)=>{this.hideCorrectionLoader(t)}),this.toggleSmartLoader(!1)}getActiveLoaders(){return Array.from(this.activeLoaders.keys())}};"undefined"!=typeof module&&module.exports&&(module.exports=Mr),"undefined"!=typeof window&&(window.correctionSidebarLoader=Mr);const Ir="hgf_important_secure_bots_text_to_speech";let Br=null,Hr=!1;const Kr=1e4;function Dr(){const e=window.quill1?.root?.innerHTML;if(!e)return"";const t="function"==typeof yn?yn(e):e,n=document.createElement("div");n.innerHTML=t;return(n.textContent||n.innerText||"").trim()}async function Pr(e){if(Hr)return;const t=Dr();if(!t)return console.error("L No text content found"),void alert(pe("tts.noTextToConvert"));if(function(e){if(!window.__SS_PUBLIC_MODE)return!1;const t=Number(window.__SS_PUBLIC_WORD_LIMIT)||200,n=String(e||"").replace(/\s+/g," ").trim();return(n?n.split(" ").length:0)>t}(t))window.SSPublicLoginGate&&"function"==typeof window.SSPublicLoginGate.show?window.SSPublicLoginGate.show({trigger:document.activeElement||null,source:"skrivebord-audio-download-word-limit"}):window.location.href="https://app.skrivsikkert.dk/";else{if(t.length>Kr)return console.error(`L Text exceeds 10000 characters (${t.length} chars)`),void alert(pe("tts.textTooLong",{limit:Kr,current:t.length}));!function(){Hr=!0,rt(pe("download.preparing"),!1);const e=document.getElementById("downloadBtn");e&&(e.innerHTML='<div class="dotted-loader" style="display: inline-block; transform: scale(0.9);">\n <div class="dot"></div>\n <div class="dot"></div>\n <div class="dot"></div>\n <div class="dot"></div>\n <div class="dot"></div>\n <div class="dot"></div>\n <div class="dot"></div>\n <div class="dot"></div>\n </div>',e.disabled=!0)}();try{const n=await Vr(t,function(){const e=function(e){if(!e)return"";const t=String(e).trim();if(!t)return"";if("undefined"!=typeof TTSEngine&&TTSEngine&&"function"==typeof TTSEngine.normalizeLanguage){const e="__unknown_tts_language__",n=TTSEngine.normalizeLanguage(t,e);if(n&&n!==e)return n}const n={da:"Danish",danish:"Danish",en:"English",english:"English",de:"German",ge:"German",german:"German",fr:"French",french:"French",es:"Spanish",spanish:"Spanish",sv:"Swedish",swedish:"Swedish",no:"Norwegian",nb:"Norwegian",nn:"Norwegian",norwegian:"Norwegian",fi:"Finnish",finnish:"Finnish",pl:"Polish",polish:"Polish",it:"Italian",italian:"Ital
1ian",pt:"Portuguese",portuguese:"Portuguese",nl:"Dutch",dutch:"Dutch",tr:"Turkish",turkish:"Turkish",ru:"Russian",russian:"Russian",ar:"Arabic",arabic:"Arabic",ja:"Japanese",japanese:"Japanese",ko:"Korean",korean:"Korean"};return n[t.split("-")[0].toLowerCase()]||n[t.toLowerCase()]||""};try{if("undefined"!=typeof localStorage){const t=localStorage.getItem("ss_chat_lang");if(t){const n=JSON.parse(t),r=n&&e(n.ttsName);if(r)return r;const o=n&&e(n.code);if(o)return o}}}catch(e){}const t="undefined"!=typeof window?window:{},n=e(t.__CHAT_LANG_NAME);if(n)return n;return e(t.__CHAT_LANG)||{da:"Danish",en:"English",ge:"German",fr:"French",es:"Spanish"}[yt()]||"English"}(),function(){return Hr},!1);if("undefined"==typeof TTSEngine||"function"!=typeof TTSEngine.fetchAudio)throw new Error("TTSEngine is not available for audio download");const r=window.HGF_ajax_object||{},o=await TTSEngine.fetchAudio({text:t,lang:n,gender:e,voice:Wr(),quality:"premium",endpoint:r.ajax_url||"/api/grammar-bot.php",action:Ir,maxLength:Kr}),i=document.createElement("a");i.href=o,i.download=`text-to-speech-${Date.now()}.mp3`,document.body.appendChild(i),i.click(),document.body.removeChild(i),setTimeout(function(){try{URL.revokeObjectURL(o)}catch(e){}},1e3),rt(pe("download.success"),!1)}catch(e){console.error("L Download failed:",e),alert(pe("tts.downloadFailed"))}finally{!function(){Hr=!1;const e=document.getElementById("downloadBtn");e&&(e.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>\n <polyline points="7 10 12 15 17 10"></polyline>\n <line x1="12" y1="15" x2="12" y2="3"></line>\n</svg>',e.disabled=!1)}()}}}let Nr,jr=!1,Rr=!1,Fr=null,Or=localStorage.getItem("ss_tts_voice")||"female",Ur=null,$r=null,zr=0;function Gr(){if(zr+=1,$r){try{$r.abort()}catch(e){}$r=null}}async function Vr(e,t,n,r){const o=function(e){return String(e||"").replace(/\s+/g," ").trim().split(" ").filter(Boolean).slice(0,80).join(" ")}(e);if(o.length<3)return t;const i=await async function(){try{if(window.SSGrammarAuth&&"function"==typeof window.SSGrammarAuth.getAuthToken){const e=await window.SSGrammarAuth.getAuthToken();if("string"==typeof e&&e)return e}if(window.SSAuth&&"function"==typeof window.SSAuth.token){const e=await window.SSAuth.token();if("string"==typeof e&&e)return e}if(window._supabase&&window._supabase.auth&&"function"==typeof window._supabase.auth.getSession){const e=await window._supabase.auth.getSession(),t=e&&e.data?e.data.session:null;return t&&t.access_token?t.access_token:""}}catch(e){}return""}();if("function"==typeof n&&!n())return t;const a={"Content-Type":"application/json"};i&&(a.Authorization="Bearer "+i);const l="undefined"!=typeof AbortController?new AbortController:null;r&&($r=l);try{const e=await fetch("/robots/skrivebord/php/tts/doc-lang-classify.php",{method:"POST",credentials:"same-origin",headers:a,body:JSON.stringify({text:o}),signal:l?l.signal:void 0}),n=await e.json().catch(function(){return null}),r=e.ok&&n&&!0===n.ok&&n.data?n.data.language:"";return"string"==typeof r&&r.trim()?"undefined"!=typeof TTSEngine&&TTSEngine&&"function"==typeof TTSEngine.normalizeLanguage?TTSEngine.normalizeLanguage(r,t):r.trim():t}catch(e){return t}finally{r&&$r===l&&($r=null)}}function Wr(){let e="";try{e=localStorage.getItem("ss_tts_voice_variant")||""}catch(e){}return"mads"===e||"lars"===e||"anders"===e||"sofie"===e||"freja"===e||"ida"===e?e:"male"===(localStorage.getItem("ss_tts_voice")||"female")?"mads":"sofie"}let Jr=[],Zr="",Yr="",Qr="",Xr="",eo=!1,to=0,no=[],ro=null,oo=!1;function io(){const e=document.getElementById("readBtn");if(!e)return void console.error("Read button not found in the DOM");const t=e.cloneNode(!0);e.parentNode.replaceChild(t,e),function(){const e=document.createElement("div");e.id="audioControls",e.className="audio-controls",e.style.display="none",e.style.justifyContent="center",e.style.alignItems="center";const t=document.createElement("button");
1t.id="pausePlayBtn",t.className="control-btn tts-contrl-btn",t.setAttribute("aria-label","Pause/Afspil"),t.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">\n <line x1="6" y1="4" x2="6" y2="20"></line>\n <line x1="18" y1="4" x2="18" y2="20"></line>\n </svg>',t.style.border="none",t.style.cursor="pointer",t.style.display="flex",t.style.justifyContent="center",t.style.alignItems="center";const n=document.createElement("button");n.id="stopBtn",n.className="control-btn tts-contrl-btn",n.setAttribute("aria-label","Stop"),n.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24">\n <rect x="5" y="5" width="14" height="14" rx="2" fill="currentColor"></rect>\n </svg>',n.style.border="none",n.style.cursor="pointer",n.style.display="flex",n.style.justifyContent="center",n.style.alignItems="center",t.addEventListener("click",function(e){e.stopPropagation(),jr?Br&&"playing"===Br.getState()?Br.pause():Nr&&(Nr.pause(),jr=!1,bo(),So("paused")):function(){if(Br&&"paused"===Br.getState())Br.resume();else if(Nr)Nr.play().then(()=>{jr=!0,bo(),So("playing"),so()}).catch(ko);else if(Jr.length>0){const e=wo();e&&(to=Jr.length,e.replayFromCache(Jr.slice()))}else Fr&&function(e){const t=URL.createObjectURL(e);Nr=new Audio(t),g(Nr),window.currentTTSAudio=Nr,window.isSpeaking=!1,Nr.onerror=ko,Nr.onended=ao,Nr.play().then(()=>{jr=!0,window.isSpeaking=!0,So("playing"),so(),bo()}).catch(e=>{console.error("â TTS: Audio play failed:",e),ko(e)})}(Fr)}()}),n.addEventListener("click",function(e){e.stopPropagation(),ao()});const r=document.createElement("div");r.className="tts-progress-bar";const o=document.createElement("div");o.className="tts-progress-fill",o.id="ttsProgressFill",r.appendChild(o),e.appendChild(t),e.appendChild(n),e.appendChild(r);const i=document.getElementById("readBtn");if(i)i.style.position="relative",i.style.overflow="visible",i.appendChild(e);else{const t=document.getElementById("copyBtn");t&&t.parentNode?(t.parentNode.style.position="relative",t.parentNode.insertBefore(e,t)):document.body.appendChild(e)}}(),t.addEventListener("click",function(e){Rr?function(){Gr(),Br&&Br.stop();if(go(),Ur&&Ur.xhr){try{Ur.xhr.abort()}catch(e){}Ur=null}Jr=[],Zr="",Yr="",Qr="",Xr="",Nr&&(Nr.pause(),Nr.currentTime=0,Nr.ontimeupdate=null,Nr=null);jr=!1,Rr=!1,So("idle"),co(),Fr=null}():jr||Fr?ao():(Or=localStorage.getItem("ss_tts_voice")||"female",async function(){if(Rr||jr)return;Rr=!0,So("loading");const e=++zr;try{if(!navigator.onLine)throw new Error("No internet connection");const t=await function(e,t){return Vr(e,"Danish",function(){return t===zr&&Rr},!0)}(Dr(),e);if(e!==zr||!Rr)return;po&&clearTimeout(po),po=setTimeout(function(){po=null,Rr&&!jr&&ko(new Error("TTS playback did not start in time"))},2e4),function(e){go();const t=window.quill1.root.innerHTML,n=function(e){const t=document.createElement("div");t.innerHTML=e;const n=[],r=Array.from(t.childNodes);if(0===r.length){return(t.textContent||t.innerText||"").trim()}r.forEach(e=>{if(e.nodeType===Node.TEXT_NODE){const t=e.textContent.trim();t&&n.push(t)}else if(e.nodeType===Node.ELEMENT_NODE){const t=mo(e);t&&n.push(t)}});return n.join("\n").trim()}("function"==typeof yn?yn(t):t);if(!n||""===n)return Rr=!1,void So("idle");const r=e||"Danish",o=function(){const e=window.quill1&&window.quill1.root;if(!e||!e.children)return[];const t=[],n=function(e){const n=function(e){if(!e)return"";const t=mo(e);return t?t.trim():""}(e);n&&t.push({element:e,text:n})};return Array.from(e.children).forEach(function(e){if(!e||e.nodeType!==Node.ELEMENT_NODE)return;const t=e.tagName?e.tagName.toLowerCase():"";"ol"!==t&&"ul"!==t?/^(p|div|h[1-6]|blockquote|pre)$/.test(t)&&n(e):Array.from(e.querySelectorAll("li")).forEach(n)}),t}(),i=o.length>0?function(e,t){no=[];const n=[];return e.forEach(function(e){vo(e.text).forEach(function(r){ho([r],t).forEach(function(t){n.push(t),no.push(e.element)})})}),n}(o,r):ho(vo(n),r);0===o.length&&(no=i.map(function(){return null}));const a=(l=i,TTSEngine.getChunkLanguageSignature(l));var l;if(n===Zr&&Or===Yr&&r===Qr&&a===Xr&&Jr.length>0){Rr=!1;const e=wo();if(e){to=Jr.length,oo=!0;
1try{e.replayFromCache(Jr.slice())}finally{oo=!1}}return}n===Zr&&(Or!==Yr||r!==Qr||a!==Xr)&&Jr.length>0&&(Jr.forEach(e=>{try{URL.revokeObjectURL(e)}catch(e){}}),Jr=[]);Zr=n,Yr=Or,Qr=r,Xr=a,Jr=[];const s=wo();if(!s)return Rr=!1,void ko(new Error("TTSEngine unavailable"));s.gender=Or,to=i.length,oo=!0;try{s.startFromChunks(i)}finally{oo=!1}}(t)}catch(t){if(e!==zr)return;ko(t)}}())}),window.addEventListener("beforeunload",function(){ao()})}function ao(){if(Gr(),Br&&Br.stop(),go(),Ur&&Ur.xhr){try{Ur.xhr.abort()}catch(e){}Ur=null}Nr&&(Nr.pause(),Nr.currentTime=0,Nr.ontimeupdate=null,Nr.onerror=null,Nr.onended=null,Nr=null),Jr=[],Zr="",Yr="",Qr="",Xr="",to=0,jr=!1,Rr=!1,eo=!1,So("idle"),co(),Fr=null}let lo=null;function so(){const e=document.getElementById("audioControls");if(e){lo&&(clearTimeout(lo),lo=null);const t=document.querySelector(".ed-overflow-menu");t&&t.classList.remove("active"),e.style.display="flex",e.style.opacity="1",e.style.pointerEvents="auto";const n=document.getElementById("ttsProgressFill");n&&(n.style.width="0%"),function(){const e=document.getElementById("downloadBtn");if(!e)return!0;const t=Dr().length;t>Kr?(e.disabled=!0,e.style.opacity="0.5",e.style.cursor="not-allowed",e.title=pe("tts.downloadDisabled",{limit:Kr,current:t})):(e.disabled=!1,e.style.opacity="1",e.style.cursor="pointer",e.title=pe("tts.downloadAudio"))}()}}function co(){const e=document.getElementById("audioControls");if(e){e.style.opacity="0",e.style.pointerEvents="none",setTimeout(function(){e.style.display="none"},150);const t=document.getElementById("ttsProgressFill");t&&(t.style.width="0%")}}function uo(e,t){const n=document.getElementById("ttsProgressFill");n&&t>0&&(n.style.width=Math.min(100,Math.round(e/t*100))+"%")}let po=null;function mo(e){if(!e)return"";const t=e.cloneNode(!0);return(t.textContent||t.innerText||"").replace(/\s+/g," ").trim()}function fo(){const e=window.quill1&&window.quill1.root;ro&&ro.classList&&ro.classList.remove("skv2-tts-active"),e&&(e.classList.remove("skv2-tts-playing"),e.querySelectorAll(".skv2-tts-active").forEach(function(e){e.classList.remove("skv2-tts-active")})),ro=null}function go(){fo(),no=[]}function ho(e,t){return TTSEngine.splitChunksWithLanguage(e,t)}function vo(e,t){return TTSEngine.splitText(e,{minWords:t})}function yo(e,t,n,r){var o=Date.now();return new Promise(function(i,a){if(r&&r.aborted)a(new DOMException("Aborted","AbortError"));else{var l=!1,s=jQuery.ajax({url:HGF_ajax_object.ajax_url,type:"POST",data:{action:Ir,nonce:window.HGF_ajax_object.nonce,text:xn(String(e).trim()),lang:t||"Danish",gender:n||Or,voice:Wr()},xhrFields:{responseType:"blob"},success:function(e){l||(e&&0!==e.size?i({audioUrl:URL.createObjectURL(e),latencyMs:Date.now()-o}):a(new Error("Received empty audio file")))},error:function(e,t,n){l||a("abort"===t?new DOMException("Aborted","AbortError"):new Error("HTTP error: "+t+" - "+n))}});r&&r.addEventListener("abort",function(){l=!0;try{s.abort()}catch(e){}a(new DOMException("Aborted","AbortError"))},{once:!0})}})}function wo(){return Br||("undefined"==typeof TTSEngine?(console.error("TTSEngine not loaded"),null):(Br=TTSEngine.create({fetchChunk:yo,gender:Or,onChunkStart:function(e){!function(e){const t=window.quill1&&window.quill1.root,n=no[e]||null;t&&n&&n.classList?(ro&&ro!==n&&ro.classList&&ro.classList.remove("skv2-tts-active"),t.classList.add("skv2-tts-playing"),n.classList.add("skv2-tts-active"),ro=n):fo()}(e.chunkIndex)},onStateChange:function(e){switch(e){case"loading":Rr=!0,jr=!1,eo=!1,So("loading");break;case"playing":Rr=!1,jr=!0,eo=!1,Nr=Br.getAudio(),so(),bo(),So("playing");break;case"paused":jr=!1,bo(),So("paused");break;case"buffering":break;case"complete":jr=!1,Rr=!1,eo=!1,Jr=Br.getCachedUrls(),uo(to,to),lo&&clearTimeout(lo),lo=setTimeout(function(){co(),lo=null},2500),So("idle"),go();break;case"error":jr=!1,Rr=!1,eo=!1,So("idle"),co(),go();break;case"idle":jr=!1,Rr=!1,eo=!1,oo||go()}},onProgress:function(e){uo(e.chunkIndex+(e.duration>0?e.currentTime/e.duration:0),e.chunkTotal)},onChunkFetched:function(e){Jr[e.chunkIndex]=e.audioUrl},onError:function(e){e.fatal&&console.error("[TTS] Chunk "+(e.chunkIndex+1)+" failed after retries")},onTelemetry:function(e){"function"==typeof ss_track&&ss_track("tts_"+e.event,{chunks:e.totalChunks,retries:e.retries,underruns:e.underruns,avg_latency_ms:e.avgLatencyMs,elapsed_ms:e.elapsedMs,surface:"skrivebord"})}}),Br))}function bo(){const e=document.getElementById("pausePlayBtn");e&&(e.innerHTML=eo?'<span class="loading-spinner"></span>':jr?'<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">\n <line x1="6" y1="4" x2="6" y2="20"></line>\n <line x1="18" y1="4" x2="18" y2="20"></line>\n </svg>':'<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="currentColor" stroke="none">\n <polygon points="5 3 19 12 5 21 5 3"></polygon>\n </svg>')}function ko(e){console.error(e.message),Rr=!1,jr=!1,Ur=null,So("idle"),co()}function So(e){const t=document.getElementById("readBtn");if(!t)return;"loading"!==e&&po&&(clearTimeout(po),po=null);
1t.querySelectorAll(".loader").forEach(e=>e.remove());const n=t.querySelector("#audioControls");switch(e){case"loading":t.style.backgroundColor="",t.style.color="",t.dataset.ttsState="loading",t.setAttribute("aria-label",pe("tts.cancelReading")),t.setAttribute("title",pe("tts.cancelReading"));{const e=t.querySelector("svg:not(#audioControls svg)");e&&(e.style.display="none");const r=document.createElement("div");r.className="loader",r.style.display="inline-flex",r.style.alignItems="center",r.style.justifyContent="center",r.innerHTML='<span class="loading-spinner" style="height:18px;width:18px;"></span>',t.insertBefore(r,n)}break;case"playing":case"paused":t.style.backgroundColor="rgba(155, 96, 80, 0.12)",t.style.color="#9B6050",t.dataset.ttsState="playing",t.setAttribute("aria-label",pe("tts.stopReading")),t.setAttribute("title",pe("tts.stopReading"));{const e=t.querySelector("svg:not(#audioControls svg)");e&&e.remove();const r=document.createElement("div");r.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" stroke="none">\n <rect x="5" y="5" width="14" height="14" rx="2"></rect>\n </svg>',t.insertBefore(r.firstChild,n)}break;default:t.style.backgroundColor="",t.style.color="",t.dataset.ttsState="idle",t.setAttribute("aria-label",pe("tts.readAloud")),t.setAttribute("title",pe("tts.readAloud"));{const e=t.querySelector("svg:not(#audioControls svg)");e&&e.remove();const r=document.createElement("div");r.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n <polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"></polygon>\n <path d="M15.54 8.46a5 5 0 0 1 0 7.07"></path>\n <path d="M19.07 4.93a10 10 0 0 1 0 14.14"></path>\n </svg>',t.insertBefore(r.firstChild,n)}}}TTSEngine.TTS_CHUNK_MAX_CHARS;const xo=window.HGF_ajax_object?.ajax_url||window.ajaxurl||"/wp-admin/admin-ajax.php";let To={isPlaying:!1,currentAudio:null,currentAudioUrl:null,isPaused:!1,currentTime:0,duration:0,volume:p(),isMuted:!1},Lo=null,Eo=null,Co=!1,_o=null;function Ao(){document.addEventListener("click",function(e){if(e.target.closest(".explanation-audio-btn")){e.preventDefault(),e.stopPropagation();const t=e.target.closest(".explanation-audio-btn");if(t.disabled||Co)return;const n=t.dataset.state;"play"===n?async function(e){if(Co)return;Lo&&qo();const t=e.closest(".explanation-item"),n=t?.querySelector(".change-reason"),r=n?.textContent?.trim();if(!r)return;Co=!0,Ho(e,"loading"),Eo=e;try{const e=yt();let t={da:"da",en:"en",ge:"de",fr:"fr",es:"es"}[e]||e;t&&"string"==typeof t&&""!==t.trim()||(t="en");const n="female",o=new FormData;if(o.append("action","hgf_important_secure_bots_text_to_speech"),o.append("nonce",window.HGF_ajax_object?.nonce||""),o.append("text",xn(function(e){if(!e)return"";let t=e.replace(/^%%\s*:?\s*/i,"").trim();return t=t.replace(/<[^>]*>/g,"").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),t=t.replace(/^#{1,6}\s+/gm,"").replace(/\*\*(.*?)\*\*/g,"$1").replace(/__(.*?)__/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/_(.*?)_/g,"$1").replace(/~~(.*?)~~/g,"$1").replace(/```[\s\S]*?```/g,"").replace(/`([^`]+)`/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/^[-*]{3,}$/gm,"").replace(/^>\s*/gm,"").replace(/^[\s]*[-*+]\s+/gm,"").replace(/^[\s]*\d+\.\s+/gm,"").replace(/\n\s*\n/g,"\n").replace(/[ \t]+/g," ").trim(),t=t.replace(/["'ââââ:]/g,""),t}(r))),o.append("language",t),o.append("gender",n),_o)try{_o.abort()}catch(e){}_o=new AbortController;const{signal:i}=_o,a=await fetch(xo,{method:"POST",body:o,signal:i});if(!a.ok){const e=await a.text().catch(()=>"Unknown error");throw new Error(`WordPress AJAX Error: ${a.status} - ${e}`)}const l=await a.blob(),s=URL.createObjectURL(l);await async function(e){try{const t=new Audio(e);g(t),Lo=t,To.currentAudio=t,To.currentAudioUrl=e,function(e){e.onloadstart=()=>{},e.oncanplay=()=>{To.duration=e.duration},e.onplay=()=>{To.isPlaying=!0,To.isPaused=!1},e.onpause=()=>{To.isPlaying=!1,To.isPaused=!0},e.ontimeupdate=()=>{To.currentTime=e.currentTime},e.onended=()=>{To.isPlaying=!1,To.isPaused=!1,To.currentTime=0,qo()},e.onerror=e=>{To.isPlaying=!1,Bo()}}(t),t.volume=To.volume,t.muted=To.isMuted,await t.play(),Ho(Eo,"stop")}catch(e){Bo()}}(s)}catch(e){Bo()}finally{Co=!1,_o&&(_o=null)}}(t):"stop"===n&&qo()}}),document.addEventListener("click",function(e){if(!e.target.closest(".explanation-audio-btn"))try{Io()}catch(e){}})}function qo(){if(Lo&&(Lo.pause(),Lo.currentTime=0,Lo=null),_o){try{_o.abort()}catch(e){}_o=null}To.isPlaying=!1,To.isPaused=!1,To.currentTime=0,Eo&&(Ho(Eo,"play"),Eo=null),Co=!1}function Mo(){Lo&&(Lo.pause(),Lo.currentTime=0,Lo.src="",Lo=null),To.currentAudioUrl&&(URL.revokeObjectURL(To.currentAudioUrl),To.currentAudioUrl=null),To.isPlaying=!1,To.isPaused=!1,To.currentTime=0,To.duration=0,To.currentAudio=null,Eo&&(Ho(Eo,"play"),Eo=null),Co=!1}function Io(){if(_o)try{_o.abort(),_o=null}catch(e){}Lo&&(Lo.pause(),Lo.currentTime=0,Lo=null),Co=!1,Eo&&(Ho(Eo,"play"),Eo=null)}function Bo(){Mo()}function Ho(e,t){if(!e)return;const n=e.querySelector(".play-icon"),r=e.querySelector(".stop-icon");switch(e.dataset.state=t,t){case"play":n.style.display="inline",r.style.display="none",e.style.opacity="1",e.disabled=!1;break;case"stop":n.style.display="none",r.style.display="inline",e.disabled=!1,e.style.opacity="1";break;case"loading":e.disabled=!0,e.style.opacity="0.6"}}async function Ko(e){const t=window.quill1,n=t&&t.root?t.root.innerHTML:"",r=wn(yn(n)),o=bn(window.convertBulletListToUl(r)),i=It(),a=new URLSearchParams({action:"hgf_ask_robot_process",command:e,language:i,content:o,nonce:HGF_ajax_object.nonce});let l=(await async function(e){const t=be();try{const n=await fetch(HGF_ajax_object.ajax_url,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/x-www-form-urlencoded;"},body:e.toString(),signal:t.signal});if(window.isRequestCancelled&&window.isRequestCancelled())throw new Error("Request cancelled");const r=await n.json();if(!r||!r.success)throw new Error(r&&r.error_message||"Ask request failed");return r.data&&r.data.content||r.content||""}catch(e){if("AbortError"===e.name)throw new Error("Request cancelled");throw e}finally{ke()}}(a)).replace(/\\/g,"");return l=l.replace(/```html|```HTML/g,""),l=l.replace(/```/g,""),l}async function Do(e){const t=window.quill1,n=t&&t.root?t.root.innerHTML:"",r=wn(yn(n)),o=bn(window.convertBulletListToUl(r)),i=It(),a=new URLSearchParams({action:"hgf_edit_robot_process",command:e,language:i,content:o,nonce:HGF_ajax_object.nonce});let l=(await async function(e){const t=be();try{const n=await fetch(HGF_ajax_object.ajax_url,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/x-www-form-urlencoded;"},body:e.toString(),signal:t.signal});if(window.isRequestCancelled&&window.isRequestCancelled())throw new Error("Request cancelled");const r=await n.json();if(!r||!r.success)throw new Error(r&&r.error_message||"Edit request failed");return r.data&&r.data.content||r.content||""}catch(e){if("AbortError"===e.name)throw new Error("Request cancelled");throw e}finally{ke()}}(a)).replace(/\\/g,"");return l=l.replace(/```html|```HTML/g,""),l=l.replace(/```/g,""),l}async function Po(e,t,n){try{if(!e||!t||!n)throw new Error("Missing command, selected text, or full text");let r="";if(window.quill1)try{const e=window.quill1.getSelection();if(e&&e.length>0){const t=window.quill1.getContents(e.index,e.length),n=document.createElement("div");n.style.display="none",document.body.appendChild(n);const o=new Quill(n,{theme:null,modules:{}});o.setContents(t),r=o.root.innerHTML,document.body.removeChild(n)}}catch(e){console.error("Error getting selection HTML:",e),r=t}const o=window.quill1&&window.quill1.root?window.quill1.root.innerHTML:"",i=wn(yn(o)),a=r?wn(yn(r)):"",l=window.convertBulletListToUl(bn(window.convertBulletListToUl(i))),s=window.convertBulletListToUl(bn(window.convertBulletListToUl(a))),c=It(),d=new URLSearchParams({action:"hgf_sidebar_robot_ask_selection_process",command:e,language:c,full_text:l,selected_text:s||t,nonce:HGF_ajax_object.nonce}),u=be(),p=await fetch(HGF_ajax_object.ajax_url,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/x-www-form-urlencoded;"},body:d.toString(),signal:u.signal}),m=await p.json();if(window.isRequestCancelled&&window.isRequestCancelled())throw new Error("Request cancelled");if(!m.success)throw new Error(m.data?.error_message||"Request failed");const f=(m&&m.data&&m.data.content||m.content||"").toString().trim();if(!f)throw new Error("Empty response");return f}catch(e){if("AbortError"===e.name)throw new Error("Request cancelled");throw console.error("Ask selection processing error:",e),e}finally{ke()}}async function No(e,t,n){try{if(!e||!t||!n)throw new Error("Missing command, selected text, or full text");let r="";if(window.quill1)try{const e=window.quill1.getSelection();if(e&&e.length>0){const t=window.quill1.getContents(e.index,e.length),n=document.createElement("div");n.style.display="none",document.body.appendChild(n);const o=new Quill(n,{theme:null,modules:{}});o.setContents(t),r=o.root.innerHTML,document.body.removeChild(n)}}catch(e){console.error("Error getting selection HTML:",e),r=t}const o=window.quill1&&window.quill1.root?window.quill1.root.innerHTML:"",i=wn(yn(o)),a=r?wn(yn(r)):"",l=window.convertBulletListToUl(bn(window.convertBulletListToUl(i))),s=window.convertBulletListToUl(bn(window.convertBulletListToUl(a))),c=It(),d=new URLSearchParams({action:"hgf_sidebar_robot_edit_selection_process",command:e,language:c,full_text:l,selected_text:s||t,nonce:HGF_ajax_object.nonce}),u=be(),p=await fetch(HGF_ajax_object.ajax_url,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/x-www-form-urlencoded;"},body:d.toString(),signal:u.signal}),m=await p.json();if(window.isRequestCancelled&&window.isRequestCancelled())throw new Error("Request cancelled");if(!m.success)throw new Error(m.data?.error_message||"Request failed");const f=(m&&m.data&&m.data.content||m.content||"").toString().trim();if(!f)throw new Error("Empty response");return f}catch(e){if("AbortError"===e.name)throw new Error("Request cancelled");throw console.error("Edit selection processing error:",e),e}finally{ke()}}"undefined"!=typeof window&&(window.stopExplanationSpeaking=function(){qo()},window.cleanupExplanationTTS=function(){Mo()},window.getExplanationTTSState=function(){return{...To}});let jo=null,Ro=null;function Fo(){jo&&(clearTimeout(jo),jo=null),Ro&&(Ro.stop(),Ro=null),window.sidebarSTT=null}let Oo=null;function Uo(){if("function"==typeof window.cleanupSidebarAudio&&window.cleanupSidebarAudio(),Oo){try{Oo.pause(),Oo.currentTime=0,Oo.src=""}catch(e){}!function(e){if(!e)return;const t=e.cloneNode(!0);e.parentNode&&e.parentNode.replaceChild(t,e)}(Oo)}Oo=null;const e=document.getElementById("sidebar-volume-bar");e&&e.classList.remove("show"),function(e){const t=document.getElementById("sidebar-audio-play-pause");t&&(t.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="11" height="15" viewBox="0 0 11 15" fill="none">\n<path d="M5.503 2.00999L5.437 1.96998C4.689 1.51498 4.031 1.11399 3.467 0.911985C3.15609 0.792491 2.8237 0.739024 2.491 0.754985C2.14078 0.781719 1.80602 0.910336 1.528 1.12498C0.949 1.55898 0.699 2.19799 0.562 2.90499C0.429 3.58999 0.378 4.48198 0.315 5.56798L0.312 5.62398C0.274 6.27398 0.25 6.91698 0.25 7.49998C0.25 8.08298 0.274 8.72698 0.312 9.37698L0.315 9.43198C0.378 10.518 0.429 11.41 0.562 12.094C0.699 12.802 0.949 13.44 1.528 13.875C1.814 14.09 2.135 14.218 2.491 14.245C2.833 14.27 3.161 14.198 3.467 14.088C4.031 13.886 4.689 13.485 5.437 13.031L5.503 12.991C5.929 12.731 6.347 12.464 6.72 12.201C7.1768 11.876 7.62207 11.5351 8.055 11.179L8.105 11.138C8.869 10.515 9.517 9.98598 9.965 9.46598C10.453 8.89598 10.75 8.28398 10.75 7.49998C10.75 6.71598 10.453
16.10299 9.964 5.53399C9.517 5.01399 8.869 4.48399 8.106 3.86199L8.056 3.82099C7.602 3.45099 7.146 3.09698 6.72 2.79898C6.32274 2.52292 5.91687 2.26045 5.503 2.00999Z" fill="#6C757D"/>\n</svg>',t.classList.toggle("playing",e))}(!1)}window.cleanupSidebarAudioControls=Uo;const $o=window.HGF_ajax_object?.ajax_url||window.ajaxurl||"/wp-admin/admin-ajax.php";let zo={isPlaying:!1,currentAudio:null,currentAudioUrl:null,isPaused:!1,currentTime:0,duration:0,volume:p(),isMuted:!1,cachedText:null,cachedLanguage:"da"},Go=!1,Vo=m(),Wo=null,Jo={volumeBtn:null};function Zo(){Jo={playPauseBtn:document.getElementById("sidebar-audio-play-pause"),progressFill:document.getElementById("sidebar-audio-progress-fill"),volumeBtn:document.getElementById("sidebar-audio-volume"),progressTrack:document.querySelector(".sidebar-audio-progress-track")},Jo.volumeBtn&&ui()}function Yo(e,t="da"){if(!e||0===e.trim().length)return;const n=xn(e.trim()),r="ge"===(t||"da").toLowerCase()?"de":t||"da";zo.currentAudio&&zo.cachedText===n?zo.isPlaying?oi():ti():(null!==zo.cachedText&&zo.cachedText!==n&&fi(),zo.cachedText=n,zo.cachedLanguage=r,ti())}async function Qo(e=!1){if(!zo.cachedText)return;const t=ye("tts");try{zo.currentAudio&&(zo.currentAudio.pause(),zo.currentAudio.onplay=null,zo.currentAudio.onpause=null,zo.currentAudio.ontimeupdate=null,zo.currentAudio.onended=null,zo.currentAudio.oncanplay=null,zo.currentAudio.onerror=null,zo.currentAudio.src=""),zo.currentAudioUrl&&URL.revokeObjectURL(zo.currentAudioUrl),zo.currentAudio=null,zo.currentAudioUrl=null,pi();const n=new FormData;n.append("action","hgf_important_secure_bots_text_to_speech"),n.append("nonce",window.HGF_ajax_object?.nonce||""),n.append("text",zo.cachedText),n.append("language",zo.cachedLanguage),n.append("gender","female");const r=await fetch($o,{method:"POST",body:n,signal:t.signal});if(window.isRequestCancelled&&window.isRequestCancelled())throw new Error("TTS request cancelled");if(!r.ok){const e=await r.text().catch(()=>"Unknown error");throw new Error(`WordPress AJAX Error: ${r.status} - ${e}`)}const o=await r.blob();if(window.isRequestCancelled&&window.isRequestCancelled())throw new Error("TTS request cancelled");const i=URL.createObjectURL(o);if(window.isRequestCancelled&&window.isRequestCancelled())throw URL.revokeObjectURL(i),new Error("TTS request cancelled");await async function(e,t=!1){if(window.isRequestCancelled&&window.isRequestCancelled())return void URL.revokeObjectURL(e);try{const n=new Audio(e),r=g(n);if(window.isRequestCancelled&&window.isRequestCancelled())return void URL.revokeObjectURL(e);zo.currentAudio=n,zo.currentAudioUrl=e,zo.volume=r,function(e){e.onloadstart=()=>{},e.oncanplay=()=>{zo.duration=e.duration},e.onplay=()=>{zo.isPlaying=!0,zo.isPaused=!1,Xo("playing"),pi(),Wo=setInterval(()=>{zo.currentAudio&&zo.isPlaying&&(zo.currentTime=zo.currentAudio.currentTime,ni())},100),ui()},e.onpause=()=>{zo.isPlaying=!1,zo.isPaused=!0,e&&!isNaN(e.currentTime)&&(zo.currentTime=e.currentTime),Xo("paused"),pi()},e.ontimeupdate=()=>{e&&zo.currentAudio&&(zo.currentTime=e.currentTime,ni())},e.onended=()=>{zo.isPlaying=!1,zo.isPaused=!1,zo.currentTime=0,Xo("stopped"),pi(),zo.currentAudio&&(zo.currentAudio.currentTime=0)},e.onerror=e=>{console.error("â Sidebar audio playback error:",e),zo.isPlaying=!1,Xo("error")}}(n),n.muted=zo.isMuted,t||Xo("paused")}catch(e){throw console.error("â Error playing sidebar audio:",e),e}}(i,e)}catch(e){if("AbortError"===e.name||"TTS request cancelled"===e.message)return;throw console.error("SIDEBAR TTS REQUEST ERROR:",e),ti(),e}finally{(n=t)&&"function"==typeof n.clear&&n.clear()}var n}function Xo(e){zo.isPlaying="playing"===e,zo.isPaused="paused"===e,ti(),ni()}function ei(){Te(),ti()}function ti(){const e=document.getElementById("sidebar-audio-play-pause");e&&(e.classList.remove("loading"),zo.isPlaying?(e.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="12" height="15" viewBox="0 0 12 15" fill="none">\n<path d="M2 0.75C1.53587 0.75 1.09075 0.934375 0.762563 1.26256C0.434375 1.59075 0.25 2.03587 0.25 2.5V12.5C0.25 13.466 1.034 14.25 2 14.25H3C3.46413 14.25 3.90925 14.0656 4.23744 13.7374C4.56563 13.4092 4.75 12.9641 4.75 12.5V2.5C4.75 2.03587 4.56563 1.59075 4.23744 1.26256C3.90925 0.934375 3.46413 0.75 3 0.75H2ZM8.5 0.75C8.03587 0.75 7.59075 0.934375 7.26256 1.26256C6.93437 1.59075 6.75 2.03587 6.75 2.5V12.5C6.75 13.466 7.534 14.25 8.5 14.25H9.5C9.96413 14.25 10.4092 14.0656 10.7374 13.7374C11.0656 13.4092 11.25 12.9641 11.25 12.5V2.5C11.25 2.03587 11.0656 1.59075 10.7374 1.26256C10.4092 0.934375 9.96413 0.75 9.5 0.75H8.5Z" fill="#6C757D"/>\n</svg>',e.classList.add("playing")):(e.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="11" height="15" viewBox="0 0 11 15" fill="none">\n<path d="M5.503 2.00999L5.437 1.96998C4.689 1.51498 4.031 1.11399 3.467 0.911985C3.15609 0.792491 2.8237 0.739024 2.491 0.754985C2.14078 0.781719 1.80602 0.910336 1.528 1.12498C0.949 1.55898 0.699 2.19799 0.562 2.90499C0.429 3.58999 0.378 4.48198 0.315 5.56798L0.312 5.62398C0.274 6.27398 0.25 6.91698 0.25 7.49998C0.25 8.08298 0.274 8.72698 0.312 9.37698L0.315 9.43198C0.378 10.518 0.429 11.41 0.562 12.094C0.699 12.802 0.949 13.44 1.528 13.875C1.814 14.09 2.135 14.218 2.491 14.245C2.833 14.27 3.161 14.198 3.467 14.088C4.031 13.886 4.689 13.485 5.437 13.031L5.503 12.991C5.929 12.731 6.347 12.464 6.72 12.201C7.1768 11.876 7.62207 11.5351 8.055 11.179L8.105 11.138C8.869 10.515 9.517 9.98598 9.965 9.46598C10.453 8.89598 10.75 8.28398 10.75 7.49998C10.75 6.71598 10.453
16.10299 9.964 5.53399C9.517 5.01399 8.869 4.48399 8.106 3.86199L8.056 3.82099C7.602 3.45099 7.146 3.09698 6.72 2.79898C6.32274 2.52292 5.91687 2.26045 5.503 2.00999Z" fill="#6C757D"/>\n</svg>',e.classList.remove("playing")),e.onclick=()=>window.toggleSidebarAudio())}function ni(){const e=document.getElementById("sidebar-audio-progress-fill");if(!e)return;if(!zo.duration||0===zo.duration)return;zo.currentAudio&&!isNaN(zo.currentAudio.currentTime)&&(zo.currentTime=zo.currentAudio.currentTime);const t=zo.currentTime/zo.duration*100,n=Math.min(100,Math.max(0,t));e.style.width=`${n}%`}async function ri(){if(zo.isPlaying)oi();else if(zo.currentAudio)(zo.currentAudio.ended||zo.currentTime>=zo.duration)&&(zo.currentAudio.currentTime=0,zo.currentTime=0,ni()),ii();else{if(!zo.cachedText)return;!function(){const e=document.getElementById("sidebar-audio-play-pause");e&&(e.innerHTML='<div class="dotted-loader">\n <div class="dot"></div>\n <div class="dot"></div>\n <div class="dot"></div>\n <div class="dot"></div>\n <div class="dot"></div>\n <div class="dot"></div>\n <div class="dot"></div>\n <div class="dot"></div>\n </div>',e.classList.add("loading"),e.onclick=ei)}();try{await Qo(!0),ii()}catch(e){"AbortError"!==e.name&&"TTS request cancelled"!==e.message&&console.warn("Sidebar TTS failed:",e),ti()}}}function oi(){zo.currentAudio&&zo.isPlaying&&zo.currentAudio.pause()}function ii(){zo.currentAudio&&((zo.currentAudio.ended||zo.currentTime>=zo.duration)&&(zo.currentAudio.currentTime=0,zo.currentTime=0),zo.currentAudio.play())}function ai(){Go=!Go;const e=document.getElementById("sidebar-volume-bar"),t=document.getElementById("sidebar-audio-volume");e&&(Go?(e.classList.add("show"),t&&t.classList.add("volume-bar-open"),document.addEventListener("click",li),setTimeout(()=>ci(),100)):(e.classList.remove("show"),t&&t.classList.remove("volume-bar-open"),document.removeEventListener("click",li)))}function li(e){if(!e.target.closest(".sidebar-volume-container")&&Go){Go=!1;const e=document.getElementById("sidebar-volume-bar"),t=document.getElementById("sidebar-audio-volume");e&&e.classList.remove("show"),t&&t.classList.remove("volume-bar-open"),document.removeEventListener("click",li)}}let si=null;function ci(){const e=document.getElementById("sidebar-volume-handle"),t=document.querySelector(".sidebar-volume-track");if(!e||!t)return;si&&e.removeEventListener("mousedown",si);let n=!1;function r(e){e.preventDefault(),e.stopPropagation(),n=!0,document.addEventListener("mousemove",o),document.addEventListener("mouseup",i)}function o(e){if(!n)return;e.preventDefault(),e.stopPropagation();const r=t.getBoundingClientRect(),o=e.clientY-r.top,i=Math.max(0,Math.min(1,1-o/r.height));di(Math.round(100*i))}function i(){n=!1,document.removeEventListener("mousemove",o),document.removeEventListener("mouseup",i)}si=r,e.addEventListener("mousedown",r)}function di(e){const t=5*Math.round(e/5);Vo=Math.max(0,Math.min(100,t));const n=f(Vo);zo.volume=n,zo.isMuted=0===Vo,function(e){const t=document.getElementById("sidebar-volume-fill"),n=document.getElementById("sidebar-volume-handle");if(t&&n){const r=e;t.style.height=`${r}%`,n.style.bottom=r-10+"%"}}(Vo),zo.currentAudio&&(0===Vo?zo.currentAudio.muted=!0:(zo.currentAudio.muted=!1,zo.currentAudio.volume=n)),ui()}function ui(){const e=document.getElementById("sidebar-audio-volume");e&&(zo.isMuted||0===Vo?(e.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18" fill="none">\n<path d="M13.5 10.6071L15 9.10713M15 9.10713L16.5 7.60713M15 9.10713L13.5 7.60713M15 9.10713L16.5 10.6071" stroke="none" stroke-linecap="round" stroke-linejoin="round"></path>\n<path d="M1.5 10.4999V7.71438C1.5 7.31655 1.65804 6.93502 1.93934 6.65372C2.22064 6.37241 2.60218 6.21438 3 6.21438H5.175C5.32164 6.21434 5.46505 6.17132 5.5875 6.09063L10.0875 3.12363C10.2006 3.04917 10.3317 3.0067 10.4669 3.00073C10.6022 2.99476 10.7365 3.02551 10.8557 3.08972C10.9749 3.15392 11.0745 3.24919 11.1439 3.36542C11.2133 3.48165 11.25 3.6145 11.25 3.74988V14.4644C11.25 14.5998 11.2133 14.7326 11.1439 14.8488C11.0745 14.9651 10.9749 15.0603 10.8557 15.1245C10.7365 15.1887 10.6022 15.2195 10.4669
115.2135C10.3317 15.2076 10.2006 15.1651 10.0875 15.0906L5.5875 12.1236C5.46505 12.0429 5.32164 11.9999 5.175 11.9999H3C2.60218 11.9999 2.22064 11.8418 1.93934 11.5605C1.65804 11.2792 1.5 10.8977 1.5 10.4999Z" stroke="#6C757D"></path>\n</svg>',e.classList.add("muted")):(e.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18" fill="none">\n<path d="M15.375 5.73213C15.375 5.73213 16.5 6.85713 16.5 8.73213C16.5 10.6071 15.375 11.7321 15.375 11.7321" stroke="none" stroke-linecap="round" stroke-linejoin="round"></path>\n<path d="M2.25 10.4999V7.71438C2.25 7.31655 2.40804 6.93502 2.68934 6.65372C2.97064 6.37241 3.35218 6.21438 3.75 6.21438H5.925C6.07164 6.21434 6.21505 6.17132 6.3375 6.09063L10.8375 3.12363C10.9506 3.04917 11.0817 3.0067 11.2169 3.00073C11.3522 2.99476 11.4865 3.02551 11.6057 3.08972C11.7249 3.15392 11.8245 3.24919 11.8939 3.36542C11.9633 3.48165 12 3.6145 12 3.74988V14.4644C12 14.5998 11.9633 14.7326 11.8939 14.8488C11.8245 14.9651 11.7249 15.0603 11.6057 15.1245C11.4865 15.1887 11.3522 15.2195 11.2169 15.2135C11.0817 15.2076 10.9506 15.1651 10.8375 15.0906L6.3375 12.1236C6.21505 12.0429 6.07164 11.9999 5.925 11.9999H3.75C3.35218 11.9999 2.97064 11.8418 2.68934 11.5605C2.40804 11.2792 2.25 10.8977 2.25 10.4999Z" stroke="#6C757D"></path>\n</svg>',e.classList.remove("muted")))}function pi(){Wo&&(clearInterval(Wo),Wo=null)}function mi(e){if(!zo.currentAudio||!zo.duration)return;const t=e.currentTarget.getBoundingClientRect(),n=(e.clientX-t.left)/t.width*zo.duration;zo.currentAudio.currentTime=n,zo.currentTime=n,ni()}function fi(){if(pi(),zo.currentAudio){const e=zo.currentAudio;e.pause(),e.currentTime=0,e.onplay=null,e.onpause=null,e.ontimeupdate=null,e.onended=null,e.oncanplay=null,e.onerror=null,e.src="",zo.currentAudio=null}zo.currentAudioUrl&&(URL.revokeObjectURL(zo.currentAudioUrl),zo.currentAudioUrl=null),zo.isPlaying=!1,zo.isPaused=!1,zo.currentTime=0,zo.duration=0;const e=document.getElementById("sidebar-audio-volume"),t=document.getElementById("sidebar-volume-bar");e&&e.classList.remove("volume-bar-open"),t&&t.classList.remove("show"),Go=!1,Xo("stopped")}"undefined"!=typeof window&&(window.toggleSidebarAudio=ri,window.toggleSidebarVolume=ai,window.seekSidebarAudio=mi,window.cleanupSidebarAudio=fi,window.stopSidebarTTS=function(){fi()},window.forceCleanupSidebarAudio=function(){fi()},window.refreshSidebarTTSProgress=function(){zo.currentAudio&&!zo.isPlaying&&(isNaN(zo.currentAudio.currentTime)||(zo.currentTime=zo.currentAudio.currentTime),ni())},window.handleVolumeClick=function(e){e.stopPropagation();const t=e.currentTarget.getBoundingClientRect(),n=e.clientY-t.top,r=Math.max(0,Math.min(1,1-n/t.height));di(Math.round(100*r))},window.setVolumeLevel=di,window.initVolumeSliderDrag=ci,window.startSidebarTTS=Yo);const gi=window.HGF_ajax_object?.ajax_url||window.ajaxurl||"/wp-admin/admin-ajax.php",hi={audio:null,audioUrl:null,isPlaying:!1,isPaused:!1,currentTime:0,duration:0,cachedText:null,requestController:null,progressInterval:null,volumeLevel:m(),volumeSliderVisible:!1,volumeDragInitialized:!1,volumeDragHandler:null};function vi(){hi.requestController&&(hi.requestController.abort(),hi.requestController=null),yi()}function yi(){const e=document.getElementById("analyze-bubble-play-pause");e&&(e.classList.remove("loading"),hi.isPlaying?(e.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="12" height="15" viewBox="0 0 12 15" fill="none">\n<path d="M2 0.75C1.53587 0.75 1.09075 0.934375 0.762563 1.26256C0.434375 1.59075 0.25 2.03587 0.25 2.5V12.5C0.25 13.466 1.034 14.25 2 14.25H3C3.46413 14.25 3.90925 14.0656 4.23744 13.7374C4.56563 13.4092 4.75 12.9641 4.75 12.5V2.5C4.75 2.03587 4.56563 1.59075 4.23744 1.26256C3.90925 0.934375 3.46413 0.75 3 0.75H2ZM8.5 0.75C8.03587 0.75 7.59075 0.934375 7.26256 1.26256C6.93437 1.59075 6.75 2.03587 6.75 2.5V12.5C6.75 13.466 7.534 14.25 8.5 14.25H9.5C9.96413 14.25 10.4092 14.0656 10.7374 13.7374C11.0656 13.4092 11.25 12.9641 11.25 12.5V2.5C11.25 2.03587 11.0656 1.59075 10.7374 1.26256C10.4092 0.934375 9.96413 0.75 9.5 0.75H8.5Z" fill="#6C757D"/>\n</svg>',e.classList.add("playing")):(e.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="11" height="15" viewBox="0 0 11 15" fill="none">\n<path d="M5.503 2.00999L5.437 1.96998C4.689 1.51498 4.031 1.11399 3.467 0.911985C3.15609 0.792491 2.8237 0.739024 2.491 0.754985C2.14078 0.781719 1.80602 0.910336 1.528 1.12498C0.949 1.55898 0.699 2.19799 0.562 2.90499C0.429 3.58999 0.378 4.48198 0.315 5.56798L0.312 5.62398C0.274 6.27398 0.25 6.91698 0.25 7.49998C0.25 8.08298 0.274 8.72698 0.312 9.37698L0.315 9.43198C0.378 10.518 0.429 11.41 0.562 12.094C0.699 12.802 0.949 13.44 1.528 13.875C1.814 14.09 2.135 14.218 2.491 14.245C2.833 14.27 3.161 14.198 3.467 14.088C4.031 13.886 4.689 13.485 5.437 13.031L5.503 12.991C5.929 12.731 6.347 12.464 6.72 12.201C7.1768 11.876 7.62207 11.5351 8.055 11.179L8.105 11.138C8.869 10.515 9.517 9.98598 9.965 9.46598C10.453 8.89598 10.75 8.28398 10.75 7.49998C10.75 6.71598 10.453
16.10299 9.964 5.53399C9.517 5.01399 8.869 4.48399 8.106 3.86199L8.056 3.82099C7.602 3.45099 7.146 3.09698 6.72 2.79898C6.32274 2.52292 5.91687 2.26045 5.503 2.00999Z" fill="#6C757D"/>\n</svg>',e.classList.remove("playing")),e.onclick=()=>window.toggleAnalyzeBubbleAudio())}function wi(){const e=document.getElementById("analyze-bubble-progress-fill");if(!e)return;if(!hi.duration||0===hi.duration)return;hi.audio&&!isNaN(hi.audio.currentTime)&&(hi.currentTime=hi.audio.currentTime);const t=hi.currentTime/hi.duration*100,n=Math.min(100,Math.max(0,t));e.style.width=`${n}%`}function bi(){const e=document.getElementById("analyze-bubble-volume-fill"),t=document.getElementById("analyze-bubble-volume-handle");e&&t&&(e.style.height=`${hi.volumeLevel}%`,t.style.bottom=hi.volumeLevel-10+"%")}function ki(){const e=document.getElementById("analyze-bubble-volume");e&&(0===hi.volumeLevel?e.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18" fill="none">\n<path d="M2.25 10.4999V7.71438C2.25 7.31655 2.40804 6.93502 2.68934 6.65372C2.97064 6.37241 3.35218 6.21438 3.75 6.21438H5.925C6.07164 6.21434 6.21505 6.17132 6.3375 6.09063L10.8375 3.12363C10.9506 3.04917 11.0817 3.0067 11.2169 3.00073C11.3522 2.99476 11.4865 3.02551 11.6057 3.08972C11.7249 3.15392 11.8245 3.24919 11.8939 3.36542C11.9633 3.48165 12 3.6145 12 3.74988V14.4644C12 14.5998 11.9633 14.7326 11.8939 14.8488C11.8245 14.9651 11.7249 15.0603 11.6057 15.1245C11.4865 15.1887 11.3522 15.2195 11.2169 15.2135C11.0817 15.2076 10.9506 15.1651 10.8375 15.0906L6.3375 12.1236C6.21505 12.0429 6.07164 11.9999 5.925 11.9999H3.75C3.35218 11.9999 2.97064 11.8418 2.68934 11.5605C2.40804 11.2792 2.25 10.8977 2.25 10.4999Z" stroke="#6C757D"></path>\n</svg>':e.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18" fill="none">\n<path d="M15.375 5.73213C15.375 5.73213 16.5 6.85713 16.5 8.73213C16.5 10.6071 15.375 11.7321 15.375 11.7321" stroke="none" stroke-linecap="round" stroke-linejoin="round"></path>\n<path d="M2.25 10.4999V7.71438C2.25 7.31655 2.40804 6.93502 2.68934 6.65372C2.97064 6.37241 3.35218 6.21438 3.75 6.21438H5.925C6.07164 6.21434 6.21505 6.17132 6.3375 6.09063L10.8375 3.12363C10.9506 3.04917 11.0817 3.0067 11.2169 3.00073C11.3522 2.99476 11.4865 3.02551 11.6057 3.08972C11.7249 3.15392 11.8245 3.24919 11.8939 3.36542C11.9633 3.48165 12 3.6145 12 3.74988V14.4644C12 14.5998 11.9633 14.7326 11.8939 14.8488C11.8245 14.9651 11.7249 15.0603 11.6057 15.1245C11.4865 15.1887 11.3522 15.2195 11.2169 15.2135C11.0817 15.2076 10.9506 15.1651 10.8375 15.0906L6.3375 12.1236C6.21505 12.0429 6.07164 11.9999 5.925 11.9999H3.75C3.35218 11.9999 2.97064 11.8418 2.68934 11.5605C2.40804 11.2792 2.25 10.8977 2.25 10.4999Z" stroke="#6C757D"></path>\n</svg>')}function Si(){hi.progressInterval&&(clearInterval(hi.progressInterval),hi.progressInterval=null)}function xi(){hi.audio&&(hi.audio.onplay=()=>{hi.isPlaying=!0,hi.isPaused=!1,yi(),Si(),hi.progressInterval=setInterval(()=>{hi.audio&&hi.isPlaying&&(hi.currentTime=hi.audio.currentTime,wi())},100)},hi.audio.onpause=()=>{hi.isPlaying=!1,hi.isPaused=!0,hi.audio&&!isNaN(hi.audio.currentTime)&&(hi.currentTime=hi.audio.currentTime,wi()),yi(),Si()},hi.audio.ontimeupdate=()=>{hi.audio&&(hi.currentTime=hi.audio.currentTime,wi())},hi.audio.onended=()=>{hi.isPlaying=!1,hi.isPaused=!1,hi.currentTime=0,yi(),Si(),hi.audio&&(hi.audio.currentTime=0)},hi.audio.oncanplay=()=>{hi.duration=hi.audio.duration,hi.isPlaying||wi()},hi.audio.onerror=()=>{hi.isPlaying=!1,yi(),Si()})}function Ti(){hi.audio&&(hi.audio.ended||hi.currentTime>=hi.duration?(hi.audio.currentTime=0,hi.currentTime=0):(isNaN(hi.audio.currentTime)||(hi.currentTime=hi.audio.currentTime),!isNaN(hi.audio.duration)&&hi.audio.duration>0&&(hi.duration=hi.audio.duration)),wi(),hi.audio.play())}function Li(){hi.audio&&hi.isPlaying&&hi.audio.pause()}function Ei(e){if(!e)return;const t=function(e){if(!e)return"";let t=e.replace(/^%%\s*:?\s*/i,"").trim();return t=t.replace(/<[^>]*>/g,""),t=t.replace(/\*\*(.*?)\*\*/g,"$1"),t=t.replace(/\*(.*?)\*/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1"),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/^[-*+]\s+/gm,""),t.trim()}(e);hi.audio&&hi.cachedText===t?hi.isPlaying?Li():yi():(null!==hi.cachedText&&hi.cachedText!==t&&(!function(){if(Si(),hi.requestController&&(hi.requestController.abort(),hi.requestController=null),hi.audio){const e=hi.audio;e.pause(),e.currentTime=0,e.onplay=null,e.onpause=null,e.ontimeupdate=null,e.onended=null,e.oncanplay=null,e.onerror=null,e.src="",hi.audio=null}hi.audioUrl&&(URL.revokeObjectURL(hi.audioUrl),hi.audioUrl=null),hi.isPlaying=!1,hi.isPaused=!1,hi.currentTime=0,hi.duration=0,yi();const e=document.getElementById("analyze-bubble-volume-bar");e&&e.classList.remove("show"),hi.volumeSliderVisible=!1,hi.volumeDragInitialized=!1;const t=document.getElementById("analyze-bubble-volume-handle");t&&hi.volumeDragHandler&&(t.removeEventListener("mousedown",hi.volumeDragHandler),hi.volumeDragHandler=null)}(),hi.cachedText=null),hi.cachedText=t,yi())}function Ci(){hi.requestController&&(hi.requestController.abort(),hi.requestController=null),hi.isPlaying&&Li()}function _i(e){if(!e.target.closest(".sidebar-volume-container")&&hi.volumeSliderVisible){hi.volumeSliderVisible=!1;const e=document.getElementById("analyze-bubble-volume-bar"),t=document.getElementById("analyze-bubble-volume");e&&e.classList.remove("show"),t&&t.classList.remove("volume-bar-open"),document.removeEventListener("click",_i)}}function Ai(e){hi.volumeLevel=Math.max(0,Math.min(100,e));const t=f(hi.volumeLevel);bi(),hi.audio&&(hi.audio.volume=t),ki()}function qi(){const e=document.getElementById("analyze-bubble-volume-handle"),t=document.querySelector("#analyze-bubble-volume-bar .sidebar-volume-track");if(!e||!t)return;hi.volumeDragHandler&&e.removeEventListener("mousedown",hi.volumeDragHandler);let n=!1;function r(e){function r(e){if(!n)return;e.preventDefault(),e.stopPropagation();const r=t.getBoundingClientRect(),o=e.clientY-r.top,i=Math.max(0,Math.min(1,1-o/r.height));Ai(Math.round(100*i))}e.preventDefault(),e.stopPropagation(),n=!0,document.addEventListener("mousemove",r),document.addEventListener("mouseup",function e(){n=!1,document.removeEventListener("mousemove",r),document.removeEventListener("mouseup",e)})}hi.volumeDragHandler=r,e.addEventListener("mousedown",r)}window.toggleAnalyzeBubbleAudio=async function(){if(hi.isPlaying)Li();else if(hi.audio)Ti();else{if(!hi.cachedText)return;!function(){const e=document.getElementById("analyze-bubble-play-pause");e&&(e.innerHTML='<div class="dotted-loader">\n <div class="dot"></div>\n <div class="dot"></div>\n <div class="dot"></div>\n <div class="dot"></div>\n <div class="dot"></div>\n <div class="dot"></div>\n <div class="dot"></div>\n <div class="dot"></div>\n </div>',e.classList.add("loading"),e.onclick=vi)}();try{const e=function(){const e=(yt()||"en").toLowerCase();return"da"===e?"da":"de"===e||"ge"===e?"de":"en"===e?"en":"da"}();await async function(e,t){const n=new AbortController;hi.requestController=n;const r=new FormData;r.append("action","hgf_important_secure_bots_text_to_speech"),r.append("nonce",window.HGF_ajax_object?.nonce||""),r.append("text",xn(e.trim())),r.append("language",t),r.append("gender","female");const o=await fetch(gi,{method:"POST",body:r,signal:n.signal});if(!o.ok)throw new Error(`TTS request failed: ${o.status}`);const i=await o.blob(),a=URL.createObjectURL(i);hi.audioUrl=a,hi.audio=new Audio(a),hi.volumeLevel=m(),g(hi.audio),xi(),yi(),ki(),bi()}(hi.cachedText,e),Ti()}catch(e){"AbortError"!==e.name&&console.warn("Analyze bubble TTS failed:",e),yi()}}},window.seekAnalyzeBubbleAudio=function(e){if(!hi.audio||!hi.duration)return;const t=e.currentTarget.getBoundingClientRect(),n=(e.clientX-t.left)/t.width*hi.duration;hi.audio.currentTime=n,hi.currentTime=n,wi()},window.toggleAnalyzeBubbleVolume=function(){hi.volumeSliderVisible=!hi.volumeSliderVisible;const e=document.getElementById("analyze-bubble-volume-bar"),t=document.getElementById("analyze-bubble-volume");e&&(hi.volumeSliderVisible?(e.classList.add("show"),t&&t.classList.add("volume-bar-open"),document.addEventListener("click",_i),setTimeout(()=>{qi(),hi.volumeDragInitialized=!0},50)):(e.classList.remove("show"),t&&t.classList.remove("volume-bar-open"),document.removeEventListener("click",_i)))},window.handleAnalyzeBubbleVolumeClick=function(e){e.stopPropagation();const t=e.currentTarget.getBoundingClientRect(),n=e.clientY-t.top,r=Math.max(0,Math.min(1,1-n/t.height));Ai(Math.round(100*r))};let Mi="";function Ii(){try{const e=(yt()||"en").toLowerCase();return"da"===e?"da-DK":e}catch(e){return"en"}}function Bi(e){if(!e)return"";let t=e.replace(/^%%\s*:?\s*/i,"").trim();return t=t.replace(/<[^>]*>/g,"").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),t=t.replace(/^#{1,6}\s+/gm,"").replace(/\*\*(.*?)\*\*/g,"$1").replace(/__(.*?)__/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/_(.*?)_/g,"$1").replace(/~~(.*?)~~/g,"$1").replace(/```[\s\S]*?```/g,"").replace(/`([^`]+)`/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/^[-*]{3,}$/gm,"").replace(/^>\s*/gm,"").replace(/^[\s]*[-*+]\s+/gm,"").replace(/^[\s]*\d+\.\s+/gm,"").replace(/\n\s*\n/g,"\n").replace(/[ \t]+/g," ").trim(),t=t.replace(/["'ââââ:]/g,""),t}async function Hi(e,t){try{const n=window.sidebarCurrentSnapshot||window.sidebarPreviousSnapsh
1ot||(window.quill1?window.quill1.root.innerHTML:"");let r=t.replace(/\\/g,"");r=r.replace(/```html|```HTML/g,""),r=r.replace(/```/g,""),window.displayResponse(r);const o=document.getElementById("mainSwitcher");o&&(o.disabled=!1);if(window.innerWidth<480)return void Sa("success",{message:pe("sidebarRobot.textChanged")});const i=window.quill1?window.quill1.root.innerHTML:"",a=It(),l=await async function(e,t,n){e=wn(yn(e)),t=wn(yn(t));const r=document.createElement("div");r.innerHTML=e,e=r.textContent||r.innerText||"",r.innerHTML=t,t=r.textContent||r.innerText||"";try{const r=new FormData;r.append("action","hgf_edit_sidebar_explainer"),r.append("textBefore",e),r.append("textCurrent",t),r.append("language",n),r.append("userInput",Mi),r.append("nonce",HGF_ajax_object.nonce);const o=await fetch(HGF_ajax_object.ajax_url,{method:"POST",body:r}),i=await o.json();return i.success?i.data.explanation:null}catch(e){return console.warn("Sidebar explainer failed:",e),null}}(n,i,a),s=l||pe("sidebarRobot.textChangedExplanation").replace("{command}",e);if(function(e,{showOkButton:t=!0}={}){let n=document.getElementById("sidebar-robot-bubble-tts");if(n){const e=n.querySelector("#bubble-tts-ok-btn");e&&e.replaceWith(e.cloneNode(!0))}else{n=document.createElement("div"),n.id="sidebar-robot-bubble-tts",n.className="sidebar-robot-bubble secondary-tts";(document.getElementById("sidebar-robot-bubble")?.parentNode||document.body).appendChild(n)}let r="";r+=`<div class="bubble-inner-content">${e||""}</div>`,t&&(r+=Ni(),r+=`\n <div class="bubble-reject-accept-container" id="bubble-reject-accept-container">\n <button class="bubble-reject-btn" id="bubble-reject-btn">\n <svg xmlns="http://www.w3.org/2000/svg" fill="#FF0000" width="24" height="24" viewBox="0 0 32 32"><path d="M7.004 23.087l7.08-7.081-7.07-7.071L8.929 7.02l7.067 7.069L23.084 7l1.912 1.913-7.089 7.093 7.075 7.077-1.912 1.913-7.074-7.073L8.917 25z"/></svg>\n Fortryd\n </button>\n <button class="bubble-accept-btn" id="bubble-accept-btn">\n <svg xmlns="http://www.w3.org/2000/svg" fill="#008000" width="24" height="24" viewBox="0 0 32 32"><path d="M5 16.577l2.194-2.195 5.486 5.484L24.804 7.743 27 9.937l-14.32 14.32z"/></svg>\n Godkend\n </button>\n </div>\n <div class="bubble-ok-button-container">\n <button class="bubble-ok-button" id="bubble-tts-ok-btn">\n <span>${pe("sidebarRobot.closeExplanation")}</span>\n </button>\n </div>`);n.innerHTML=r,n.style.display="flex",n.style.opacity="1",n.style.zIndex="10002",n.classList.add("show"),Ri.bubble&&(Ri.bubble.style.display="none");n.addEventListener("mouseenter",e=>{e.stopPropagation()}),n.addEventListener("mouseleave",e=>{e.stopPropagation()}),setTimeout(()=>{Zo()},0);const o=n.querySelector("#bubble-reject-btn"),i=n.querySelector("#bubble-accept-btn");n.querySelector("#bubble-reject-accept-container"),o&&o.addEventListener("click",()=>{Qi();const e=document.querySelector("#bubble-tts-ok-btn");e?.click()});i&&i.addEventListener("click",()=>{const e=document.querySelector("#bubble-tts-ok-btn");e?.click()});const a=n.querySelector("#bubble-tts-ok-btn");a&&a.addEventListener("click",()=>{try{fi(),Sa("idle")}catch(e){}La()})}(Pi(s),{showOkButton:!0}),!oa())try{const e=Bi(s);if(await Yo(e,Ii()),oa())return void fi()}catch(e){console.warn("Edit TTS failed:",e)}}catch(e){throw console.error("Edit response handling failed:",e),e}}function Ki(){const e=document.getElementById("sidebar-counter-nav-div"),t=document.querySelector(".sidebar-word-count"),n=document.querySelector(".link-to-login");if(!e||!t)return;const r=quill1?quill1.getText().trim().length:0;if(r>0){e.style.display="flex",document.querySelector(".sidebar-robot-bubble").style.flexWrap="wrap";const o=r.toLocaleString("da-DK");t.textContent=`${o} ${pe("membership.characters")}`,n&&(n.style.display="none")}else e.style.display="none",document.querySelector(".sidebar-robot-bubble").style.flexWrap=""}function Di(){quill1&&quill1.getText().trim().length;const e=document.querySelector('.bubble-action-btn[onclick*="ask"]'),t=document.querySelector('.bubble-action-btn[onclick*="edit"]'),n=document.querySelector('.button-info-item[onclick*="ask"]'),r=document.querySelector('.button-info-item[onclick*="edit"]');for(const o of[e,t,n,r])o&&(o.disabled=!1,o.style.opacity="1",o.style.cursor="pointer")}function Pi(e){try{const t=e.replace(/^%%\s*:?\s*/i,"").trim(),n=marked.parse(t),r="undefined"!=typeof DOMPurify?DOMPurify.sanitize(n,{ADD_TAGS:["ham-dan"],KEEP_CONTENT:!0}):n;return formatMarkdownOutput$1(r)}catch(t){const n=e.replace(/^%%\s*:?\s*/i,"").trim();return"undefined"!=typeof DOMPurify?DOMPurify.sanitize(n,{KEEP_CONTENT:!0}):n}}function Ni(){return'\n <div class="sidebar-ask-audio-controls" id="sidebar-ask-audio-controls">\n <button class="sidebar-audio-control-btn" id="sidebar-audio-play-pause" onclick="toggleSidebarAudio()">\n <svg xmlns="http://www.w3.org/2000/svg" width="12" height="15" viewBox="0 0 12 15" fill="none">\n<path d="M2 0.75C1.53587 0.75 1.09075 0.934375 0.762563 1.26256C0.434375 1.59075 0.25 2.03587 0.25 2.5V12.5C0.25 13.466 1.034 14.25 2 14.25H3C3.46413 14.25 3.90925 14.0656 4.23744 13.7374C4.56563 13.4092 4.75 12.9641 4.75 12.5V2.5C4.75 2.03587 4.56563 1.59075 4.23744 1.26256C3.90925 0.934375 3.46413 0.75 3 0.75H2ZM8.5 0.75C8.03587 0.75 7.59075 0.934375 7.26256 1.26256C6.93437 1.59075 6.75 2.03587 6.75 2.5V12.5C6.75 13.466 7.534 14.25 8.5 14.25H9.5C9.96413 14.25 10.4092 14.0656 10.7374 13.7374C11.0656 13.4092 11.25 12.9641 11.25 12.5V2.5C11.25 2.03587 11.0656 1.59075 10.7374 1.26256C10.4092 0.934375 9.96413 0.75 9.5 0.75H8.5Z" fill="#6C757D"/>\n</svg>\n </button>\n <div class="sidebar-audio-progress-container">\n <div class="sidebar-audio-progress-track" onclick="seekSidebarAudio(event)">\n <div class="sidebar-audio-progress-fill" id="sidebar-audio-progress-fill"></div>\n </div>\n </div>\n <div class="sidebar-volume-container">\n <button class="sidebar-audio-control-btn" id="sidebar-audio-volume" onclick="toggleSidebarVolume()">\n <svg xmlns="http://www.w3.org/2000/svg" width="16" height="14" viewBox="0 0 16 14" fill="none">\n <path d="M12.5 8.60718L14 7.10718M14 7.10718L15.5 5.60718M14 7.10718L12.5 5.60718M14 7.10718L15.5 8.60718" stroke="#6C757D" stroke-linecap="round" stroke-linejoin="round"/>\n <path d="M0.5 8.49988V5.71438C0.5 5.31655 0.658035 4.93502 0.93934 4.65372C1.22064 4.37241 1.60218 4.21438 2 4.21438H4.175C4.32164 4.21434 4.46505 4.17132 4.5875 4.09063L9.0875 1.12363C9.20056 1.04917 9.33168 1.0067 9.46692 1.00073C9.60217 0.994759 9.73652 1.02551 9.8557 1.08972C9.97489 1.15392 10.0745 1.24919 10.1439 1.36542C10.2133 1.48
1165 10.25 1.6145 10.25 1.74988V12.4644C10.25 12.5998 10.2133 12.7326 10.1439 12.8488C10.0745 12.9651 9.97489 13.0603 9.8557 13.1245C9.73652 13.1887 9.60217 13.2195 9.46692 13.2135C9.33168 13.2076 9.20056 13.1651 9.0875 13.0906L4.5875 10.1236C4.46505 10.0429 4.32164 9.99991 4.175 9.99988H2C1.60218 9.99988 1.22064 9.84184 0.93934 9.56054C0.658035 9.27923 0.5 8.8977 0.5 8.49988Z" stroke="#6C757D"/>\n</svg>\n </button>\n <div class="sidebar-volume-bar" id="sidebar-volume-bar">\n <div class="sidebar-volume-track" onclick="handleVolumeClick(event)">\n <div class="sidebar-volume-fill" id="sidebar-volume-fill"></div>\n <div class="sidebar-volume-handle" id="sidebar-volume-handle"></div>\n </div>\n </div>\n </div>\n </div>'}window.updateSidebarCharacterCounter=Ki,window.updateSidebarButtonStates=Di;let ji="idle",Ri={},Fi=null,Oi="",Ui=null,$i=null,zi=!1,Gi=!1,Vi=!1,Wi=!1,Ji=null,Zi=null;function Yi(){try{if(void 0!==window.quill1&&window.quill1&&window.quill1.root){window.preApiSnapshot&&window.preApiSnapshot.trim().length>0&&(Ji=window.preApiSnapshot,window.sidebarPreviousSnapshot=Ji);const e=window.quill1.root.innerHTML;Zi=e,window.sidebarCurrentSnapshot=Zi,window.preApiSnapshot=e}}catch(e){}}function Qi(){try{void 0!==window.quill1&&window.quill1&&window.quill1.root&&(Zi&&Zi.trim().length>0?(window.quill1.root.innerHTML=Zi,Ji&&Ji.trim().length>0?window.preApiSnapshot=Ji:window.preApiSnapshot=Zi):Ji&&Ji.trim().length>0&&(window.quill1.root.innerHTML=Ji,window.preApiSnapshot=Ji),Ji=null,Zi=null,window.sidebarPreviousSnapshot=null,window.sidebarCurrentSnapshot=null,"function"==typeof window.updateUndoRedoButtonState&&window.updateUndoRedoButtonState())}catch(e){}}function Xi(){Ji=null,Zi=null,window.sidebarPreviousSnapshot=null,window.sidebarCurrentSnapshot=null}let ea=!1,ta=null,na=!1;function ra(){if(na=!0,"function"==typeof ta){try{ta()}catch(e){}ta=null}Te(),Se(),window.sidebarSTT&&Ka(),Uo(),fi(),clearTimeout(la),Sa("idle"),setTimeout(()=>{na=!1},1e3)}function oa(){return na}const ia={hoverButtons:{title:pe("robot.howCanIHelp"),showInfo:!1,buttons:[{id:"edit",text:pe("sidebarRobot.changeText"),description:pe("sidebarRobot.editDescription"),icon:"edit"},{id:"ask",text:pe("sidebarRobot.question"),description:pe("sidebarRobot.askDescription"),icon:"ask"}]},slideTemplate:null,indicatorTemplate:null};async function aa(){if(ia.slideTemplate=(e,t)=>
1`\n <div class="bubble-main-text">\n <span>${e}</span>\n <svg xmlns="http://www.w3.org/2000/svg" width="16" height="17" viewBox="0 0 16 17" fill="none">\n <g clip-path="url(#clip0_4185_3241)">\n <path d="M13.8083 5.73221L13.6443 6.10955C13.6187 6.17099 13.5755 6.22348 13.5201 6.2604C13.4647 6.29731 13.3996 6.31701 13.333 6.31701C13.2664 6.31701 13.2013 6.29731 13.1459 6.2604C13.0905 6.22348 13.0473 6.17099 13.0217 6.10955L12.8577 5.73221C12.5693 5.06469 12.0413 4.52949 11.3777 4.23221L10.8717 4.00621C10.8103 3.97797 10.7583 3.93273 10.7218 3.87583C10.6854 3.81894 10.666 3.75278 10.666 3.68521C10.666 3.61764 10.6854 3.55149 10.7218 3.49459C10.7583 3.4377 10.8103 3.39245 10.8717 3.36421L11.3497 3.15155C12.0299 2.8458 12.567 2.2908 12.8503 1.60088L13.0197 1.19355C13.0444 1.13045 13.0877 1.07628 13.1437 1.0381C13.1997 0.999914 13.2659 0.979492 13.3337 0.979492C13.4015 0.979492 13.4677 0.999914 13.5237 1.0381C13.5797 1.07628 13.6229 1.13045 13.6477 1.19355L13.8163 1.60021C14.0993 2.29026 14.6362 2.8455 15.3163 3.15155L15.795 3.36488C15.8562 3.3932 15.908 3.43844 15.9443 3.49526C15.9807 3.55208 16 3.61811 16 3.68555C16 3.75298 15.9807 3.81901 15.9443 3.87583C15.908 3.93265 15.8562 3.97789 15.795 4.00621L15.2883 4.23155C14.6249 4.52912 14.0971 5.06456 13.809 5.73221M5.66634 4.98021H4.33301V12.9802H5.66634V4.98021ZM2.66634 7.64688H1.33301V10.3135H2.66634V7.64688ZM8.66634 2.31355H7.33301V15.6469H8.66634V2.31355ZM11.6663 6.31355H10.333V12.9802H11.6663V6.31355ZM14.6663 7.64688H13.333V10.3135H14.6663V7.64688Z" fill="#495057"/>\n </g>\n <defs>\n <clipPath id="clip0_4185_3241">\n <rect width="16" height="16" fill="white" transform="translate(0 0.980225)"/>\n </clipPath>\n </defs>\n </svg>\n </div>\n <div class="bubble-description">${t?t.replace(/\n/g,"<br>"):""}</div>\n `,ia.indicatorTemplate=(e,t)=>
1Array.from({length:e},(e,n)=>`<span class="bubble-dot ${n===t?"active":""}"></span>`).join(""),Ri={wrapper:document.querySelector(".sidebar-robot-wrapper"),gif:document.getElementById("gif-sidebar-collapsed"),bubble:document.getElementById("sidebar-robot-bubble"),bubbleText:document.querySelector("#sidebar-robot-bubble .bubble-text"),bubbleLoader:document.querySelector("#sidebar-robot-bubble .sidebar-bubble-loader"),keyboardIcon:document.querySelector("#sidebar-robot-bubble .keyboard-icon"),input:document.getElementById("sidebar-robot-input"),inputField:document.getElementById("sidebar_custom_input"),micButton:document.getElementById("sidebar-micButton"),submitButton:document.getElementById("sidebar-submit"),wordLimit:document.getElementById("sidebar-word-limit")},!Ri.wrapper||!Ri.gif)return!1;if(await Mr.initializePreloader(),Zo(),zo.isMuted=!1,zo.volume=p(),function(){document.addEventListener("click",ua);const{wrapper:e,gif:t,keyboardIcon:n,micButton:r,submitButton:o,inputField:i}=Ri;if(!e||!t)return;e&&(e.addEventListener("mouseenter",ma),e.addEventListener("mouseleave",fa));Ri.bubble&&(Ri.bubble.addEventListener("mouseenter",()=>{const e=document.getElementById("sidebar-robot-bubble-tts");e&&"none"!==e.style.display&&e.classList.contains("show")||"idle"===ji&&Sa("hover")}),Ri.bubble.addEventListener("click",e=>{(e.target.closest(".sidebar-volume-container")||e.target.closest(".bubble-info-icon"))&&e.stopPropagation()}));t&&(t.addEventListener("mousedown",ca),t.addEventListener("click",ga));n&&(n.addEventListener("mousedown",da),n.addEventListener("click",pa));Ri.bubble&&(Ri.bubble.addEventListener("mousedown",e=>{e.target&&e.target.closest&&e.target.closest(".keyboard-icon")&&da(e)}),Ri.bubble.addEventListener("click",e=>{e.target&&e.target.closest&&e.target.closest(".keyboard-icon")&&pa(e)}));r&&r.addEventListener("click",ha);o&&o.addEventListener("click",va);i&&(i.addEventListener("input",ya),i.addEventListener("keypress",wa))}(),function(){if(!Ri.gif)return;Ri.gif.setAttribute("role","button"),Ri.gif.setAttribute("aria-label","Voice input robot"),Ri.gif.setAttribute("tabindex","0"),Ri.gif.addEventListener("keydown",e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),ga())})}(),"idle"===ji)try{Mr.loadAnimationByState("ready","#gif-sidebar-collapsed")}catch(e){console.error("â Direct animation load failed:",e)}else Sa("idle");return!0}let la;function sa(e=3e4){clearTimeout(la),la=setTimeout(()=>{"listening"!==ji&&"processing"!==ji||Sa("error",{message:pe("sidebarRobot.errorTryAgain")})},e)}function ca(e){if(e.preventDefault(),window.quill1&&"function"==typeof window.quill1.getSelection){const e=window.quill1.getSelection();e&&e.length>0?(Ui={index:e.index,length:e.length,text:window.quill1.getText(e.index,e.length)},Fi=Ui,window.quill1.focus(),setTimeout(()=>{window.quill1&&Ui&&window.quill1.setSelection(Ui.index,Ui.length,"silent")},0)):e&&(Ui={index:e.index,length:0,text:""},Fi=Ui)}}function da(e){if(e.preventDefault(),e.stopPropagation(),window.quill1&&"function"==typeof window.quill1.getSelection){const e=window.quill1.getSelection();e&&(Ui={index:e.index,length:e.length,text:e.length>0?window.quill1.getText(e.index,e.length):""},Fi=Ui)}}function ua(e){if("input"===ji){const t=e.target.closest("#sidebar-robot-input"),n=e.target.closest("#sidebar-robot-bubble"),r=e.target.closest(".keyboard-icon");t||n||r||Sa("idle")}if("hover"===ji&&(zi||Vi)){const t=e.target.closest("#sidebar-robot-bubble"),n=e.target.closest(".sidebar-robot-wrapper");t||n||(zi=!1,Vi=!1,Sa("idle"))}}function pa(e){e.stopPropagation(),"listening"===ji&&(Ka(),clearTimeout(la));try{if(window.quill1&&"function"==typeof window.quill1.getSelection){const e=window.quill1.getSelection();e&&e.length>0?(Ui={index:e.index,length:e.length,text:window.quill1.getText(e.index,e.length)},Fi=Ui):Ui&&Ui.length>0?Fi=Ui:Fi&&Fi.length>0&&(Ui=Fi)}}catch(e){}Ba()}function ma(){const e=document.getElementById("sidebar-robot-bubble-tts");e&&"none"!==e.style.display&&e.classList.contains("show")||"idle"===ji&&Sa("hover")}function fa(){"hover"!==ji||zi||Vi||Sa("idle")}async function ga(e){const t=document.getElementById("sidebar-robot-bubble-tts");if(t&&"none"!==t.style.display){Te();try{Uo(),fi(),window.currentTTSAudio&&(window.currentTTSAudio.pause(),window.currentTTSAudio.currentTime=0,window.currentTTSAudio.src="");
1document.querySelectorAll("audio").forEach(e=>{e.pause(),e.currentTime=0,e.src=""}),window.currentTTSAudio=null,window.isSpeaking=!1,window.audioBlob=null}catch(e){}return La(),Sa("idle"),void($i=null)}if("listening"!==ji&&"transcribing"!==ji&&"processing"!==ji){if("success"===ji&&Wi){Te();try{Uo(),fi(),window.currentTTSAudio&&(window.currentTTSAudio.pause(),window.currentTTSAudio.currentTime=0,window.currentTTSAudio.src="");document.querySelectorAll("audio").forEach(e=>{e.pause(),e.currentTime=0,e.src=""}),window.currentTTSAudio=null,window.isSpeaking=!1,window.audioBlob=null}catch(e){}return Uo(),fi(),Wi=!1,Sa("idle"),void($i=null)}if((Ui||Fi)&&(Ui&&(Fi=Ui),window.quill1&&Fi&&Fi.length>0))try{window.quill1.focus(),window.quill1.setSelection(Fi.index,Fi.length,"user")}catch(e){}"idle"!==ji&&"hover"!==ji&&"input"!==ji&&"success"!==ji&&"error"!==ji||("hover"===ji&&(zi||Vi)?(zi=!1,Vi=!1,Sa("idle")):(zi=!0,Sa("hover")))}else ra()}async function ha(){Ri.inputField&&(Ri.inputField.value="",ba()),Ha();try{if(window.quill1&&"function"==typeof window.quill1.getSelection){const e=window.quill1.getSelection();e&&(Fi=e)}}catch(e){}Ma()}function va(){const e=Ri.inputField.value.trim();e&&("edit"!==$i||Pa())&&(Ha(),Na(e),Ri.inputField.value="",ba())}function ya(e){"function"==typeof window.toggleClearIcon&&window.toggleClearIcon(e.target),ba()}function wa(e){if("Enter"===e.key){if(e.shiftKey)return;e.preventDefault(),va()}}function ba(){if(!Ri.inputField||!Ri.wordLimit)return;const e=Ri.inputField.value;e.length>300&&(Ri.inputField.value=e.slice(0,300));const t=Ri.inputField.value.length;Ri.wordLimit.textContent=`${t}/300`}function ka(e){var t=document.querySelector(".sidebar-robot-glow-bg");t&&(t.style.display=e?"flex":"none")}function Sa(e,t={}){if((!Ri.bubble||!Ri.bubble.querySelector(".bubble-ok-button")||"idle"===e||"idle"===ji)&&(ka("listening"===ji),function(e){return{idle:["hover","idle"],hover:["idle","hover","listening","input","error"],listening:["transcribing","idle","input","error"],transcribing:["processing","idle","error"],processing:["success","error","idle"],success:["idle"],error:["idle"],input:["listening","processing","idle","error"]}[ji]?.includes(e)||!1}(e)))switch(clearTimeout(la),"listening"===ji&&Ka(),window.sidebarSTT&&Ka(),ji=e,e){case"idle":Ia(),Ha(),Oi="",Mr.loadAnimationByState("ready","#gif-sidebar-collapsed"),zi=!1,Vi=!1;try{Ri.bubble?.classList.remove("loading")}catch(e){}break;case"hover":Vi||(ia.hoverButtons.showInfo=!1),xa("",!1,!1,!1,0,null,ia.hoverButtons),Mr.loadAnimationByState("analyzed","#gif-sidebar-collapsed");try{Ri.bubble?.classList.remove("loading")}catch(e){}break;case"listening":!async function(){try{"function"==typeof window.manuallyCloseMicButton&&(window.manuallyCloseMicButton("micButton1"),window.manuallyCloseMicButton("micButton2")),Ui&&Ui.length>0&&(Fi=Ui);const e=Date.now(),t=1500;sa(1e4);const n=br();await async function({language:e,onFinal:t,onPartialText:n,onInterimActivity:r,onError:o,onReady:i,onStreamReady:a}){Fo();let l="";const s={"da-DK":"da","en-US":"en","de-DE":"de","fr-FR":"fr","es-ES":"es","sv-SE":"sv","no-NO":"no"}[e]||e.split("-")[0]||"da";return Ro=le({service:"chat",lang:s,onTranscript:function(e){if(!e)return;jo&&clearTimeout(jo),r&&r();const n=l.trim();l=n?n+" "+e:e,t&&t(l,!1),jo=setTimeout(function(){t&&t(l,!0)},3e3)},onPartial:function(e){jo&&clearTimeout(jo),r&&r(),e&&n&&n(l,e),jo=setTimeout(function(){t&&t(l,!0)},3e3)},onError:function(e){o&&o(e)},onStateChange:function(e){"listening"===e&&i&&i()}}),Ro.start(),window.sidebarSTT={_managed:!0},window.sidebarSTT}({language:n,onReady:()=>{try{const n=Date.now()-e,r=Math.max(0,t-n);setTimeout(()=>{"listening"===ji&&xa("Lytter...",!0,!0)},r)}catch(e){console.error("STT ready error:",e),Sa("error",{message:"Recording failed"})}},onInterimActivity:()=>{sa(1e4)},onPartialText:(e,t)=>{if("listening"!==ji)return;if(oa())return;const n=e?e+" "+t:t;n&&xa(`"${n}"`,!1,!1)},onFinal:(e,t)=>{"listening"===ji&&(oa()||(!t||e?(e&&!t&&xa(`"${e}"`,!1,!1),t&&(Oi=`"${e}"`,Sa("transcribing",{text:Oi}),setTimeout(async()=>{if("transcribing"===ji)try{if(oa())return;if(Sa("processing",{message:pe("robot.thinking")}),"ask"===$i){if(!!(Ui&&Ui.length>0)||!!(Fi&&Fi.length>0)){if(oa())return;const e=(Ui?.text||Fi?.text||"").trim(),t=window.quill1?window.quill1.getText():"",n=await Po(Oi,e,t);if(oa())return;
1if(xa(Pi(n),!1,!1,!1,0,null,null,!0),Sa("success",{message:"",preserveBubble:!0,showUndo:!1}),!oa())try{const e=Bi(n);if(await Yo(e,Ii()),oa())return void fi()}catch(e){}}else{if(oa())return;const e=await Ko(Oi);if(oa())return;if(xa(Pi(e),!1,!1,!1,0,null,null,!0),Sa("success",{message:"",preserveBubble:!0,showUndo:!1}),!oa())try{const t=Bi(e);if(await Yo(t,Ii()),oa())return void fi()}catch(e){}}}else if("edit"===$i){if(!!(Ui&&Ui.length>0)||!!(Fi&&Fi.length>0)){if(oa())return;const e=(Ui?.text||Fi?.text||"").trim(),t=window.quill1?window.quill1.getText():"";Yi();const n=await No(Oi,e,t);if(Mi=Oi,oa())return;await Hi(Oi,n)}else{if(oa())return;Yi();const e=await Do(Oi);if(Mi=Oi,oa())return;await Hi(Oi,e)}}else Na(Oi);$i=null}catch(e){oa()||Sa("error",{message:"Connection failed"})}},1e3))):Sa("error",{message:pe("sidebarRobot.errorTryAgain")})))},onError:e=>{const t=(e||"").toString().toLowerCase();t.includes("denied")||t.includes("permission")||t.includes("microphone")?Ba():Sa("error",{message:e})},onStreamReady:({mediaRecorder:e})=>{}})}catch(e){console.error("Sidebar STT start error:",e),Ba()}}(),Ta(pe("robot.connecting")),ka("listening"===ji),Mr.loadAnimationByState("loading","#gif-sidebar-collapsed"),sa(1e4);break;case"input":Ia(),Mr.loadAnimationByState("ready","#gif-sidebar-collapsed");try{Ri.bubble?.classList.remove("loading")}catch(e){}break;case"transcribing":xa(t.text||Oi);try{Ri.bubble?.classList.remove("loading")}catch(e){}break;case"processing":Ta(t.message||pe("robot.thinking")),Mr.loadAnimationByState("loading","#gif-sidebar-collapsed");break;case"success":t.preserveBubble||xa("",!1,!1,!1,0);try{Ri.bubble?.classList.remove("loading")}catch(e){}Mr.loadAnimationByState("analyzed","#gif-sidebar-collapsed"),setTimeout(()=>Sa("idle"),4e3);break;case"error":xa(t.message||"Error occurred"),Mr.loadAnimationByState("ready","#gif-sidebar-collapsed");try{Ri.bubble?.classList.remove("loading")}catch(e){}setTimeout(()=>Sa("idle"),3e3)}}function xa(e,t=!1,n=!1,r=!1,o=0,i=null,a=null,l=!1){if(Ri.bubble&&Ri.bubbleText){if(Gi&&e!==pe("robot.connecting")){const e=document.querySelector(".sidebar-robot-blur-effect");e&&(e.style.display="none",Gi=!1)}Ca(),qa();try{Ri.bubble.classList.remove("loading")}catch(e){}if(a)!function(e){const{title:t,showInfo:n,buttons:r}=e,o={ask:'<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18" fill="none">\n <path fill-rule="evenodd" clip-rule="evenodd" d="M9 0.85523C6.97583 0.85523 4.98583 1.00356 3.04 1.2894C1.39167 1.53106 0.25 2.97606 0.25 4.59773V9.61273C0.25 11.2344 1.39167 12.6794 3.04 12.9211C3.77111 13.0283 4.50778 13.1161 5.25 13.1844V16.4802C5.25011 16.6038 5.28682 16.7245 5.35551 16.8272C5.42419 16.9299 5.52176 17.0099 5.6359 17.0571C5.75003 17.1044 5.87561 17.1168 5.99678 17.0927C6.11795 17.0686 6.22926 17.0092 6.31667 16.9219L9.80333 13.4361C9.86303 13.3785 9.94207 13.3452 10.025 13.3427C11.6972 13.3005 13.3422 13.16 14.96 12.9211C16.6083 12.6794 17.75 11.2352 17.75 9.61273V4.59773C17.75 2.97523 16.6083 1.53106 14.96 1.2894C12.9866 0.999303 10.9946 0.854193 9 0.85523ZM5.875 6.16773C5.62636 6.16773 5.3879 6.2665 5.21209 6.44232C5.03627 6.61813 4.9375 6.85659 4.9375 7.10523C4.9375 7.35387 5.03627 7.59233 5.21209 7.76814C5.3879 7.94396 5.62636 8.04273 5.875 8.04273C6.12364 8.04273 6.3621 7.94396 6.53791 7.76814C6.71373 7.59233 6.8125 7.35387 6.8125 7.10523C6.8125 6.85659 6.71373 6.61813 6.53791 6.44232C6.3621 6.2665 6.12364 6.16773 5.875 6.16773ZM8.0625 7.10523C8.0625 6.85659 8.16127 6.61813 8.33709 6.44232C8.5129 6.2665 8.75136 6.16773 9 6.16773C9.24864 6.16773 9.4871 6.2665 9.66291 6.44232C9.83873 6.61813 9.9375 6.85659 9.9375 7.10523C9.9375 7.35387 9.83873 7.59233 9.66291 7.76814C9.4871 7.94396 9.24864 8.04273 9 8.04273C8.75136 8.04273 8.5129 7.94396 8.33709 7.76814C8.16127 7.59233 8.0625 7.35387 8.0625 7.10523ZM12.125 6.16773C11.8764 6.16773 11.6379 6.2665 11.4621 6.44232C11.2863 6.61813 11.1875 6.85659 11.187
15 7.10523C11.1875 7.35387 11.2863 7.59233 11.4621 7.76814C11.6379 7.94396 11.8764 8.04273 12.125 8.04273C12.3736 8.04273 12.6121 7.94396 12.7879 7.76814C12.9637 7.59233 13.0625 7.35387 13.0625 7.10523C13.0625 6.85659 12.9637 6.61813 12.7879 6.44232C12.6121 6.2665 12.3736 6.16773 12.125 6.16773Z" fill="#6C757D"/>\n</svg>',edit:'<svg xmlns="http://www.w3.org/2000/svg" width="18" height="20" viewBox="0 0 18 20" fill="none">\n <path d="M3.92792 6.92039L3.72293 7.39206C3.69089 7.46886 3.63684 7.53447 3.56759 7.58062C3.49834 7.62677 3.41698 7.65139 3.33376 7.65139C3.25054 7.65139 3.16918 7.62677 3.09993 7.58062C3.03068 7.53447 2.97663 7.46886 2.94459 7.39206L2.73959 6.92039C2.37916 6.08599 1.71908 5.41699 0.889592 5.04539L0.257092 4.76289C0.180357 4.7276 0.115353 4.67103 0.0697863 4.59992C0.0242192 4.5288 0 4.44611 0 4.36164C0 4.27718 0.0242192 4.19449 0.0697863 4.12337C0.115353 4.05225 0.180357 3.99569 0.257092 3.96039L0.854592 3.69456C1.70493 3.31238 2.37631 2.61863 2.73043 1.75623L2.94209 1.24706C2.97306 1.16819 3.02707 1.10047 3.09708 1.05275C3.16709 1.00502 3.24986 0.979492 3.33459 0.979492C3.41932 0.979492 3.50209 1.00502 3.5721 1.05275C3.64212 1.10047 3.69613 1.16819 3.72709 1.24706L3.93793 1.75539C4.29167 2.61796 4.96275 3.312 5.81292 3.69456L6.41126 3.96123C6.48776 3.99663 6.55253 4.05318 6.59793 4.1242C6.64332 4.19523 6.66745 4.27777 6.66745 4.36206C6.66745 4.44635 6.64332 4.52889 6.59793 4.59991C6.55253 4.67094 6.48776 4.72749 6.41126 4.76289L5.77793 5.04456C4.9486 5.41653 4.28882 6.08583 3.92876 6.92039M2.55376 18.9912C3.40876 13.8321 5.26042 2.64456 17.5004 2.64456C16.2538 5.14456 15.4171 6.39456 14.5838 7.22789L13.7504 8.06123L15.0004 8.89456C14.1671 11.3946 11.6671 14.3112 8.33376 14.7279C6.10987 15.0057 4.72043 16.5334 4.16543 19.3112H2.50043L2.55376 18.9912Z" fill="#6C757D"/>\n</svg>',info:'<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 16 16" fill="none">\n<mask id="mask0_8002_5572" style="mask-type:luminance" maskUnits="userSpaceOnUse" x="0" y="0" width="16" height="16">\n<path d="M7.99968 14.6468C8.87532 14.6479 9.74254 14.4759 10.5515 14.1408C11.3605 13.8057 12.0953 13.3141 12.7137 12.6941C13.3336 12.0758 13.8253 11.341 14.1604 10.532C14.4955 9.72301 14.6674 8.85579 14.6663 7.98015C14.6674 7.10451 14.4955 6.23729 14.1604 5.42831C13.8253 4.61933 13.3336 3.88454 12.7137 3.26615C12.0953 2.6462 11.3605 2.15455 10.5515 1.81945C9.74254 1.48435 8.87532 1.3124 7.99968 1.31348C7.12404 1.3124 6.25682 1.48435 5.44784 1.81945C4.63886 2.15455 3.90407 2.6462 3.28568 3.26615C2.66573 3.88454 2.17409 4.61933 1.83898 5.42831C1.50388 6.23729 1.33193 7.10451 1.33301 7.98015C1.33193 8.85579 1.50388 9.72301 1.83898 10.532C2.17409 11.341 2.66573 12.0758 3.28568 12.6941C3.90407 13.3141 4.63886 13.8057 5.44784 14.1408C6.25682 14.4759 7.12404 14.6479 7.99968 14.6468Z" fill="white" stroke="white" stroke-width="1.33333" stroke-linejoin="round"/>\n<path d="M8 9.52181V8.18848C8.39556 8.18848 8.78224 8.07118 9.11114 7.85142C9.44004 7.63165 9.69638 7.3193 9.84776 6.95384C9.99913 6.58839 10.0387 6.18626 9.96157 5.7983C9.8844 5.41033 9.69392 5.05397 9.41421 4.77426C9.13451 4.49456 8.77814 4.30408 8.39018 4.22691C8.00222 4.14974 7.60009 4.18934 7.23463 4.34072C6.86918 4.49209 6.55682 4.74844 6.33706 5.07734C6.1173 5.40624 6 5.79291 6 6.18848" stroke="black" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/>\n<path fill-rule="evenodd" clip-rule="evenodd" d="M7.99935 12.5219C8.22036 12.5219 8.43232 12.4341 8.5886 12.2778C8.74488 12.1215 8.83268 11.9096 8.83268 11.6886C8.83268 11.4675 8.74488 11.2556 8.5886 11.0993C8.43232 10.943 8.22036 10.8552 7.99935 10.8552C7.77834 10.8552 7.56637 10.943 7.41009 11.0993C7.25381 11.2556 7.16602 11.4675 7.16602 11.6886C7.16602 11.9096 7.25381 12.1215 7.41009 12.2778C7.56637 12.4341 7.77834 12.5219 7.99935 12.5219Z" fill="black"/>\n</mask>\n<g mask="url(#mask0_8002_5572)">\n<path d="M0 -0.0197754H16V15.9802H0V-0.0197754Z" fill="#6C757D"/>\n</g>\n</svg>'};let i='\n <div class="bubble-buttons-container">\n ';n?(i+='<div class="bubble-button-info">
1',r.forEach(e=>{i+=`\n <button class="button-info-item" onclick="handleBubbleButtonClick('${e.id}')">\n <div class="button-info-content">\n <div class="button-info-header">\n ${o[e.icon]}\n <div class="button-info-text">\n <span class="button-title">${e.text}</span>\n <span class="button-info-desc">${e.description.replace(/\n/g,"<br>")}</span>\n </div>\n </div>\n </div>\n </button>\n`}),i+="</div>",document.addEventListener("click",function(e){e.target.closest("#show-sidebar-tutorial-btn")})):(i+='<div class="bubble-buttons">',r.forEach(e=>{i+=`\n <button class="bubble-action-btn" onclick="handleBubbleButtonClick('${e.id}')">\n ${o[e.icon]}\n <span>${e.text}</span>\n </button>\n `}),i+="</div>");i+="</div>",i+=`\n <div class="sidebar-counter-nav-div" id="sidebar-counter-nav-div" style="display: none">\n <div class="sidebar-word-counter-div">\n <span class="sidebar-word-count">0 ${pe("membership.characters")}</span>\n </div>\n </div>\n `,Ri.bubble.innerHTML=i,Ki(),Di(),window.innerWidth<=480&&Ri.bubble.style.setProperty("--arrow-position","134px")}(a),Ri.bubble.style.setProperty("--bubble-width","fit-content"),Ri.bubble.style.setProperty("--bubble-max-width","250px");else if(i&&i.length>1)Ri.bubble.style.setProperty("--bubble-width","165px"),Ri.bubble.style.setProperty("--bubble-max-width","165px"),function(e){Aa.slides=e,Aa.currentIndex=0,Ri.bubbleText.innerHTML=`\n <div class="bubble-slider-container">\n <div class="bubble-slide-content">\n ${ia.slideTemplate(e[0].text,e[0].description)}\n </div>\n <div class="bubble-indicators">\n ${ia.indicatorTemplate(e.length,0)}\n </div>\n </div>\n `,"hover"===ji&&(Aa.positionTimeout=requestAnimationFrame(()=>{Ea()}));e.length>1&&(Aa.interval=setInterval(()=>{"hover"===ji&&function(){const e=Aa.slides;if(e.length<=1)return;Aa.currentIndex=(Aa.currentIndex+1)%e.length,function(){const e=Aa.slides[Aa.currentIndex],t=Ri.bubbleText.querySelector(".bubble-slide-content"),n=Ri.bubbleText.querySelectorAll(".bubble-dot");t&&(t.innerHTML=ia.slideTemplate(e.text,e.description),t.offsetHeight);n.forEach((e,t)=>{e.classList.toggle("active",t===Aa.currentIndex)})}()}()},2e3))}(i);else{if(r&&o>0)startCountdownWithCross(e,o);else{const r=i?.[0]||{text:e,description:""};let o="";n&&(o+='<span class="sidebar-bubble-loader" style="display: flex;"><svg xmlns="http://www.w3.org/2000/svg" width="14" height="16" viewBox="0 0 15 17" fill="none" class="processing-animation">\n <path d="M8.5 0.980225V16.9802H10.5V0.980225H8.5ZM4.5 2.98022V14.9802H6.5V2.98022H4.5ZM12.5 4.98022V12.9802H14.5V4.98022H12.5ZM0.5 6.98022V10.9802H2.5V6.98022H0.5Z" fill="#C7899C"></path>\n </svg></span>');const a=r.text.includes('<div class="markdown-body">');o+=r.description?`<div class="bubble-main-text">${r.text}</div><div class="bubble-description">${r.description.replace(/\n/g,"<br>")}</div>`:a?r.text:`<span class="bubble-text">${r.text}</span>`,l&&(o+='\n <div class="sidebar-ask-audio-controls" id="sidebar-ask-audio-controls">\n <button class="sidebar-audio-control-btn" id="sidebar-audio-play-pause" onclick="toggleSidebarAudio()">\n <svg xmlns="http://www.w3.org/2000/svg" width="12" height="15" viewBox="0 0 12 15" fill="none">\n<path d="M2 0.75C1.53587 0.75 1.09075 0.934375 0.762563 1.26256C0.434375 1.59075 0.25 2.03587 0.25 2.5V12.5C0.25 13.466 1.034 14.25 2 14.25H3C3.46413 14.25 3.90925 14.0656 4.23744 13.7374C4.56563 13.4092 4.75 12.9641 4.75 12.5V2.5C4.75 2.03587 4.56563 1.59075 4.23744 1.26256C3.90925 0.934375 3.46413 0.75 3 0.75H2ZM8.5 0.75C8.03587 0.75 7.59075 0.934375 7.26256 1.26256C6.93437 1.59075 6.75 2.03587 6.75 2.5V12.5C6.75 13.466 7.534 14.25 8.5 14.25H9.5C9.96413 14.25 10.4092 14.0656 10.7374 13.7374C11.0656 13.4092 11.25 12.9641 11.25 12.5V2.5C11.25 2.03587 11.0656 1.59075 10.7374 1.26256C10.4092 0.934375 9.96413 0.75 9.5 0.75H8.5Z" fill="#6C757D"/>\n</svg>\n </button>\n <div class="sidebar-audio-progress-container">\n <div class="sidebar-audio-progress-track" onclick="seekSidebarAudio(event)">\n <div class="sidebar-audio-progress-fill" id="sidebar-audio-progress-fill"></div>\n </div>\n </div>\n <div class="sidebar-volume-container">\n <button class="sidebar-audio-control-btn" id="sidebar-audio-volume" onclick="toggleSidebarVolume()">\n <svg xmlns="http://www.w3.org/2000/svg" width="16" height="14" viewBox="0 0 16 14" fill="none">\n <path d="M12.5 8.60718L14 7.10718M14 7.10718L15.5 5.60718M14 7.10718L12.5 5.60718M14 7.10718L15.5 8.60718" stroke="#6C757D" stroke-linecap="round" stroke-linejoin="round"/>\n <path d="M0.5 8.49988V5.71438C0.5 5.31655 0.658035 4.93502 0.93934 4.65372C1.22064 4.37241 1.60218 4.21438 2 4.21438H4.175C4.32164 4.21434 4.46505 4.17132 4.5875 4.09063L9.0875 1.12363C9.20056 1.04917 9.33168 1.0067 9.46692 1.00073C9.60217 0.994759 9.73652 1.02551 9.8557 1.08972C9.97489 1.15392 10.0745 1.24919 10.1439 1.36542C10.2133 1.48
1165 10.25 1.6145 10.25 1.74988V12.4644C10.25 12.5998 10.2133 12.7326 10.1439 12.8488C10.0745 12.9651 9.97489 13.0603 9.8557 13.1245C9.73652 13.1887 9.60217 13.2195 9.46692 13.2135C9.33168 13.2076 9.20056 13.1651 9.0875 13.0906L4.5875 10.1236C4.46505 10.0429 4.32164 9.99991 4.175 9.99988H2C1.60218 9.99988 1.22064 9.84184 0.93934 9.56054C0.658035 9.27923 0.5 8.8977 0.5 8.49988Z" stroke="#6C757D"/>\n</svg>\n </button>\n <div class="sidebar-volume-bar" id="sidebar-volume-bar">\n <div class="sidebar-volume-track" onclick="handleVolumeClick(event)">\n <div class="sidebar-volume-fill" id="sidebar-volume-fill"></div>\n <div class="sidebar-volume-handle" id="sidebar-volume-handle"></div>\n </div>\n </div>\n </div>\n </div>',o+=`\n <div class="bubble-ok-button-container">\n <button class="bubble-ok-button" onclick="handleOkButtonClick()">\n <span>${pe("sidebarRobot.closeExplanation")}</span>\n </button>\n </div>`),t&&(o+='<span class="bubble-divider"><svg xmlns="http://www.w3.org/2000/svg" width="2" height="22" viewBox="0 0 2 22" fill="none">\n <path d="M1 1.23022V20.7302" stroke="#E4E4E4" stroke-linecap="round"/>\n</svg></span>',o+='<div class="keyboard-icon" style="display: flex;"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="12" viewBox="0 0 16 12" fill="none">\n <path d="M4.66634 3.98014C4.66634 4.15695 4.5961 4.32652 4.47108 4.45155C4.34605 4.57657 4.17649 4.64681 3.99967 4.64681C3.82286 4.64681 3.65329 4.57657 3.52827 4.45155C3.40325 4.32652 3.33301 4.15695 3.33301 3.98014C3.33301 3.80333 3.40325 3.63376 3.52827 3.50874C3.65329 3.38371 3.82286 3.31348 3.99967 3.31348C4.17649 3.31348 4.34605 3.38371 4.47108 3.50874C4.5961 3.63376 4.66634 3.80333 4.66634 3.98014ZM4.66634 5.98014C4.66634 6.15695 4.5961 6.32652 4.47108 6.45155C4.34605 6.57657 4.17649 6.64681 3.99967 6.64681C3.82286 6.64681 3.65329 6.57657 3.52827 6.45155C3.40325 6.32652 3.33301 6.15695 3.33301 5.98014C3.33301 5.80333 3.40325 5.63376 3.52827 5.50874C3.65329 5.38371 3.82286 5.31348 3.99967 5.31348C4.17649 5.31348 4.34605 5.38371 4.47108 5.50874C4.5961 5.63376 4.66634 5.80333 4.66634 5.98014ZM6.66634 5.98014C6.66634 6.15695 6.5961 6.32652 6.47108 6.45155C6.34605 6.57657 6.17649 6.64681 5.99967 6.64681C5.82286 6.64681 5.65329 6.57657 5.52827 6.45155C5.40325 6.32652 5.33301 6.15695 5.33301 5.98014C5.33301 5.80333 5.40325 5.63376 5.52827 5.50874C5.65329 5.38371 5.82286 5.31348 5.99967 5.31348C6.17649 5.31348 6.34605 5.38371 6.47108 5.50874C6.5961 5.63376 6.66634 5.80333 6.66634 5.98014ZM6.66634 3.98014C6.66634 4.15695 6.5961 4.32652 6.47108 4.45155C6.34605 4.57657 6.17649 4.64681 5.99967 4.64681C5.82286 4.64681 5.65329 4.57657 5.52827 4.45155C5.40325 4.32652 5.33301 4.15695 5.33301 3.98014C5.33301 3.80333 5.40325 3.63376 5.52827 3.50874C5.65329 3.38371 5.82286 3.31348 5.99967 3.31348C6.17649 3.31348 6.34605 3.38371 6.47108 3.50874C6.5961 3.63376 6.66634 3.80333 6.66634 3.98014ZM8.66634 3.98014C8.66634 4.15695 8.5961 4.32652 8.47108 4.45155C8.34605 4.57657 8.17649 4.64681 7.99967 4.64681C7.82286 4.64681 7.65329 4.57657 7.52827 4.45155C7.40325 4.32652 7.33301 4.15695 7.33301 3.98014C7.33301 3.80333 7.40325 3.63376 7.52827 3.50874C7.65329 3.38371 7.82286 3.31348 7.99967 3.31348C8.17649 3.31348 8.34605 3.38371 8.47108 3.50874C8.5961 3.63376 8.66634 3.80333 8.66634 3.98014ZM8.66634 5.98014C8.66634 6.15695 8.5961 6.32652 8.47108 6.45155C8.34605 6.57657 8.17649 6.64681 7.99967 6.64681C7.82286 6.64681 7.65329 6.57657 7.52827 6.45155C7.40325 6.32652 7.33301 6.15695 7.33301 5.98014C7.33301 5.80333 7.40325 5.63376 7.52827 5.50874C7.65329 5.38371 7.82286 5.31348 7.99967 5.31348C8.17649 5.31348 8.34605 5.38371 8.47108 5.50874C8.5961 5.63376 8.66634 5.80333 8.66634 5.98014ZM10.6663 3.98014C10.6663 4.15695 10.5961 4.32652 10.4711 4.45155C10.3461 4.57657 10.1765 4.64681 9.99967 4.64681C9.82286 4.64681 9.65329 4.57657 9.52827 4.45155C9.40325 4.32652 9.33301 4.15695 9.33301 3.98014C9.33301 3.80333 9.40325 3.63376 9.52827 3.50874C9.65329 3.38371 9.82286 3.31348 9.99967 3.31348C10.1765 3.31348 10.3461 3.38371 10.4711 3.50874C10.5961 3.63376 10.6663 3.80333 10.6663 3.98014ZM10.6663 5.98014C10.6663 6.15695 10.5961 6.32652 10.4711 6.45155C10.3461 6.57657 10.1765 6.64681 9.99967 6.64681C9.82286 6.64681 9.65329 6.57657 9.52827 6.45155C9.40325 6.32652 9.33301 6.15695 9.33301 5.98014C9.33301 5.80333 9.40325 5.63376 9.52827 5.50874C9.65329 5.38371 9.82286 5.31348 9.99967 5.31348C10.1765 5.31348 10.3461 5.38371 10.4711 5.50874C10.5961 5.63376 10.6663 5.80333 10.6663 5.98014ZM12.6663 3.98014C12.6663 4.15695 12.5961 4.32652 12.4711 4.45155C12.3461 4.57657 12.1765 4.64681 11.9997 4.64681C11.8229 4.64681 11.6533 4.57657 11.5283 4.45155C11.4032 4.32652 11.333 4.15695 11.333 3.98014C11.333 3.80333 11.4032 3.63376 11.5283 3.50874C11.6533 3.38371 11.8229 3.31348 11.9997 3.31348C12.1765 3.31348 12.3461 3.38371 12.4711 3.50874C12.5961 3.63376 12.6663 3.80333 12.6663 3.98014ZM12.6663 5.98014C12.6663
16.15695 12.5961 6.32652 12.4711 6.45155C12.3461 6.57657 12.1765 6.64681 11.9997 6.64681C11.8229 6.64681 11.6533 6.57657 11.5283 6.45155C11.4032 6.32652 11.333 6.15695 11.333 5.98014C11.333 5.80333 11.4032 5.63376 11.5283 5.50874C11.6533 5.38371 11.8229 5.31348 11.9997 5.31348C12.1765 5.31348 12.3461 5.38371 12.4711 5.50874C12.5961 5.63376 12.6663 5.80333 12.6663 5.98014Z" fill="#6C757D"/>\n <path d="M10.6663 1.31348C12.5517 1.31348 13.495 1.31348 14.0803 1.89948C14.6663 2.48481 14.6663 3.42814 14.6663 5.31348V6.64681C14.6663 8.53214 14.6663 9.47548 14.0803 10.0608C13.495 10.6468 12.5517 10.6468 10.6663 10.6468H5.33301C3.44767 10.6468 2.50434 10.6468 1.91901 10.0608C1.33301 9.47548 1.33301 8.53214 1.33301 6.64681V5.31348C1.33301 3.42814 1.33301 2.48481 1.91901 1.89948C2.50434 1.31348 3.44767 1.31348 5.33301 1.31348H7.99967M4.66634 8.64681H11.333" stroke="#ADB5BD" stroke-width="1.5" stroke-linecap="round"/>\n </svg></div>'),Ri.bubble.innerHTML=o;try{Ri.bubble.querySelectorAll("a[href]").forEach(e=>{e.setAttribute("target","_blank"),e.setAttribute("rel","noopener noreferrer"),e.addEventListener("click",e=>{e.stopPropagation()})})}catch(e){}l?(Ri.bubble.classList.add("has-ok-button"),Wi=!0,Mr.loadAnimationByState("analyzed","#gif-sidebar-collapsed")):(Ri.bubble.classList.remove("has-ok-button"),Wi=!1);try{Ri.keyboardIcon=Ri.bubble.querySelector(".keyboard-icon")||null,Ri.bubbleLoader=Ri.bubble.querySelector(".sidebar-bubble-loader")||null,Ri.bubbleText=Ri.bubble.querySelector(".bubble-text")||Ri.bubbleText}catch(e){}}Ri.bubble.style.setProperty("--bubble-width","max-content"),Ri.bubble.style.setProperty("--bubble-max-width","250px")}if(Ri.keyboardIcon&&(Ri.keyboardIcon.style.display=t?"flex":"none"),Ri.bubbleLoader){Ri.bubbleLoader.style.display=n?"flex":"none";const e=Ri.bubbleLoader.querySelector("svg");e&&(n?(e.classList.add("processing-animation"),e.classList.remove("spin-animation")):(e.classList.remove("processing-animation"),e.classList.remove("spin-animation")))}Ri.bubble.style.display="flex",Ri.bubble.style.visibility="visible",Ri.bubble.style.opacity="1",Ri.bubble.style.zIndex="10001",requestAnimationFrame(()=>{Ri.bubble.classList.add("show"),a||i&&!(i.length<=1)||setTimeout(()=>Ea(),50)})}else console.error("â Sidebar bubble elements not found!")}function Ta(e){if(!Ri.bubble)return;Ca(),qa(),Ri.bubble.style.setProperty("--bubble-width","max-content"),Ri.bubble.style.setProperty("--bubble-max-width","200px");const t=`\n <div class="bubble-main-text" style="display:flex;align-items:center;gap:8px;">\n <div class="gradient-loader"></div>
1\n <span class="bubble-text">${"string"==typeof e&&e.trim()?e.trim():pe("robot.thinking")}</span>\n </div>\n `;if(Ri.bubble.innerHTML=t,Ri.bubble.innerHTML=t,e===pe("robot.connecting")&&!Gi){const e=document.querySelector(".sidebar-robot-blur-effect");e&&(e.style.display="flex",Gi=!0)}Ri.keyboardIcon&&(Ri.keyboardIcon.style.display="none"),Ri.bubble.style.display="flex",Ri.bubble.style.visibility="visible",Ri.bubble.style.opacity="1";try{Ri.bubble.classList.add("loading")}catch(e){}const n=document.querySelector(".sidebar-robot-blur-effect");n&&(n.style.display=e===pe("robot.connecting")?"block":"none"),requestAnimationFrame(()=>{Ri.bubble.classList.add("show"),setTimeout(()=>Ea(),50)})}function La(){const e=document.getElementById("sidebar-robot-bubble-tts");if(e&&e.parentNode)try{e.parentNode.removeChild(e)}catch(e){}Ri.bubble&&"idle"!==ji&&"input"!==ji&&(Ri.bubble.style.display="flex")}function Ea(){Ri.bubble&&Ri.gif&&requestAnimationFrame(()=>{if(Wi){const e=window.innerWidth<=480?"167px":"217px";return void Ri.bubble.style.setProperty("--arrow-position",e)}Ca(),Ri.bubble.offsetHeight;const e=Ri.bubble.getBoundingClientRect(),t=Ri.gif.getBoundingClientRect(),n=t.left+t.width/2;if(e.left<20)e.left,Ri.bubble.style.right="auto",Ri.bubble.style.left="20px",Ri.bubble.style.transform="translateY(0)",requestAnimationFrame(()=>{const e=Ri.bubble.getBoundingClientRect(),t=Math.max(15,Math.min(200,n-e.left));Ri.bubble.style.setProperty("--arrow-position",`${t}px`)});else{const t=Math.max(15,Math.min(200,n-e.left));Ri.bubble.style.setProperty("--arrow-position",`${t}px`)}})}function Ca(){Ri.bubble&&(Ri.bubble.style.removeProperty("--arrow-position"),Ri.bubble.style.left="auto",Ri.bubble.style.right="7px",Ri.bubble.style.transform="translateY(0)",Ri.bubble.style.setProperty("--arrow-position","200px"))}function _a(){Ri.input&&(Ri.input.style.removeProperty("--arrow-position"),Ri.input.style.left="auto",Ri.input.style.right="0px",Ri.input.style.transform="translateY(0)")}document.addEventListener("DOMContentLoaded",function(){const e=document.getElementById("sidebar_custom_input");if(!e)return;const t=()=>{const t=e.scrollTop;e.style.height,e.style.height="auto";const n=e.scrollHeight,r=Math.min(Math.max(n,80),300);e.style.height=`${r}px`,n>300?(e.style.overflowY="auto",e.scrollTop=t):e.style.overflowY="hidden"};e.addEventListener("input",t),e.addEventListener("paste",()=>setTimeout(t,0)),t()});let Aa={slides:[],currentIndex:0,interval:null,positionTimeout:null};function qa(){Aa.positionTimeout&&(clearTimeout(Aa.positionTimeout),cancelAnimationFrame(Aa.positionTimeout),Aa.positionTimeout=null),Aa.interval&&(clearInterval(Aa.interval),Aa.interval=null),Aa.slides=[],Aa.currentIndex=0}async function Ma(){if(!("edit"!==$i||window.quill1&&window.quill1.getText().trim()))return Sa("error",{message:pe("sidebarRobot.insertTextFirst")}),void setTimeout(()=>Sa("idle"),3e3);await new Promise(async e=>{try{if(!window.MediaRecorder||!navigator.mediaDevices)return void e(!1);(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e(!0)}catch(t){e(!1)}})?Sa("listening"):Ba()}function Ia(){Uo(),fi();try{stopSpeaking(),window.speechSynthesis&&window.speechSynthesis.cancel();document.querySelectorAll("audio").forEach(e=>{e.pause(),e.currentTime=0}),window.ttsTimeout&&(clearTimeout(window.ttsTimeout),window.ttsTimeout=null),window.ttsInterval&&(clearInterval(window.ttsInterval),window.ttsInterval=null)}catch(e){}if(qa(),Ri.bubble){setTimeout(()=>{},150);const e=Ri.bubbleLoader?.querySelector("svg");e&&(e.classList.remove("processing-animation"),e.classList.remove("spin-animation"),e.classList.remove("subtle")),Ca(),Ri.bubble.classList.remove("show"),setTimeout(()=>{Ri.bubble.style.display="none",Ri.bubble.classList.remove("has-ok-button")},150)}window.undoAutoDismiss&&window.undoAutoDismiss.timeoutId&&(clearTimeout(window.undoAutoDismiss.timeoutId),window.undoAutoDismiss=null)}function Ba(){Ri.input&&Ri.inputField&&("listening"===ji&&Da(),Ia(),Sa("input"),_a(),Ri.inputField&&(Ri.inputField.value="",Ri.inputField.style.height="80px",Ri.inputField.style.overflowY="hidden",ba()),Ri.input.style.display="flex",setTimeout(()=>{Ri.input.classList.add("show");const e=Ui||Fi;if(window.quill1&&e&&e.length>0)try{window.quill1.focus(),window.quill1.setSelection(e.index,e.length,"user"),setTimeout(()=>{Ri.inputField.focus()},50)}catch(e){Ri.inputField.focus()}else Ri.inputField.focus();setTimeout(()=>{Ri.input&&Ri.gif&&requestAnimationFrame(()=>{_a(),Ri.input.offsetHeight;const e=Ri.input.getBoundingClientRect(),t=Ri.gif.getBoundingClientRect(),n=t.left+t.width/2;if(e.left<20)e.left,Ri.input.style.right="auto",Ri.input.style.left="20px",Ri.input.style.transform="translateY(0)",requestAnimationFrame(()=>{const e=Ri.input.getBoundingClientRect(),t=Math.max(15,Math.min(175,n-e.left));Ri.input.style.setProperty("--arrow-position",`${t}px`)});else{const t=Math.max(15,Math.min(175,n-e.left));Ri.input.style.setProperty("--arrow-position",`${t}px`)}})},50)},10))}function Ha(){Ri.input&&Ri.inputField&&(_a(),Ri.input.classList.remove("show"),setTimeout(()=>{Ri.input.style.display="none",Ri.inputField.value=""},150))}function Ka(){Fo()}function Da(){Ka()}function Pa(){return window.quill1&&window.quill1.getText().trim().length>0}async function Na(e){try{if(oa())return;if("edit"===$i&&!Pa())return void Sa("error",{message:pe("sidebarRobot.insertTextFirst")});if(Sa("processing",{message:pe("robot.thinking")}),oa())return;if(!!(Ui&&Ui.length>0)||!!(Fi&&Fi.length>0)){const t=(Ui?.text||Fi?.text||"").trim(),n=window.quill1?window.quill1.getText():"";if("ask"===$i){if(oa())return;const r=await Po(e,t,n);if(oa())return;
1if(xa(Pi(r||""),!1,!1,!1,0,null,null,!0),Sa("success",{message:"",preserveBubble:!0,showUndo:!1}),!oa())try{const e=Bi(r);if(await Yo(e,Ii()),oa())return void fi()}catch(e){}return void($i=null)}if("edit"===$i){if(oa())return;Yi();const r=await No(e,t,n);if(oa())return;return await Hi(Oi,r),void($i=null)}}else{if("ask"===$i){if(oa())return;const t=await Ko(e);if(oa())return;if(xa(Pi(t||""),!1,!1,!1,0,null,null,!0),Sa("success",{message:"",preserveBubble:!0,showUndo:!1}),!oa())try{const e=Bi(t);if(await Yo(e,Ii()),oa())return void fi()}catch(e){}return void($i=null)}if("edit"===$i){if(oa())return;Yi();const t=await Do(e);if(Mi=e,oa())return;return await Hi(Oi,t),void($i=null)}}Ui=null,Fi=null}catch(e){console.error("Sidebar processing error:",e),oa()||Sa("error",{message:"Processing failed"})}}window.handleBubbleButtonClick=function(e){if("ask"!==e&&"edit"!==e||Ci(),na=!1,$i=e,window.quill1&&"function"==typeof window.quill1.getSelection){const e=window.quill1.getSelection();e&&e.length>0?(Ui={index:e.index,length:e.length,text:window.quill1.getText(e.index,e.length)},Fi=Ui):(Ui=null,Fi=null)}Ma()},window.toggleSidebarAudio=ri,window.toggleSidebarVolume=ai,window.seekSidebarAudio=mi,window.handleOkButtonClick=function(){Te(),na=!0;try{Uo(),window.currentTTSAudio&&(window.currentTTSAudio.pause(),window.currentTTSAudio.currentTime=0,window.currentTTSAudio.src="");try{"function"==typeof stopSpeaking&&stopSpeaking()}catch(e){}try{"function"==typeof manualStopSpeaking&&manualStopSpeaking()}catch(e){}document.querySelectorAll("audio").forEach((e,t)=>{e.pause(),e.currentTime=0,e.src=""}),window.currentTTSAudio=null,window.isSpeaking=!1,window.audioBlob=null,["ttsTimeout","ttsInterval","currentFetch"].forEach(e=>{window[e]&&("function"==typeof window[e].abort?window[e].abort():"number"==typeof window[e]&&(clearTimeout(window[e]),clearInterval(window[e])),window[e]=null)})}catch(e){}Uo(),fi(),Sa("idle"),$i=null},"undefined"!=typeof window&&(window.sidebarRobot={setSidebarRobotState:Sa},window.cancelAllRequests=ra,window.isRequestCancelled=oa,window.saveSidebarSnapshot=Yi,window.restoreSidebarSnapshot=Qi,window.clearSidebarSnapshots=Xi,window.sidebarPreviousSnapshot=Ji,window.sidebarCurrentSnapshot=Zi);const{readMessage:ja,stopChatTTS:Ra,initializeChatTTS:Fa}=function(e={}){const t=e.window||globalThis.window,n=e.document||t.document,r=e.CustomEvent||t.CustomEvent,o=e.jQuery||t.jQuery,i=e.Audio||t.Audio,a=e.URL||t.URL,l=e.console||t.console,s=e.t,c=e.removeHyphens,d=e.SVG_ICONS,u=e.getTTSLanguageNameForSelectionToolbar,p=e.applySkrivsikkertTtsVolume;let m=null,f=null,g=null,h=0,v=[],y=null,w=!1,b=0,k="idle",S=null,x=[];function T(e,t){if(e)switch(e.classList.remove("active","loading","playing","paused"),e.querySelectorAll(".loader").forEach(e=>e.remove()),t){case"loading":e.classList.add("loading"),e.title=s("action.stop");const t=n.createElement("div");t.className="loader",t.style.display="inline-flex",t.innerHTML='<span class="loading-spinner"></span>',e.innerHTML="",e.appendChild(t);break;case"playing":e.classList.add("playing"),e.title=s("action.pause"),e.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="6" y1="4" x2="6" y2="20"></line><line x1="18" y1="4" x2="18" y2="20"></line></svg>';break;case"paused":e.classList.add("paused"),e.title=s("action.resume"),e.innerHTML=d.READ;break;default:e.title=s("action.readAloud"),e.innerHTML=d.READ}}function L(){x.forEach(e=>{try{a.revokeObjectURL(e)}catch(e){}}),x=[],S=null}function E(e){k="idle",n.querySelectorAll(".action-icon.read-btn").forEach(e=>T(e,"idle")),m=null,f=null,g=null,v=[],h=0,y=null}function C(e,n,r,l,s){const d=b;if(w||d!==b)return void E();if(h>=v.length)return E(),void(l&&l());(function(e,n,r){const i=t.HGF_ajax_object?.ajax_url||t.NBT_ajax_object?.ajax_url,l=t.HGF_ajax_object?.nonce||t.NBT_ajax_object?.nonce;return i&&l?new Promise((t,s)=>{o.ajax({url:i,type:"POST",data:{action:"hgf_important_secure_bots_text_to_speech",nonce:l,text:c(e.trim()),lang:n,gender:r},xhrFields:{responseType:"blob"},beforeSend(e){g=e},success(e){g=null,e&&e.size>0?t(a.createObjectURL(e)):s(new Error("Empty audio"))},error(e,t,n){g=null,s("abort"===t?new Error("Aborted"):new Error(String(n)))}})}):Promise.reject(new Error("AJAX configuration missing"))})(v[h],n,r).then(t=>{if(w||d!==b){try{a.revokeObjectURL(t)}catch(e){}return void E()}null!==m&&(S!==m&&L(),S=m,x.push(t));const o=new i(t);p(o),f=o,k="playing",T(e,"playing"),o.onended=()=>{f=null,h+=1,C(e,n,r,l,s)},o.onerror=e=>{f=null,E(),s&&s(e)},o.play().catch(e=>{f=null,E(),s&&s(e)})}).catch(e=>{E(),s&&s(e)})}function _(e){const t=b;if(w||t!==b)return void E();if(h>=x.length)return void E();const n=x[h],r=new i(n);p(r),f=r,k="playing",T(e,"playing"),r.onended=()=>{f=null,t===b&&(h+=1,_(e))},r.onerror=()=>{f=null,t===b&&E()},r.play().catch(()=>{f=null,t===b&&E()})}function A(){if(b++,w=!0,g&&g.abort){try{g.abort()}catch(e){}g=null}f&&(f.pause(),f.currentTime=0,f=null),E(),w=!1}const q="chat";return{readMessage:function(e){n.dispatchEvent(new r("nbt-tts-before-start",{detail:{source:q}}));const t=n.querySelector(`.message-bubble.ai[data-msg-id="${e}"]`);if(!t)return;const o=(t.textContent||t.innerText||"").trim();if(!o)return;const i=n.querySelector(`.message-actions[data-msg-id="${e}"]`),a=i?.querySelector(".read-btn");if(!a)return;if(m===e)switch(k){case"loading":return void A();case"playing":return void("playing"===k&&f&&y&&(f.pause(),k="paused",T(y,"paused")));case"paused":return void("paused"===k&&f&&y&&(f.play().catch(()=>E()),k="playing",T(y,"playing")))}if(A(),S===e&&x.length>0)return m=e,y=a,h=0,b++,w=!1,void _(a);if(null!==S&&S!==e&&L(),m=e,y=a,k="loading",T(a,"loading"),v=function(e,t=60){if(!e||""===e.trim())return[];const n=e.match(/[^.!?,;\n]+[.!?,;\n]+|[^.!?,;\n]+$/g)||[e],r=[];let o="";for(let e=0;e<n.length;e++){const i=n[e].trim();i&&(o=o?o+" "+i:i,o.split(/\s+/).length>=t&&(r.push(o.trim()),o=""))}return o.trim()&&r.push(o.trim()),r}(o,60),0===v.length)return void E();h=0,b++,w=!1,C(a,u(),"female",()=>{},e=>{l.warn("Chat TTS error:",e)})},stopChatTTS:A,initializeChatTTS:function(){n.addEventListener("nbt-tts-before-start",e=>{e.detail&&e.detail.source!==q&&A()})}}}({window:window,document:document,CustomEvent:CustomEvent,jQuery:jQuery,Audio:Audio,URL:URL,console:console,t:pe,removeHyphens:xn,SVG_ICONS:Ln,getTTSLanguageNameForSelectionToolbar:Bt,applySkrivsikkertTtsVolume:g});Fa();const{loadInstructionsIfNeeded:Oa,initializeInstructionModal:Ua}=function(e={}){const t=e.window||globalThis.window,n=e.document||t.document,r=e.fetch||((...e)=>t.fetch(...e)),o=e.FormData||t.FormData,i=e.CustomEvent||t.CustomEvent,a=e.t,l=e.makeAjaxRequest,s=e.showToast,c=e.escapeHTML,d=e.SVG_ICONS;let u=null,p=!1;function m(){const e=t.HGF_ajax_object?.ajax_url||"/wp-admin/admin-ajax.php",n=t.HGF_ajax_object?.nonce||"",i=new o;return i.append("action","hgf_grammar_bot_instructions"),i.append("nonce",n),r(e,{method:"POST",body:i}).then(e=>e.json()).then(e=>e.success&&e.data?.instructions?e.data.instructions:[]).catch(e=>Promise.reject(e))}function f(e){const t=n.getElementById("user-instructions");t&&t.classList.toggle("loading",e)}let g=null;function h(e){const t=n.getElementById("instruction-modal");if(!t||!t.classList.contains("active"))return;if("Escape"===e.key)return e.preventDefault(),void y();if("Tab"!==e.key)return;const r=function(e){return Array.prototype.slice.call(e.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), [tabindex]:not
1([tabindex="-1"])')).filter(e=>null!==e.offsetParent)}(t);if(0===r.length)return;const o=r[0],i=r[r.length-1],a=n.activeElement;e.shiftKey?a!==o&&t.contains(a)||(e.preventDefault(),i.focus()):a!==i&&t.contains(a)||(e.preventDefault(),o.focus())}function v(e){if(!e)return;g=n.activeElement,e.classList.add("active"),e.setAttribute("aria-hidden","false"),n.addEventListener("keydown",h,!0);const t=n.getElementById("instruction-title");if(t)try{t.focus()}catch(e){}}function y(){u=null;const e=n.getElementById("instruction-modal"),t=n.getElementById("instruction-title"),r=n.getElementById("instruction-content"),o=e?.querySelector(".instruction-modal-header h3"),i=n.getElementById("instruction-submit-btn");!function(e){if(!e)return;e.classList.remove("active"),e.setAttribute("aria-hidden","true"),n.removeEventListener("keydown",h,!0);const t=g;if(g=null,t&&"function"==typeof t.focus)try{t.focus()}catch(e){}}(e),t&&(t.value=""),r&&(r.value=""),o&&(o.textContent=a("instruction.createShortcut")),i&&(i.textContent=a("instruction.save"))}function w(e,t){const r=n.getElementById("instruction-title"),o=n.getElementById("instruction-content");r&&(r.value=e),o&&(o.value=t,o.focus())}function b(){const e=n.getElementById("instruction-title"),t=n.getElementById("instruction-content"),r=e?.value.trim()||"",o=t?.value.trim()||"";if(!r||!o)return void s(a("instruction.fillBothFields"),{type:"warning"});const i=u||0;!function({id:e=0,title:t,content:n},r,o){const i={title:t,content:n};e&&(i.id=String(e)),l("hgf_grammar_bot_save_instruction",i,r,o)}({id:i,title:r,content:o},()=>{y(),s(a(i?"instruction.shortcutUpdated":"instruction.shortcutSaved")),T()},e=>s(a("instruction.error"),{type:"error"}))}function k(e){!function(e,t,n){l("hgf_grammar_bot_delete_instruction",{id:String(e)},t,n)}(e,()=>{s(a("instruction.shortcutDeleted")),T()},e=>s(a("instruction.error"),{type:"error"}))}function S(e){const t=c(e.title);return`<div class="instruction-icon">${d.FILE}</div>\n <span class="instruction-text">${t}</span>\n <div class="instruction-actions">\n <button class="instruction-send" type="button" title="${a("instruction.send")}">${d.SEND}</button>\n <button class="instruction-edit" type="button" title="${a("instruction.edit")}">${d.EDIT}</button>\n <button class="instruction-delete" type="button" title="${a("instruction.delete")}">${d.DELETE}</button>\n </div>`}function x(e){const t=n.getElementById("user-instructions"),r=t?.querySelector(".instructions-mine-content");if(!r)return;if(!e||0===e.length)return void(r.innerHTML=`<div class="instructions-empty">\n <p class="instructions-empty-text">${a("instruction.noShortcutsYet")}</p>\n <button class="create-instruction-btn" type="button">${d.ADD} ${a("instruction.createShortcut")}</button>\n </div>`);r.innerHTML="";for(let t=0;t<e.length;t++){const o=e[t],i=n.createElement("div");i.className="instruction-card user-instruction",i.dataset.instructionId=String(o.id),i.dataset.instructionTitle=o.title,i.dataset.instructionContent=o.content,i.innerHTML=S(o),r.appendChild(i)}const o=n.createElement("button");o.className="create-instruction-btn",o.type="button",o.innerHTML=d.ADD+" "+a("instruction.createShortcut"),r.appendChild(o)}function T(){f(!0),m().then(x).then(()=>f(!1)).catch(()=>{f(!1),s(a("instruction.couldNotLoad"),{type:"error"})})}function L(e){if(e.target.closest(".create-instruction-btn"))return void function(){u=null;const e=n.getElementById("instruction-modal"),t=n.getElementById("instruction-title"),r=n.getElementById("instruction-content"),o=e?.querySelector(".instruction-modal-header h3"),i=n.getElementById("instruction-submit-btn");t&&(t.value=""),r&&(r.value=""),o&&(o.textContent=a("instruction.createShortcut")),i&&(i.textContent=a("instruction.save")),v(e)}();const t=e.target.closest(".instruction-card.user-instruction");if(!t)return;const r=e.target.closest("button"),o=r&&r.classList.contains("instruction-delete"),l=r&&r.classList.contains("instruction-edit");if(o){e.stopPropagation();const n=t.dataset.instructionId;return void k(Number(n))}if(l){e.stopPropagation();const r=t.dataset.instructionId;return void function(e){const t=n.querySelector(`.instruction-card.user-instruction[data-instruction-id="${e}"]`);if(!t)return;u=e;const r=n.getElementById("instruction-modal"),o=n.getElementById("instruction-title"),i=n.getElementById("instruction-content"),l=r?.querySelector(".instruction-modal-header h3"),s=n.getElementById("instruction-submit-btn");o&&(o.value=t.dataset.instructionTitle??""),i&&(i.value=t.dataset.instructionContent??""),l&&(l.textContent=a("instruction.editShortcut")),s&&(s.textContent=a("instruction.saveChanges")),v(r)}(Number(r))}const s=t.dataset.instructionContent,c=new i("instruction-send",{detail:{content:void 0===s?"":s}});n.dispatchEvent(c)}return{loadInstructionsIfNeeded:function(){p||(p=!0,f(!0),m().then(x).then(()=>f(!1)).catch(()=>{p=!1,f(!1)}))},initializeInstructionModal:function(){const e=n.getElementById("instruction-modal");if(e){e.addEventListener("click",t=>{t.target===e&&y()});const t=n.getElementById("instruction-modal-close");t&&t.addEventListener("click",y);const r=n.getElementById("instruction-submit-btn");r&&r.addEventListener("click",b);const o=e.querySelector(".example-chips");o&&o.addEventListener("click",e=>{const t=e.target.closest(".example-chip");if(!t)return;const n=t.getAttribute("data-title"),r=t.getAttribute("data-content"),o=t.getAttribute("data-content-id");n&&r?w(n,r):n&&o&&w(n,"")})}const t=n.getElementById("user-instructions");t&&t.addEventListener("click",L)}}}({window:window,document:document,fetch:(...e)=>fetch(...e),FormData:FormData,CustomEvent:CustomEvent,t:pe,makeAjaxRequest:function(e,t,n,r,o){const i=window.HGF_ajax_object?.ajax_url||window.NBT_ajax_object?.ajax_url,a=window.HGF_ajax_object?.nonce||window.NBT_ajax_object?.nonce;if(!i||!a)return console.error("AJAX configuration missing"),void(r&&r("AJAX configuration missing"));const l=new FormData;l.append("action",e),l.append("nonce",a);for(const e in t)l.append(e,t[e]);fetch(i,{method:"POST",body:l}).then(e=>e.json()).then(e=>{e.success?n&&n(e.data):r&&r(e.data?.message||"Request failed")}
1).catch(e=>{"AbortError"!==e.name&&(console.error("AJAX error:",e),r&&r("Network error"))})},showToast:Ce,escapeHTML:En,SVG_ICONS:Ln});let $a=[],za=null,Ga=0,Va=null,Wa={};function Ja(){const e=document.getElementById("chat-messages");e&&setTimeout(()=>e.scrollTop=e.scrollHeight,50)}function Za(e){const t=document.getElementById("chat-messages");if(!t)return null;!function(){const e=document.getElementById("chat-messages");if(!e)return;e.querySelectorAll(".message-actions").forEach(e=>{const t=e.querySelector(".apply-btn");t&&t.remove();const n=e.querySelector(".undo-btn");n&&n.remove()})}();const n=document.getElementById("chat-welcome-state");n&&n.classList.add("hidden");const r=++Ga;$a.push({id:r,role:"user",text:e,html:"",status:"done"});const o=document.createElement("div");o.className="message-bubble user",o.dataset.msgId=String(r),o.textContent=e,t.appendChild(o);const i=document.getElementById("chat-reset-link");return i&&(i.style.display=""),Ja(),r}function Ya(){const e=document.getElementById("chat-typing-indicator");e&&e.remove()}function Qa(e,t="",n=!0){rl();const r=document.getElementById("chat-messages");if(!r)return null;const o=++Ga;$a.push({id:o,role:"ai",text:t,html:e,status:"done",isEdit:n});const i=document.createElement("div");i.className="message-bubble ai",i.dataset.msgId=String(o),i.innerHTML=e,r.appendChild(i);const a=document.createElement("div");a.className="message-actions",a.dataset.msgId=String(o);const l=n?`<button class="action-btn apply-btn" type="button" title="${pe("action.applyChange")}">${Ln.APPLY} ${pe("action.apply")}</button>`:"";return a.innerHTML=`\n ${l}\n <button class="action-icon copy-btn" type="button" title="${pe("action.copyTitle")}">${Ln.COPY}</button>\n <button class="action-icon read-btn" type="button" title="${pe("action.readAloud")}">${Ln.READ}</button>\n `,r.appendChild(a),Ja(),o}function Xa(){Ra(),kr("chatMicBtn"),za&&(za(),za=null),$a=[],Ga=0,Va=null,rl();const e=document.getElementById("chat-messages");if(!e)return;const t=document.getElementById("chat-welcome-state");t?(t.remove(),e.innerHTML="",e.appendChild(t),t.classList.remove("hidden")):e.innerHTML="";const n=document.getElementById("chat-reset-link");n&&(n.style.display=""),Ja()}function el(){return $a}function tl(e){Va=e}function nl(e){return Wa[e]??null}function rl(){Wa={}}function ol(e,t){const n=$a.find(t=>t.id===e);n&&(n.status=t)}function il(e,t){const n=e.trim();if(0===n.length)return!1;Za(n),function(){const e=document.getElementById("chat-messages");if(!e)return;const t=e.querySelector(".typing-indicator");t&&t.remove();const n=document.createElement("div");n.className="typing-indicator",n.id="chat-typing-indicator",n.innerHTML="<span></span><span></span><span></span>",e.appendChild(n),Ja()}();const{signal:r,abort:o}=ye();return za=o,(async()=>{try{const e=Vn(),o=$a.slice(-4).map(e=>`${e.role}: ${e.text||Cn(e.html)}`).join("\n"),i=await async function(e,t,n,r,o){const i=window.HGF_ajax_object?.ajax_url||"/wp-admin/admin-ajax.php",a=window.HGF_ajax_object?.nonce||"",l=new FormData;l.append("action","hgf_grammar_bot_chat"),l.append("nonce",a),l.append("questionText",e),l.append("lastMessages",t),l.append("quillContent",bn(window.convertBulletListToUl(n))),l.append("language",It()),o&&l.append("instruction_id",o);const s={method:"POST",body:l};r&&(s.signal=r);const c=await fetch(i,s);if(!c.ok)throw new Error("Network response was not ok");const d=await c.json();if(!d.success)throw new Error(d.data?.message||"API request failed");return d.data}(n,o,e,r,t);Ya();const a="string"==typeof i?i:i.content||"",l="string"==typeof i||!1!==i.isEdit;Qa(function(e){if(!e||"string"!=typeof e||!e.trim())return`<p><em>${pe("chat.noResponse")}</em></p>`;const t=function(e){return String(e||"").replace(/```ssworkshop[\s\S]*?```/g,"").replace(/```ssworkshop[\s\S]*$/g,"").replace(/`ssworkshop\s*\{[\s\S]*?\}\s*`/g,"").replace(/\n{3,}/g,"\n\n").trim()}(e);if(!t)return`<p><em>${pe("chat.noResponse")}</em></p>`;return`<div class="markdown-body-chat">${_n(t)}</div>`}(a),a,l)}catch(e){if(za=null,"AbortError"===e.name)return void Ya();console.error("Chat error:",e),Ya();Qa(`<p><em>${pe("chat.error")}</em></p>`,"",!0)}za=null})(),!0}function al(){const e=document.getElementById("chat-messages");e&&e.addEventListener("copy",e=>{const t=window.getSelection();if(!t||0===t.rangeCount)return;const n=t.anchorNode;if(!n||!n.isConnected)return;if(!(n.nodeType===Node.ELEMENT_NODE?n.closest(".message-bubble.ai"):n.parentElement?.closest(".message-bubble.ai")))return;e.preventDefault();const r=t.toString(),o=t.getRangeAt(0).cloneContents(),i=document.createElement("div");i.appendChild(o);let a=i.innerHTML;a=function(e){if(!e||"string"!=typeof e)return"";try{const t=(new DOMParser).parseFromString(e,"text/html");
1return t.body.querySelectorAll("*").forEach(e=>{if(e.style&&(e.style.background="",e.style.backgroundColor="",null!==e.getAttribute("style"))){const t=e.getAttribute("style").replace(/\s*background(-color)?\s*:[^;]+;?/gi,"").trim();t?e.setAttribute("style",t):e.removeAttribute("style")}}),t.body.innerHTML}catch(t){return e}}(a),e.clipboardData.setData("text/plain",r),e.clipboardData.setData("text/html",a)})}function ll(e){if(!e)return;e.style.height="auto";const t=Math.max(e.scrollHeight,27);t>80?(e.style.height="80px",e.style.overflowY="auto"):(e.style.height=t+"px",e.style.overflowY="hidden")}function sl(e,t){if(!e)return;const n=e.value.trim();if(0===n.length)return;!1!==t(n)&&(e.value="",e.style.height="auto",e.style.overflowY="hidden")}function cl(){return function(){const e=document.getElementById("skrivsikkert-instructions");e&&e.addEventListener("click",e=>{const t=e.target.closest(".instruction-card");if(!t)return;const n=t.getAttribute("data-instruction-id");if(n)return void il(t.querySelector(".instruction-text")?.textContent||n,n);const r=t.getAttribute("data-instruction");r&&il(r)})}(),function(){const e=document.getElementById("chat-reset-link");e&&e.addEventListener("click",Xa)}(),document.addEventListener("instruction-send",e=>{e.detail.content&&il(e.detail.content)}),al(),function(){const e=document.querySelectorAll(".chat-tab"),t=document.getElementById("skrivsikkert-instructions"),n=document.getElementById("user-instructions");e.length&&t&&n&&e.forEach(r=>{r.addEventListener("click",()=>{const o=r.getAttribute("data-tab");e.forEach(e=>e.classList.remove("active")),r.classList.add("active"),"skrivsikkert"===o?(t.classList.remove("hidden"),n.classList.add("hidden")):"mine"===o&&(t.classList.add("hidden"),n.classList.remove("hidden"),Oa())})})}(),function(e){const t=document.getElementById("chat-custom-input"),n=document.getElementById("chat-send-btn");t&&(t.addEventListener("input",()=>{ll(t)}),t.addEventListener("keydown",n=>{"Enter"===n.key&&(n.shiftKey||(n.preventDefault(),sl(t,e)))}),n&&n.addEventListener("click",()=>{sl(t,e)}),ll(t))}(il),il}async function dl(e){const t=(n=e,$a.find(e=>e.id===n));var n;if(!t)return;if("applied"===t.status)return;if(!Gn())return;const r=nl(e);if(r){return tl(Vn()),Wn(r),ol(e,"applied"),ul(e),void Ce(pe("chatAction.changeApplied"))}Ar.showTextAreaLoader(".textarea-wrapper",pe("chatAction.applying"),!1);try{tl(Vn());const t=It(),{userMessage:n,aiResponseMessage:r}=function(){const e=el();if(e.length<2)return{userMessage:"",aiResponseMessage:""};const t=e.slice(-2),n=t[0],r=t[1];var o;return{userMessage:n?.text||"",aiResponseMessage:(o=r?.text||"")?o.replace(/\*\*\*(.+?)\*\*\*/g,"$1").replace(/\*\*(.+?)\*\*/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/_(.+?)_/g,"$1").replace(/^\s*[-*+]\s+/gm,"").replace(/^\s*\d+\.\s+/gm,"").replace(/^#{1,6}\s+/gm,"").replace(/```[\s\S]*?```/g,"").replace(/`(.+?)`/g,"$1").replace(/\[(.+?)\]\(.+?\)/g,"$1").replace(/^\s*>\s+/gm,"").replace(/\n{3,}/g,"\n\n").trim():""}}(),i=await async function(e,t,n){const r=window.HGF_ajax_object?.ajax_url||window.NBT_ajax_object?.ajax_url||"/wp-admin/admin-ajax.php",o=window.HGF_ajax_object?.nonce||window.NBT_ajax_object?.nonce||"",i=Vn(),a=new FormData;a.append("action","hgf_grammar_bot_edit"),a.append("nonce",o),a.append("language",e),a.append("quillContent",i?bn(window.convertBulletListToUl(i)):""),a.append("userMessage",t),a.append("aiResponseMessage",n);const l=await fetch(r,{method:"POST",body:a});if(!l.ok)throw new Error("Network response was not ok");const s=await l.json();if(!s.success)throw new Error(s.data?.message||"API request failed");return s.data}(t,n,r);let a="string"==typeof i?i:i.content||"";if(!a)return void Ce(pe("chatAction.noAIResponse"),{type:"error"});a=a.replace(/\\/g,"").replace(/```html|```HTML/g,"").replace(/```/g,"");const l=(o=a)?o.replace(/--/g,"-"):o,s="undefined"!=typeof DOMPurify?DOMPurify.sanitize(l,{ADD_TAGS:["ham-dan"],ADD_ATTR:["class","id"],ALLOWED_ATTR:["class","id"],KEEP_CONTENT:!0}):l;!function(e,t){Wa[e]=t}(e,s),Wn(s),ol(e,"applied"),ul(e),Ce(pe("chatAction.changeApplied"))}catch(e){console.error("Apply error:",e),Ce(pe("chatAction.applyError"),{type:"error"})}finally{Ar.hideTextAreaLoader(".textarea-wrapper")}var o}function ul(e){const t=document.querySelector(`.message-actions[data-msg-id="${e}"]`);if(!t)return;const n=t.querySelector(".apply-btn");if(!n)return;n.disabled=!1,n.classList.remove("loading"),n.classList.add("applied"),n.innerHTML=Ln.APPLY+" "+pe("chatAction.applied");const r=document.createElement("button");r.className="action-btn undo-btn",r.type="button",r.title=pe("chatAction.undo"),r.innerHTML=Ln.UNDO+" "+pe("chatAction.undo"),t.insertBefore(r,n.nextSibling)}function pl(e){const t=Va;if(!t)return;Gn()&&(Wn(t),Va=null,ol(e,"done"),function(e){const t=document.querySelector(`.message-actions[data-msg-id="${e}"]`);if(!t)return;const n=t.querySelector(".undo-btn");n&&n.remove();const r=t.querySelector(".apply-btn");r&&(r.disabled=!1,r.classList.remove("applied","loading"),r.innerHTML=Ln.APPLY+" "+pe("action.apply"))}(e),Ce(pe("chatAction.undone")))}async function ml(e){const t=document.querySelector(`.message-bubble.ai[data-msg-id="${e}"]`);if(!t)return;const n=t.innerHTML.trim();if(!n)return;const{html:r,text:o}=function(e){if(!e||!e.trim())return{html:"",text:""};let t=Rt(e.trim(),"chat-message"),n=jt(t);return Dt()&&(t=Nt(t),n=Pt(n)),{html:t,text:n}}(n);await Ft(r,o)?(!function(e){const t=document.querySelector(`.message-actions[data-msg-id="${e}"]`);if(!t)return;const n=t.querySelector(".copy-btn");if(!n)return;const r=n.innerHTML;n.classList.add("copied"),n.innerHTML=Ln.CHECKMARK,setTimeout(()=>{n.classList.remove("copied"),n.innerHTML=r},2e3)}(e),Ce(pe("chatAction.copiedToClipboard"))):console.error("Failed to copy")}function fl(){const e=document.getElementById("chat-messages");e&&e.addEventListener("click",async e=>{const t=e.target.closest("button");if(!t)return;const n=t.closest(".message-actions");
1if(!n)return;const r=n.getAttribute("data-msg-id");if(!r)return;const o=Number(r);if(t.classList.contains("apply-btn")){if(t.classList.contains("applied"))return;const e=t;if(nl(o))return void await dl(o);const n=e.innerHTML;e.disabled=!0,e.classList.add("loading"),e.innerHTML=`<span class="loader" style="display:inline-flex;align-items:center;margin-right:6px;"><span class="loading-spinner" style="height:14px;width:14px;"></span></span> ${pe("chatAction.applyingShort")}`;try{await dl(o)}finally{e.closest(".message-actions")&&e.classList.contains("apply-btn")&&!e.classList.contains("applied")&&(e.innerHTML=n,e.disabled=!1,e.classList.remove("loading"))}return}t.classList.contains("undo-btn")?pl(o):t.classList.contains("copy-btn")?ml(o):t.classList.contains("read-btn")&&function(e){ja(e)}(o)})}window.explanationResults=!1;let gl=null,hl=null;function vl(){gl?.root&&(gl.root.querySelectorAll("ham-dan.hamdanActive").forEach(e=>e.classList.remove("hamdanActive")),gl.setSelection?.(null)),document.querySelectorAll(".explanation-item.active-explanation").forEach(e=>e.classList.remove("active-explanation"))}function yl(){if(!window.formattingCompleted||!window.explanationResults)return;const e=gl?.root?.querySelectorAll('ham-dan[class*="grammar-correction"]'),t=document.querySelectorAll(".explanation-item");if(!e?.length||!t?.length)return window.explanationResults=!1,void(window.formattingCompleted=!1);e.forEach((e,t)=>{e.id||(e.id=`grammar-correction-${t+1}`)}),e.length===t.length?t.forEach((t,n)=>{t.dataset.correctionId=e[n].id,e[n].dataset.explanationIndex=String(n)}):function(e,t){const n=new Set;e.forEach((e,r)=>{const o=(e.querySelector(".corrected")?.textContent||"").trim().toLowerCase(),i=(e.querySelector(".not-corrected")?.textContent||"").trim().toLowerCase();let a=null,l=0;for(const e of t){if(n.has(e.id))continue;const t=e.textContent.trim().toLowerCase(),r=t.replace(/[.,;:!?"""'']/g,"");let s=0;t===o||r===o.replace(/[.,;:!?"""'']/g,"")?s=100:t===i||r===i.replace(/[.,;:!?"""'']/g,"")?s=90:o.includes(t)&&t.length>0?s=70+t.length:i.includes(t)&&t.length>0&&(s=60+t.length),s>l&&(l=s,a=e)}a&&l>=60&&(e.dataset.correctionId=a.id,a.dataset.explanationIndex=String(r),n.add(a.id))})}(t,e);const n=new Map;for(const t of e){if(null==t.dataset.explanationIndex)continue;const e=t.textContent.trim().toLowerCase().replace(/[.,;:!?"""'']/g,"");e&&!n.has(e)&&n.set(e,t.id)}for(const t of e){if(null!=t.dataset.explanationIndex)continue;const e=t.textContent.trim().toLowerCase().replace(/[.,;:!?"""'']/g,""),r=n.get(e);r&&(t.dataset.linkedCorrection=r)}!window.explanationTTSInitialized&&hl&&(hl(),window.explanationTTSInitialized=!0),t.forEach(e=>{e.removeEventListener("click",wl),e.addEventListener("click",wl)}),window.explanationResults=!1,window.formattingCompleted=!1}function wl(e){if(e.target.closest(".explanation-audio-btn"))return;const t=e.currentTarget;if(t.classList.contains("active-explanation"))return void vl();vl(),t.classList.add("active-explanation");const n=t.dataset.correctionId;if(!n||!gl?.root)return;const r=gl.root.querySelector(`#${CSS.escape(n)}`);r&&(r.classList.add("hamdanActive"),gl.root.querySelectorAll(`ham-dan[data-linked-correction="${n}"]`).forEach(e=>e.classList.add("hamdanActive")),r.scrollIntoView({behavior:"smooth",block:"center"}))}function bl(e){if(!gl)return;const t=document.querySelector(".correction-sidebar");if(document.body.classList.contains("grammar-interactions-disabled")||t?.classList.contains("collapsed"))return;const n=e.target.closest('ham-dan[class*="grammar-correction"]');if(!n?.id)return;let r=document.querySelector(`.explanation-item[data-correction-id="${n.id}"]`);if(!r&&n.dataset.linkedCorrection&&(r=document.querySelector(`.explanation-item[data-correction-id="${n.dataset.linkedCorrection}"]`)),!r)return;vl(),r.classList.add("active-explanation"),n.classList.add("hamdanActive");const o=r.closest(".explanation-list");if(o){const e=r.offsetTop-o.clientHeight/2+r.offsetHeight/2;o.scrollTo({top:Math.max(0,e),behavior:"smooth"})}else r.scrollIntoView({behavior:"smooth",block:"center"})}function kl(e){const t=document.querySelector('.sidebar-icon-btn[data-option="improve-text"]');if(!t)return;const n=t.querySelector(".sidebar-badge");if(n&&n.remove(),e>0){const n=document.createElement("div");n.className="sidebar-badge";const r=document.createElement("span");r.className="sidebar-badge-count",r.textContent=e,n.appendChild(r),t.appendChild(n)}}function Sl(e){try{const t=e.replace(/^`+|`+$/g,"").replace(/^(json|JSON)\s*/i,"").replace(/â/g,"â").replace(/[\u201C\u201D]/g,'"').replace(/[\u2018\u2019]/g,"'").trim();return JSON.parse(t).explanations||[]}catch(e){return console.error("Error processing explanations:",e),[]}}function xl(e){const t=Sl(e),n=t.filter(e=>!e.reason.startsWith("Ingen ændring")&&!e.reason.startsWith("No change"));if(t.length>0)!function(e){const t=document.querySelector(".correction-content");
1if(!t)return;if(!e||0===e.length)return kl(0),t.classList.remove("has-explanations"),void(t.innerHTML=`\n <div style="display:block" id="gif"></div>\n <div style="display:block" class="correction-message">\n <span style="color:#2DB62D">${pe("sidebar.textCorrect")}</span>\n </div>\n `);t.innerHTML="",t.classList.add("has-explanations");const n=document.createElement("div");n.className="explanation-header-wrapper",n.innerHTML=`\n <div class="no-of-changes">\n <span class="no-of-changes-text">${pe("sidebar.errors")} </span>\n <span class="no-of-changes-count">${e.length}</span>\n </div>\n <div class="explanation-header-left">\n <span class="show-hide-underlines">\n <svg\n xmlns="http://www.w3.org/2000/svg"\n width="18"\n height="18"\n viewBox="0 0 24 24"\n fill="none"\n stroke="currentColor"\n stroke-width="2"\n stroke-linecap="round"\n stroke-linejoin="round"\n class="lucide lucide-eye"\n >\n <path d="M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"></path>\n <circle cx="12" cy="12" r="3"></circle>\n </svg>\n</span>\n\n <button class="explanation-premium-plus-btn">\n ${window.grammarModeSlider?window.grammarModeSlider.getButtonHTML(window.grammarModelDepth||2):`<span>${pe("grammar.standard")}</span><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 20 21" fill="none">
1<path d="M16.2314 10.0855C16.2314 5.18792 12.7389 1.2146 8.43404 1.2146C4.12918 1.2146 0.636719 5.18792 0.636719 10.0855C0.636719 14.9831 4.12918 18.9564 8.43404 18.9564" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"></path><path d="M6.16406 10.8381H11.4404" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"></path><path d="M4.9248 13.5538L8.8779 4.92114L12.6132 13.5538" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"></path><path d="M10.2764 15.5739L12.8978 19.5472L19.1625 12.3533" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"></path></svg><span class="explanation-premium-plus-tooltip">${pe("grammar.descStandard")} </span>`}\n </button>\n <div>\n `;const r=document.createElement("div");r.className="explanation-list";const o=e=>{const t=document.createElement("div");return t.textContent=e,t.innerHTML};e.forEach(e=>{const t=e.change.split(/(?:â|â)/),n=t[0]?t[0].trim():"",i=t[1]?t[1].trim():"",a=document.createElement("div");a.className="explanation-item",a.innerHTML=`\n <div class="change-text">\n <span class="not-corrected">${o(n)}</span>\n <span class="explanation-arrow">â</span>\n <span class="corrected">${o(i)}</span>\n <button class="explanation-audio-btn" data-state="play">\n <svg class="play-icon" width="20" height="16" viewBox="0 0 20 16" fill="none" xmlns="http://www.w3.org/2000/svg" style="display: inline;">\n <path d="M11.6666 10.3448V5.65555C11.6666 3.03455 11.6666 1.72405 10.8955 1.39791C10.1244 1.07177 9.21692 1.99844 7.40189 3.85176C6.46195 4.81153 5.92567 5.02407 4.58832 5.02407C3.41877 5.02407 2.83399 5.02407 2.41392 5.31068C1.54192 5.90562 1.67373 7.06849 1.67373 8.00016C1.67373 8.93184 1.54192 10.0947 2.41392 10.6896C2.83399 10.9763 3.41877 10.9763 4.58832 10.9763C5.92567 10.9763 6.46195 11.1888 7.40189 12.1486C9.21692 14.0019 10.1244 14.9286 10.8955 14.6024C11.6666 14.2763 11.6666 12.9658 11.6666 10.3448Z" stroke="rgba(160, 160, 160, 1)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path>\n <path d="M14.1666 5.5C14.6878 6.18306 15 7.05287 15 8C15 8.94713 14.6878 9.81694 14.1666 10.5" stroke="rgba(160, 160, 160, 1)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path>\n <path d="M16.6666 3.8335C17.709 4.97193 18.3333 6.42161 18.3333 8.00016C18.3333 9.57872 17.709 11.0284 16.6666 12.1668" stroke="#90979d" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path>\n </svg>\n <svg class="stop-icon" width="13" height="14" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 278.25 278.25" style="display: none;">\n <rect width="278.25" height="278.25" rx="40" ry="40" style="fill: #7b7b7b;"/>\n </svg>\n </button>\n </div>\n <div class="change-reason">${o(e.reason)}</div>\n `,r.appendChild(a)}),t.appendChild(n),t.appendChild(r),n.querySelector(".no-of-changes").classList.add("fade-in"),r.classList.add("fade-in"),kl(e.length),n.querySelector(".explanation-premium-plus-btn").onclick=e=>{const t=e.currentTarget,n=t.querySelector("span").textContent;let r,o,i;n===pe("grammar.light")?(r=2,o=pe("grammar.standard"),i=pe("grammar.descStandard")):n===pe("grammar.standard")?(r=3,o=pe("grammar.max"),i=pe("grammar.descMax")):(r=1,o=pe("grammar.light"),i=pe("grammar.descBasic")),"function"==typeof window.selectGrammarMode&&window.selectGrammarMode(r,!0),t.innerHTML=`<span>${o}</span><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 20 21" fill="none">
1<path d="M16.2314 10.0855C16.2314 5.18792 12.7389 1.2146 8.43404 1.2146C4.12918 1.2146 0.636719 5.18792 0.636719 10.0855C0.636719 14.9831 4.12918 18.9564 8.43404 18.9564" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"></path><path d="M6.16406 10.8381H11.4404" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"></path><path d="M4.9248 13.5538L8.8779 4.92114L12.6132 13.5538" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"></path><path d="M10.2764 15.5739L12.8978 19.5472L19.1625 12.3533" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"></path></svg><span class="explanation-premium-plus-tooltip">${i}</span>`};const i=n.querySelector(".show-hide-underlines");if(i){let e=!1!==window.eyeIconState;i.style.cursor="pointer";const t=e=>{i.innerHTML=e?'\n <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-eye">\n <path d="M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"></path>\n <circle cx="12" cy="12" r="3"></circle>\n </svg>\n ':'\n <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-eye-off" style="color: rgb(108, 117, 125); opacity: 0.7;">\n <path d="M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49"></path>\n <path d="M14.084 14.158a3 3 0 0 1-4.242-4.242"></path>\n <path d="M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143"></path>\n <path d="m2 2 20 20"></path>\n </svg>\n '};t(e),i.addEventListener("click",()=>{window.eyeIconState=!window.eyeIconState,e=window.eyeIconState,t(e),window.hideUnderlines&&window.shouldShowUnderlines&&window.hideUnderlines(window.shouldShowUnderlines())})}}(n),window.explanationResults=!0,yl();else{const e=document.querySelector(".correction-content");e&&(e.classList.remove("has-explanations"),e.innerHTML=`\n <div style="display:block" id="gif"></div>\n <div style="display:block" class="correction-message">\n <span style="color:#2DB62D">${pe("sidebar.textCorrect")}</span>\n </div>\n `)}}Tn();let Tl=5,Ll={isAnalyzed:!1,analysisData:null,buttonState:{isImproved:!0,isUndo:!1,improvedText:"",previousText:""}};document.addEventListener("DOMContentLoaded",async function(){he(),Mr.setLottieFunction(Ae),await aa();"option-stave"===ns()?document.body.classList.remove("grammar-interactions-disabled"):document.body.classList.add("grammar-interactions-disabled");const e=document.querySelector(".demo-inner .hamdan-speech-bubble");e&&(e.style.display="none");const t=document.querySelector(".improv-inner .correction-content #gif");t&&!t.querySelector("svg")&&Mr.loadAnimationByState("ready",t)}),window.addEventListener("uilangchange",()=>{if(window.grammarModeSlider){const e=document.getElementById("grammarModeContainer");if(e){e.innerHTML=window.grammarModeSlider.getSliderHTML(),window.grammarModeSlider.attachListeners();const t=window.grammarModelDepth||2;window.grammarModeSlider.selectLevel(t,!1)}}window.quill1&&window.quill1.root.setAttribute("data-placeholder",pe("editor.placeholder"));const e=document.documentElement.classList.contains("wp-dark-mode-active")||document.body.classList.contains("wp-dark-mode-active"),t=document.querySelector(".ss-darkmode-label"),n=document.querySelector(".ss-darkmode-label-desktop"),r=pe(e?"dropdown.lightMode":"dropdown.darkMode");t&&(t.textContent=r),n&&(n.textContent=r)}),function(e={}){window.addEventListener("load",function(){fetch(HGF_ajax_object.ajax_url+"?action=hgf_login_check_user_membership&nonce="+HGF_ajax_object.nonce).then(e=>e.json()).then(e=>e.success?e.data.has_active_membership:(console.error("Failed to check membership"),!1)).catch(e=>(console.error("Error:",e),!1)).then(t=>{_r(),"function"==typeof e.onReady&&e.onReady()})})}({onReady(){}});let El,Cl={},_l=-1,Al="",ql="",Ml=!1,Il=!0,Bl="";window.formattingCompleted=!1,window.isMainSwtich=Il,window.switcherText=Bl;let Hl,Kl,Dl="",Pl=!1,Nl=!1,jl=[],Rl=[];window.editOriginalText=null,window.userOriginalInput=null,window.trueOriginalText="",window.lastRequestCancelled=!1;window.grammarModelDepth=!1,window.lastCorrectedText=Al,window.preApiSnapshot="",window.savePreApiSnapshot=function(e="unknown"){try{if(void 0!==Gl&&Gl&&Gl.root){const e=Gl.root.innerHTML||"",t=window.preApiSnapshot||"",n=e=>{try{return("function"==typeof yn?yn(e):e).trim()}catch(t){return(e||"").trim()}};if(n(t)===n(e))return;const r=(t||"").trim(),o=(window.userOriginalInput||"").trim();r?window.trueOriginalText=r:o&&(window.trueOriginalText=o),window.preApiSnapshot=e;try{Il=!0,Bl="",window.isMainSwtich=Il,window.switcherText=Bl}catch(e){}}}catch(e){}}
1,Quill.register({"modules/table-better":QuillTableBetter},!0);const Fl=Quill.import("delta"),Ol=/^(\s*)([\u2022\u00B7â¢]|[0-9]+[.)]|[A-Za-z]+[.)])\s+/;function Ul(e,t){const n=t.ops.map(e=>({...e})),r=n.find(e=>"string"==typeof e.insert&&e.insert.trim().length);if(!r)return t;const o=r.insert.match(Ol);if(!o)return t;const i=o[0],a=o[2];r.insert=r.insert.slice(i.length);const l=n[n.length-1];"string"==typeof l.insert&&l.insert.endsWith("\n")&&(l.insert=l.insert.slice(0,-1));const s=/^\d/.test(a)?"ordered":"bullet";let c=0;const d=(e.getAttribute("style")||"").replace(/\s+/g,"").match(/level(\d+)/);return d&&(c=parseInt(d[1],10)-1),n.push({insert:"\n",attributes:{list:s,indent:c}}),new Fl(n)}const $l=[["p.MsoListParagraphCxSpFirst",Ul],["p.MsoListParagraphCxSpMiddle",Ul],["p.MsoListParagraphCxSpLast",Ul],["p.MsoListParagraph",Ul],["p.msolistparagraph",Ul],["p.MsoNormal",function(e,t){const n=t.ops[0].insert.trimLeft()[0];return"â¢"===n||"·"===n||/^[0-9A-Za-z][.)]/.test(t.ops[0].insert)?Ul(e,t):t}]],zl=Quill.import("blots/inline");Quill.register({"formats/grammar-added":class extends zl{static blotName="grammar-added";static tagName="ham-dan";static className="grammar-correction-added";static create(e){let t=super.create(e);return e&&"object"==typeof e&&e.id&&t.setAttribute("id",e.id),t}static formats(e){const t={};return e.hasAttribute("id")&&(t.id=e.getAttribute("id")),t}},"formats/grammar-removed":class extends zl{static blotName="grammar-removed";static tagName="ham-dan";static className="grammar-correction-removed";static create(e){let t=super.create(e);return e&&"object"==typeof e&&e.id&&t.setAttribute("id",e.id),t}static formats(e){const t={};return e.hasAttribute("id")&&(t.id=e.getAttribute("id")),t}},"formats/grammar-punct":class extends zl{static blotName="grammar-punct";static tagName="ham-dan";static className="grammar-correction-punctuation";static create(e){let t=super.create(e);return e&&"object"==typeof e&&e.id&&t.setAttribute("id",e.id),t}static formats(e){const t={};return e.hasAttribute("id")&&(t.id=e.getAttribute("id")),t}}},!0);Quill.register({"formats/mark":class extends zl{static blotName="mark";static tagName="mark";static className="word-highlight"}},!0);const Gl=new Quill("#inputText",{theme:"snow",spellcheck:!1,modules:{toolbar:[],clipboard:{matchVisual:!1,matchers:$l},table:!1,"table-better":{operationMenu:{items:{unmergeCells:{text:"Unmerge cells"}}}},keyboard:{bindings:QuillTableBetter.keyboardBindings}},placeholder:pe("editor.placeholder")});function Vl(e){return(t,n)=>{const r=t.getAttribute("id");return n.ops.forEach(t=>{t.attributes={...t.attributes||{},[e]:!0},r&&(t.attributes[e]={id:r})}),n}}var Wl;Gl.root&&Gl.root.setAttribute("spellcheck","false"),window.quill1=Gl,function(){var e=Gl.keyboard;function t(e){return function(t,n){if(function(e){var t=e&&e.format;return!(!t||!(t.list||t.table||t["table-better"]||t["table-cell-line"]))}(n))return!0;var r=function(e){if(e)return document.querySelector(".skv2-doc-title")||document.getElementById("doc-title");for(var t=document.querySelectorAll(".format-toolbar .format-btn"),n=0;n<t.length;n++)if(t[n].offsetParent)return t[n];return null}(e);return!r||!r.focus||(r.focus(),!1)}}e&&e.bindings&&(e.bindings.Tab=e.bindings.Tab||[],e.bindings.Tab.unshift({key:"Tab",shiftKey:!1,handler:t(!1)},{key:"Tab",shiftKey:!0,handler:t(!0)}))}(),Gl.clipboard.addMatcher("ham-dan.grammar-correction-added",Vl("grammar-added")),Gl.clipboard.addMatcher("ham-dan.grammar-correction-removed",Vl("grammar-removed")),Gl.clipboard.addMatcher("ham-dan.grammar-correction-punctuation",Vl("grammar-punct")),Gl.clipboard.addMatcher("mark.word-highlight",(Wl="mark",(e,t)=>(t.ops.forEach(e=>{e.attributes={...e.attributes||{},[Wl]:!0}}),t)));var Jl=["bold","italic","underline","strike","link","list","header","mark","grammar-added","grammar-removed","grammar-punct","blockquote","code-block","indent","direction","align","script"];Gl.clipboard.addMatcher(Node.ELEMENT_NODE,function(e,t){return t.ops.forEach(function(e){e.attributes&&Object.keys(e.attributes).forEach(function(t){-1===Jl.indexOf(t)&&delete e.attributes[t]})}),t});if("ontouchstart"in window||navigator.maxTouchPoints>0){const e=Gl.root;e.addEventListener("compositionstart",()=>{e.classList.remove("ql-blank")}),e.addEventListener("compositionend",()=>{setTimeout(()=>{0===Gl.getText().trim().length&&e.classList.add("ql-blank")},0)}),e.addEventListener("input",()=>{e.textContent.trim().length>0&&e.classList.remove("ql-blank")})}function Zl(){try{const e=document.getElementById("autoSaveHistory");if(!(!!e&&e.checked))return void localStorage.removeItem("quillEditorAutoSave");if(Gl&&Gl.root){const e=Gl.root.innerHTML;localStorage.setItem("quillEditorAutoSave",e)}}catch(e){console.error("Error saving editor content:",e)}}function Yl(){try{localStorage.removeItem("quillEditorAutoSave")}catch(e){console.error("Error clearing saved editor content:",e)}}function Ql(e){if(Gl){const e=pe("editor.placeholder");Gl.root.setAttribute("data-placeholder",e)}else console.error("Quill editor not initialized.")}Gl.on("text-change",function(e,t,n){(jr||Rr)&&ao(),Ts(),Ls(),Zl()}),Gl.on("text-change",_r);const Xl=document.getElementById("mainSwitcher");function es(e){const t=document.getElementById("inputText");if(!t)return;t.querySelectorAll("ham-dan.grammar-correction-added, ham-dan.grammar-correction-removed, ham-dan.grammar-correction-punctuation").forEach(t=>
1{e?(t.style.borderBottom="2px solid",t.classList.contains("grammar-correction-added")?t.style.borderColor="#1768FE":t.classList.contains("grammar-correction-removed")?(t.style.display="inline",t.style.borderColor="#C00F0C"):t.classList.contains("grammar-correction-punctuation")&&(t.style.borderColor="#E5A000")):(t.style.borderBottom="none",t.classList.contains("grammar-correction-removed")&&(t.style.display="none"))})}function ts(){return"option-stave"===ns()&&window.eyeIconState}function ns(){const e=document.querySelector(".hk-dropdown-option.active");if(e&&e.id)return e.id;const t=document.querySelector(".hk-dropdown-option");return t&&t.id?t.id:""}document.addEventListener("DOMContentLoaded",()=>{Mt("da",Ql)}),document.addEventListener("DOMContentLoaded",()=>{!function(){document.querySelector(".inner-textarea-bottom");const e=document.querySelector(".correction-sidebar"),t=window.innerWidth<=767;es(ts()),function(){if(window.innerWidth>767){"option-stave"===ns()&&(_l>0&&!Nl&&Mr.showCorrectionLoader(".correction-message","Analyzing..."),cs())}}(),t||(e.style.display="flex",e.classList.remove("collapsed"),e.classList.remove("grammar-interactions-disabled"),document.body.classList.remove("grammar-interactions-disabled"))}()}),document.querySelectorAll(".sidebar-icon-btn").forEach(e=>{e.addEventListener("click",function(){document.querySelector(".correction-sidebar");const e=this.getAttribute("data-option"),t=document.querySelector('.hk-dropdown-option[data-option="'+e+'"]');t&&ls(t)})}),window.eyeIconState=!0,window.shouldShowUnderlines=ts,window.hideUnderlines=es;const rs=document.querySelectorAll(".hk-dropdown-option"),os=document.querySelector(".correction-inner"),is=document.querySelector(".style-inner"),as=document.querySelector(".improv-inner");function ls(e){const t=e.id,n=document.querySelector(".voice-section"),r=document.querySelector(".write-applicationDiv"),o=document.querySelector(".voice-change-btn"),i=document.querySelector(".analyze-request-btn");"function"==typeof window.stopAllSkrivebordTTS&&window.stopAllSkrivebordTTS(),Ci(),rs.forEach(e=>{e.classList.remove("active"),e.setAttribute("aria-selected","false"),e.setAttribute("tabindex","-1")}),e.classList.add("active"),e.setAttribute("aria-selected","true"),e.setAttribute("tabindex","0"),r&&(r.style.display="none"),o&&(o.style.display="none"),i&&(i.style.display="none");const a=document.getElementById("chat-view");"option-bedre"===t?(as.style.display="none",os.style.display="none",is.style.display="none",n&&(n.style.display="none"),a&&(a.style.display="none",a.classList.remove("active")),es(!1),vl(),document.body.classList.add("grammar-interactions-disabled")):"option-stave"===t?(as.style.display="flex",os.style.display="none",is.style.display="none",n&&(n.style.display="none"),a&&(a.style.display="none",a.classList.remove("active")),es(ts()),document.body.classList.remove("grammar-interactions-disabled"),r&&(r.style.display="flex")):"option-tone"===t?(as.style.display="none",os.style.display="none",is.style.display="none",n&&(n.style.display="flex"),a&&(a.style.display="none",a.classList.remove("active")),es(!1),vl(),document.body.classList.add("grammar-interactions-disabled"),o&&(o.style.display="flex")):"option-chat"===t&&(as.style.display="none",os.style.display="none",is.style.display="none",n&&(n.style.display="none"),a&&(a.style.display="flex",a.classList.add("active")),es(!1),vl(),document.body.classList.add("grammar-interactions-disabled"),_r()),function(e){if("smart-help"===e.dataset.option)if(""!=Al&&0==Pl);else if(Ll.isAnalyzed&&Ll.analysisData)bs(Ll.analysisData),Mr.hideCorrectionLoader(".correction-message"),setTimeout(()=>{!function(){hi.audio&&(document.getElementById("analyze-bubble-progress-fill")&&(!isNaN(hi.audio.duration)&&hi.audio.duration>0&&(hi.duration=hi.audio.duration),isNaN(hi.audio.currentTime)||(hi.currentTime=hi.audio.currentTime),wi()),isNaN(hi.audio.volume)||(hi.volumeLevel=Math.round(100*hi.audio.volume)));bi(),ki(),hi.volumeSliderVisible&&setTimeout(()=>{qi()},100)}()},200);else{const e=document.querySelector(".demo-inner"),t=document.querySelector(".correction-inner-main");e&&(e.style.display="flex"),t&&(t.style.display="none");const n=document.querySelector(".correction-inner .demo-inner #gif");n&&!n.querySelector("svg")&&qe(n),Mr.hideCorrectionLoader(".correction-message"),Mr.toggleSmartLoader(!1)}else"improve-text"===e.dataset.option?(_l>0&&!Nl&&Mr.showCorrectionLoader(".correction-message","Analyzing..."),cs()):("change-style"===e.dataset.option||"tone-style"===e.dataset.option)&&(Mr.hideCorrectionLoader(".correction-message"),Mr.toggleSmartLoader(!1));vl(),_r()}(e)}const ss=Array.from(rs);function cs(){if(-1!=_l){if(0==_l)return Mr.hideCorrectionLoader(".correction-message"),Mr.showPerfectState(),void Mr.toggleSmartLoader(!1);if(_l>0&&!Nl){document.querySelector(".gradient-loader")||Mr.showCorrectionLoader(".correction-message","Analyzing...");const e=window.currentHtmlParts||[Cl.html];if(1===e.length){let e=us(Hl);ms("explanations",{original:Cl.text,corrected:El,noOfChanges:_l.toString(),grammarClasses:JSON.stringify(e),uiLang:me()},window.grammarModelDepth).then(e=>{Nl=!0,xl(e),Mr.hideCorrectionLoader(".correction-message"),Mr.toggleSmartLoader(!1)}).catch(e=>{"AbortError"!==e.name&&(console.error("Explanation API Error:",e),qs())})}else{const t=function(e){const t=e.map(e=>{const t=document.createElement("div");return t.innerHTML=e,function(e){const t=document.createElement("div");
1t.innerHTML=e,t.querySelectorAll("br").forEach(e=>{e.replaceWith(document.createTextNode("\n"))});t.querySelectorAll("div, p, h1, h2, h3, h4, h5, h6, ul, ol, li, table, tr, blockquote").forEach(e=>{const t="P"===e.tagName&&1===e.childNodes.length&&e.firstChild.nodeType===Node.ELEMENT_NODE&&"STRONG"===e.firstChild.tagName,n=/^H[1-6]$/i.test(e.tagName)||t,r=n?"\n\n":"\n",o=document.createTextNode(r);if(e.parentNode.insertBefore(o,e.nextSibling),n){const t=document.createTextNode(r);e.parentNode.insertBefore(t,e)}}),t.querySelectorAll("strong, em, b, i, u, s, span, a, mark, sub, sup, code").forEach(e=>{var t=e.previousSibling;if(t&&t.nodeType===Node.TEXT_NODE&&t.textContent&&!/\s$/.test(t.textContent)){var n=(e.textContent||"")[0];n&&!/[\s.,;:!?)\]\-]/.test(n)&&e.parentNode.insertBefore(document.createTextNode(" "),e)}var r=e.nextSibling;if(r&&r.nodeType===Node.TEXT_NODE&&r.textContent&&!/^\s/.test(r.textContent)){var o=(e.textContent||"").slice(-1);o&&!/[\s.,;:!?(\[\-]/.test(o)&&e.parentNode.insertBefore(document.createTextNode(" "),r)}}),t.innerHTML=t.innerHTML.replace(/ /g," ");let n=t.textContent||t.innerText||"";return n=n.replace(/\n\s*\n/g,"\n\n"),n}(t.innerHTML)}),n=[];return e.forEach((e,r)=>{const o=t[r]||"",i=jl[r]||"",a=Rl[r]||"",l=a?us(a):[],s=l.length;s>0&&n.push({original:o,corrected:i,noOfChanges:s.toString(),grammarClasses:JSON.stringify(l),uiLang:me()})}),n}(e);As("explanations",t,window.grammarModelDepth).then(e=>{const t=function(e){if(!e||0===e.length)return"";if(1===e.length)return e[0];try{const t=[];e.forEach((e,n)=>{const r=Sl(e);r&&r.length>0&&t.push(...r)});const n={explanations:t};return JSON.stringify(n)}catch(t){return console.error("Error combining explanation results:",t),e.join(" ")}}(e);Nl=!0,xl(t),Mr.hideCorrectionLoader(".correction-message"),Mr.toggleSmartLoader(!1)}).catch(e=>{"AbortError"!==e.name&&(console.error("Parallel Explanation API Error:",e),qs())})}}else Mr.hideCorrectionLoader(".correction-message"),Mr.toggleSmartLoader(!1)}else Mr.hideCorrectionLoader(".correction-message"),Mr.toggleSmartLoader(!1)}function ds(){return Gl.root.innerHTML}function us(e){const t=[];return(new DOMParser).parseFromString(e,"text/html").querySelectorAll("ham-dan").forEach(e=>{const n=e.textContent,r=e.cloneNode(!1);r.textContent=n,t.push(r.outerHTML)}),t} 2//! =================================================== api calls ================================================= 3function ps(e,t=!0,n=!1,r=!1){n||(window.lastRequestCancelled=!1);const o=Gl.scroll.domNode.parentNode;let i=0;t||(i=o.scrollTop),Gl.setContents([]);const a=marked.parse(e),l=DOMPurify.sanitize(a,{ADD_TAGS:["ham-dan"],ADD_ATTR:["class","id"],ALLOWED_ATTR:["class","id"],KEEP_CONTENT:!0});Gl.clipboard.dangerouslyPasteHTML(0,l,"api");const s=Gl.getContents();let c=!1;if(s.ops.forEach(e=>{if(e.attributes&&e.attributes.background){e.attributes["grammar-added"]||e.attributes["grammar-removed"]||e.attributes["grammar-punct"]||(delete e.attributes.background,c=!0)}}),c&&Gl.setContents(s,"silent"),r||Gl.getText(),t){const e=Gl.getLength();Gl.setSelection(e,0,"silent"),Gl.root.scrollTop=Gl.root.scrollHeight,Gl.focus()}else o.scrollTop=i,o.scrollTop=i;es(ts()),_r()}
3rs.forEach((e,t)=>{e.addEventListener("click",()=>{ls(e)}),e.addEventListener("keydown",n=>{if("Enter"===n.key||" "===n.key)n.preventDefault(),e.click();else if("ArrowRight"===n.key||"ArrowDown"===n.key){n.preventDefault();const e=ss[(t+1)%ss.length];e.focus(),e.click()}else if("ArrowLeft"===n.key||"ArrowUp"===n.key){n.preventDefault();const e=ss[(t-1+ss.length)%ss.length];e.focus(),e.click()}else"Home"===n.key?(n.preventDefault(),ss[0].focus(),ss[0].click()):"End"===n.key&&(n.preventDefault(),ss[ss.length-1].focus(),ss[ss.length-1].click())})}),window.addEventListener("DOMContentLoaded",()=>{const e=document.querySelector(".write-applicationDiv"),t=document.querySelector(".voice-change-btn"),n=document.querySelector(".analyze-request-btn");e&&(e.style.display="none"),t&&(t.style.display="none"),n&&(n.style.display="none");const r=document.querySelector(".hk-dropdown-option.active");r?"option-stave"===r.id&&e?e.style.display="flex":ls(r):rs.length>0&&ls(rs[0]);const o=document.querySelector(".hk-dropdown-option.active")?.id;if("option-chat"!==o){const e=document.querySelector(".improv-inner"),t=document.querySelector(".correction-inner"),n=document.querySelector(".style-inner"),r=document.querySelector(".voice-section"),o=document.getElementById("chat-view");e.style.display="flex",t.style.display="none",n.style.display="none",r&&(r.style.display="none"),o&&(o.style.display="none",o.classList.remove("active"))}}),document.addEventListener("DOMContentLoaded",function(){_r()}),Gl.on("text-change",_r),window.displayResponse=ps;const ms=async(e,t,n=!1)=>{const r={action:"hgf_korrektur_grammar",type:e,params:JSON.stringify(t),modal_depth:n,nonce:HGF_ajax_object.nonce};try{const e=await fetch(HGF_ajax_object.ajax_url,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/x-www-form-urlencoded;"},body:new URLSearchParams(r).toString(),signal:xe()}
3),t=await e.json();if(t.success)return t.data;throw new Error(t.data||"API request failed")}catch(t){throw console.error(`Error in ${e} call: `,t),t}};function fs(e,t){if(Cr)return!1;if(window.quill1&&(window.userOriginalInput=window.quill1.root.innerHTML),Ar.showTextAreaLoader(".textarea-wrapper",pe("loader.improvingText"),!0),!Nn()[0]){Nn()[0]={responses:[e]}}const n=new FormData;n.append("action","hgf_handle_style_change_grammer"),n.append("text",e),n.append("prompt_number",t),n.append("language",It()),n.append("nonce",HGF_ajax_object.nonce),fetch(HGF_ajax_object.ajax_url,{method:"POST",credentials:"same-origin",body:new URLSearchParams(n),signal:xe()}).then(e=>{if(!e.ok)throw new Error(`HTTP error! status: ${e.status} `);return e.json()}).then(e=>{if(!e.success)throw new Error(e.data?.message||"Style change failed");{const t=function(e){let t=e.replace(/\\/g,"");return t=t.replace(/```html|```HTML/g,""),t=t.replace(/```/g,""),t}(e.data);ps(t),Pn(),Nn()[0].responses.push(t);const n=Nn()[0].responses.length;document.querySelectorAll(".response-counter").forEach(e=>{e.textContent=pe("style.responseCounter",{current:n,total:n})}),In()}}).catch(e=>{console.error("Style change request failed:",e),alert(pe("style.changeError"))}).finally(()=>{Ar.hideTextAreaLoader(".textarea-wrapper")})}document.querySelectorAll(".style-option").forEach((e,t)=>{e.addEventListener("click",function(){if(!Gl.getText().trim().length)return;const e=t+1;ql=Gl.root.innerHTML,fs(yn(Al),e)})});let gs="",hs=1,vs=!1,ys=!1;function ws(){vs=!0,Ar.showTextAreaLoader(".textarea-wrapper",pe("loader.analyzingText"),!0),Mr.toggleSmartLoader(!0);const e=document.querySelector(".demo-inner .hamdan-speech-bubble");e&&(e.style.display=""),window.quill1&&(window.userOriginalInput=window.quill1.root.innerHTML);const t=window.quill1?window.quill1.root.innerHTML:"",n=wn(yn(kn(window.convertBulletListToUl(t)))),r=new FormData;r.append("action","hgf_analyze_text_style_grammer"),r.append("text",n),r.append("language",It()),r.append("nonce",HGF_ajax_object.nonce),fetch(HGF_ajax_object.ajax_url,{method:"POST",credentials:"same-origin",body:new URLSearchParams(r),signal:xe()}).then(e=>e.json()).then(e=>{if(!e.success)throw new Error("Server returned error response");{let t="object"==typeof e.data?e.data:{};if("string"==typeof e.data)try{t=JSON.parse(e.data)}catch(e){t={}}if(!t||!t.analysis)throw new Error("Invalid response structure - missing analysis data");{bs(t.analysis),gs=t.improvementHandle||"",Kl=!0,Pl=!0,Ar.hideTextAreaLoader(".textarea-wrapper"),vs=!1;const e=document.getElementById("analyzeRequestBtn");e&&(e.style.display="none")}}}).catch(e=>{if("AbortError"===e.name)return vs=!1,void Ar.hideTextAreaLoader(".textarea-wrapper");if(console.error("Text analysis failed:",e),hs<2)hs++,ws();else{vs=!1;bs({textType:pe("analysis.defaultTextType"),issue:pe("analysis.defaultIssue"),currentStyle:pe("analysis.defaultCurrentStyle"),targetStyle:pe("analysis.defaultTargetStyle"),buttonText:pe("analysis.defaultButton")}),Mr.toggleSmartLoader(!1),Ar.hideTextAreaLoader(".textarea-wrapper");const e=document.getElementById("analyzeRequestBtn");e&&(e.style.display="none")}}).finally(()=>{(Pl||hs>=2)&&(Kl=!0,Pl=!0,Ts(),Ar.hideTextAreaLoader(".textarea-wrapper"),vs=!1)})}function bs(e){Ll.isAnalyzed=!0,Ll.analysisData=e;const t=document.getElementById("improvement-section");t&&(t.style.display="none"),document.getElementById("improvement-section").style.display="none";const n=document.querySelector(".analysis-subtitle");n&&(n.textContent=e.textType);const r=document.querySelector(".warning-msg");r&&(r.textContent=e.issue);const o=document.getElementById("actionBtn");o&&(o.disabled=!1,o.style.pointerEvents="auto",o.style.cursor="pointer",o.classList.remove("disabled-gen-btn"),o.textContent=e.buttonText);const i=document.getElementById("analyzeRequestBtn");i&&(i.style.display="none");const a=document.querySelector(".correction-inner");a&&(a.style.paddingTop="16px");const l=document.querySelector(".demo-inner");l&&(l.style.display="none");const s=document.querySelector(".correction-inner-main");s&&(s.style.display="flex"),document.querySelector(".demo-inner .hamdan-speech-bubble");const c=document.querySelector(".correction-inner-main .hamdan-speech-bubble");if(c&&e.issue){try{if("undefined"!=typeof marked){const t=marked.parse(e.issue);c.innerHTML=formatMarkdownOutput$1(t)}else c.textContent=e.issue}catch(t){console.warn("Error parsing markdown for speech bubble:",t),c.textContent=e.issue}!function(e){if(!e)return;if(e.querySelector(".analyze-bubble-audio-controls"))return;e.insertAdjacentHTML("beforeend",'\n <div class="analyze-bubble-audio-controls sidebar-ask-audio-controls">\n <button class="sidebar-audio-control-btn" id="analyze-bubble-play-pause" onclick="window.toggleAnalyzeBubbleAudio()">\n <svg xmlns="http://www.w3.org/2000/svg" width="11" height="15" viewBox="0 0 11 15" fill="none">\n<path d="M5.503 2.00999L5.437 1.96998C4.689 1.51498 4.031 1.11399 3.467 0.911985C3.15609 0.792491 2.8237 0.739024 2.491 0.754985C2.14078 0.781719 1.80602 0.910336 1.528 1.12498C0.949 1.55898 0.699 2.19799 0.562 2.90499C0.429 3.58999 0.378 4.48198 0.315 5.56798L0.312 5.62398C0.274 6.27398 0.25 6.91698 0.25 7.49998C0.25 8.08298 0.274 8.72698 0.312 9.37698L0.315 9.43198C0.378 10.518 0.429 11.41 0.562 12.094C0.699 12.802 0.949 13.44 1.528 13.875C1.814 14.09 2.135 14.218 2.491 14.245C2.833 14.27 3.161 14.198 3.467 14.088C4.031 13.886 4.689 13.485 5.437 13.031L5.503 12.991C5.929 12.731 6.347 12.464 6.72 12.201C7.1768 11.876 7.62207 11.5351 8.055 11.179L8.105 11.138C8.869 10.515 9.517 9.98598 9.965 9.46598C10.453 8.89598 10.75 8.28398 10.75 7.49998C10.75 6.71598 10.453
36.10299 9.964 5.53399C9.517 5.01399 8.869 4.48399 8.106 3.86199L8.056 3.82099C7.602 3.45099 7.146 3.09698 6.72 2.79898C6.32274 2.52292 5.91687 2.26045 5.503 2.00999Z" fill="#6C757D"/>\n</svg>\n </button>\n <div class="sidebar-audio-progress-container">\n <div class="sidebar-audio-progress-track" onclick="window.seekAnalyzeBubbleAudio(event)">\n <div class="sidebar-audio-progress-fill" id="analyze-bubble-progress-fill"></div>\n </div>\n </div>\n <div class="sidebar-volume-container">\n <button class="sidebar-audio-control-btn" id="analyze-bubble-volume" onclick="window.toggleAnalyzeBubbleVolume()">\n <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18" fill="none">\n<path d="M15.375 5.73213C15.375 5.73213 16.5 6.85713 16.5 8.73213C16.5 10.6071 15.375 11.7321 15.375 11.7321" stroke="none" stroke-linecap="round" stroke-linejoin="round"></path>\n<path d="M2.25 10.4999V7.71438C2.25 7.31655 2.40804 6.93502 2.68934 6.65372C2.97064 6.37241 3.35218 6.21438 3.75 6.21438H5.925C6.07164 6.21434 6.21505 6.17132 6.3375 6.09063L10.8375 3.12363C10.9506 3.04917 11.0817 3.0067 11.2169 3.00073C11.3522 2.99476 11.4865 3.02551 11.6057 3.08972C11.7249 3.15392 11.8245 3.24919 11.8939 3.36542C11.9633 3.48165 12 3.6145 12 3.74988V14.4644C12 14.5998 11.9633 14.7326 11.8939 14.8488C11.8245 14.9651 11.7249 15.0603 11.6057 15.1245C11.4865 15.1887 11.3522 15.2195 11.2169 15.2135C11.0817 15.2076 10.9506 15.1651 10.8375 15.0906L6.3375 12.1236C6.21505 12.0429 6.07164 11.9999 5.925 11.9999H3.75C3.35218 11.9999 2.97064 11.8418 2.68934 11.5605C2.40804 11.2792 2.25 10.8977 2.25 10.4999Z" stroke="#6C757D"></path>\n</svg>\n </button>\n <div class="sidebar-volume-bar" id="analyze-bubble-volume-bar">\n <div class="sidebar-volume-track" onclick="window.handleAnalyzeBubbleVolumeClick(event)">\n <div class="sidebar-volume-fill" id="analyze-bubble-volume-fill"></div>\n <div class="sidebar-volume-handle" id="analyze-bubble-volume-handle"></div>\n </div>\n </div>\n </div>\n </div>')}(c),Ei(e.issue)}const d=document.querySelector(".correction-inner-main .hamdan-robot-container #gif");if(d&&Mr.loadAnimationByState("analyzed",d),Ll.buttonState.improvedText){Kl=Ll.buttonState.isImproved,Ml=Ll.buttonState.isUndo,Dl=Ll.buttonState.improvedText,ql=Ll.buttonState.previousText;const e=document.querySelector(".action-button");e&&(!Kl&&Ml?e.innerHTML=`\n <span>${pe("format.newText")}</span>\n <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" style="transform: scaleX(-1);">\n <circle cx="9.99996" cy="9.99984" r="8.33333" stroke="#ffff" stroke-width="1.5" stroke-linejoin="round"/>\n <path d="M13.3333 7.9165H14.0833C14.0833 7.50229 13.7475 7.1665 13.3333 7.1665V7.9165ZM14.0833 14.1665V7.9165H12.5833V14.1665H14.0833ZM6.66663 8.6665H13.3333V7.1665H6.66663V8.6665Z" fill="#ffff"/>\n <path d="M8.74996 5.83301L6.66663 7.91634L8.74996 9.99967" stroke="#ffff" stroke-width="1.5"/>\n </svg>\n `:Kl||Ml||(e.innerHTML=`\n <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">\n <circle cx="9.99996" cy="9.99984" r="8.33333" stroke="#ffff" stroke-width="1.5" stroke-linejoin="round"/>\n <path d="M13.3333 7.9165H14.0833C14.0833 7.50229 13.7475 7.1665 13.3333 7.1665V7.9165ZM14.0833 14.1665V7.9165H12.5833V14.1665H14.0833ZM6.66663 8.6665H13.3333V7.1665H6.66663V8.6665Z" fill="#ffff"/>\n <path d="M8.74996 5.83301L6.66663 7.91634L8.74996 9.99967" stroke="#ffff" stroke-width="1.5"/>\n </svg>\n <span>${pe("format.originalText")}</span>\n `))}setTimeout(()=>{const e=document.querySelector(".demo-inner"),t=document.querySelector(".correction-inner-main");document.querySelector(".demo-inner .hamdan-speech-bubble"),document.querySelector(".correction-inner-main .hamdan-speech-bubble"),e&&window.getComputedStyle(e).display,t&&window.getComputedStyle(t).display},5e3)}document.addEventListener("DOMContentLoaded",function(){const e=document.getElementById("analyzeRequestBtn");e&&e.addEventListener("click",function(){Gl&&Gl.getText().trim().length&&(vs||(Es(),hs=1,ws()))})});const ks=document.querySelector(".correction-inner-main .hamdan-robot-container #gif");function Ss(e){e.classList.remove("triggered"),requestAnimationFrame(()=>{e.classList.add("triggered"),setTimeout(()=>e.classList.remove("triggered"),250)})}ks&&!ks.querySelector("svg")&&qe(ks),document.querySelector(".action-button")?.addEventListener("click",function(){ys||(Kl?(ql=ds(),function(e){if(ys)return;ys=!0,"function"==typeof window.savePreApiSnapshot&&window.savePreApiSnapshot("improveText");window.quill1&&(window.userOriginalInput=window.quill1.root.innerHTML);const t=document.getElementById("actionBtn");if(t){if(!Ar.buttonTexts.actionBtn){const e=t.querySelector("span");Ar.buttonTexts.actionBtn=e?e.textContent:t.innerHTML}t.disabled=!0,t.style.pointerEvents="none",t.style.cursor="not-allowed",t.classList.add("disabled-gen-btn");const e=t.querySelector("span");e?e.textContent=pe("loader.pleaseWait"):t.textContent=pe("loader.pleaseWait")}Ar.showTextAreaLoader(".textarea-wrapper",pe("loader.improvingText"),!0);const n=wn(yn(kn(window.convertBulletListToUl(ds())))),r=new FormData;r.append("action","hgf_improve_text_style_grammer"),r.append("text",n),r.append("improvement_handle",e),r.append("language",It()),r.append("nonce",HGF_ajax_object.nonce),fetch(HGF_ajax_object.ajax_url,{method:"POST",credentials:"same-origin",body:new URLSearchParams(r),signal:xe()}).then(e=>e.json()).then(e=>{if(!e.success)throw new Error(e.data?.message||"Text improvement failed");{const t=e.data.improved_text.replace(/\\/g,"");ps(t),Dl=t,Ll.buttonState.improvedText=t;const n=document.getElementById("actionBtn");n&&(n.innerHTML=`\n <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">\n <circle cx="9.99996" cy="9.99984" r="8.33333" stroke="#ffff" stroke-width="1.5" stroke-linejoin="round"/>\n <path d="M13.3333 7.9165H14.0833C14.0833 7.50229 13.7475 7.1665 13.3333 7.1665V7.9165ZM14.0833 14.1665V7.9165H12.5833V14.1665H14.0833ZM6.66663 8.6665H13.3333V7.1665H6.66663V8.6665Z" fill="#ffff"/>\n <path d="M8.74996 5.83301L6.66663 7.91634L8.74996 9.99967" stroke="#ffff" stroke-width="1.5"/>\n </svg>
3\n <span>${pe("format.originalText")}</span>\n `,n.disabled=!1,n.style.pointerEvents="auto",n.style.cursor="pointer",n.classList.remove("disabled-gen-btn"),delete Ar.buttonTexts.actionBtn),Kl=!1,Ll.buttonState.isImproved=Kl,Ll.buttonState.previousText=ql}}).catch(e=>{if("AbortError"===e.name)return;console.error("Text improvement failed:",e),alert(pe("style.improveError"));const t=document.getElementById("actionBtn");if(t){const e=Ar.buttonTexts.actionBtn;if(e){const n=t.querySelector("span");n?n.textContent=e:t.innerHTML=e}t.disabled=!1,t.style.pointerEvents="auto",t.style.cursor="pointer",t.classList.remove("disabled-gen-btn"),delete Ar.buttonTexts.actionBtn}}).finally(()=>{Ar.hideTextAreaLoader(".textarea-wrapper"),ys=!1})}(gs)):(!function(){Ml?(ps(Dl,!1),Ml=!1,document.querySelector(".action-button").innerHTML=`\n <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">\n <circle cx="9.99996" cy="9.99984" r="8.33333" stroke="#ffff" stroke-width="1.5" stroke-linejoin="round"/>\n <path d="M13.3333 7.9165H14.0833C14.0833 7.50229 13.7475 7.1665 13.3333 7.1665V7.9165ZM14.0833 14.1665V7.9165H12.5833V14.1665H14.0833ZM6.66663 8.6665H13.3333V7.1665H6.66663V8.6665Z" fill="#ffff"/>\n <path d="M8.74996 5.83301L6.66663 7.91634L8.74996 9.99967" stroke="#ffff" stroke-width="1.5"/>\n </svg>\n <span>${pe("format.originalText")}</span>\n `):(ps(ql,!1),Ml=!0,document.querySelector(".action-button").innerHTML=`\n\n <span>${pe("format.newText")}</span>\n <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" style="transform: scaleX(-1);">\n <circle cx="9.99996" cy="9.99984" r="8.33333" stroke="#ffff" stroke-width="1.5" stroke-linejoin="round"/>\n <path d="M13.3333 7.9165H14.0833C14.0833 7.50229 13.7475 7.1665 13.3333 7.1665V7.9165ZM14.0833 14.1665V7.9165H12.5833V14.1665H14.0833ZM6.66663 8.6665H13.3333V7.1665H6.66663V8.6665Z" fill="#ffff"/>\n <path d="M8.74996 5.83301L6.66663 7.91634L8.74996 9.99967" stroke="#ffff" stroke-width="1.5"/>\n </svg>\n `);Ll.buttonState.isUndo=Ml,Ll.buttonState.isImproved=Kl}(),Ll.buttonState.isUndo=Ml,Ll.buttonState.isImproved=Kl))}),document.addEventListener("DOMContentLoaded",function(){const e=document.querySelector(".analysis-reset-button");e&&e.addEventListener("click",function(){Ci(),Ll.isAnalyzed=!1,Ll.analysisData=null,Ll.buttonState={isImproved:!0,isUndo:!1,improvedText:"",previousText:""},Pl=!1,gs="";const e=document.querySelector(".correction-inner .demo-inner"),t=document.querySelector(".correction-inner-main"),n=document.querySelector(".correction-inner .improvement-section");e&&(e.style.display="flex"),t&&(t.style.display="none"),n&&(n.style.display="grid");const r=document.getElementById("analyzeRequestBtn");r&&(r.style.display="flex");const o=document.querySelector(".correction-inner .demo-inner .hamdan-speech-bubble");o&&(o.innerHTML=`<span>${pe("sidebar.refiningText")}</span>`,o.style.display="none");const i=document.querySelector(".correction-inner .demo-inner #gif");i&&Mr.loadAnimationByState("ready",i),Mr.toggleSmartLoader(!1);const a=document.getElementById("analyzeRequestBtn");
3a&&(a.style.display="flex"),console.log("â
Analysis section (correction-inner) reset to initial state")})}),Xl.addEventListener("click",function(){const e=window.lastRequestCancelled?window.trueOriginalText||window.editOriginalText||window.preApiSnapshot:window.preApiSnapshot||window.editOriginalText||window.trueOriginalText;if(!e||!e.trim())return;const t=void 0!==window.isMainSwtich?window.isMainSwtich:Il,n=void 0!==window.switcherText?window.switcherText:Bl;t?(Bl=ds(),window.switcherText=Bl,Gl.root.innerHTML=yn(e),Il=!1,window.isMainSwtich=!1,Xl.classList.add("viewing-original")):(Gl.root.innerHTML=n,Il=!0,window.isMainSwtich=!0,Xl.classList.remove("viewing-original")),Ls(),Ts()}),document.querySelector("#revertBack")?.addEventListener("click",e=>{e.preventDefault(),Gl.history.undo(),Ss(document.querySelector("#revertBack"))}),document.querySelector("#redoBtn").addEventListener("click",e=>{e.preventDefault(),Gl.history.redo(),Ss(document.querySelector("#redoBtn"))}),document.addEventListener("DOMContentLoaded",function(){!function({quill:e,correctionSidebarLoader:t,initializeExplanationTTS:n}){gl=e,hl=n,gl?.root&&gl.root.addEventListener("click",bl)}({quill:Gl,correctionSidebarLoader:Mr,initializeExplanationTTS:Ao})}),document.addEventListener("DOMContentLoaded",function(){let e;const t=document.querySelector(".ql-editor");t&&t.__quill?e=t.__quill:window.quill&&(e=window.quill),e&&e.on("text-change",function(){}),t&&(t.addEventListener("keyup",function(e){["Enter","Backspace","Delete","Tab"].includes(e.key)}),t.addEventListener("paste",function(){}),t.addEventListener("input",function(){})),window.addEventListener("resize",function(){})}),document.addEventListener("DOMContentLoaded",()=>{const e=document.querySelector(".voice-slider-container"),t=document.querySelector(".voice-handle"),n=document.querySelector(".voice-progress");if(!e||!t||!n)return;let r=!1,o=100;const i=[0,25,50,75,100],a={0:"simplify",25:"elaborate",50:"convencing",75:"concise",100:"professional"};function l(e){const t="#E68A00",n="#F2C27A",r="#A5C5E2",o="#005F9E";return e<=i[0]?t:e<=i[1]?`linear-gradient(90deg, ${t} 0%, ${n} 100%)`:e<=i[2]?`linear-gradient(90deg, ${t} 0%, ${n} 25%, ${r} 100%)`:e<=i[3]?`linear-gradient(90deg, ${t} 0%, ${n} 25%, ${r} 50%, ${o} 100%)`:`linear-gradient(90deg, ${t} 0%, ${n} 25%, ${r} 50%, ${o} 75%, ${o} 100%)`}function s(e){const t=["#E68A00","#CF7C2B","#8CA5C8","#3F7DBF","#005F9E"],n=i.findIndex(t=>e<=t);return t[-1!==n?n:t.length-1]}function c(e){const t=i.reduce((t,n)=>Math.abs(n-e)<Math.abs(t-e)?n:t);return a[t]}function d(e){const t=document.getElementById("voiceCardTitle"),n=document.getElementById("voiceCardSubtitle"),r={simplify:{title:pe("voice.simplify"),subtitle:pe("voice.simplifyDesc")}
3,elaborate:{title:pe("voice.elaborate"),subtitle:pe("voice.elaborateDesc")},convencing:{title:pe("voice.convencing"),subtitle:pe("voice.convencingDesc")},concise:{title:pe("voice.concise"),subtitle:pe("voice.conciseDesc")},professional:{title:pe("voice.professional"),subtitle:pe("voice.professionalDesc")}};r[e]&&t&&n&&(t.textContent=r[e].title,n.textContent=r[e].subtitle)}function u(a){const c=e.getBoundingClientRect(),d=(a.type.includes("touch")?a.touches[0].clientX:a.clientX)-c.left;let u=Math.min(Math.max(d/c.width*100,0),100);return r||(t.style.left=`${u}%`,n.style.width=`${u}%`,n.style.background=l(u),t.style.backgroundColor=s(u),t.style.borderColor="white",u=i.reduce((e,t)=>Math.abs(t-u)<Math.abs(e-u)?t:e)),o=u,p(u),u}function p(e){t.style.left=`${e}%`,n.style.width=`${e}%`,n.style.background=l(e),t.style.backgroundColor=s(e),t.style.borderColor="white",Tl=c(e),d(Tl)}function m(e){e.preventDefault(),r=!0,u(e),document.addEventListener(e.type.includes("touch")?"touchmove":"mousemove",u)}function f(){if(!r)return;r=!1;p(i.reduce((e,t)=>Math.abs(t-o)<Math.abs(e-o)?t:e)),document.removeEventListener("mousemove",u),document.removeEventListener("touchmove",u)}t.addEventListener("mousedown",m),t.addEventListener("touchstart",m),document.addEventListener("mouseup",f),document.addEventListener("touchend",f),e.addEventListener("click",e=>{e.target!==t&&u(e)}),p(100),document.getElementById("voiceChangeBtn")?.addEventListener("click",()=>{if(!Gl.getText().trim().length)return;Es();const e=c(o),t=document.getElementById(e);t&&t.click()})});const xs=document.querySelector("#clearBtn");function Ts(e="center"){const t=document.querySelector("#revertBack"),n=document.querySelector("#clearBtn");if("false"===e)t&&(t.disabled=!1),n&&(n.disabled=!1);else if("true"===e)t&&(t.disabled=!0),n&&(n.disabled=!0);else{const e=Gl.getText().trim().length>0,r=window.textAreaLoader&&window.textAreaLoader.hasActiveLoaders(),o=Gl.history&&Gl.history.stack.undo.length>0;t&&(t.disabled=!e&&!o),n&&(n.disabled=!e||r)}}function Ls(){const e=document.querySelector("#revertBack"),t=document.querySelector("#redoBtn");if(e){const t=Gl.history.stack.undo.length>0;e.disabled=!t,e.title=pe("undoRedo.undo")}if(t){const e=Gl.history.stack.redo.length>0;t.disabled=!e,t.title=pe("undoRedo.redo")}}function Es(){Ci(),ao();try{Se(),console.log("â
Aborted in-progress explanations request")}catch(e){console.error("Error aborting request:",e)}Mr.showReadyState(),vl(),kl(0),Nl=!1,_l=-1;const e=document.querySelector(".improv-inner .correction-content");e&&e.classList.contains("has-explanations")&&e.classList.remove("has-explanations"),console.log("â
Reset .improv-inner to initial state")}function Cs(e){var t=!(!e||!0!==e.skipEditor);Ci(),el().length>0&&Xa(),ao(),t||(Gl.history&&"function"==typeof Gl.history.cutoff&&Gl.history.cutoff(),Gl.setContents([],"user"),Gl.history&&"function"==typeof Gl.history.cutoff&&Gl.history.cutoff()),Yl(),kr("micButton1"),Gl.focus(),Gl.root.dispatchEvent(new Event("input"));const n=document.querySelector(".correction-inner .demo-inner"),r=document.querySelector(".correction-inner .improvement-section"),o=document.querySelector(".correction-inner-main");n&&(n.style.display="flex"),r&&(r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center"),o&&(o.style.display="none");const i=document.querySelector(".correction-inner .demo-inner .hamdan-speech-bubble");i&&(i.innerHTML=`<span>${pe("sidebar.refiningText")}</span>`,i.style.display="none");const a=document.querySelector(".correction-inner .demo-inner #gif");a&&Mr.loadAnimationByState("ready",a),Mr.showReadyState(),Dn();const l=document.querySelector(".dk-hamdan-custom-input");l&&(l.value="",l.textContent="",l.innerHTML="",l.hasAttribute("placeholder")&&l.setAttribute("data-placeholder",l.getAttribute("placeholder")),l.dispatchEvent(new Event("input",{bubbles:!0})),l.dispatchEvent(new Event("change",{bubbles:!0})),l.classList.remove("filled","active","error"),l.classList.add("empty")),Al="",window.lastCorrectedText=Al,Ql(wt(yt())),_r(),document.querySelector("#mainSwitcher").disabled=!0,Il=!0,Bl="",window.isMainSwtich=Il,window.switcherText=Bl,Ml=!1,_l=-1,Cl.html="",Cl.text="",Ll.isAnalyzed=!1,Ll.anal
3ysisData=null,Ll.buttonState={isImproved:!0,isUndo:!1,improvedText:"",previousText:""},Pl=!1,kl(0);if("option-bedre"===ns()){const e=document.getElementById("analyzeRequestBtn");e&&(e.style.display="flex")}Ts(),Ls(),window.trueOriginalText="",window.lastRequestCancelled=!1,document.dispatchEvent(new CustomEvent("skrivebord:editor-cleared"))}function _s(e,t=500,n=2){const r=e=>e.textContent.length,o=(e,t,n)=>e.slice(t,n).map(e=>e.outerHTML??e.textContent).join("").trim(),i=(new DOMParser).parseFromString(e,"text/html").body,a=Array.from(i.childNodes),l=r(i);if(a.map((e,t)=>`[${t}] ${e.nodeName} (${r(e)} chars)`),l<=t||1===n)return[e];const s=new Set(["UL","OL","TABLE","THEAD","TBODY","TFOOT","TR","BLOCKQUOTE","SECTION","ARTICLE","HEADER","FOOTER","NAV","ASIDE","MAIN"]);a.filter(e=>s.has(e.nodeName));const c=[];a.reduce((e,t,n)=>(c[n]=e+r(t),c[n]),0);const d=a.filter(e=>!s.has(e.nodeName)).length,u=Math.min(n,d+1),p=[];for(let e=1;e<u;e++)p.push(l*e/u);const m=new Set,f=[],g=e=>{let t=-1,n=1/0;for(let r=0;r<c.length;r++){if(m.has(r))continue;if(s.has(a[r].nodeName))continue;const o=Math.abs(c[r]-e);o<n&&(n=o,t=r)}return-1!==t&&m.add(t),t};for(const e of p){const t=g(e);-1!==t&&f.push(t)}if(f.sort((e,t)=>e-t),f.length!==p.length&&0===f.length)return[e];const h=[];let v=0;for(const e of f){const t=o(a,v,e+1);h.push(t),v=e+1}const y=o(a,v,a.length);return h.push(y),h}document.querySelector("#revertBack"),xs?.addEventListener("click",Cs),window.trueOriginalText=null,document.addEventListener("keydown",e=>{const t="string"==typeof e.key?e.key.toLowerCase():e.key;if((e.ctrlKey||e.metaKey)&&"Delete"===e.key&&(e.preventDefault(),Cs()),(e.ctrlKey||e.metaKey)&&"z"===t&&!e.shiftKey){e.preventDefault(),e.stopPropagation();const t=document.querySelector("#revertBack");t&&!t.disabled&&(Gl.history.undo(),Ss(t))}if((e.ctrlKey||e.metaKey)&&"y"===t||(e.ctrlKey||e.metaKey)&&e.shiftKey&&"z"===t){e.preventDefault(),e.stopPropagation();const t=document.querySelector("#redoBtn");t&&!t.disabled&&(Gl.history.redo(),Ss(t))}},!0),Ts(),window.robustHtmlDivider=_s,window.processComplexHtml=function(e,t=600){const n="function"==typeof i&&"function"==typeof yn?i(yn(e)):e,r=function(e){const t=document.createElement("div");return t.innerHTML=e,t.textContent.trim().length}(n),o=Math.ceil(r/600);try{const e=_s(n,600,o);return 1===e.length&&o>1?[n]:e}catch(e){return console.error("â ERROR: robustHtmlDivider crashed:",e),[n]}};const As=async(e,t,n=!1)=>{const r={action:"hgf_korrektur_grammar_parallel",type:e,parts:JSON.stringify(t),modal_depth:n,nonce:HGF_ajax_object.nonce};try{const e=await fetch(HGF_ajax_object.ajax_url,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/x-www-form-urlencoded;"},body:new URLSearchParams(r).toString(),signal:xe()}
3),t=await e.json();if(t.success)return t.data;throw new Error(t.data||"Parallel API request failed")}catch(t){if("AbortError"===t.name)throw t;throw console.error(`Error in parallel ${e} call:`,t),t}};function qs(){const e=document.querySelector(".correction-content");e&&(e.classList.contains("has-explanations")&&e.classList.remove("has-explanations"),e.innerHTML=`\n <div class="correction-message">\n <span style="color:#FF5555">${pe("explanation.processingError")}</span>\n </div>\n `),Mr.hideCorrectionLoader(".correction-message"),Mr.toggleSmartLoader(!1)}const Ms=document.querySelector("#pasteBtn");Ms?.addEventListener("click",async()=>{try{var e=await navigator.clipboard.readText();if(e&&e.length>5e3){var t=e.substring(0,200).replace(/[\r\n]+/g," ")+"â¦",n=e.length.toLocaleString("da-DK");if(!confirm("Vil du indsætte "+n+" tegn?\n\n"+t))return}}catch(e){}cr(!0,!0)});const Is=document.querySelector(".ql-editor");function Bs(){const e=window.innerWidth<=480,t=document.getElementById("mobileControlsContainer"),n=document.querySelector(".dk-translation-box"),r=document.querySelector(".sidebar-controls");t&&n&&(e?(n.parentElement!==t&&t.appendChild(n),t.classList.add("mobile-active")):(r&&n.parentElement!==r&&r.appendChild(n),t.classList.remove("mobile-active")))}Is&&Is.addEventListener("paste",e=>{const t=e.clipboardData||window.clipboardData;let n=!1;if(t&&t.items){for(const e of t.items)if("string"===e.kind&&/text\/(plain|html)/.test(e.type)){n=!0;break}if(!n){let n=!1;for(const e of t.items)if("file"===e.kind&&e.type.startsWith("image/")){n=!0;break}if(n)return e.preventDefault(),e.stopPropagation(),void cr(!1,!1)}}if(e.preventDefault(),e.stopPropagation(),t&&"function"==typeof t.getData){const e=t.getData("text/html"),n=t.getData("text/plain");if(e&&e.trim()){ar(e);const t=e.replace(/<img[^>]*>/gi,"").replace(/background-image\s*:\s*url\([^)]+\)/gi,"").replace(/<svg[^>]*>.*?<\/svg>/gis,"").replace(/<picture[^>]*>.*?<\/picture>/gis,"").replace(/data:image\/[^;]+;base64,[^\s'"]+/gi,"").replace(/<video[^>]*>.*?<\/video>/gis,"").replace(/<iframe[^>]*>.*?<\/iframe>/gis,"").replace(/<embed[^>]*>/gi,"").replace(/<object[^>]*>.*?<\/object>/gis,""),r=Sn(t);if(ur(r)&&("function"!=typeof An||!An(r,n,t))&&function(e){if(!window.quill1||!ur(e))return!1;const t=0===window.quill1.getText().trim().length,n=window.quill1.getSelection(),r=n?n.index:window.quill1.getLength(),o=n?n.length:0;o>0&&window.quill1.deleteText(r,o),t&&"<p><br></p>"===window.quill1.root.innerHTML&&window.quill1.setText("");const i=window.quill1.getLength(),a=t?0:r;window.quill1.clipboard.dangerouslyPasteHTML(a,e,"user");const l=window.quill1.getLength(),s=Math.max(0,l-i),c=t?Math.max(0,l-1):r+s;return window.quill1.setSelection(c,0),window.quill1.focus(),!0}(r))return}if(n&&function(e){if(!window.quill1||!e||!e.trim())return!1;if(0===window.quill1.getText().trim().length)"<p><br></p>"===window.quill1.root.innerHTML&&window.quill1.setText(""),window.quill1.insertText(0,e,"user"),window.quill1.setSelection(e.length,0);else{const t=window.quill1.getSelection(),n=t?t.index:window.quill1.getLength(),r=t?t.length:0;r>0&&window.quill1.deleteText(n,r),window.quill1.insertText(n,e,"user"),window.quill1.setSelection(n+e.length,0)}return window.quill1.focus(),!0}(n))return}cr(!1,!1)},!0),document.addEventListener("paste",e=>{document.activeElement===Is||Is.contains(document.activeElement)},!0),document.addEventListener("DOMContentLoaded",()=>{sr()}),document.addEventListener("DOMContentLoaded",()=>{const e=document.getElementById("autoSaveHistory");e&&e.addEventListener("change",()=>{e.checked?Zl():Yl()})}),document.addEventListener("DOMContentLoaded",function(){setTimeout(()=>{!function(){try{const e=localStorage.getItem("quillEditorAutoSave");e&&Gl&&Gl.root&&(Gl.getText().trim()||Gl.clipboard.dangerouslyPasteHTML(0,e,"api"))}catch(e){console.error("Error restoring editor content:",e)}}()},100),io(),Object.keys(pr).forEach(e=>{const t=document.getElementById(e);t&&(t.classList.add("ss-mic"),t.setAttribute("aria-busy","false"),t.setAttribute("aria-pressed","fal
3se"),t.getAttribute("aria-label")||t.setAttribute("aria-label",pe("controls.stt")),"inputText"===pr[e]?(t.addEventListener("mousedown",function(e){e.preventDefault(),fr=vr()}),t.addEventListener("click",function(t){t.preventDefault(),fr=vr(),window.quill1.focus(),null!==fr&&window.quill1.setSelection(fr,0),Tr(e)})):t.addEventListener("click",()=>Tr(e)))}),window.quill1&&window.quill1.on("selection-change",function(e){e&&(fr=e.index)}),ot({processQuillContentForCopy:lr,downloadAudioFile:()=>Pr(Or)}),cl(),fl(),Ua(),window.addEventListener("beforeunload",function(){Zl()}),function(){const e=window.quill1;e&&(fn(),e.on("text-change",fn))}(),function(e){const t=document.getElementById("formatBold"),n=document.getElementById("formatItalic"),r=document.getElementById("formatList");t&&n&&r&&(t.addEventListener("click",function(){!function(e,t){const n=e.getSelection();if(!n)return;const r=!0===e.getFormat(n).bold;e.format("bold",!r),r?t.classList.remove("active"):t.classList.add("active")}(e,t)}),n.addEventListener("click",function(){!function(e,t){const n=e.getSelection();if(!n)return;const r=!0===e.getFormat(n).italic;e.format("italic",!r),r?t.classList.remove("active"):t.classList.add("active")}(e,n)}),r.addEventListener("click",function(){!function(e,t){const n=e.getSelection();if(!n)return;const r="bullet"===e.getFormat(n).list;e.format("list",!r&&"bullet"),r?t.classList.remove("active"):t.classList.add("active")}(e,r)}),e.on("selection-change",function(){gn(e,t,n,r)}),gn(e,t,n,r))}(Gl),Ls(),or({showLoader:(e,t,n=!1)=>Ar.showTextAreaLoader(e,t,n),hideLoader:e=>Ar.hideTextAreaLoader(e),handleClear:Cs,displayResponse:ps,scrollAfterPaste:dr,manuallyCloseMicButton:kr,getLanguageName:wt,getCurrentLanguage:yt,getLanguageFullName:It,HGF_ajax_object:HGF_ajax_object}),function({displayResponse:e,onResponseGenerated:t,showLoader:n,hideLoader:r,originalContent:o,languageMap:i,getCurrentLanguage:a,HGF_ajax_object:l,dkHamdanCloseModal:s,clearHighlights:c,manuallyCloseMicButton:d}){function u(){return!Cr&&!!quill1.getText().trim().length}window._rewriteSystem={displayResponse:e,onResponseGenerated:t,showLoader:n,hideLoader:r,originalContent:o,languageMap:i,getCurrentLanguage:a,HGF_ajax_object:l,dkHamdanCloseModal:s,clearHighlights:c,manuallyCloseMicButton:d};const p=document.getElementById("convencing");p&&p.addEventListener("click",()=>{u()&&Bn("convencing")});const m=document.getElementById("simplify");m&&m.addEventListener("click",()=>{u()&&Bn("simplify")});const f=document.getElementById("elaborate");f&&f.addEventListener("click",()=>{u()&&Bn("elaborate")});const g=document.getElementById("concise");g&&g.addEventListener("click",()=>{u()&&Bn("concise")});const h=document.getElementById("professional");h&&h.addEventListener("click",()=>{u()&&Bn("professional")}),document.querySelectorAll(".prev-btn").forEach(e=>{e.addEventListener("click",()=>{Hn("prev")})}),document.querySelectorAll(".next-btn").forEach(e=>{e.addEventListener("click",()=>{Hn("next")})});const v=document.getElementById("submint_rewrite");v&&v.addEventListener("click",()=>{if(!u())return;const e=document.getElementById("custom_rewrite_input");(e?e.value.trim():"").length>0&&Bn("custom")});const y=document.querySelector("#rewriteBtn");y&&y.addEventListener("click",()=>{window._rewriteSystem.clearHighlights(),jn()});const w=document.querySelector(".dk-hamdan-close-button");w&&w.addEventListener("click",s)}({displayResponse:ps,onResponseGenerated:Fn,showLoader:(e,t,n=!1)=>Ar.showTextAreaLoader(e,t,n),hideLoader:e=>Ar.hideTextAreaLoader(e),originalContent:Cl,languageMap:it,getCurrentLanguage:yt,HGF_ajax_object:HGF_ajax_object,dkHamdanCloseModal:Rn,clearHighlights:vl,manuallyCloseMicButton:kr})}),document.addEventListener("DOMContentLoaded",function(){const e=document.getElementById("show-tutorial-btn"),t=document.getElementById("tutorial-popup"),n=document.querySelector(".tutorial-close-btn"),r=document.getElementById("tutorial-video");if(!(e&&t&&n&&r))return;const o=r.src;function i(){t.style.display="none",t.hidden=!0,r.src=""}e.addEventListener("click",()=>{t.hidden=!1,t.style.display="flex",t.style.justifyContent="space-evenly",r.src=o}),n.addEventListener("click",i),window.addEventListener("click",e=>{e.target===t&&i()}),document.addEventListener("keydown",e=>{"Escape"===e.key&&"block"===t.style.display&&i()})}),window.stopSpeaking=ao,window.stopAllSkrivebordTTS=function(){ao(),Io(),"function"==typeof window.cleanupSelectionTTS&&window.cleanupSelectionTTS(),document.dispatchEvent(new CustomEvent("skrivebord:tts-stop-all"))},window.manuallyCloseMicButton=kr,window.correctionSidebarLoader=Mr,window.resetNavText=Dn,window.handleClear=Cs,window.updateClearRevertButtonState=Ts,window.resetNavText=Dn,window.showNavigation=Pn,window.resetSidebarRobot=function(){Sa("idle"),Da(),Ha(),Oi="",Xi()},window.setSidebarRobotState=(e,t)=>
3{window.sidebarRobot&&window.sidebarRobot.setSidebarRobotState&&window.sidebarRobot.setSidebarRobotState(e,t)},window.stopSidebarListening=()=>{kr("sidebar-micButton")},window.dkHamdanOpenModal=jn,window.dkHamdanCloseModal=Rn,document.addEventListener("DOMContentLoaded",()=>{document.querySelector(".left-controls");const e=document.querySelector(".middle-controls"),t=document.querySelector(".right-controls"),n=new Map;let r=!1;const o=()=>{const o=window.innerWidth,i=o>=300&&o<=426;i&&!r?(e&&(e.style.display="none"),r=!0):!i&&r&&(n.forEach((e,t)=>{e.appendChild(t)}),n.clear(),e&&(e.style.display=""),t&&(t.style.display=""),r=!1)};o(),window.addEventListener("resize",o)}),window.addEventListener("load",function(){setTimeout(()=>{document.querySelectorAll(".style-option").forEach((e,t)=>{e.replaceWith(e.cloneNode(!0))}),document.querySelectorAll(".style-option").forEach((e,t)=>{e.addEventListener("click",function(){if(!Gl.getText().trim().length)return;const e=t+1;ql=Gl.root.innerHTML,fs(yn(ds()),e)})})},2e3)}),"undefined"!=typeof window&&(window.resetGrammarBotState=function(){_l=-1,Nl=!1,Pl=!1,jl=[],Rl=[],El="",Hl="",window.currentHtmlParts=[],window.editOriginalText=null,window.userOriginalInput=null,window.analysisState&&(window.analysisState.analysisData=null,window.analysisState.isAnalyzing=!1)},window.resetSidebar=function(e=!1){Ci();const t=document.querySelector(".correction-inner-main"),n=t&&"none"!==window.getComputedStyle(t).display,r=document.querySelector(".correction-content.has-explanations");if(e&&(n||null!==r))return;const o=document.querySelector(".demo-inner");o&&(o.style.display="flex");const i=document.querySelector(".improvement-section");i&&(i.style.display="grid"),t&&(t.style.display="none");const a=document.querySelector(".demo-inner .hamdan-speech-bubble");a&&(a.innerHTML=`<span>${pe("sidebar.refiningText")}</span>`,a.style.display="none");const l=document.querySelector(".demo-inner #gif");l&&(l.innerHTML="",l.className="",qe(l)),"option-stave"!==ns()&&Mr.showReadyState(),Ll.isAnalyzed=!1,Ll.analysisData=null,Ll.buttonState={isImproved:!0,isUndo:!1,improvedText:"",previousText:""},Pl=!1,Nl=!1,kl(0)}),document.addEventListener("DOMContentLoaded",function(){const e=document.getElementById("sidebar-tutorial-popup"),t=document.querySelector(".sidebar-tutorial-close-btn"),n=document.getElementById("sidebar-tutorial-video");function r(){e.style.display="none",e.hidden=!0,n.src=""}e&&t&&n&&(t.addEventListener("click",r),window.addEventListener("click",t=>{t.target===e&&r()}),document.addEventListener("keydown",t=>{"Escape"===t.key&&"flex"===e.style.display&&r()}))}),document.addEventListener("DOMContentLoaded",function(){Bs(),window.addEventListener("resize",Bs)});var Hs=window.SkrivebordApp=window.SkrivebordApp||{};Hs.DOC_TABLE="documents",Hs.SAVE_INTERVAL_MS=3e4,Hs.SCRATCH_AUTOSAVE_MS=5e3,Hs.SCRATCH_BACKUP_KEY="skrivsikkert_scratch_backup",Hs.DOC_SESSION_KEY="skrivsikkert_current_doc",Hs.MIN_WORDS_TO_SAVE=10,Hs.MIN_WORDS_BEFOREUNLOAD=10,Hs.MAX_BACKUP_AGE_MS=6048e5;Hs.currentDocId=null,Hs.lastSavedHtml="",Hs.isSaving=!1,Hs.isScratchMode=!1,Hs.autoSaveInitialized=!1,Hs.autoSaveIntervalId=null,Hs.scratchIntervalId=null,Hs.pendingSaveBlocked=!1,Hs.waitForQuill=function(){return new Promise(function(e){if(window.quill1)return void e(window.quill1);const t=Date.now(),n=setInterval(function(){window.quill1?(clearInterval(n),e(window.quill1)):Date.now()-t>15e3&&(clearInterval(n),e(null))},500)})},Hs.stripGrammarMarkup=function(e){if(!e)return"";if(!(-1!==e.indexOf("ham-dan")||-1!==e.indexOf("inline-correction")))return e;var t=document.createElement("div");t.innerHTML=e;for(var n=t.querySelectorAll("ham-dan"),r=0;r<n.length;r++){for(var o=n[r].parentNode;n[r].firstChild;)o.insertBefore(n[r].firstChild,n[r]);o.removeChild(n[r])}for(var i=t.querySelectorAll("mark.inline-correction"),a=0;a<i.length;a++){for(var l=i[a].parentNode;i[a].firstChild;)l.insertBefore(i[a].firstChild,i[a]);l.removeChild(i[a])}return t.innerHTML},Hs.countWords=function(e){const t=(e||"").trim();return t?t.split(/\s+/).length:0},Hs.setScratchBackup=function(e){try{localStorage.setItem(Hs.SCRATCH_BACKUP_KEY,JSON.stringify(e))}catch(e){"QuotaExceededError"===e.name&&"function"==typeof window.showToast&&window.showToast("Lokal lagring er fuld. Gem dit dokument manuelt.","warning")}},Hs.getScratchBackup=function(){try{var e=JSON.parse(localStorage.getItem(Hs.SCRATCH_BACKUP_KEY));return e&&"object"==typeof e?"string"!=typeof e.content?null:e:null}catch(e){return null}},Hs.clearScratchBackup=function(){try{localStorage.removeItem(Hs.SCRATCH_BACKUP_KEY)}catch(e){}},Hs.setBackup=function(e){Hs.setScratchBackup(e)},Hs.getBackup=function(){return Hs.getScratchBackup()},Hs.clearBackup=function(){Hs.clearScratchBackup()},Hs.updateRecentDoc=function(e,t){try{var n="skrivsikkert_recent_docs",r=t||("function"==typeof SKT?SKT("toolbar.untitled"):"Unavngivet dokument"),o=JSON.parse(localStorage.getItem(n)||"[]");(o=o.filter(function(t){return t&&t.id!==e})).unshift({id:e,title:r,ts:Date.now()}),o.length>5&&(o=o.slice(0,5)),localStorage.setItem(n,JSON.stringify(o))}catch(e){}},Hs.getEditorDocId=function(){return Hs.currentDocId||sessionStorage.getItem(Hs.DOC_SESSION_KEY)||null},window.getEditorDocId=Hs.getEditorDocId;function Ks(e){var t=(e=e||{}).readRaw,n=e.writeRaw,r=e.removeRaw,o=e.now||function(){return Date.now()},i=String(e.tabId||"tab0"),a="number"==typeof e.maxAgeMs?e.maxAgeMs:6048e5,l=e.onStorageError||function(){},s=e.acquireLock||function(e,t){try{return Promise.resolve(t())}catch(e){return Promise.reject(e)}},c=e.setTimer||function(e,t){return setTimeout(e,t)},d={rev:0,ackedRev:0,activeSaves:0}
3,u=Object.create(null),p=Object.create(null);function m(){return d.activeSaves>0}function f(e){d={rev:d.rev,ackedRev:d.ackedRev,activeSaves:d.activeSaves+e}}function g(){var e,n;try{e=t()}catch(e){return l("read",e),{v:2,slots:{}}}if(!e)return{v:2,slots:{}};try{n=JSON.parse(e)}catch(e){return{v:2,slots:{}}}if(!n||"object"!=typeof n)return{v:2,slots:{}};if(2===n.v&&n.slots&&"object"==typeof n.slots)return n;if("string"==typeof n.content){var r={v:2,slots:{}},o=n.docId?"doc:"+n.docId:"scratch:legacy";return r.slots[o]={content:n.content,title:"string"==typeof n.title?n.title:"",wordCount:n.wordCount,rev:0,ts:"number"==typeof n.timestamp?n.timestamp:0,tabId:"legacy",docId:n.docId||null},r}return{v:2,slots:{}}}function h(e){for(var t in e){var n=e[t];n&&"string"==typeof n.content?(0===t.indexOf("scratch:")||0===t.indexOf("clear:"))&&"number"==typeof n.ts&&n.ts>0&&o()-n.ts>a&&delete e[t]:delete e[t]}}function v(e){try{return n(JSON.stringify(e)),!0}catch(e){return l("write",e),!1}}function y(e){return Promise.resolve(s("sk_doc_env",function(){var t=g();return e(t.slots),h(t.slots),{ok:v(t)}})).catch(function(e){return l("lock",e),{ok:!1}})}function w(e){var t=g();return e(t.slots),h(t.slots),{ok:v(t)}}function b(){return"scratch:"+i}function k(e){return{content:String(e.content||""),title:"string"==typeof e.title?e.title:"",wordCount:e.wordCount,rev:"number"==typeof e.rev?e.rev:d.rev,ts:o(),tabId:i,docId:e.docId||null}}function S(e){return"doc:"+e+":"+i}function x(e,t){var n="doc:"+t;return e===n||0===e.indexOf(n+":")}function T(e,t){return!(!t||"string"!=typeof t.ackedContent)&&(e.content===t.ackedContent&&(("string"!=typeof t.ackedTitle||(e.title||"")===t.ackedTitle)&&!("number"==typeof t.ackedAtMostTs&&(e.ts||0)>t.ackedAtMostTs)))}function L(e){return"clear:"+e}return{getState:function(){return d},noteEdit:function(){return(d={rev:d.rev+1,ackedRev:d.ackedRev,activeSaves:d.activeSaves}).rev},isSaving:m,needsFollowUp:function(){return d.rev>d.ackedRev},runSave:function(e,t,n){if(p[e])return p[e];var r=n&&"number"==typeof n.timeoutMs?n.timeoutMs:0;f(1);var o=(u[e]||Promise.resolve()).then(function(){p[e]===o&&delete p[e];var n=d.rev,i=!1,a={aborted:!1,_subs:[],abort:function(){a.aborted||(a.aborted=!0,a._subs.forEach(function(e){try{e()}catch(e){}}))},onAbort:function(e){if(a.aborted)try{e()}catch(e){}else a._subs.push(e)}},l=Promise.resolve().then(function(){return t(n,a)}),s=l;return r>0&&(s=new Promise(function(e){l.then(e,e),c(function(){i||(a.abort(),c(function(){i||e({ok:!1,saved:!1,reason:"transport-timeout",zombie:!0})},2e3))},r)}).then(function(e){if(e instanceof Error)throw e;return e})),Promise.resolve(s).then(function(e){return i?e:(i=!0,f(-1),e&&e.ok&&function(e){e>d.ackedRev&&(d={rev:d.rev,ackedRev:e,activeSaves:d.activeSaves})}(n),e||{ok:!1,saved:!1,reason:"no-result"})},function(e){return i=!0,f(-1),{ok:!1,saved:!1,reason:"exception",error:e}})});return p[e]=o,u[e]=o.then(function(){},function(){}),o},runExclusive:function(e,t){return Promise.resolve(s(e,t))},waitIdle:function(e,t){t=t||function(e){return new Promise(function(t){setTimeout(t,e)})};var n=o()+e;return function e(){return m()?o()>=n?Promise.resolve(!1):t(50).then(e):Promise.resolve(!0)}()},scratchSlotKey:b,docSlotKey:S,writeRecovery:function(e,t){return y(function(n){n[e]=k(t)})},writeRecoverySync:function(e,t){return w(function(n){n[e]=k(t)})},readRecovery:function(e){var t=g().slots[e];return t&&"string"==typeof t.content?t:null},clearRecovery:function(e,t){return y(function(n){var r=n[e];r&&(t&&"number"==typeof t.ifRevAtMost&&"number"==typeof r.rev&&r.rev>t.ifRevAtMost||delete n[e])})},clearRecoverySync:function(e){return w(function(t){delete t[e]})},moveRecovery:function(e,t,n){return y(function(r){delete r[e],r[t]=k(n)})},newestScratchSlot:function(){var e=g().slots,t=e[b()];if(t&&"string"==typeof t.content)return{key:b(),slot:t};var n=null;for(var r in e)0===r.indexOf("scratch:")&&e[r]&&"string"==typeof e[r].content&&(!n||(e[r].ts||0)>(e[n].ts||0))&&(n=r);return n?{key:n,slot:e[n]}:null},newestDocSlot:function(e){var t=g().slots,n=null;for(var r in t)x(r,e)&&t[r]&&"string"==typeof t[r].content&&(!n||(t[r].ts||0)>(t[n].ts||0))&&(n=r);return n?{key:n,slot:t[n]}:null},clearDocSlots:function(e,t){return y(function(n){var r=S(e);for(var o in n)if(x(o,e)){var i=n[o];if(i){if(t&&"number"==typeof t.ifRevAtMost){if(o===r){if("number"==typeof i.rev&&i.rev>t.ifRevAtMost)continue}else if(!T(i,t))continue}else if(t&&"string"==typeof t.contentEquals&&o!==r&&i.content!==t.contentEquals)continue;delete n[o]}else delete n[o]}})},setClearIntent:function(e,t){return y(function(n){var r=S(e);for(var a in n)if(x(a,e)){var l=n[a];
3l?(a===r||"string"==typeof t&&l.content===t)&&delete n[a]:delete n[a]}n[L(e)]={content:"",clearedContent:"string"==typeof t?t:null,rev:0,ts:o(),tabId:i,docId:e}})},getClearIntent:function(e){var t=g().slots[L(e)];return t&&"object"==typeof t?t:null},resolveClearIntent:function(e){return y(function(t){var n=t[L(e)];if(delete t[L(e)],n&&"string"==typeof n.clearedContent)for(var r in t)x(r,e)&&t[r]&&t[r].content===n.clearedContent&&delete t[r]})},clearScratchSlots:function(){return y(function(e){delete e[b()],delete e["scratch:legacy"]})},clearScratchSlotsSync:function(){return w(function(e){delete e[b()],delete e["scratch:legacy"]})},clearAllRecovery:function(){try{r()}catch(e){l("remove",e)}}}}function Ds(e){var t=(e=e||{}).getClient,n=e.table||"documents",r=e.pdfBucket||"user-pdfs";function o(e){if(!e)return{kind:"server",code:null,message:"unknown error",status:null};if("AbortError"===e.name)return{kind:"network",code:"aborted",message:String(e.message||"aborted"),status:null};if("string"==typeof e.code&&e.code)return"PGRST116"===e.code?{kind:"no-rows",code:e.code,message:e.message||"",status:e.status||null}:"PGRST301"===e.code||"401"===e.code||"42501"===e.code?{kind:"auth",code:e.code,message:e.message||"",status:e.status||null}:{kind:"server",code:e.code,message:e.message||"",status:e.status||null};if(void 0!==e.statusCode){var t=parseInt(e.statusCode,10);return{kind:401===t||403===t?"auth":404===t?"no-rows":"server",code:String(e.statusCode),message:e.message||"",status:t}}return e.message&&/fetch|network|load failed/i.test(String(e.message))?{kind:"network",code:null,message:String(e.message),status:null}:{kind:"server",code:null,message:String(e.message||e),status:null}}function i(e){return{ok:!1,error:o(e)}}async function a(e){var n=null;try{n=t()}catch(e){return i(e)}if(!n)return{ok:!1,error:{kind:"network",code:"no-client",message:"supabase client not ready",status:null}};try{var r=await e(n);if(r&&r.error)return i(r.error);var o=r?r.data:null,a={ok:!0,data:o};return Array.isArray(o)&&(a.rowCount=o.length),a}catch(e){return i(e)}}return{mapError:o,list:function(e,t){return a(function(r){return r.from(n).select(t).eq("user_id",e).is("deleted_at",null).eq("is_draft",!1).order("updated_at",{ascending:!1})})},getSingle:function(e,t,r){return a(function(o){return o.from(n).select(r||"*").eq("id",e).eq("user_id",t).is("deleted_at",null).single()})},getColumn:function(e,t,r){return a(function(o){return o.from(n).select(r).eq("id",e).eq("user_id",t).single()})},update:function(e,t,r,o){return o=o||{},a(function(i){var a=i.from(n).update(r).eq("id",e).eq("user_id",t);return o.signal&&"function"==typeof a.abortSignal&&(a=a.abortSignal(o.signal)),o.select&&(a=a.select(o.select)),a})},insert:function(e,t){return t=t||{},a(function(r){var o=r.from(n).insert(e);return t.signal&&"function"==typeof o.abortSignal&&(o=o.abortSignal(t.signal)),t.select&&(o=o.select(t.select)),t.single&&(o=o.single()),o})},storageRemovePdf:function(e){return a(function(t){return t.storage.from(r).remove([e])})},storageDownloadPdf:function(e){return a(function(t){return t.storage.from(r).download(e)})}}}"undefined"!=typeof window&&"undefined"!=typeof document&&function(){var e,t,n=window.SkrivebordApp=window.SkrivebordApp||{},r=n.SCRATCH_BACKUP_KEY||"skrivsikkert_scratch_backup";try{(e=sessionStorage.getItem("sk_doc_tab_id"))||(e="t"+Date.now().toString(36)+Math.random().toString(36).slice(2,8),sessionStorage.setItem("sk_doc_tab_id",e))}catch(t){e="tab0"}try{navigator&&navigator.locks&&"function"==typeof navigator.locks.request&&(t=function(e,t){return navigator.locks.request(e,t)})}catch(e){}n._docSession=Ks({readRaw:function(){return localStorage.getItem(r)},writeRaw:function(e){localStorage.setItem(r,e)},removeRaw:function(){localStorage.removeItem(r)},tabId:e,maxAgeMs:n.MAX_BACKUP_AGE_MS,acquireLock:t,onStorageError:function(e,t){"write"===e&&t&&"QuotaExceededError"===t.name&&"function"==typeof window.showToast&&window.showToast("Lokal lagring er fuld. Gem dit dokument manuelt.","warning")}}),n.setScratchBackup=function(e){var t=(e=e||{}).docId?"doc:"+e.docId:n._docSession.scratchSlotKey();return n._docSession.writeRecoverySync(t,e)},n.getScratchBackup=function(){var e=n._docSession.newestScratchSlot();return e?{content:e.slot.content,title:e.slot.title,wordCount:e.slot.wordCount,timestamp:e.slot.ts,_slotKey:e.key}:null},n.clearScratchBackup=function(e){return"string"==typeof e&&e?n._docSession.clearRecoverySync(e):n._docSession.clearScratchSlotsSync()}}(),"undefined"!=typeof window&&"undefined"!=typeof document&&function(){var e=window.SkrivebordApp=window.SkrivebordApp||{};e._apiClient=Ds({getClient:function(){return window._supabase},table:e.DOC_TABLE||"documents"})}();var Ps=Object.freeze({__proto__:null,createSkApiClient:Ds}),Ns=window.SkrivebordApp=window.SkrivebordApp||{};function js(e){Ns._hydratingGen="number"==typeof e?e:Ns._ctxGen}function Rs(e){"number"==typeof e&&Ns._hydratingGen!==e||(Ns._hydratingGen=null)}function Fs(){return null!=Ns._hydratingGen&&Ns._hydratingGen===Ns._ctxGen}function Os(){Ns.autoSaveIntervalId&&(clearInterval(Ns.autoSaveIntervalId),Ns.autoSaveIntervalId=null),Ns.scratchIntervalId&&(clearInterval(Ns.scratchIntervalId),Ns.scratchIntervalId=null),Ns.autoSaveInitialized=!1,Ns._kladdeTimer&&(clearTimeout(Ns._kladdeTimer),Ns._kladdeTimer=null),Ns._existingVisibilityHandler&&(window.removeEventListener("visibilitychange",Ns._existingVisibilityHandler),Ns._existingVisibilityHandler=null),Ns._existingBeforeUnloadHandler&&(window.removeEventListener("beforeunload",Ns._existingBeforeUnloadHandler),Ns._existingBeforeUnloadHandler=null),Ns._scratchBeforeUnloadHandler&&(window.removeEventListener("beforeunload",Ns._scratchBeforeUnloadHandler),Ns._scratchBeforeUnloadHandler=null),Ns._scratchVisibilityHandler&&(window.removeEventListener("visibilitychange",Ns._scratchVisibilityHandler),Ns._scratchVisibilityHandler=null),Ns._titleBlurTarget&&Ns._titleBlurHandler&&(Ns._titleBlurTarget.removeEventListener("blur",Ns._titleBlurHandler),Ns._titleBlurTarget=null,Ns._titleBlurHandler=null)}async function Us(e,t,n){n=n||{};var r=Ns._ctxGen=(Ns._ctxGen||0)+1;Os(),Ns.currentDocId=e||null,Ns.isScratchMode=!e,Ns.pendingSaveBlocked=!1;const o=await getCurrentUser();if(!o)return;if(Ns._ctxGen!==r)return;const i=document.querySelector(".skv2-doc-title")||document.getElementById("doc-title");if(e){if(Ns.isScratchMode=!1,await async function(e,t,n,r,o){const i=await Ns._apiClient.getSingle(e,r,"*"),a=i.ok?i.data:null,l=i.ok?null:i.error;if("number"==typeof o&&Ns._ctxGen!==o)return;
3if(l||!a){if(console.error(l),!(!l||"no-rows"!==l.kind)&&Ns._docSession&&Ns._ctxGen===o)try{if(!Ns._docSession.getClearIntent(e)){var s=Ns._docSession.readRecovery(Ns._docSession.scratchSlotKey()),c=Ns._docSession.newestDocSlot(e);if(c&&c.slot&&c.slot.content&&(!s||!s.content)){var d=await Ns._docSession.moveRecovery(c.key,Ns._docSession.scratchSlotKey(),{content:c.slot.content,title:c.slot.title,wordCount:c.slot.wordCount});d&&d.ok&&await Ns._docSession.clearDocSlots(e,{contentEquals:c.slot.content})}}}catch(e){console.warn("[SkrivSikkert] orphan rescue:",e&&e.message)}return void setTimeout(function(){if("number"!=typeof o||Ns._ctxGen===o)if("function"!=typeof Ns.requestNav)try{history.pushState({},"","/skrivebord/"),window.dispatchEvent(new PopStateEvent("popstate"))}catch(e){window.location.href="/skrivebord/"}else Ns.requestNav("scratch",o)},2e3)}if("pdf"===a.doc_type&&a.storage_path)return void("function"==typeof Ns.openPdfExternal&&Ns.openPdfExternal(e));var u=null;try{u=Ns._docSession?Ns._docSession.getClearIntent(a.id):null}catch(e){}const p=u?"":Ns.stripGrammarMarkup(a.content||"");js(o);try{t.setContents([]),p&&(-1!==p.indexOf("<")&&-1!==p.indexOf(">")?t.clipboard.dangerouslyPasteHTML(0,p,"api"):t.setText(p)),"function"==typeof window.resetGrammarBotState&&window.resetGrammarBotState()}finally{Rs(o)}n&&(n.value=u?"":a.title||"");Ns.currentDocId=a.id,Ns.lastSavedHtml=t.root.innerHTML,sessionStorage.setItem(Ns.DOC_SESSION_KEY,a.id);try{if(u)""!==(a.content||"")?ec(a.id,r):Ns._docSession.resolveClearIntent(a.id);else{var m=Ns._docSession?Ns._docSession.newestDocSlot(a.id):null,f=m?m.slot:null;if(f&&f.content){var g=p,h="string"==typeof f.title?f.title.trim():"",v=""!==h&&!Vs(h)&&h!==(a.title||"").trim();if(f.content!==g||v){js(o);try{t.setContents([]),-1!==f.content.indexOf("<")&&-1!==f.content.indexOf(">")?t.clipboard.dangerouslyPasteHTML(0,f.content,"api"):t.setText(f.content)}finally{Rs(o)}n&&h&&!Vs(h)&&(n.value=f.title),Ns.lastSavedHtml="";var y=Ns._docSession.noteEdit();Ns._docSession.moveRecovery(m.key,Ns._docSession.docSlotKey(a.id),{content:f.content,title:f.title,wordCount:f.wordCount,rev:y,docId:a.id}),w=f.content,b=a.title||"",k=o,function(e,t,n){var r=document.getElementById("scratch-restore-toast");r&&r.remove();var o=document.createElement("div");o.id="scratch-restore-toast",o.className="scratch-restore-toast",o.setAttribute("role","status"),o.setAttribute("aria-live","polite");var i=document.createElement("span");i.textContent="function"==typeof SKT?SKT("doc.draft_restored"):"Kladde gendannet",o.appendChild(i);var a=document.createElement("button");a.type="button",a.className="scratch-restore-undo",a.textContent="function"==typeof SKT?SKT("doc.undo"):"Fortryd",o.appendChild(a),document.body.appendChild(o),o.offsetHeight,o.classList.add("visible");var l=!1;function s(){l||(l=!0,o.classList.remove("visible"),setTimeout(function(){o.remove()},250))}a.addEventListener("click",function(){if("function"==typeof n)try{n()}catch(e){console.warn("[SkrivSikkert] restore undo:",e&&e.message)}else e.setContents([]),t&&(t.value=""),Ns.clearScratchBackup();s()}),setTimeout(s,6e3)}(t,n,function(){if(Ns._ctxGen===k){js(k);try{t.setContents([]),g&&(-1!==g.indexOf("<")&&-1!==g.indexOf(">")?t.clipboard.dangerouslyPasteHTML(0,g,"api"):t.setText(g))}finally{Rs(k)}n&&(n.value=b),Ns.lastSavedHtml=t.root.innerHTML,Ns._docSession&&Ns._docSession.clearDocSlots(a.id,{contentEquals:w})}})}else Ns._docSession.clearDocSlots(a.id,{contentEquals:f.content})}}}catch(e){console.warn("[SkrivSikkert] doc recovery restore:",e&&e.message)}var w,b,k;t.history&&"function"==typeof t.history.clear&&t.history.clear()}(e,t,i,o.id,r),Ns._ctxGen!==r)return;$s(t,i,o.id)}else{Ns.isScratchMode=!0,localStorage.removeItem("quillEditorAutoSave"),sessionStorage.removeItem(Ns.DOC_SESSION_KEY),Ns.currentDocId=null,js(r);try{!1!==n.clearEditor&&t.setContents([]),i&&!1!==n.clearTitle&&(i.value=""),n.skipScratchRestore||function(e,t){if(!e)return;var n=Ns.getScratchBackup();if(!n||!n.content)return;if(n.timestamp&&Date.now()-n.timestamp>Ns.MAX_BACKUP_AGE_MS)return void Ns.clearScratchBackup(n._slotKey);if(void 0!==n.wordCount&&n.wordCount<1)return void Ns.clearScratchBackup(n._slotKey);var r=Ns.stripGrammarMarkup(n.content)||"";e.setContents([]),-1!==r.indexOf("<")&&-1!==r.indexOf(">
3")?e.clipboard.dangerouslyPasteHTML(0,r,"api"):e.setText(r);t&&n.title&&(t.value=n.title);"function"==typeof window.resetGrammarBotState&&window.resetGrammarBotState();e.history&&"function"==typeof e.history.clear&&e.history.clear();try{Ns._docSession&&n._slotKey&&n._slotKey!==Ns._docSession.scratchSlotKey()&&Ns._docSession.moveRecovery(n._slotKey,Ns._docSession.scratchSlotKey(),{content:n.content,title:n.title||"",wordCount:n.wordCount})}catch(e){}}(t,i)}finally{Rs(r)}Ns.lastSavedHtml=t.root.innerHTML,Ns.isScratchMode&&(function(e,t){Ns.scratchIntervalId=setInterval(function(){if(!Ns.isScratchMode)return;const n=e.root.innerHTML,r=Ns.stripGrammarMarkup(n),o=t?(t.value||"").trim():"",i=Ns.countWords(e.getText());i>0&&Ns.setScratchBackup({content:r,title:o,wordCount:i,timestamp:Date.now()}),i>0&&r!==Ns.lastSavedHtml&&(Ns.lastSavedHtml=r)},Ns.SCRATCH_AUTOSAVE_MS)}(t,i,o.id),function(e,t){const n=function(){if(!Ns.isScratchMode)return;const n=Ns.countWords(e.getText());if(n>=1){const r="function"==typeof SKT?SKT("toolbar.untitled"):"Unavngivet dokument",o=t&&(t.value||"").trim()||r;Ns.setScratchBackup({content:Ns.stripGrammarMarkup(e.root.innerHTML),title:o,wordCount:n,timestamp:Date.now()})}};Ns._scratchBeforeUnloadHandler=n,window.addEventListener("beforeunload",Ns._scratchBeforeUnloadHandler),Ns._scratchVisibilityHandler=function(){"hidden"===document.visibilityState&&n()},window.addEventListener("visibilitychange",Ns._scratchVisibilityHandler)}(t,i,o.id))}!function(e,t,n){if(Ns._explicitSaveHandler=function(){return async function(e,t,n){var r=document.getElementById("doc-save-btn");if(r&&"1"===r.getAttribute("data-saving"))return;var o,i=Ns.countWords(e.getText());if(!Ns.currentDocId&&i<1)return;r&&(r.setAttribute("data-saving","1"),r.setAttribute("aria-busy","true"),r.disabled=!0,r.classList.add("is-saving"));try{o=await async function(e,t,n){const r=Ns.countWords(e.getText());if(!Ns.currentDocId&&r<1)return{status:"empty"};return Ns.currentDocId?await Xs(e,t,n,!0):await async function(e,t,n){if(Ns.currentDocId)return await Xs(e,t,n,!0);const r=Ns._ctxGen,o=await Ns._docSession.runSave("create",async function(o,i){if(Ns._ctxGen!==r)return{ok:!1,saved:!1,reason:"context-switched"};if(Ns.currentDocId)return await Xs(e,t,n,!0);const a=e.root.innerHTML,l=Ns.stripGrammarMarkup(a),s=Ns.countWords(e.getText());if(s<1)return{ok:!1,saved:!1,reason:"empty"};if(l.length>Zs)return{ok:!1,saved:!1,reason:"too-large"};const c="function"==typeof SKT?SKT("toolbar.untitled"):"Unavngivet dokument";var d=t?(t.value||"").trim():"";if(Vs(d)){var u=zs(l);u?(d=u,t&&(t.value=u),Ns._autoTitle=u):d=c}return await Ns._docSession.runExclusive("sk_doc_create",async function(){const a="skrivsikkert_creating_doc";var c=null;try{c=localStorage.getItem(a)}catch(e){}if(c&&Date.now()-parseInt(c,10)<3e4)return{ok:!1,saved:!1,reason:"locked-other-tab"};try{localStorage.setItem(a,Date.now().toString())}catch(e){}try{const a=await Ns._apiClient.insert({user_id:n,title:d,content:l,word_count:s,is_draft:!1},{signal:Ws(i),select:"*",single:!0});if(!a.ok)return console.error(a.error),{ok:!1,saved:!1,error:a.error};const c=a.data.id;"function"==typeof Ns.updateRecentDoc&&Ns.updateRecentDoc(c,d);try{window.dispatchEvent(new CustomEvent("ss-doc-saved",{detail:{docId:c}}))}catch(e){}if(Ns._ctxGen===r){Ns.currentDocId=a.data.id,Ns.isScratchMode=!1,Ns.lastSavedHtml=l;try{sessionStorage.setItem(Ns.DOC_SESSION_KEY,c)}catch(e){}try{window.history.replaceState({doc:c},"","/skrivebord/?doc="+encodeURIComponent(c))}catch(e){}var u=Ns._docSession.scratchSlotKey(),p=Ns._docSession.readRecovery(u);p&&"number"==typeof p.rev&&p.rev>o?await Ns._docSession.moveRecovery(u,Ns._docSession.docSlotKey(c),{content:p.content,title:p.title,wordCount:p.wordCount,rev:p.rev,docId:c}):Ns.clearScratchBackup(),Ns.scratchIntervalId&&(clearInterval(Ns.scratchIntervalId),Ns.scratchIntervalId=null),$s(e,t,n)}else try{Ce("Kladde gemt som dokument",{type:"info",duration:2500})}catch(e){}return{ok:!0,saved:!0,docId:c}}finally{try{localStorage.removeItem(a)}catch(e){}}})},{timeoutMs:Js});o&&o.ok&&o.saved&&Ns._ctxGen===r&&Ns.currentDocId&&Ns._docSession.needsFollowUp()&&setTimeout(function(){Xs(e,t,n,!1)},0);return o}(e,t,n)}
3(e,t,n)}catch(e){console.error(e),o={ok:!1,error:e}}r&&(r.removeAttribute("data-saving"),r.removeAttribute("aria-busy"),r.disabled=!1,r.classList.remove("is-saving"));if(o&&!1===o.ok&&"too-large"===o.reason){Ce("function"==typeof SKT?SKT("doc.too_large"):"Dokumentet er for stort til at gemme (maks 2 mio. tegn)",{type:"error",duration:4e3})}else if(o&&!1===o.ok){Ce("function"==typeof SKT?SKT("doc.save_error"):"Kunne ikke gemme. Prøv igen.",{type:"error",duration:3e3})}else if(o&&!0===o.ok){Ce("function"==typeof SKT?SKT("toast.saved"):"Gemt",{type:"success",duration:1800})}}(e,t,n)},document.getElementById("doc-save-btn"))return;const r=document.querySelector(".left-controls");if(!r)return;function o(){window.__skDocSaveShortcutBound||(window.__skDocSaveShortcutBound=!0,document.addEventListener("keydown",function(e){(e.ctrlKey||e.metaKey)&&"s"===e.key&&(e.preventDefault(),"function"==typeof Ns._explicitSaveHandler&&Ns._explicitSaveHandler())}))}if(Boolean(r.closest(".bb-skrivebord"))){o();var i=document.querySelector(".skv2-action-controls");if(i&&!document.getElementById("doc-save-btn")){var a="http://www.w3.org/2000/svg",l=document.createElement("button");l.id="doc-save-btn",l.className="control-btn doc-save-btn",l.type="button",l.title="function"==typeof SKT?SKT("toolbar.save"):"Gem dokument (Ctrl+S)",l.setAttribute("aria-label","function"==typeof SKT?SKT("toolbar.save_aria"):"Gem dokument");var s=document.createElementNS(a,"svg");s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke","currentColor"),s.setAttribute("stroke-width","1.5"),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("width","16"),s.setAttribute("height","16");var c=document.createElementNS(a,"path");c.setAttribute("d","M19 21H5a2 2 0 01-2-2V5a2 2 0 012-2h11l5 5v11a2 2 0 01-2 2z");var d=document.createElementNS(a,"polyline");d.setAttribute("points","17 21 17 13 7 13 7 21");var u=document.createElementNS(a,"polyline");u.setAttribute("points","7 3 7 8 15 8"),s.appendChild(c),s.appendChild(d),s.appendChild(u),l.appendChild(s);var p=document.createElement("span");p.className="controls-sep",i.insertBefore(p,i.firstChild),i.insertBefore(l,i.firstChild),l.addEventListener("click",function(){"function"==typeof Ns._explicitSaveHandler&&Ns._explicitSaveHandler()})}return}
3const m=document.createElement("button");m.id="doc-save-btn",m.className="control-btn doc-save-btn",m.title="function"==typeof SKT?SKT("toolbar.save"):"Gem dokument (Ctrl+S)",m.setAttribute("aria-label","function"==typeof SKT?SKT("toolbar.save_aria"):"Gem dokument");const f="http://www.w3.org/2000/svg",g=document.createElementNS(f,"svg");g.setAttribute("viewBox","0 0 24 24"),g.setAttribute("fill","none"),g.setAttribute("stroke","currentColor"),g.setAttribute("stroke-width","1.2"),g.setAttribute("stroke-linecap","round"),g.setAttribute("stroke-linejoin","round"),g.setAttribute("width","22"),g.setAttribute("height","22");const h=document.createElementNS(f,"path");h.setAttribute("d","M19 21H5a2 2 0 01-2-2V5a2 2 0 012-2h11l5 5v11a2 2 0 01-2 2z");const v=document.createElementNS(f,"polyline");v.setAttribute("points","17 21 17 13 7 13 7 21");const y=document.createElementNS(f,"polyline");y.setAttribute("points","7 3 7 8 15 8"),g.appendChild(h),g.appendChild(v),g.appendChild(y),m.appendChild(g),r.insertBefore(m,r.firstChild),m.addEventListener("click",function(){"function"==typeof Ns._explicitSaveHandler&&Ns._explicitSaveHandler()}),o()}(t,i,o.id),!Ns._revKladdeWired&&t&&"function"==typeof t.on&&(Ns._revKladdeWired=!0,t.on("text-change",function(){if(!Fs()){Ns._docSession&&Ns._docSession.noteEdit();var e=Ns._ctxGen,n=Ns.currentDocId,r=Ns.isScratchMode;Ns._kladdeTimer&&clearTimeout(Ns._kladdeTimer),Ns._kladdeTimer=setTimeout(function(){if(Ns._ctxGen===e&&Ns.currentDocId===n&&Ns.isScratchMode===r&&!Fs())try{var o=Ns.countWords(t.getText()),a=i?(i.value||"").trim():"";Ns.isScratchMode?o>=1&&Ns.setScratchBackup({content:Ns.stripGrammarMarkup(t.root.innerHTML),title:a,wordCount:o,timestamp:Date.now()}):Ns.currentDocId&&Ns._docSession&&Ns._docSession.writeRecovery(Ns._docSession.docSlotKey(Ns.currentDocId),{content:Ns.stripGrammarMarkup(t.root.innerHTML),title:a,wordCount:o,docId:Ns.currentDocId})}catch(e){}},700)}})),Ns.flushCurrentDoc=async function(){try{if(Ns.currentDocId)return Ns.stripGrammarMarkup(t.root.innerHTML)===Ns.lastSavedHtml?{ok:!0,saved:!1,reason:"unchanged"}:await Promise.race([Xs(t,i,o.id,!0),new Promise(function(e){setTimeout(function(){e(null)},4e3)})])||{ok:!1,saved:!1,reason:"timeout"};if(Ns.isScratchMode&&Ns.countWords(t.getText())>=1){var e=Ns.countWords(t.getText()),n="function"==typeof SKT?SKT("toolbar.untitled"):"Unavngivet dokument";return Ns.setScratchBackup({content:Ns.stripGrammarMarkup(t.root.innerHTML),title:i&&(i.value||"").trim()||n,wordCount:e,timestamp:Date.now()}),{ok:!0,saved:!1,reason:"scratch-local"}}return{ok:!0,saved:!1,reason:"empty"}}catch(e){return console.warn("[SkrivSikkert] flushCurrentDoc:",e&&e.message),{ok:!1,saved:!1,reason:"exception"}}},Ns.verifyCurrentDocRecovered=function(){try{if(!Ns._docSession)return!1;var e=Ns.stripGrammarMarkup(t.root.innerHTML),n=Ns.countWords(t.getText()),r=i?(i.value||"").trim():"";if(Ns.currentDocId){var o=Ns._docSession.docSlotKey(Ns.currentDocId),a=Ns._docSession.readRecovery(o);if(a&&a.content===e)return!0;var l=Ns._docSession.writeRecoverySync(o,{content:e,title:r,wordCount:n,docId:Ns.currentDocId});return!(!l||!l.ok)}if(n<1)return!0;var s=Ns._docSession.readRecovery(Ns._docSession.scratchSlotKey());if(s&&s.content===e)return!0;var c=Ns.setScratchBackup({content:e,title:r,wordCount:n,timestamp:Date.now()});return!(!c||!c.ok)}catch(e){return!1}},i&&(Ns._titleBlurTarget=i,Ns._titleBlurHandler=function(){if(Ns.currentDocId&&i.value.trim()){var e=Ns.currentDocId,t=i.value.trim();Ns._apiClient.update(e,o.id,{title:t}).then(function(n){if(n.ok){"function"==typeof Ns.updateRecentDoc&&Ns.updateRecentDoc(e,t);try{window.dispatchEvent(new CustomEvent("ss-doc-saved",{detail:{docId:e}}))}catch(e){}}else console.error(n.error)})}},i.addEventListener("blur",Ns._titleBlurHandler))}function $s(e,t,n){if(Ns.autoSaveInitialized)return;Ns.autoSaveInitialized=!0,null==Ns.lastSavedHtml&&(Ns.lastSavedHtml=e.root.innerHTML),Ns.autoSaveIntervalId=setInterval(function(){Xs(e,t,n,!1)},Ns.SAVE_INTERVAL_MS);const r=function(){if(Ns.currentDocId&&e.root.innerHTML!==Ns.lastSavedHtml){try{Ns._docSession&&Ns._docSession.writeRecoverySync(Ns._docSession.docSlotKey(Ns.currentDocId),{content:Ns.stripGrammarMarkup(e.root.innerHTML),title:t?(t.value||"").trim():"",wordCount:Ns.countWords(e.getText()),docId:Ns.currentDocId})}catch(e){}Xs(e,t,n,!0)}};Ns._existingVisibilityHandler=function(){"hidden"===document.visibilityState&&r()},window.addEventListener("visibilitychange",Ns._existingVisibilityHandler),Ns._existingBeforeUnloadHandler=function(){r()},window.addEventListener("beforeunload",Ns._existingBeforeUnloadHandler)}function zs(e){try{var t=document.createElement("div");t.innerHTML=e||"";var n=t.querySelectorAll("p, h1, h2, h3, h4, li, div"),r=[];if(Array.prototype.forEach.call(n.length?n:[t],function(e){var t=(e.textContent||"").replace(/\s+/g," ").trim();t&&r.push(t)}),!r.length){var o=(t.textContent||"").replace(/\s+/g," ").trim();o&&(r=[o])}if(!r.length)return"";for(var i=/^(emne|vedr|vedrørende|ang|angÃ¥ende|re|subject|sag)\s*[:.]\s*(.+)$/i,a=/^(hej|hejsa|halløj|kære|goddag|godmorgen|godaften|til|att\.?|dear|hi|hello|hey)\b/i,l=/^(med venlig hilsen|venlig hilsen|mvh|kh|de bedste hilsner|hilsen|pÃ¥ forhÃ¥nd tak|tak pÃ¥ forhÃ¥nd|best regards|kind regards|regards)\b/i,s=/^\s*\d{1,2}[.\/-]\s*\w+.{0,8}\d{0,4}\s*$/,c=0;c<r.length&&c<6;c++){var d=r[c].match(i);if(d&&d[2]&&d[2].replace(/[^\wæøåÃÃÃ
]/g,"").length>=3)return Gs(d[2])}for(var u=0;u<r.length;u++){var p=r[u];if(!s.test(p)&&!l.test(p)){var m=p.replace(/^(hej|hejsa|halløj|kære|goddag|godmorgen|godaften|til|att\.?|dear|hi|hello|hey)\b[^,.!?]{0,25}[,.!]+\s*/i,"").trim()||p;if(!(a.test(m)&&m.split(/\s+/).length<=4||m.replace(/[^\wæøåÃÃÃ
]/g,"").length<5||m.split(/\s+/).length<2))return Gs(m)}}return Gs(r[0])}catch(e){return""}}function Gs(e){return(e=(e||"").replace(/\s+/g," ").trim().replace(/[\s.,;:!]+$/,""))&&(e=e.charAt(0).toUpperCase()+e.slice(1)),e.length>60?e.substring(0,60).replace(/\s+\S*$/,"")+"â¦":e}function Vs(e){var t="function"==typeof SKT?SKT("toolbar.untitled"):"Unavngivet dokument";return!e||e===t||"Kladde"===e||"Unavngivet dokument"===e}function Ws(e){if(e&&"function"==typeof AbortController){var t=new AbortController;return e.onAbort(function(){try{t.abort()}catch(e){}}),t.signal}}var Js=8e3,Zs=2e6,Ys=0;function Qs(e){var t=Date.now();if(!(t-Ys<12e4)){Ys=t;var n="too-large"===e?"function"==typeof SKT?SKT("doc.too_large"):"Dokumentet er for stort til at gemme (maks 2 mio. tegn
3)":"function"==typeof SKT?SKT("doc.save_error"):"Fejl â prøv igen";try{Ce(n,{type:"error",duration:4e3})}catch(e){}}}async function Xs(e,t,n,r){const o=Ns.currentDocId;if(!o)return{ok:!1,saved:!1,reason:"no-doc"};const i=Ns._ctxGen,a=await Ns._docSession.runSave("doc:"+o,async function(a,l){if(Ns.currentDocId!==o||Ns._ctxGen!==i)return{ok:!1,saved:!1,reason:"doc-switched"};const s=e.root.innerHTML,c=Ns.stripGrammarMarkup(s),d=Ns.countWords(e.getText());if(!r&&c===Ns.lastSavedHtml)return{ok:!0,saved:!1,reason:"unchanged"};const u="function"==typeof SKT?SKT("toolbar.untitled"):"Unavngivet dokument";var p=t?(t.value||"").trim():"";if(Vs(p)){var m=zs(c);m?(p=m,t&&(t.value=m),Ns._autoTitle=m):p=u}const f=Date.now();if(await Ns._docSession.writeRecovery(Ns._docSession.docSlotKey(o),{content:c,title:p,wordCount:d,rev:a,docId:o}),c.length>Zs)return r||Qs("too-large"),{ok:!1,saved:!1,reason:"too-large"};const g=await Ns._apiClient.update(o,n,{content:c,word_count:d,title:p},{signal:Ws(l),select:"id"});if(!g.ok)return console.error(g.error),r||Qs("save-error"),{ok:!1,saved:!1,error:g.error};if(!g.rowCount)return r||Qs("save-error"),{ok:!1,saved:!1,reason:"not-found"};if(Ns.currentDocId!==o||Ns._ctxGen!==i||l.aborted||(Ns.lastSavedHtml=c),await Ns._docSession.clearDocSlots(o,{ifRevAtMost:a,ackedContent:c,ackedTitle:p,ackedAtMostTs:f}),"function"==typeof Ns.updateRecentDoc&&Ns.updateRecentDoc(o,p),r)try{window.dispatchEvent(new CustomEvent("ss-doc-saved",{detail:{docId:o}}))}catch(e){}return{ok:!0,saved:!0,rev:a}},{timeoutMs:Js});return a&&a.ok&&a.saved&&Ns.currentDocId===o&&Ns._ctxGen===i&&Ns._docSession.needsFollowUp()&&setTimeout(function(){Xs(e,t,n,!1)},0),a}async function ec(e,t){var n=document.querySelector(".skv2-doc-title")||document.getElementById("doc-title"),r=n&&n.value?n.value.trim():"",o=await Ns._docSession.runSave("doc:"+e,async function(n,o){var i=await Ns._apiClient.update(e,t,{content:"",word_count:0},{signal:Ws(o),select:"id"});return i.ok?i.rowCount?(Ns._docSession&&await Ns._docSession.resolveClearIntent(e),"function"==typeof Ns.updateRecentDoc&&Ns.updateRecentDoc(e,r||void 0),{ok:!0,saved:!0}):(Ns._docSession&&await Ns._docSession.resolveClearIntent(e),{ok:!1,saved:!1,reason:"not-found"}):(console.error("Clear persist failed:",i.error),{ok:!1,saved:!1,error:i.error})},{timeoutMs:Js});return o&&o.ok&&Ns.currentDocId===e&&Ns._docSession.needsFollowUp()&&"function"==typeof Ns.flushCurrentDoc&&setTimeout(function(){Ns.flushCurrentDoc()},0),o}Ns.persistClearedDocument=async function(e){if(e){var t=await getCurrentUser();if(t){if(Ns._docSession){var n=Ns._docSession.newestDocSlot(e),r=n&&n.slot?n.slot.content:null,o=await Ns._docSession.setClearIntent(e,r);if(!o||!o.ok){try{Ce("Kunne ikke rydde sikkert â prøv igen",{type:"error",duration:3e3})}catch(e){}return{ok:!1,saved:!1,reason:"intent-write-failed"}}}return ec(e,t.id)}}},Ns.resetToScratch=async function(e){Ns._ctxGen=(Ns._ctxGen||0)+1,Os(),Ns.currentDocId=null,Ns.isScratchMode=!0,Ns.pendingSaveBlocked=!1,Ns.lastSavedHtml="";try{localStorage.removeItem("quillEditorAutoSave")}catch(e){}try{sessionStorage.removeItem(Ns.DOC_SESSION_KEY)}catch(e){}"function"==typeof Ns.clearScratchBackup&&Ns.clearScratchBackup(),window._wf&&"function"==typeof window._wf.resetChatForDocumentChange&&window._wf.resetChatForDocumentChange();var t=document.querySelector(".skv2-doc-title")||document.getElementById("doc-title");if(e){js();try{e.setContents([])}finally{Rs()}}t&&(t.value=""),e&&await Us(null,e,{skipScratchRestore:!0,clearEditor:!1,clearTitle:!1})},window.addEventListener("ss:lang-changed",function(){if("function"==typeof SKT){var e=document.getElementById("doc-save-btn");e&&(e.title=SKT("toolbar.save"),e.setAttribute("aria-label",SKT("toolbar.save_aria")))}}),Ns.initDocumentPersistence=Us;var tc=window.SkrivebordApp=window.SkrivebordApp||{},nc=[{key:"mads",gender:"male",label:"Mads"},{key:"lars",gender:"male",label:"Lars"},{key:"anders",gender:"male",label:"Anders"},{key:"sofie",gender:"female",label:"Sofia"},{key:"freja",gender:"female",label:"Freja"},{key:"ida",gender:"female",label:"Ida"}];function rc(){var e="";try{e=localStorage.getItem("ss_tts_voice_variant")||""}catch(e){}for(var t=0;t<nc.length;t++)if(nc[t].key===e)return e;return"male"===function(){try{return"male"===(localStorage.getItem("ss_tts_voice")||"female")?"male":"female"}catch(e){return"female"}}()?"mads":"sofie"}function oc(){return"function"==typeof SKT?SKT("toolbar.draft_placeholder"):"Kladde"}function ic(){var e=document.querySelector(".skv2-doc-title");e&&(e.setAttribute("placeholder",oc()),e.setAttribute("autocomplete","off"))}function ac(e){for(var t=String(e||""),n=2166136261,r=0;r<t.length;r++)n^=t.charCodeAt(r),n=Math.imul(n,16777619);return(n>>>0).toString(36)}
3function lc(e,t){return!e||!e.docHash||String(e.docHash)!==String(t||"")}function sc(e,t){var n=String(e||"").trim(),r=String(t||"").toLowerCase();if(!n)return"unknown";var o=/omskriv|forkort|udvid|\bret\b|ændr|tilføj|fjern|flyt|erstat|oversæt|omformul|formul[eé]r|skriv om|gør .* kortere|gør .* længere|gør .* (formel|uformel|kortfattet|professionel)|forbedr|pol[eé]r|simplific|rewrite|shorten|expand|fix |chang|add |remov|replac|translat|rephras|make .* shorter|make .* longer|improv|polish|simplif|more (formal|casual|concise|professional|playful)|lav .{0,40} om til\b|lav (min |din |den |det |hele )?tekst(en)? om\b|om til (engelsk|dansk|tysk|fransk|spansk|svensk|norsk|italiensk|nederlandsk|polsk)\b|skriv (den|det|teksten?) p[åa] (engelsk|dansk|tysk|fransk|spansk|svensk|norsk|italiensk)\b|\b(mere|mindre) (formel|uformel|venlig|kort|kortfattet|professionel|afslappet|direkte|enkel|personlig|varm|høflig|levende)\b|\b(kortere|længere|enklere|varmere|venligere|strammere|blødere|skarpere)\b|\bbedre\b|\bpænere\b|\bflottere\b/i.test(r),i=/hvad (betyder|er)|forklar|hvorfor|hvordan|hvornår|fortæl|defin[eé]r|what (does|is|are)|explain|why |how (does|do|is)|when (does|do|is)|tell me|defin[ei]/i.test(r),a=/\b(opsumm(er|ér)\w*|resum[eé]\w*|sammendrag|sammenfat\w*|kort fortalt|tl;?dr|summar(y|ies|ise|ize|izing|ising)|sum (it )?up|in summary)(?!\w)/i.test(r),l=/skriv (en|et|den|det)|lav (en|et)|udkast|mail|e-mail|brev|ansøgning|cv|opslag|tekst til (?!engelsk\b|dansk\b|tysk\b|fransk\b|spansk\b|svensk\b|norsk\b|italiensk\b|ukrainsk\b|nederlandsk\b|polsk\b|portugisisk\b|english\b|danish\b|german\b)|write (a|an|the|me)|draft|compose|create (a|an)/i.test(r)&&!o,s=/p[åa] (engelsk|dansk|tysk|fransk|spansk|svensk|norsk|italiensk)\b|\b(?:om\s+)?til (engelsk|dansk|tysk|fransk|spansk|svensk|norsk|italiensk|ukrainsk|nederlandsk|polsk|portugisisk)\b|\b(g[øo]r|lav) (hele )?(min |din |den )?tekst(en)? (engelsk|dansk|tysk|fransk|spansk|svensk|norsk|italiensk)\b|(engelsk|english) version|(in|into|to) (english|danish|german|french|spanish|swedish|norwegian)\b/i.test(r)&&!l&&!i;if(i)return"explanation";if(a)return"summary";var c=/\?\s*$/.test(n)&&n.replace(/\s+/g," ").trim().length<160&&n.split("\n").filter(function(e){return e.trim()}).length<=1;if((o||s)&&!c)return"rewrite";if(/\?\s*$/.test(n)&&n.length<160)return"question";if(n.length<40)return"explanation";if(function(e){var t=/^(got it|i see|understood|okay|ok so|alright|sure|i understand|thanks for|thank you for|good question|great question|interesting|hmm|let me clarify|to clarify|just to confirm|so you('d| would) like|it sounds like|it seems like|based on what you)/i,n=/^(forstået|ok[ay]?[\s,]|jeg forstår|godt|fint|tak for|det lyder som|det virker som|for at|bare for at|så du (vil|gerne|ønsker)|lad mig lige|klart|selvf[øo]lgelig|naturligvis|det kan jeg)/i,r=e.split("\n")[0].trim();if(!t.test(r)&&!n.test(r))return!1;var o=/\?\s*$/.test(e)||/\?\s*\([^()\n]{0,80}\)\s*$/.test(e),i=/what (would|do|should|shall) you|how (would|do|should|shall) (you|i)|would you like|do you want|could you (clarify|tell|specify|explain|let me know)|can you (clarify|tell|specify|explain)|which (one|version|option|approach|part)|is (that|this|it) (correct|right|what)|shall i|want me to|lad mig vide|hvad (vil|ønsker|foretrækker) du|skal jeg|vil du (have|gerne)|kunne du|inds[æa]+t hvad|hvad og hvor|hvor henne|hvilken (del|tekst|version|s[æa]+tning|placering)/i;return o||i.test(e)}(n))return"clarification";var d=gc(n.split("\n")[0].trim())&&/(version|rewrite|rewritten|revised|rephrased|concise|shorter|longer|polished|updated|formal|casual|tone)/i.test(n.split("\n")[0]);return/^(det betyder|dette (ord|udtryk)|forklaringen er|grunden til|det skyldes|forskellen er|it means|this (word|term|phrase)|the (reason|explanation|difference) is|because )/im.test(n)?"explanation":/^(selvfølgelig|klart|her er|nedenfor|forslag|den? omskrevne|den? rettede|den? forkortede|den? opdaterede|den? nye version)/im.test(n)||d?"rewrite":l||/^(udkast|emne:|kære|hej [^\n,]+,|til hvem det måtte vedrøre|dear |hi [^\n,]+,|to whom it may concern|subject:)/im.test(n)?"draft":"unknown"}function cc(e){var t=e||{};if(!t.hasQuill)return!1;if(!String(t.answer||"").trim())return!1;if(t.isCorrection||t.chipAction)return!1;var n=sc(t.answer,t.query);return"rewrite"===n?!!String(t.editorText||"").trim():"draft"===n}function dc(e){var t=String(e||"");return(t=(t=(t=(t=(t=(t=(t=(t=(t=t.replace(/\r\n/g,"\n")).replace(/```[\s\S]*?```/g,function(e){return e.replace(/^```[^\n]*\n?/,"").replace(/\n?```$/,"")})).replace(/\*\*(.+?)\*\*/g,"$1")).replace(/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g,"$1")).replace(/`(.+?)`/g,"$1")).replace(/\[(\d+)\]/g,"")).replace(/^[>\t ]+/gm,"")).replace(/^\s*[-*]\s+/gm,"")).replace(/^\s*\d+[.)\]]\s+/gm,"")).trim()}tc.initToolbar=function(e){ic();const t=document.querySelector(".top-controls");if(t){const G=document.createElement("div");G.className="ed-title-wrap";
3const V=document.createElement("input");V.type="text",V.id="doc-title",V.className="doc-title-input",V.placeholder=oc(),V.maxLength=200,G.appendChild(V),t.insertBefore(G,t.firstChild)}const n=document.querySelector(".format-toolbar");if(n){var r=document.getElementById("formatList");if(r){r.style.setProperty("display","none","important"),r.setAttribute("aria-hidden","true");var o=r.previousElementSibling;o&&o.classList.contains("format-separator")&&(o.style.setProperty("display","none","important"),o.setAttribute("aria-hidden","true"))}if(!n.querySelector(".calm-heading-trigger")){var i=document.createElement("button");i.className="format-btn calm-heading-trigger",i.type="button",i.setAttribute("aria-expanded","false"),i.setAttribute("aria-controls","calm-heading-popover"),i.setAttribute("aria-label","function"==typeof SKT?SKT("toolbar.headings_lists"):"Overskrifter og lister"),i.innerHTML='<span class="calm-trigger-label">T</span><span class="calm-trigger-caret" aria-hidden="true"></span>';var a=document.createElement("div");a.className="format-separator calm-heading-separator",a.setAttribute("aria-hidden","true"),n.insertBefore(a,n.firstChild),n.insertBefore(i,n.firstChild);var l=document.createElement("div");l.className="calm-heading-popover",l.id="calm-heading-popover",l.setAttribute("role","group"),l.setAttribute("aria-label","function"==typeof SKT?SKT("toolbar.headings_lists"):"Overskrifter og lister");var s=function(e,t){return"function"==typeof SKT?SKT(e):t},c=[{key:"paragraph",sktKey:"toolbar.fmt_paragraph",label:s("toolbar.fmt_paragraph","Brødtekst"),format:"header",value:!1},{key:"header-1",sktKey:"toolbar.fmt_h1",label:s("toolbar.fmt_h1","Overskrift 1"),format:"header",value:1},{key:"header-2",sktKey:"toolbar.fmt_h2",label:s("toolbar.fmt_h2","Overskrift 2"),format:"header",value:2},{key:"header-3",sktKey:"toolbar.fmt_h3",label:s("toolbar.fmt_h3","Overskrift 3"),format:"header",value:3}],d=[{key:"list-bullet",sktKey:"toolbar.fmt_bullet",label:s("toolbar.fmt_bullet","Punktliste"),format:"list",value:"bullet"},{key:"list-ordered",sktKey:"toolbar.fmt_numbered",label:s("toolbar.fmt_numbered","Nummereret"),format:"list",value:"ordered"},{key:"list-check",sktKey:"toolbar.fmt_checklist",label:s("toolbar.fmt_checklist","Tjekliste"),format:"list",value:"unchecked"},{key:"indent",sktKey:"toolbar.fmt_indent",label:s("toolbar.fmt_indent","Indryk"),format:"indent",value:"+1"}],u="http://www.w3.org/2000/svg",p={"list-bullet":function(){var e=document.createElementNS(u,"svg");return e.setAttribute("viewBox","0 0 18 18"),e.setAttribute("width","18"),e.setAttribute("height","18"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.3"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round"),[{x1:"7",y1:"4",x2:"16",y2:"4"},{x1:"7",y1:"9",x2:"16",y2:"9"},{x1:"7",y1:"14",x2:"16",y2:"14"}].forEach(function(t){var n=document.createElementNS(u,"line");n.setAttribute("x1",t.x1),n.setAttribute("y1",t.y1),n.setAttribute("x2",t.x2),n.setAttribute("y2",t.y2),e.appendChild(n)}),[{cx:"3",cy:"4"},{cx:"3",cy:"9"},{cx:"3",cy:"14"}].forEach(function(t){var n=document.createElementNS(u,"circle");n.setAttribute("cx",t.cx),n.setAttribute("cy",t.cy),n.setAttribute("r","1.2"),n.setAttribute("fill","currentColor"),n.setAttribute("stroke","none"),e.appendChild(n)}),e},"list-ordered":function(){var e=document.createElementNS(u,"svg");return e.setAttribute("viewBox","0 0 18 18"),e.setAttribute("width","18"),e.setAttribute("height","18"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.3"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round"),[{x1:"7",y1:"4",x2:"16",y2:"4"},{x1:"7",y1:"9",x2:"16",y2:"9"},{x1:"7",y1:"14",x2:"16",y2:"14"}].forEach(function(t){var n=document.createElementNS(u,"line");n.setAttribute("x1",t.x1),n.setAttribute("y1",t.y1),n.setAttribute("x2",t.x2),n.setAttribute("y2",t.y2),e.appendChild(n)}),["1","2","3"].forEach(function(t,n){var r=document.createElementNS(u,"text");r.setAttribute("x","3"),r.setAttribute("y",String(5.5+5*n)),r.setAttribute("text-anchor","middle"),r.setAttribute("font-size","5.5"),r.setAttribute("font-weight","600"),r.setAttribute("fill","currentColor"),r.setAttribute("stroke","none"),r.setAttribute("font-family","inherit"),r.textContent=t,e.appendChild(r)}),e},"list-check":function(){var e=document.createElementNS(u,"svg");e.setAttribute("viewBox","0 0 18 18"),e.setAttribute("width","18"),e.setAttribute("height","18"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.3"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round"),[{x1:"8",y1:"4",x2:"16",y2:"4"},{x1:"8",y1:"9",x2:"16",y2:"9"},{x1:"8",y1:"14",x2:"16",y2:"14"}
3].forEach(function(t){var n=document.createElementNS(u,"line");n.setAttribute("x1",t.x1),n.setAttribute("y1",t.y1),n.setAttribute("x2",t.x2),n.setAttribute("y2",t.y2),e.appendChild(n)}),[{y:2},{y:7},{y:12}].forEach(function(t){var n=document.createElementNS(u,"rect");n.setAttribute("x","1"),n.setAttribute("y",String(t.y)),n.setAttribute("width","4"),n.setAttribute("height","4"),n.setAttribute("rx","0.8"),n.setAttribute("stroke","currentColor"),n.setAttribute("fill","none"),e.appendChild(n)});var t=document.createElementNS(u,"polyline");return t.setAttribute("points","1.8 9.2 2.8 10.2 4.5 8"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.2"),e.appendChild(t),e},indent:function(){var e=document.createElementNS(u,"svg");e.setAttribute("viewBox","0 0 18 18"),e.setAttribute("width","18"),e.setAttribute("height","18"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.3"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round"),[{x1:"8",y1:"4",x2:"16",y2:"4"},{x1:"8",y1:"9",x2:"16",y2:"9"},{x1:"8",y1:"14",x2:"16",y2:"14"}].forEach(function(t){var n=document.createElementNS(u,"line");n.setAttribute("x1",t.x1),n.setAttribute("y1",t.y1),n.setAttribute("x2",t.x2),n.setAttribute("y2",t.y2),e.appendChild(n)});var t=document.createElementNS(u,"polyline");return t.setAttribute("points","2 6 5 9 2 12"),e.appendChild(t),e}};function ge(e){var t=document.createElement("span");if(t.className="calm-pop-glyph","paragraph"===e.key)t.textContent="T";else{var n=document.createElement("span");n.textContent="H",t.appendChild(n);var r=document.createElement("sub");r.textContent=String(e.value),t.appendChild(r)}return t}function he(t,n,r){var o=document.createElement("div");o.className="calm-popover-section calm-pop-section";var i=document.createElement("div");i.className="calm-popover-label calm-pop-label",i.setAttribute("data-skt-key",t),i.textContent=s(t,n),o.appendChild(i);var a=document.createElement("div");return a.className="calm-popover-row calm-pop-grid",r.forEach(function(t){var n=document.createElement("button");n.className="calm-popover-btn",n.type="button",n.setAttribute("data-calm-format",t.key),t.sktKey&&n.setAttribute("data-skt-key",t.sktKey),n.setAttribute("aria-label",t.label),n.setAttribute("title",t.label),"indent"!==t.format&&n.setAttribute("aria-pressed","false"),p[t.key]?n.appendChild(p[t.key]()):n.appendChild(ge(t)),n.addEventListener("click",function(){"indent"===t.format?(e.format("indent",t.value),Te()):xe(t)}),a.appendChild(n)}),o.appendChild(a),o}l.appendChild(he("toolbar.section_text","Tekst",c)),l.appendChild(he("toolbar.section_lists","Lister",d));var m=[{key:"blockquote",sktKey:"toolbar.blockquote",label:s("toolbar.blockquote","Citat"),format:"blockquote"},{key:"strike",sktKey:"toolbar.strikethrough",label:s("toolbar.strikethrough","Gennemstreget"),format:"strike"}],f={blockquote:function(){var e=document.createElementNS(u,"svg");return e.setAttribute("viewBox","0 0 18 18"),e.setAttribute("width","18"),e.setAttribute("height","18"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.3"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round"),[{x1:"3",y1:"3.5",x2:"3",y2:"14.5"},{x1:"8",y1:"4.5",x2:"16",y2:"4.5"},{x1:"8",y1:"9",x2:"16",y2:"9"},{x1:"8",y1:"13.5",x2:"16",y2:"13.5"}].forEach(function(t){var n=document.createElementNS(u,"line");n.setAttribute("x1",t.x1),n.setAttribute("y1",t.y1),n.setAttribute("x2",t.x2),n.setAttribute("y2",t.y2),e.appendChild(n)}),e},strike:function(){var e=document.createElementNS(u,"svg");e.setAttribute("viewBox","0 0 18 18"),e.setAttribute("width","18"),e.setAttribute("height","18"),e.setAttribute("fill","none"),e.setAttribute("stroke","currentColor"),e.setAttribute("stroke-width","1.3"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round");var t=document.createElementNS(u,"line");return t.setAttribute("x1","2"),t.setAttribute("y1","9"),t.setAttribute("x2","16"),t.setAttribute("y2","9"),e.appendChild(t),["M13 5.5c0-1.8-1.6-3-4-3s-4 1.2-4 3","M5 12.5c0 1.8 1.6 3 4 3s4-1.2 4-3"].forEach(function(t){var n=document.createElementNS(u,"path");n.setAttribute("d",t),e.appendChild(n)}),e}},g=document.createElement("div");
3g.className="calm-popover-section calm-pop-section calm-pop-extra";var h=document.createElement("div");h.className="calm-popover-row calm-pop-grid",m.forEach(function(t){var n=document.createElement("button");n.className="calm-popover-btn",n.type="button",n.setAttribute("data-calm-format",t.key),n.setAttribute("data-skt-key",t.sktKey),n.setAttribute("aria-label",t.label),n.setAttribute("title",t.label),n.setAttribute("aria-pressed","false"),n.appendChild(f[t.key]()),n.addEventListener("click",function(){var n=e.getFormat();e.format(t.format,!n[t.format]),Te()}),h.appendChild(n)}),g.appendChild(h),l.appendChild(g),document.body.appendChild(l);var v=!1,y={},w=null;function ve(e){return e?{index:e.index,length:e.length||0}:null}function ye(){var t=null;try{t="function"==typeof e.getSelection?e.getSelection(!1):null}catch(e){t=null}return t&&!v&&(w=ve(t)),w}function we(){var t=w;if(!t)try{t=ve(e.getSelection(!1))}catch(e){t=null}if(!t)return null;try{e.setSelection(t.index,t.length,"silent")}catch(e){}return t}function be(t){try{return t?e.getFormat(t.index,t.length)||{}:e.getFormat()||{}}catch(e){return{}}}function ke(t,n,r){var o=t&&"number"==typeof t.index?t.index:0,i=t&&t.length?t.length:0;return e.formatLine(o,i,n,r,"user"),{index:o,length:i}}function Se(t,n){var r=t&&"number"==typeof t.index?t.index:0,o=t&&t.length?t.length:0;if(!n||0===o){if(e.formatLine(r,o,"header",n,"user"),0===o)try{e.setSelection(r,0,"silent")}catch(e){}return{index:r,length:o}}for(var i=e.getText(),a=r,l=r+o;l>a&&"\n"===i.charAt(l-1);)l--;if(l<=a)return e.formatLine(r,0,"header",n,"user"),{index:r,length:0};if(-1!==i.slice(a,l).indexOf("\n")){e.formatLine(a,l-a,"header",n,"user");try{e.setSelection(a,l-a,"silent")}catch(e){}return{index:a,length:l-a}}var s=0===a||"\n"===i.charAt(a-1);l>=i.length||"\n"===i.charAt(l)||e.insertText(l,"\n","user"),s||e.insertText(a,"\n","user");var c=s?a:a+1;e.formatLine(c,0,"header",n,"user");try{e.setSelection(c,l-a,"silent")}catch(e){}return{index:c,length:l-a}}function xe(e){var t=we(),n=be(t),r=t;"header"===e.format?r=Se(t,n.header!==e.value&&e.value)||t:"list"===e.format&&(r=ke(t,"list",n.list!==e.value&&e.value)||t),w=ve(r),Te()}function Te(){var e,t=(e=ye())?y=be(e):y,n="";1===t.header?n="header-1":2===t.header?n="header-2":3===t.header&&(n="header-3");var r="";"bullet"===t.list?r="list-bullet":"ordered"===t.list?r="list-ordered":"unchecked"!==t.list&&"checked"!==t.list||(r="list-check");for(var o=l.querySelectorAll(".calm-popover-btn"),a=0;a<o.length;a++){var s,c=o[a].getAttribute("data-calm-format");if("indent"!==c)s="blockquote"===c?!!t.blockquote:"strike"===c?!!t.strike:c===n||c===r||"paragraph"===c&&!n,o[a].setAttribute("aria-pressed",s?"true":"false")}i.setAttribute("data-active",n||r||t.blockquote||t.strike?"true":"false")}function Le(){var e;v||(ye(),v=!0,e=i.getBoundingClientRect(),l.style.left=Math.max(8,e.left)+"px",l.style.bottom=window.innerHeight-e.top+6+"px",l.style.top="auto",Te(),l.classList.add("open"),i.setAttribute("aria-expanded","true"))}function Ee(e){v&&(v=!1,l.classList.remove("open"),i.setAttribute("aria-expanded","false"),e&&"function"==typeof i.focus&&i.focus())}i.addEventListener("click",function(e){e.stopPropagation(),v?Ee(!0):Le()}),i.addEventListener("keydown",function(e){"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),v?Ee(!0):Le())}),document.addEventListener("click",function(e){!v||e.target.closest(".calm-heading-popover")||e.target.closest(".calm-heading-trigger")||Ee(!1)}),document.addEventListener("keydown",function(e){"Escape"===e.key&&v&&(e.preventDefault(),e.stopPropagation(),Ee(!0))}),window.addEventListener("scroll",function(){v&&Ee(!1)},!0),window.addEventListener("resize",function(){v&&Ee(!1)}),e.on("selection-change",function(e){e&&!v&&(w=ve(e)),Te()}),e.on("text-change",function(){setTimeout(Te,0)})}const W=document.createElement("div");W.className="ed-injected-right";
3const J=document.createElement("span");J.className="ed-clear-toolbar-separator",J.setAttribute("aria-hidden","true"),W.appendChild(J);var b=document.createElement("button");b.className="format-btn ed-clear-toolbar-btn",b.id="ed-clear-btn",b.setAttribute("data-priority","2"),b.title="function"==typeof SKT?SKT("toolbar.clear"):"Ryd tekst",b.setAttribute("aria-label","function"==typeof SKT?SKT("toolbar.clear"):"Ryd tekst");var k="http://www.w3.org/2000/svg",S=document.createElementNS(k,"svg");function Z(){if(e.getText().trim().length>0)return!0;var t=window.SkrivebordApp;if(t&&t.currentDocId)return!1;if(window.innerWidth<=767)return!1;var n=document.getElementById("wm-nudge");return!(!n||!n.classList.contains("hidden"))}function Y(){var e=Z();b.disabled=!e,b.setAttribute("aria-disabled",e?"false":"true")}S.classList.add("calm-trash-icon"),S.setAttribute("viewBox","0 0 24 24"),S.setAttribute("fill","none"),S.setAttribute("stroke","currentColor"),S.setAttribute("stroke-width","2"),S.setAttribute("stroke-linecap","round"),S.setAttribute("stroke-linejoin","round"),S.setAttribute("width","18"),S.setAttribute("height","18"),[{d:"M4 7h16"},{d:"M10 11v6"},{d:"M14 11v6"},{d:"M5 7l1 12a2 2 0 002 2h8a2 2 0 002-2l1-12"},{d:"M9 7V4a1 1 0 011-1h4a1 1 0 011 1v3"}].forEach(function(e){var t=document.createElementNS(k,"path");t.setAttribute("d",e.d),S.appendChild(t)}),b.appendChild(S),e.on("text-change",function(){setTimeout(Y,0)}),document.addEventListener("skrivebord:editor-cleared",function(){setTimeout(Y,0)}),document.addEventListener("wm-form-state",function(){setTimeout(Y,0)}),window.addEventListener("resize",function(){setTimeout(Y,0)});var x=0,T=setInterval(function(){Y(),++x>=20&&clearInterval(T)},500);Y(),b.addEventListener("click",function(){if("function"==typeof window.stopAllSkrivebordTTS&&window.stopAllSkrivebordTTS(),e.getText().trim()){var t=window.SkrivebordApp,n=t?t.currentDocId:null;e.history&&"function"==typeof e.history.cutoff&&e.history.cutoff(),e.setContents([],"user"),e.history&&"function"==typeof e.history.cutoff&&e.history.cutoff(),"function"==typeof window.resetGrammarBotState&&window.resetGrammarBotState(),t&&(t.lastSavedHtml=e.root.innerHTML,n?t.persistClearedDocument(n):t.clearScratchBackup&&t.clearScratchBackup()),document.dispatchEvent(new CustomEvent("skrivebord:editor-cleared"));var r=document.querySelector(".grammar-page");r&&r.classList.add("editor-empty");var o=document.getElementById("ed-word-count");o&&(o.textContent="function"==typeof SKT?SKT("toolbar.word_count",{n:0}):"0 ord")}else{var i=window.SkrivebordApp;if(!i||!i.currentDocId){document.dispatchEvent(new CustomEvent("skrivebord:editor-cleared"));var a=document.querySelector(".grammar-page");a&&a.classList.add("editor-empty")}}});const Q=document.createElement("span");Q.id="ed-word-count",Q.textContent="function"==typeof SKT?SKT("toolbar.word_count",{n:0}):"0 ord";var L=document.querySelector(".main-textarea-section")||document.querySelector(".textarea-wrapper");if(L)Q.className="ed-word-count sk-wc-corner",L.appendChild(Q);else{const Ce=document.createElement("span");Ce.className="ed-word-count-separator",Ce.setAttribute("aria-hidden","true"),W.appendChild(Ce),Q.className="ed-word-count",Q.setAttribute("data-priority","3"),W.appendChild(Q)}const X=document.createElement("div");X.className="ed-overflow-wrap";const ee=document.createElement("button");ee.className="format-btn ed-overflow-toggle",ee.title="function"==typeof SKT?SKT("toolbar.more"):"Mere",ee.setAttribute("aria-label","function"==typeof SKT?SKT("toolbar.more"):"Mere");const te="http://www.w3.org/2000/svg",ne=document.createElementNS(te,"svg");ne.classList.add("calm-mere-icon"),ne.setAttribute("viewBox","0 0 24 24"),ne.setAttribute("fill","none"),ne.setAttribute("stroke","currentColor"),ne.setAttribute("stroke-width","2"),ne.setAttribute("width","16"),ne.setAttribute("height","16"),[5,12,19].forEach(function(e){var t=document.createElementNS(te,"circle");t.setAttribute("cx","12"),t.setAttribute("cy",String(e)),t.setAttribute("r","1.5"),ne.appendChild(t)}),ee.appendChild(ne);const re=document.createElement("div");function oe(e){var t=document.createElementNS(te,"svg");return t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.75"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),t.setAttribute("width","16"),t.setAttribute("height","16"),e.forEach(function(e){var n;"line"===e.type?((n=document.createElementNS(te,"line")).setAttribute("x1",e.x1),n.setAttribute("y1",e.y1),n.setAttribute("x2",e.x2),n.setAttribute("y2",e.y2)):"circle"===e.type?((n=document.createElementNS(te,"circle")).setAttribute("cx",e.cx),n.setAttribute("cy",e.cy),n.setAttribute("r",e.r)):"polyline"===e.type?(n=document.createElementNS(te,"polyline")).setAttribute("points",e.points):(n=document.createElementNS(te,"path")).setAttribute("d",e.d),t.appendChild(n)}),t}function ie(e){var t=re.classList.contains("active");re.classList.remove("active"),e&&t&&"function"==typeof ee.focus&&ee.focus()}re.className="ed-overflow-menu";var E=null,C=null,_=null,A=document.getElementById("readBtn");if(A&&A.parentNode){(E=document.createElement("span")).className="ed-voice-wrap",(C=document.createElement("button")).type="button",C.className="format-btn ed-voice-chevron",C.setAttribute("aria-haspopup","true"),C.setAttribute("aria-expanded","fal
3se"),C.setAttribute("aria-controls","ed-voice-popover");var q="function"==typeof SKT?SKT("toolbar.voice"):"Oplæser";C.setAttribute("aria-label",q),C.title=q,C.innerHTML='<svg viewBox="0 0 24 24" width="10" height="10" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 9l7 7 7-7"/></svg>',(_=document.createElement("div")).id="ed-voice-popover",_.className="ed-overflow-menu ed-voice-popover",E.appendChild(C),E.appendChild(_),A.parentNode.insertBefore(E,A.nextSibling)}var M=document.createElement("div");M.className="ed-overflow-voice-section";var I=document.createElement("span");I.className="ed-overflow-voice-label",I.textContent="function"==typeof SKT?SKT("toolbar.voice"):"Oplæser",M.appendChild(I);var B=document.createElement("div");B.className="ed-overflow-voice-list",B.setAttribute("role","radiogroup"),B.setAttribute("aria-label","function"==typeof SKT?SKT("toolbar.voice"):"Oplæser");var H=rc(),K={};function ae(e){var t=document.querySelector(".sk-voice-toast");t&&t.remove();var n=document.createElement("div");n.className="sk-voice-toast",n.setAttribute("role","status"),n.setAttribute("aria-live","polite");var r="function"==typeof SKT?SKT("toolbar.voice_changed"):"Oplæser skiftet til {name}";n.textContent=r.replace("{name}",e),document.body.appendChild(n),setTimeout(function(){n.classList.add("show")},10),setTimeout(function(){n.classList.remove("show"),setTimeout(function(){n.remove()},300)},2e3)}function le(e,t){if(nc.forEach(function(t){var n=K[t.key];if(n){var r=t.key===e.key;n.className="ed-overflow-voice-btn"+(r?" active":""),n.setAttribute("aria-checked",r?"true":"false"),n.tabIndex=r?0:-1;var o=n.closest?n.closest(".sk-voice-row"):null;o&&o.classList.toggle("active",r)}}),t&&K[e.key])try{K[e.key].focus()}catch(e){}}function se(e,t){for(var n=null,r=0;r<nc.length;r++)if(nc[r].key===e){n=nc[r];break}if(n){var o=n.gender,i=!1;try{window.ChatVoiceChooser&&"function"==typeof window.ChatVoiceChooser.setVoiceKey&&(window.ChatVoiceChooser.setVoiceKey(n.key),i=!0)}catch(e){}if(!i)try{localStorage.setItem("ss_tts_voice",o),localStorage.setItem("ss_tts_voice_variant",n.key)}catch(e){}le(n,t),ae(n.label)}}window.addEventListener("ss-voice-changed",function(e){for(var t=e&&e.detail&&e.detail.voiceKey,n=0;n<nc.length;n++)if(nc[n].key===t)return void le(nc[n],!1)}),B.addEventListener("keydown",function(e){var t=0;if("ArrowRight"===e.key||"ArrowDown"===e.key)t=1;else{if("ArrowLeft"!==e.key&&"ArrowUp"!==e.key)return;t=-1}for(var n=document.activeElement&&document.activeElement.getAttribute?document.activeElement.getAttribute("data-voice-key"):null,r=-1,o=0;o<nc.length;o++)if(nc[o].key===n){r=o;break}if(-1===r){n=rc();for(var i=0;i<nc.length;i++)if(nc[i].key===n){r=i;break}}e.preventDefault(),e.stopPropagation(),se(nc[(r+t+nc.length)%nc.length].key,!0)}),B.classList.add("ed-overflow-voice-grid");var D=null,P=null;function ce(){if(D){var e=D;D=null,e.setAttribute("aria-pressed","false");var t=e.querySelector(".sk-voice-wave");if(t)try{var n=getComputedStyle(t);t.style.opacity=n.opacity,t.style.transform=n.transform}catch(e){}e.classList.remove("playing"),t&&requestAnimationFrame(function(){t.style.transition="opacity .16s ease-out",t.style.opacity="0",setTimeout(function(){t.style.transition="",t.style.opacity="",t.style.transform=""},220)})}if(P){try{P.pause()}catch(e){}P=null}}function de(e){var t=B.querySelector('[data-voice-row="'+e+'"]'),n=t?t.querySelector(".sk-voice-preview"):null;if(D&&D===n)ce();else{ce(),n&&(n.classList.add("playing"),n.setAttribute("aria-pressed","true"),D=n);try{(P=new Audio("/chat/assets/voice-samples/"+e+".mp3?v=1")).addEventListener("ended",ce),P.addEventListener("error",ce);var r=P.play();r&&r.catch&&r.catch(ce)}catch(e){ce()}}}function ue(e){if(_){ce();var t=_.classList.contains("active");_.classList.remove("active"),C&&C.setAttribute("aria-expanded","false"),e&&t&&C&&"function"==typeof C.focus&&C.focus()}}nc.forEach(function(e){var t=e.key===H,n=document.createElement("div");n.className="sk-voice-row sk-voice-row--"+e.gender+(t?" active":""),n.setAttribute("data-voice-row",e.key);var r=document.createElement("button");r.type="button",r.className="sk-voice-preview";var o=("function"==typeof SKT?SKT("toolbar.mob_tts"):"Læs op")+" â "+e.label;r.setAttribute("aria-label",o),r.title=o,r.setAttribute("aria-pressed","fal
3se"),r.tabIndex=-1;var i=oe([{d:"M11 5L6 9H2v6h4l5 4z"},{d:"M15.5 8.5a5 5 0 0 1 0 7"}]);i.setAttribute("stroke-width","2.25"),i.firstChild&&i.setAttribute("viewBox","-2.25 0 24 24"),r.appendChild(i);var a=document.createElement("span");a.className="sk-voice-wave",a.setAttribute("aria-hidden","true"),r.appendChild(a),r.addEventListener("click",function(t){t.stopPropagation(),de(e.key)}),n.appendChild(r);var l=document.createElement("button");l.type="button",l.className="ed-overflow-voice-btn"+(t?" active":""),l.setAttribute("data-voice",e.gender),l.setAttribute("data-voice-key",e.key),l.setAttribute("role","radio"),l.setAttribute("aria-checked",t?"true":"false"),l.tabIndex=t?0:-1;var s=document.createElement("span");s.textContent=e.label,l.appendChild(s);var c=document.createElement("span");c.className="sk-voice-check",c.setAttribute("aria-hidden","true");var d=oe([{d:"M5 12.5l4.5 4.5L19 7"}]);d.setAttribute("stroke-width","2.25"),c.appendChild(d),l.appendChild(c),l.addEventListener("click",function(t){t.stopPropagation(),se(e.key),de(e.key)}),n.appendChild(l),B.appendChild(n),K[e.key]=l}),M.appendChild(B),_&&_.appendChild(M),C&&C.addEventListener("click",function(e){e.stopPropagation();var t=document.getElementById("genderSelector");t&&(t.style.display="none");var n=_.classList.toggle("active");C.setAttribute("aria-expanded",n?"true":"false")}),ee.addEventListener("click",function(e){e.stopPropagation(),me(),re.classList.toggle("active")}),document.addEventListener("click",function(e){e.target.closest(".ed-overflow-wrap")||ie(!1),e.target.closest(".ed-voice-wrap")||ue(!1)}),document.addEventListener("keydown",function(e){"Escape"===e.key&&re.classList.contains("active")&&(e.preventDefault(),e.stopPropagation(),ie(!0)),"Escape"===e.key&&_&&_.classList.contains("active")&&(e.preventDefault(),e.stopPropagation(),ue(!0))}),X.appendChild(ee),X.appendChild(re),W.appendChild(X),W.appendChild(b),n.appendChild(W);var N=[{id:"revertBack",labelKey:"format.undo",fallback:"Fortryd",priority:2,iconData:[{d:"M3 7v6h6"},{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13"}]},{id:"redoBtn",labelKey:"format.redo",fallback:"Gentag",priority:2,iconData:[{d:"M21 7v6h-6"},{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7"}]},{id:"copyBtn",labelKey:"format.copyText",fallback:"Kopier tekst",priority:2,iconData:[{d:"M9 9h13v13H9z"},{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"}]},{id:"formatItalic",labelKey:"format.italic",fallback:"Kursiv",priority:2,iconData:[{d:"M19 4h-9"},{d:"M14 20H5"},{d:"M15 4L9 20"}]},{id:"downloadBtnQuill",labelKey:"format.download",fallback:"Download",priority:2,iconData:[{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"},{d:"M7 10l5 5 5-5"},{d:"M12 15V3"}]}],j=window.matchMedia("(max-width: 1023.98px)"),R=window.matchMedia("(max-width: 1100px)");function pe(){for(var e=re.querySelectorAll(".ed-overflow-collapsed[data-control-id]"),t=0;t<e.length;t++){var n=e[t],r=document.getElementById(n.getAttribute("data-control-id"));r&&(n.disabled=!!r.disabled)}}function me(){for(var e=re.querySelectorAll(".ed-overflow-collapsed"),t=0;t<e.length;t++)e[t].remove();var n=j.matches,r=R.matches;if(!n&&!r)return X.classList.add("ed-overflow-idle"),void ie(!1);for(var o=n?2:3,i=document.createDocumentFragment(),a=!1,l=0;l<N.length;l++){var s=N[l];if(!(s.priority<o)){var c=document.getElementById(s.id);if(c){try{if("none"!==window.getComputedStyle(c).display)continue}catch(e){}var d=document.createElement("button");d.className="ed-overflow-item ed-overflow-collapsed",d.setAttribute("data-control-id",s.id),c.disabled&&(d.disabled=!0);var u=document.createElement("span");u.className="ed-overflow-icon",u.appendChild(oe(s.iconData)),d.appendChild(u);var p="function"==typeof SKT?SKT(s.labelKey):s.fallback;d.appendChild(document.createTextNode(p)),d.addEventListener("click",function(e){return function(t){t.preventDefault(),t.stopPropagation(),e.disabled||("downloadBtnQuill"===e.id&&"function"==typeof window.CustomEvent?e.dispatchEvent(new CustomEvent("sk:download-menu-open",{bubbles:!0,detail:{anchor:d}})):e.click(),ie(!1))}}(c)),i.appendChild(d),a=!0}}}X.classList.toggle("ed-overflow-idle",!a),a||ie(!1),re.insertBefore(i,re.firstChild),pe()}function fe(e){e.addEventListener?e.addEventListener("change",me):e.addListener&&e.addListener(me)}fe(j),fe(R),me(),e&&"function"==typeof e.on&&e.on("text-change",function(){setTimeout(pe,0)})}const F=document.getElementById("ed-word-count");var O=null;function U(){var t=null!==O?O:tc.countWords(e.getText()),n="function"==typeof SKT?SKT("toolbar.word_count",{n:t}):t+" ord";F&&(F.textContent=n)}tc.setWordCountOverride=function(e){O="number"==typeof e&&isFinite(e)&&e>=0?Math.round(e):null,U()},e.on("text-change",U),U();let $=0;const z=setInterval(function(){U(),++$>=20&&clearInterval(z)},500);window.addEventListener("ss:lang-changed",function(){if(ic(),"function"==typeof SKT){var e=document.getElementById("doc-title");e&&!e.value&&(e.placeholder=oc()),U();var t=document.getElementById("ed-clear-btn");t&&(t.title=SKT("toolbar.clear"),t.setAttribute("aria-label",SKT("toolbar.clear")));var n=document.querySelector(".ed-overflow-toggle");n&&(n.title=SKT("toolbar.more"),n.setAttribute("aria-label",SKT("toolbar.more")));var r=document.querySelector(".ed-voice-chevron");r&&(r.title=SKT("toolbar.voice"),r.setAttribute("aria-label",SKT("toolbar.voice")));var o=document.querySelector(".ed-overflow-voice-label");o&&(o.textContent=SKT("toolbar.voice")),document.querySelectorAll(".ed-overflow-item[data-skt-key]").forEach(function(e){var t=e.getAttribute("data-skt-key"),n=e.lastChild;n&&3===n.nodeType&&(n.textContent=SKT(t))});var i=document.querySelector(".calm-heading-trigger");i&&i.setAttribute("aria-label",SKT("toolbar.headings_lists"));var a=document.getElementById("calm-heading-popover");a&&(a.setAttribute("aria-label",SKT("toolbar.headings_lists")),a.querySelectorAll(".calm-pop-label[data-skt-key]").forEach(function(e){e.textContent=SKT(e.getAttribute("data-skt-key"))}),a.querySelectorAll(".calm-popover-btn[data-skt-key]").forEach(function(e){var t=SKT(e.getAttribute("data-skt-key"));e.setAttribute("aria-label",t),e.setAttribute("title",t)}));var l=document.getElementById("mob-copy-btn");if(l){l.setAttribute("aria-label",SKT("toolbar.mob_copy"));var s=l.querySelector("span");
3s&&(s.textContent=SKT("toolbar.mob_copy"))}var c=document.getElementById("mob-tts-btn");if(c){c.setAttribute("aria-label",SKT("toolbar.mob_tts"));var d=c.querySelector("span");d&&(d.textContent=SKT("toolbar.mob_tts"))}}}),window.innerWidth<=767&&(function(e){var t=document.createElement("div");t.className="mobile-format-bar",t.id="mobile-format-bar",t.style.display="none";var n="function"==typeof SKT?SKT("toolbar.mob_copy"):"Kopiér",r=document.createElement("button");r.className="mobile-format-btn",r.id="mob-copy-btn",r.setAttribute("aria-label",n),r.innerHTML='<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/></svg><span>'+n+"</span>";var o=document.createElement("div");o.className="mobile-format-sep";var i="function"==typeof SKT?SKT("toolbar.mob_tts"):"Læs op",a=document.createElement("button");function l(){var e=document.querySelector(".ss-bottom-nav")||document.querySelector('[aria-label="Hovednavigation"]');e&&(t.style.bottom=e.offsetHeight+"px")}a.className="mobile-format-btn",a.id="mob-tts-btn",a.setAttribute("aria-label",i),a.innerHTML='<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><path d="M15.54 8.46a5 5 0 010 7.07"/><path d="M19.07 4.93a10 10 0 010 14.14"/></svg><span>'+i+"</span>",t.appendChild(r),t.appendChild(o),t.appendChild(a),document.body.appendChild(t),l(),window.addEventListener("resize",l);var s,c=0,d=setInterval(function(){l(),++c>=10&&clearInterval(d)},500);function u(){var n=e.getText().trim(),r=document.querySelector("#wm-form:not(.hidden)"),o=n.length>0&&!r;t.style.display=o?"flex":"none",o&&l()}function p(){var t=e.container.querySelector(".ql-editor");if(!t)return"";var n=t.innerHTML;return n=(n=(n=(n=(n=n.replace(/<span class="ql-ui"[^>]*>.*?<\/span>/gi,"")).replace(/background(-color)?:[^;]+;?/gi,"")).replace(/font-size:[^;]+;?/gi,"")).replace(/font-family:[^;]+;?/gi,"")).replace(/color:[^;]+;?/gi,"")}function m(){var t=p(),n=e.getText().trim();if(!n)return Promise.reject();if(navigator.clipboard&&navigator.clipboard.write)try{return navigator.clipboard.write([new ClipboardItem({"text/html":new Blob([t],{type:"text/html"}),"text/plain":new Blob([n],{type:"text/plain"})})])}catch(e){}try{var r=function(e){e.clipboardData.setData("text/html",t),e.clipboardData.setData("text/plain",n),e.preventDefault(),document.removeEventListener("copy",r)};document.addEventListener("copy",r);var o=document.createRange(),i=e.container.querySelector(".ql-editor");o.selectNodeContents(i);var a=window.getSelection();a.removeAllRanges(),a.addRange(o);var l=document.execCommand("copy");if(a.removeAllRanges(),l)return Promise.resolve()}catch(e){}return navigator.clipboard.writeText(n)}function f(){r.classList.add("done"),r.querySelector("span").textContent="Kopieret!",r.querySelector("svg").innerHTML='<polyline points="20 6 9 17 4 12" stroke-width="2.5"/>',clearTimeout(s),s=setTimeout(function(){r.classList.remove("done"),r.querySelector("span").textContent="Kopiér",r.querySelector("svg").innerHTML='<rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/>'},2e3)}e.on("text-change",u),setInterval(u,500),u(),r.addEventListener("click",function(){m().then(f).catch(function(){})});var g=null,h=!1;function v(){h=!1,a.classList.remove("playing","loading"),a.querySelector("span").textContent="function"==typeof SKT?SKT("toolbar.mob_tts"):"Læs op",a.querySelector("svg").innerHTML='<polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><path d="M15.54 8.46a5 5 0 010 7.07"/><path d="M19.07 4.93a10 10 0 010 14.14"/>'}a.addEventListener("click",function(){if(h&&g)return g.pause(),g.currentTime=0,g=null,void v();var t=e.getText().trim();if(t){a.classList.add("loading"),a.querySelector("span").textContent="function"==typeof SKT?SKT("toolbar.tts_loading"):"Indlæser...";var n=window._supabase;n?n.auth.getSession().then(function(e){var n=e&&e.data&&e.data.session,r=n?n.access_token:null,o=new FormData;o.append("action","hgf_important_secure_bots_text_to_speech"),o.append("text",t.substring(0,3e3));var i=window.SkrivSikkertSkrivebord&&window.SkrivSikkertSkrivebord.languageDropdown&&window.SkrivSikkertSkrivebord.languageDropdown.getCurrentLanguage?window.SkrivSikkertSkrivebord.languageDropdown.getCurrentLanguage():"da",l={da:"Danish",en:"English",ge:"German",fr:"French",es:"Spanish",sv:"Swedish",no:"Norwegian"};o.append("lang",l[i]||"Danish"),o.append("gender","male"===(localStorage.getItem("ss_tts_voice")||"female")?"Male":"Female"),o.append("voice",rc());var s={};r&&(s.Authorization="Bearer "+r),fetch("/robots/skrivebord/grammar-api.php",{method:"POST",headers:s,body:o}).then(function(e){return e.blob()}).then(function(e){var t=URL.createObjectURL(e);(g=new Audio(t)).addEventListener("ended",function(){URL.revokeObjectURL(t),g=null,v()}),g.play(),h=!0,a.classList.remove("loading"),a.classList.add("playing"),a.querySelector("span").textContent="Stop",a.querySelector("svg").innerHTML='<rect x="6" y="4" width="4" height="16" rx="1"/><rect x="14" y="4" width="4" height="16" rx="1"/>'}).catch(function(){v()})}):v()}})}(e),function(e){var t=e.container;if(!t)return;var n=t.closest(".textarea-wrapper");
3n||(n=t.parentNode);n.style.position="relative";var r=document.createElement("div");r.className="editor-skeleton";for(var o="",i=[92,78,85,60,88,45,80,70,90,55,82,65,75,50,87,72,68,58,84,40],a=0;a<i.length;a++)o+='<div class="editor-skeleton-line" style="width:'+i[a]+'%"></div>';r.innerHTML='<div class="editor-skeleton-lines">'+o+"</div>",n.appendChild(r);var l=!1;function s(){l||(l=!0,r.classList.add("active"))}function c(){l&&(l=!1,r.classList.remove("active"))}function d(){var e=document.getElementById("ai-card-messages");if(e){var t=e.querySelector(".ai-cancel-btn"),n=e.querySelector(".ai-loading-dots");n&&n.closest(".ai-msg--assistant")&&(n=null),t||n?s():c()}}function u(){var e=document.getElementById("ai-card-messages");return!!e&&(new(window.MutationObserver||window.WebKitMutationObserver)(d).observe(e,{childList:!0,subtree:!0}),!0)}if(!u())var p=0,m=setInterval(function(){(u()||++p>=60)&&clearInterval(m)},500);e.on("text-change",function(){l&&(t.querySelector(".inline-correction")&&c())})}(e),function(){function e(e){e.addEventListener("click",function(t){t.target.closest(".ai-chip")&&!e.classList.contains("closing")&&(e.classList.add("closing"),setTimeout(function(){e.classList.remove("closing")},350))});var t=e.querySelector(".mobile-ai-overlay");t&&t.addEventListener("click",function(){e.classList.contains("closing")||(e.classList.add("closing"),setTimeout(function(){e.classList.remove("closing")},350))}),new MutationObserver(function(){!e.classList.contains("open")&&e.classList.contains("closing")&&e.classList.remove("closing")}).observe(e,{attributes:!0,attributeFilter:["class"]})}var t=document.querySelector(".mobile-ai-wrap");if(t)return e(t);var n=0,r=setInterval(function(){(t=document.querySelector(".mobile-ai-wrap"))&&(clearInterval(r),e(t)),++n>=20&&clearInterval(r)},500)}())},function(){function e(e,t){return"function"==typeof window.SKT?window.SKT(e):t}function t(t,n,r){if(t&&!t.querySelector(".wm-nudge-label")){var o=document.createElement("span");o.className="wm-nudge-label",o.textContent=e(n,r),t.appendChild(o)}}function n(){var n=document.querySelector(".bb-skrivebord");if(!n)return!1;var r=n.querySelector(".skv2-action-controls"),o=n.querySelector(".counter-nav-div");if(!r||!o)return!1;r.querySelectorAll(":scope > .controls-sep").forEach(function(e){e.remove()});var i,a=[document.getElementById("copyBtn"),document.getElementById("downloadBtnQuill"),document.getElementById("doc-save-btn"),(i=document.getElementById("shareBtn"),i||((i=document.createElement("button")).type="button",i.id="shareBtn",i.className="control-btn",i.title=e("wm.tpl_share","Del"),i.setAttribute("aria-label",e("wm.tpl_share","Del")),i.setAttribute("data-i18n-title","wm.tpl_share"),i.setAttribute("data-i18n-aria-label","wm.tpl_share"),i.setAttribute("data-ss-requires-login","1"),i.setAttribute("data-ss-login-source","skrivebord-share"),i.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M18 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM6 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM18 22a3 3 0 1 0 0-6 3 3 0 0 0 0 6ZM8.59 13.51l6.83 3.98M15.41 6.51l-6.82 3.98" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',i))].map(function(e){return function(e,t){if(!t)return null;var n=t.closest(".ctl-group");return n&&n.parentElement===e||((n=document.createElement("div")).className="ctl-group",n.appendChild(t),e.appendChild(n)),n}(r,e)}).filter(Boolean),l=Array.prototype.filter.call(r.children,function(e){return e.classList.contains("ctl-group")});a.some(function(e,t){return l[t]!==e})&&a.forEach(function(e){r.appendChild(e)}),r.querySelectorAll(":scope > .ctl-group:empty").forEach(function(e){e.remove()});var s=document.getElementById("micButton1");if(s){var c=o.querySelector(":scope > .ctl-sub");c||((c=document.createElement("span")).className="ctl-sub"),s.parentElement!==c&&c.appendChild(s),c.parentElement!==o&&o.appendChild(c)}var d=n.querySelector(".wm-nudge-panel"),u=document.getElementById("wm-start-notes"),p=document.getElementById("pasteBtn"),m=document.getElementById("uploadImg"),f=document.getElementById("imageUpload");if(d&&u&&p&&m&&f){p.classList.add("wm-nudge-action"),m.classList.add("wm-nudge-action"),t(p,"controls.paste","Indsæt"),t(m,"controls.upload","Upload");var g=[u,p,m,f];g.some(function(e,t){return d.children[t]!==e})&&g.forEach(function(e){d.appendChild(e)})}return n.setAttribute("data-toolbar-layout","ready"),Boolean(document.getElementById("doc-save-btn")&&d)}function r(){n(),new MutationObserver(n).observe(document.body,{childList:!0,subtree:!0});var e=0,t=setInterval(function(){e+=1,(n()||e>200)&&clearInterval(t)},100)}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",r,{once:!0}):r()}(),function(){function e(){return window.innerWidth<=767}function t(){return!0===window.__SS_PUBLIC_MODE}function n(){try{if(a&&a.outputLang)return String(a.outputLang).split("-")[0]}catch(e){}try{var e=localStorage.getItem("ss_chat_lang");if(e){var t=JSON.parse(e);if(t&&t.code)return t.code.split("-")[0]}}catch(e){}return"da"}function r(e){if(e){e.style.height="auto";var t=Math.min(e.scrollHeight,200);e.style.height=t+"px",e.style.overflowY=e.scrollHeight>200?"auto":"hidden"}}var o=[{label:"function"==typeof SKT?SKT("wm.tone_0"):"Uformel",desc:"function"==typeof SKT?SKT("wm.tone_0
3d"):"Afslappet og venlig",sktLabel:"wm.tone_0",sktDesc:"wm.tone_0d"},{label:"function"==typeof SKT?SKT("wm.tone_1"):"Personlig",desc:"function"==typeof SKT?SKT("wm.tone_1d"):"Varm og personlig",sktLabel:"wm.tone_1",sktDesc:"wm.tone_1d"},{label:"function"==typeof SKT?SKT("wm.tone_2"):"Neutral",desc:"function"==typeof SKT?SKT("wm.tone_2d"):"Klar og direkte",sktLabel:"wm.tone_2",sktDesc:"wm.tone_2d"},{label:"function"==typeof SKT?SKT("wm.tone_3"):"Høflig",desc:"function"==typeof SKT?SKT("wm.tone_3d"):"Respektfuld og venlig",sktLabel:"wm.tone_3",sktDesc:"wm.tone_3d"},{label:"function"==typeof SKT?SKT("wm.tone_4"):"Professionel",desc:"function"==typeof SKT?SKT("wm.tone_4d"):"Formel og autoritativ",sktLabel:"wm.tone_4",sktDesc:"wm.tone_4d"}];var i=4,a={outputLang:"da",outputLangExplicit:!1},l={Danish:"da",English:"en",German:"de",French:"fr",Spanish:"es",Norwegian:"no",Swedish:"sv",Finnish:"fi",Polish:"pl",Italian:"it",Portuguese:"pt",Dutch:"nl",Turkish:"tr",Russian:"ru",Arabic:"ar",Japanese:"ja",Korean:"ko"},s=[{endonym:"Dansk",apiName:"Danish",daName:"Dansk"},{endonym:"English",apiName:"English",daName:"Engelsk"},{endonym:"Deutsch",apiName:"German",daName:"Tysk"},{endonym:"Français",apiName:"French",daName:"Fransk"},{endonym:"Español",apiName:"Spanish",daName:"Spansk"}],c=[{endonym:"Norsk",apiName:"Norwegian",daName:"Norsk"},{endonym:"Svenska",apiName:"Swedish",daName:"Svensk"},{endonym:"Suomi",apiName:"Finnish",daName:"Finsk"},{endonym:"Polski",apiName:"Polish",daName:"Polsk"},{endonym:"Italiano",apiName:"Italian",daName:"Italiensk"},{endonym:"Português",apiName:"Portuguese",daName:"Portugisisk"},{endonym:"Nederlands",apiName:"Dutch",daName:"Nederlandsk"},{endonym:"Türkçe",apiName:"Turkish",daName:"Tyrkisk"},{endonym:"Ð ÑÑÑкий",apiName:"Russian",daName:"Russisk"},{endonym:"Ø§ÙØ¹Ø±Ø¨ÙØ©",apiName:"Arabic",daName:"Arabisk"},{endonym:"æ¥æ¬èª",apiName:"Japanese",daName:"Japansk"},{endonym:"íêµì´",apiName:"Korean",daName:"Koreansk"}];function d(){return s.concat(c)}function u(e){return e&&(e.code||l[e.apiName])||"da"}function p(e){for(var t=d(),n=0;n<t.length;n++)if(u(t[n])===e)return t[n];return s[0]}function m(){return p(a.outputLang).endonym}function f(e){var t=p(e);return a.outputLang=u(t),t.apiName,t}function g(){return window._supabase?window._supabase.auth.getSession().then(function(e){return e.data.session?e.data.session.access_token:null}):Promise.resolve(null)}function h(e){return String(null==e?"":e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}var v,y="function"==typeof SKT?SKT("wm.content_ph"):"Tilføj detaljer eller stikord...";function w(e){return g().then(function(t){var n={"Content-Type":"application/json","X-SS-Version":"voksen"};t&&(n.Authorization="Bearer "+t);var r=new AbortController,o=setTimeout(function(){r.abort()},6e4);return fetch("/api/writing-assistant-api.php",{method:"POST",headers:n,body:JSON.stringify(e),signal:r.signal}).finally(function(){clearTimeout(o)})}).then(function(e){if(413===e.status)return e.json().catch(function(){return{}}).then(function(){throw window._showDemoLimit&&window._showDemoLimit(),new Error("word_limit_exceeded")});if(429===e.status&&window.SSWordLimit)return window.SSWordLimit.handleResponse(e).then(function(e){if(e)throw window.SSWordLimit.createError(e);throw new Error("Server error")});if(!e.ok)throw new Error("Server error");return e.json()}).then(function(e){if("word_limit_exceeded"===e.error)throw window.SSWordLimit?window.SSWordLimit.show({data:e}):window._showWordLimitModal&&window._showWordLimitModal(e.used,e.limit||15e3,e.reset_date||null),new Error("word_limit_exceeded");if(e.error)throw new Error(e.error);return{text:e.text||"",review:e.review||null}})}function b(e,t,n,r){return w({task:e,content:t,tone:n+1,language:m(),language_code:a.outputLang})}!function(e){if(window.quill1)return e(window.quill1);var t=0,n=setInterval(function(){window.quill1&&(clearInterval(n),e(window.quill1)),++t>200&&clearInterval(n)},100)}(function(t){var n=document.querySelector(".textarea-wrapper");if(n&&!document.getElementById("wm-nudge")&&!document.getElementById("wm-form")){n.style.position="relative",n.insertAdjacentHTML("beforeend",'<div class="wm-nudge" id="wm-nudge"><div class="wm-nudge-panel"><button type="button" class="wm-nudge-action" id="wm-start-notes"><svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 14c.2-1 .7-1.7 1.5-2.5C17.7 10.2 18 9 18 7.5a6 6 0 1 0-12 0c0 1.5.3 2.7 1.5 4 .8.8 1.3 1.5 1.5 2.5"/><path d="M9 18h6"/><path d="M10 22h4"/></svg><span>'+("function"==typeof SKT?SKT("wm.start_notes"):"Start med stikord")+'</span></button></div></div><div class="wm-form hidden" id="wm-form"><div class="wm-form-inner"><div class="wm-form-header"><span>'+("function"==typeof SKT?SKT("wm.form_header"):"Hvad vil du skrive?")+'</span><div class="wm-recording-indicator" id="wm-recording-indicator"><div class="wm-recording-dot"></div><span>'+("function"==typeof SKT?SKT("wm.listening"):"Lytter...")+'</span></div><button class="wm-collapse-btn" id="wm-collapse" title="'+("function"==typeof SKT?SKT("wm.close"):"Luk")+'">×</button></div><div class="wm-cat-grid hidden" id="wm-cat-grid" role="group" aria-label="'+("function"==typeof SKT?SKT("wm.start_aria"):"Vælg hvordan du vil starte")+'"></div><div class="wm-fields-card"><div class="wm-field wm-field-mic wm-field-task"><label for="wm-task">'+("function"==typeof SKT?SKT("wm.task_label"):"Opgave")+'</label><div class="wm-textarea-wrap"><textarea id="wm-task" rows="1" placeholder="'+("function"==typeof SKT?SKT("wm.task_ph"):"F.eks. en e-mail til min chef...")+'" spellcheck="false" autocomplete="off"></textarea><button type="button" class="wm-clear-btn" data-for="wm-task" aria-label="Ryd felt" title="Ryd"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1.5 14a2 2 0 01-2 2h-7a2 2 0 01-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/></svg></button><button type="button" class="wm-mic-btn ss-mic" id="wm-mic-task" aria-label="'+("function"==typeof SKT?SKT("wm.dictate_task"):"Dikter opgave")+'" title="'+("function"==typeof SKT?SKT("wm.stt"):"Tale-til-tekst")+'"><svg class="lucide-mic" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewB
3ox="0 0 24 24" fill="none"><path d="M12 23V20M12 20C9.87827 20 7.84344 19.1571 6.34315 17.6569C4.84285 16.1566 4 14.1217 4 12M12 20C14.1217 20 16.1566 19.1571 17.6569 17.6569C19.1571 16.1566 20 14.1217 20 12M12 17C9.25 17 7 14.828 7 12.172V5.828C7 3.172 9.25 1 12 1C14.75 1 17 3.172 17 5.828V12.172C17 14.828 14.75 17 12 17Z" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg><span class="wm-mic-label">'+("function"==typeof SKT?SKT("wm.dictate_short"):"Dikter")+'</span></button></div></div><div class="wm-field wm-field-mic"><label for="wm-content">'+("function"==typeof SKT?SKT("wm.content_label"):"Stikord eller noter")+'</label><div class="wm-textarea-wrap"><textarea id="wm-content" placeholder="'+("function"==typeof SKT?SKT("wm.content_ph"):"Tilføj detaljer eller stikord...")+'" spellcheck="false" autocomplete="off"></textarea><button type="button" class="wm-clear-btn" data-for="wm-content" aria-label="Ryd felt" title="Ryd"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1.5 14a2 2 0 01-2 2h-7a2 2 0 01-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/></svg></button><button type="button" class="wm-mic-btn ss-mic" id="wm-mic-content" aria-label="'+("function"==typeof SKT?SKT("wm.dictate_content"):"Dikter stikord")+'" title="'+("function"==typeof SKT?SKT("wm.stt"):"Tale-til-tekst")+'"><svg class="lucide-mic" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M12 23V20M12 20C9.87827 20 7.84344 19.1571 6.34315 17.6569C4.84285 16.1566 4 14.1217 4 12M12 20C14.1217 20 16.1566 19.1571 17.6569 17.6569C19.1571 16.1566 20 14.1217 20 12M12 17C9.25 17 7 14.828 7 12.172V5.828C7 3.172 9.25 1 12 1C14.75 1 17 3.172 17 5.828V12.172C17 14.828 14.75 17 12 17Z" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg><span class="wm-mic-label">'+("function"==typeof SKT?SKT("wm.dictate_short"):"Dikter")+'</span></button></div></div><div class="wm-field wm-lang-field"><label id="wm-lang-compact-label-el" class="wm-lang-compact-label" data-i18n="wm.lang_label">'+("function"==typeof SKT?SKT("wm.lang_label"):"Sprog:")+'</label><div class="wm-language-row wm-language-row--compact wm-lang-compact-row" id="wm-language-row"><div class="wm-lang-compact-wrap" id="wm-lang-compact-wrap"><button type="button" class="wm-lang-compact-btn" id="wm-lang-compact-btn" aria-haspopup="listbox" aria-expanded="false" aria-controls="wm-lang-compact-menu" aria-labelledby="wm-lang-compact-label-el wm-lang-compact-name"><svg class="wm-lang-globe" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"/><path d="M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg><span class="wm-lang-compact-name" id="wm-lang-compact-name">Dansk</span><svg class="wm-lang-chevron" width="8" height="5" viewBox="0 0 8 5" fill="none" aria-hidden="true"><path d="M1 1L4 4L7 1" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg></button><ul class="wm-lang-compact-menu hidden" id="wm-lang-compact-menu" role="listbox" aria-labelledby="wm-lang-compact-label-el"></ul></div></div></div></div><div class="wm-section-divider"><span>'+("function"==typeof SKT?SKT("wm.tone_section"):"Vælg tonefald")+'</span></div><div class="wm-tone-card"><div class="wm-tone-current" id="wm-tone-value">'+("function"==typeof SKT?SKT("wm.tone_4"):"Professionel")+'</div><div class="wm-tone-desc" id="wm-tone-desc">'+("function"==typeof SKT?SKT("wm.tone_4d"):"Formel og autoritativ")+'</div><div class="wm-tone-track" id="wm-tone-track" role="slider" aria-label="'+("function"==typeof SKT&&SKT("wm.tone_range_aria")||"Tonefald")+'" aria-valuemin="1" aria-valuemax="5" aria-valuenow="5" aria-valuetext="'+o[4].label+'" tabindex="0"><div class="wm-tone-progress" id="wm-tone-progress" style="width:100%"></div><div class="wm-tone-thumb" id="wm-tone-thumb" style="left:100%"></div></div><div class="wm-tone-endpoints"><span>'+("function"==typeof SKT?SKT("wm.tone_min"):"Uformel")+"</span><span>"+("function"==typeof SKT?SKT("wm.tone_max"):"Professionel")+'</span></div></div><button class="wm-submit" id="wm-submit" disabled><span class="wm-submit-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 013 3L7 19l-4 1 1-4 12.5-12.5z"/></svg></span><span class="wm-submit-content"><span class="wm-btn-text">'+("function"==typeof SKT?SKT("wm.submit_text"):"Skriv teksten")+'</span><span class="wm-submit-desc">'+("function"==typeof SKT?SKT("wm.submit_desc"):"AI genererer din tekst")+'</span></span><span class="wm-btn-loader"></span></button></div></div>');var l=document.querySelector(".grammar-page")||document.querySelector(".app-layout"),g=document.getElementById("wm-nudge");e()&&g&&g.classList.add("hidden");var h=document.getElementById("wm-form"),y=document.getElementById("wm-start-notes"),k=document.getElementById("wm-collapse"),S=document.getElementById("wm-back"),x=document.getElementById("wm-task"),T=document.getElementById("wm-content"),L=document.getElementById("wm-submit"),E=document.getElementById("wm-tone-track"),C=document.getElementById("wm-tone-thumb"),A=document.getElementById("wm-tone-value"),q=document.getElementById("wm-tone-desc"),M=document.getElementById("wm-tone-progress");z(x),z(T);for(var I=h.querySelectorAll(".wm-clear-btn"),B=0;B<I.length;B++)(function(e){var t=document.getElementById(e.getAttribute("data-for"));t&&(e.addEventListener("click",function(){t.value="",r(t),G(t),t.focu
3s(),J()}),t.addEventListener("input",function(){G(t)}),t.addEventListener("paste",function(){setTimeout(function(){G(t)},0)}),G(t))})(I[B]);v=V,E.addEventListener("click",function(e){W(e.clientX)});var H=!1;C.addEventListener("mousedown",function(e){H=!0,e.preventDefault()}),C.addEventListener("touchstart",function(){H=!0},{passive:!0}),document.addEventListener("mousemove",function(e){H&&W(e.clientX)}),document.addEventListener("touchmove",function(e){H&&W(e.touches[0].clientX)}),document.addEventListener("mouseup",function(){H=!1}),document.addEventListener("touchend",function(){H=!1}),E.addEventListener("keydown",function(e){"ArrowRight"===e.key||"ArrowUp"===e.key?(e.preventDefault(),V(i+1),E.setAttribute("aria-valuenow",i+1),E.setAttribute("aria-valuetext",o[i].label)):"ArrowLeft"===e.key||"ArrowDown"===e.key?(e.preventDefault(),V(i-1),E.setAttribute("aria-valuenow",i+1),E.setAttribute("aria-valuetext",o[i].label)):"Home"===e.key?(e.preventDefault(),V(0),E.setAttribute("aria-valuenow",1),E.setAttribute("aria-valuetext",o[0].label)):"End"===e.key&&(e.preventDefault(),V(4),E.setAttribute("aria-valuenow",5),E.setAttribute("aria-valuetext",o[4].label))}),function(){if(!(window.innerWidth>767)){var e=document.querySelector(".wm-tone-card");if(e){var t=document.createElement("div");t.className="wm-tone-chips";for(var n=0;n<o.length;n++)(function(e){var n=document.createElement("button");n.type="button",n.className="wm-tone-chip"+(e===i?" active":""),n.textContent=o[e].label,n.addEventListener("click",function(){V(e)}),t.appendChild(n)})(n);e.appendChild(t)}}}(),x.addEventListener("input",J),T.addEventListener("input",J);var K=!1;y&&y.addEventListener("click",function(){ne(re)}),k.addEventListener("click",function(){ne(function(){te()?Q():ee()})}),S&&S.addEventListener("click",function(){ne(function(){te()?Q():ee()})}),h&&h.addEventListener("keydown",function(e){"Escape"!==e.key||e.defaultPrevented||(e.stopPropagation(),ne(function(){te()?Q():ee()}),setTimeout(function(){var e=document.getElementById("wm-start-notes");e&&null!==e.offsetParent?e.focus():window.quill1&&"function"==typeof window.quill1.focus&&window.quill1.focus()},120))});var D=null,P="";!function(){var e=document.getElementById("wm-lang-compact-btn"),t=document.getElementById("wm-lang-compact-menu");if(t){t.innerHTML="";for(var n=0;n<s.length;n++)t.appendChild(ue(s[n],e));var r=document.createElement("li");r.setAttribute("role","separator"),r.className="wm-lang-divider",t.appendChild(r);var o=document.createElement("li");o.setAttribute("role","presentation");var i=document.createElement("button");i.type="button",i.className="wm-lang-more-toggle",i.id="wm-lang-compact-more",i.setAttribute("aria-expanded","false"),i.setAttribute("aria-controls","wm-lang-compact-more-section"),i.innerHTML="<span>"+("function"==typeof SKT?SKT("wm.more_langs","Flere sprogâ¦"):"Flere sprogâ¦")+'</span><svg class="wm-lang-more-chevron" width="8" height="5" viewBox="0 0 8 5" fill="none"><path d="M1 1L4 4L7 1" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',i.addEventListener("click",function(e){e.preventDefault(),e.stopPropagation();var t=document.getElementById("wm-lang-compact-more-section");if(t){var n=t.classList.toggle("wm-lang-more-open");i.classList.toggle("wm-lang-more-active",n),i.setAttribute("aria-expanded",n?"true":"false")}}),i.addEventListener("keydown",function(t){"ArrowDown"===t.key?(t.preventDefault(),se(1)):"ArrowUp"===t.key?(t.preventDefault(),se(-1)):"Home"===t.key?(t.preventDefault(),ce(0)):"End"===t.key?(t.preventDefault(),ce(-1)):"Escape"!==t.key&&"Tab"!==t.key||(t.preventDefault(),oe(),e&&e.focus())}),o.appendChild(i),t.appendChild(o);var l=document.createElement("li");l.setAttribute("role","presentation");var d=document.createElement("div");d.className="wm-lang-more-section",d.id="wm-lang-compact-more-section",d.setAttribute("role","group"),d.setAttribute("aria-label","function"==typeof SKT?SKT("wm.more_langs","Flere sprog"):"Flere sprog");for(var u=0;u<c.length;u++)d.appendChild(ue(c[u],e));l.appendChild(d),t.appendChild(l),ae(a.outputLang),e&&(e.addEventListener("click",function(e){e.stopPropagation(),t.classList.contains("hidden")?ie():oe()}),e.addEventListener("keydown",function(e){"Enter"===e.key||" "===e.key||"ArrowDown"===e.key?(e.preventDefault(),ie(),se(0)):"ArrowUp"===e.key?(e.preventDefault(),ie(),se(-1)):"Escape"===e.key&&oe()}))}}(),document.addEventListener("click",function(e){var t=document.getElementById("wm-lang-compact-menu");!t||t.classList.contains("hidden")||e.target.closest("#wm-lang-compact-wrap")||oe()}),document.addEventListener("pointerdown",function(e){var t=document.getElementById("wm-lang-compact-menu");!t||t.classList.contains("hidden")||e.target.closest("#wm-lang-compact-wrap")||oe()});var N="",j="",R=4,F="Danish",O="",U=!1,$="ss_stikord_state";!function(){var e=function(){try{var e=sessionStorage.getItem($);if(!e)return null;var t=JSON.parse(e);return!t||Date.now()-t.ts>36e5?(me(),null):t}catch(e){return null}}();if(e){if(e.task&&x&&(x.value=e.task,r(x),G(x)),e.content&&T&&(T.value=e.content,r(T),G(T)),null!=e.tone&&V(e.tone),e.outputLang)f(e.outputLang),a.outputLangExplicit=!0===e.outputLangExplicit,ae(a.outputLang);else if(e.lang){var t=function(e){for(var t=d(),n=0;n<t.length;n++)if(t[n].apiName===e)return t[n];return null}(e.lang);t&&(f(u(t)),ae(a.outputLang))}J()}}(),window.addEventListener("ss:lang-changed",function(){U&&setTimeout(function(){if("function"==typeof SKT){for(var e=0;e<o.length;e++)o[e].sktLabel&&(o[e].label=SKT(o[e].sktLabel)),o[e].sktDesc&&(o[e].desc=SKT(o[e].sktDesc));var t=document.getElementById("wm-kladde-container");t&&"none"!==t.style.display&&(t.setAttribute("aria-label",fe("wm.kladde_ready","Din kladde er klar")),t.innerHTML=ge(),he(t))}},0)}),L.addEventListener("click",function(){_();var t=x.value.trim(),n=T.value.trim();(t||n)&&(!window.MarketingAdapter||MarketingAdapter.canUse("skrivebord")?(L.classList.add("loading"),L.disabled=!0,N=t,j=n,R=i,F=m(),pe(),b(t,n,i,m()).then(function(t){var n,r=t&&"object"==typeof t?t.text||"":t||"";O=r,window.MarketingAdapter&&MarketingAdapter.track("skrivebord"),ye(r),(n=document.getElementById("wm-meaning-review"))&&n.parentNode&&n.parentNode.removeChild(n),ee(),function(){U=!0;var t=document.getElementById("wm-kladde-container");if(t){var n=document.querySelector(".correction-sidebar");
3if(n&&n.classList.add("kladde-active"),t.setAttribute("aria-label",fe("wm.kladde_ready","Din kladde er klar")),t.innerHTML=ge(),t.style.display="flex",e()&&"function"==typeof window.openMobileAiSheet){var r=document.getElementById("skrivebord-mobile-sheet-body");r&&t.parentElement!==r&&r.appendChild(t),window.openMobileAiSheet("kladde")}he(t),pe()}}(),function(){if(a.outputLangExplicit)try{for(var e=p(a.outputLang),t=document.querySelectorAll(".dk-dropdown-item"),n=null,r=0;r<t.length;r++)if(t[r].getAttribute("data-lang")===e.daName){if(!t[r].classList.contains("dk-search-only")){n=t[r];break}n||(n=t[r])}n&&!n.classList.contains("dk-selected")&&n.click()}catch(e){}}()}).catch(function(e){console.error("Writing mode error:",e),"word_limit_exceeded"!==e.message&&alert(fe("wm.kladde_error","Noget gik galt. Prøv igen."))}).finally(function(){L.classList.remove("loading"),J()})):window._showDemoLimit&&window._showDemoLimit())}),t.on("text-change",function(e,t,n){h.classList.contains("hidden")&&("user"===n&&U&&ve(),te()?Q():ee())}),document.addEventListener("skrivebord:stt-preview-change",function(){h.classList.contains("hidden")&&(te()?Q():ee())}),setTimeout(function(){h.classList.contains("hidden")&&(te()?Q():ee())},1500),document.addEventListener("skrivebord:editor-cleared",function(){te()?Q():ee(),requestAnimationFrame(function(){te()&&g.classList.contains("hidden")&&Q()})})}function z(e){e&&(e.addEventListener("input",function(){r(e)}),e.addEventListener("paste",function(){setTimeout(function(){r(e)},0)}),e.addEventListener("cut",function(){setTimeout(function(){r(e)},0)}),r(e))}function G(e){if(e){var t=e.closest(".wm-textarea-wrap");if(t){var n=t.querySelector(".wm-clear-btn");n&&n.classList.toggle("visible",e.value.length>0)}}}function V(e){var t=(i=Math.max(0,Math.min(4,e)))/4*100;C.style.left=t+"%",M.style.width=t+"%",A.textContent=o[i].label,q.textContent=o[i].desc,E.setAttribute("aria-valuenow",i+1),E.setAttribute("aria-valuetext",o[i].label);for(var n=document.querySelectorAll(".wm-tone-chip"),r=0;r<n.length;r++)n[r].classList.toggle("active",r===i)}function W(e){var t=E.getBoundingClientRect(),n=(e-t.left)/t.width;V(Math.round(4*n))}function J(){var e=void 0!==Y&&Y.selectedId&&"self"!==Y.selectedId;L.disabled=e?!T.value.trim():!(x.value.trim()||T.value.trim())}function Q(){_(),e()?ee():(g.classList.remove("hidden"),h.classList.add("hidden"),document.body.classList.remove("wm-form-open"),l&&l.classList.remove("editor-empty"),document.dispatchEvent(new CustomEvent("wm-form-state",{detail:{open:!1}})))}function X(n){if(e())return ee(),void(t&&"function"==typeof t.focus&&t.focus());g.classList.add("hidden"),h.classList.remove("hidden"),document.body.classList.add("wm-form-open"),l&&l.classList.add("editor-empty"),n&&(x.value=n,r(x),J()),r(x),r(T),x.focus(),"function"==typeof syncFromGrammarBot&&syncFromGrammarBot(),de(),document.dispatchEvent(new CustomEvent("wm-form-state",{detail:{open:!0}}))}function ee(){_(),g.classList.add("hidden"),h.classList.add("hidden"),document.body.classList.remove("wm-form-open"),l&&l.classList.remove("editor-empty"),document.dispatchEvent(new CustomEvent("wm-form-state",{detail:{open:!1}}))}function te(){return 0===t.getText().trim().length}function ne(e){K||(K=!0,e(),setTimeout(function(){K=!1},100))}function re(){X(""),setTimeout(function(){T&&T.focus()},40)}function oe(){var e=document.getElementById("wm-lang-compact-wrap"),t=document.getElementById("wm-lang-compact-btn"),n=document.getElementById("wm-lang-compact-menu");e&&e.classList.remove("wm-lang-open"),n&&n.classList.add("hidden"),t&&t.setAttribute("aria-expanded","false");var r=document.getElementById("wm-lang-compact-more-section"),o=document.getElementById("wm-lang-compact-more");r&&r.classList.remove("wm-lang-more-open"),o&&(o.classList.remove("wm-lang-more-active"),o.setAttribute("aria-expanded","false"))}function ie(){var e=document.getElementById("wm-lang-compact-wrap"),t=document.getElementById("wm-lang-compact-btn"),n=document.getElementById("wm-lang-compact-menu");if(e&&e.classList.add("wm-lang-open"),n&&n.classList.remove("hidden"),t&&t.setAttribute("aria-expanded","true"),function(e){for(var t=0;t<c.length;t++)if(u(c[t])===e)return!0;return!1}(a.outputLang)){var r=document.getElementById("wm-lang-compact-more-section"),o=document.getElementById("wm-lang-compact-more");r&&r.classList.add("wm-lang-more-open"),o&&(o.classList.add("wm-lang-more-active"),o.setAttribute("aria-expanded","true"))}}function ae(e){var t=f(e),n=document.getElementById("wm-lang-compact-name");n&&(n.textContent=t.endonym);for(var r=document.querySelectorAll('#wm-lang-compact-menu [role="option"]'),o=0;o<r.length;o++){var i=r[o].getAttribute("data-lang")===a.outputLang;r[o].setAttribute("aria-selected",i?"true":"false");var l=r[o].querySelector(".wm-lang-compact-option");l&&l.classList.toggle("selected",i)}}function le(e){var t=f(e);a.outputLangExplicit=!0,ae(t.code||u(t)),oe(),document.dispatchEvent(new CustomEvent("wm:outputLangChange",{detail:{code:a.outputLang,name:t.endonym}}))}function se(e){var t=document.querySelectorAll("#wm-lang-compact-menu .wm-lang-compact-option");if(t.length){for(var n=document.activeElement,r=0,o=0;o<t.length;o++)if(t[o]===n){r=o+e;break}r<0&&(r=t.length-1),r>=t.length&&(r=0),t[r].focus()}}function ce(e){var t=document.querySelectorAll("#wm-lang-compact-menu .wm-lang-compact-option");t.length&&t[-1===e?t.length-1:0].focus()}function ue(e,t){var n=document.createElement("li"),r=u(e);n.setAttribute("role","option"),n.setAttribute("data-lang",r),n.setAttribute("aria-selected",r===a.outputLang?"true":"false");var o=document.createElement("button");return o.type="button",o.className="wm-lang-compact-option"+(r===a.outputLang?" selected":""),o.setAttribute("data-da",e.daName),o.textContent=e.endonym,o.addEventListener("click",function(e){e.stopPropagation(),le(r)}),o.addEventListener("keydown",function(e){"ArrowDown"===e.key?(e.preventDefault(),se(1)):"ArrowUp"===e.key?(e.preventDefault(),se(-1)):"Home"===e.key?(e.preventDefault(),ce(0)):"End"===e.key?(e.preventDefault(),ce(-1)):"Enter"===e.key||" "===e.key?(e.preventDefault(),le(r)):"Escape"===e.key||"Tab"===e.key?(e.preventDefault(),oe(),t&&t.focus()):"string"!=typeof e.key||1!==e.ke
3y.length||e.ctrlKey||e.metaKey||function(e){P+=e.toLowerCase(),clearTimeout(D),D=setTimeout(function(){P=""},500);for(var t=document.querySelectorAll("#wm-lang-compact-menu .wm-lang-compact-option"),n=0;n<t.length;n++)if(0===(t[n].textContent||"").toLowerCase().indexOf(P)){t[n].focus();break}}(e.key)}),n.appendChild(o),n}function pe(){try{sessionStorage.setItem($,JSON.stringify({task:x.value,content:T.value,tone:i,outputLang:a.outputLang,outputLangExplicit:a.outputLangExplicit,ts:Date.now()}))}catch(e){}}function me(){try{sessionStorage.removeItem($)}catch(e){}}function fe(e,t){if("function"!=typeof SKT)return t;var n=SKT(e);return n&&n!==e?n:t}function ge(){var e=null!=R?R:i,t=e/4*100;return'<div id="wm-kladde-panel" class="wm-kladde-panel"><div class="wm-kladde-header"><svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 013 3L7 19l-4 1 1-4 12.5-12.5z"/></svg><span>'+fe("wm.kladde_ready","Din kladde er klar")+'</span></div><div class="wm-kladde-commit"><button type="button" class="wm-kladde-btn wm-kladde-btn--commit" id="wm-kladde-commit"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg><span>'+fe("wm.kladde_commit","Behold og redigér")+'</span></button></div><button type="button" class="wm-kladde-adjust-toggle" id="wm-kladde-adjust-toggle" aria-expanded="false" aria-controls="wm-kladde-adjust"><span>'+fe("wm.kladde_adjust","Ret teksten")+'</span><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 9l6 6 6-6"/></svg></button><div class="wm-kladde-adjust" id="wm-kladde-adjust" hidden><div class="wm-kladde-refine"><button type="button" class="wm-kladde-refine-btn" data-refine="simpler"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M8 14s1.5 2 4 2 4-2 4-2"/><line x1="9" y1="9" x2="9.01" y2="9"/><line x1="15" y1="9" x2="15.01" y2="9"/></svg><span>'+fe("wm.kladde_simpler","Enklere")+'</span></button><button type="button" class="wm-kladde-refine-btn" data-refine="shorter"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 9l6 6 6-6"/></svg><span>'+fe("wm.kladde_shorten","Forkort")+'</span></button><button type="button" class="wm-kladde-refine-btn" id="wm-kladde-regen"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/></svg><span>'+fe("wm.kladde_regen","Generér igen")+'</span></button></div><div class="wm-kladde-section"><div class="wm-kladde-label">'+fe("wm.tone_landmark","Vælg tonefald")+'</div><div class="wm-kladde-tone-value" id="wm-kladde-tone-label">'+o[e].label+'</div><div class="wm-kladde-tone-desc" id="wm-kladde-tone-desc">'+o[e].desc+'</div><input type="range" class="wm-kladde-tone-range" id="wm-kladde-tone-range" min="0" max="4" step="1" value="'+e+'" aria-label="'+fe("wm.tone_range_aria","Tonefald")+'" style="--calm-slider-pct:'+t+'%"><div class="wm-kladde-tone-endpoints"><span>'+fe("wm.tone_min","Uformel")+"</span><span>"+fe("wm.tone_max","Professionel")+'</span></div></div></div><div class="wm-kladde-footer"><button type="button" class="wm-kladde-tone-pill" id="wm-kladde-tone-pill" aria-label="'+fe("wm.tone_range_aria","Tonefald")+'"><svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2"><line x1="4" y1="21" x2="4" y2="14"/><line x1="4" y1="10" x2="4" y2="3"/><line x1="12" y1="21" x2="12" y2="12"/><line x1="12" y1="8" x2="12" y2="3"/><line x1="20" y1="21" x2="20" y2="16"/><line x1="20" y1="12" x2="20" y2="3"/><line x1="1" y1="14" x2="7" y2="14"/><line x1="9" y1="8" x2="15" y2="8"/><line x1="17" y1="16" x2="23" y2="16"/></svg><span id="wm-kladde-tone-pill-label">'+o[e].label+'</span></button><button type="button" class="wm-kladde-footer-link" id="wm-kladde-back">'+fe("wm.kladde_back","Skift stikord")+"</button></div></div>"}function he(e){var t=e.querySelector("#wm-kladde-tone-range"),n=null!=R?R:i;function r(t){var n=e.querySelector("#wm-kladde-panel")||e,r=n.querySelector(".calm-kladde-error");r&&r.remove();var o=document.createElement("div");
3o.className="calm-kladde-error",o.setAttribute("role","alert"),o.textContent=t;var i=n.querySelector(".wm-kladde-commit");i?i.insertAdjacentElement("afterend",o):n.appendChild(o),setTimeout(function(){o.parentNode&&o.remove()},6e3)}t&&t.addEventListener("input",function(){var r,i,a,l,s;r=parseInt(t.value,10),i=(n=Math.max(0,Math.min(4,r)))/4*100,a=e.querySelector("#wm-kladde-tone-label"),l=e.querySelector("#wm-kladde-tone-desc"),s=e.querySelector("#wm-kladde-tone-pill-label"),a&&(a.textContent=o[n].label),l&&(l.textContent=o[n].desc),s&&(s.textContent=o[n].label),t&&(t.value=n,t.style.setProperty("--calm-slider-pct",i+"%"))});var l=e.querySelector("#wm-kladde-adjust-toggle"),s=e.querySelector("#wm-kladde-adjust");function c(e){l&&s&&(l.setAttribute("aria-expanded",e?"true":"false"),e?s.removeAttribute("hidden"):s.setAttribute("hidden",""))}l&&l.addEventListener("click",function(){c("true"!==l.getAttribute("aria-expanded"))});var d=e.querySelector("#wm-kladde-tone-pill");d&&d.addEventListener("click",function(){c(!0),t&&t.focus()});var u=e.querySelector("#wm-kladde-panel")||e;function p(){u.classList.add("loading")}function f(){u.classList.remove("loading")}var g=e.querySelector("#wm-kladde-regen");g&&g.addEventListener("click",function(){p(),R=n,b(N,j,n).then(function(e){var t=e&&"object"==typeof e?e.text||"":e||"";O=t,ye(t)}).catch(function(e){console.error("Kladde regen error:",e),"word_limit_exceeded"!==e.message&&r(fe("wm.kladde_error","Noget gik galt. Prøv igen."))}).finally(function(){f()})});var h=e.querySelector("#wm-kladde-back");h&&h.addEventListener("click",function(){V(n),ve(),X(),document.dispatchEvent(new CustomEvent("wm-form-state",{detail:{open:!0}}))});for(var v=e.querySelectorAll(".wm-kladde-refine-btn[data-refine]"),y=0;y<v.length;y++)v[y].addEventListener("click",function(){var e,t,n,o,i,l,s=this.getAttribute("data-refine");p(),(e=N,t=j,n=R,o=F,i=O,l=s,w({task:e,content:t,tone:n+1,language:o||m(),language_code:a.outputLang,action:"refine",refine_type:l,original_text:i})).then(function(e){var t=e&&"object"==typeof e?e.text||"":e||"";O=t,ye(t)}).catch(function(e){console.error("Kladde refine error:",e),"word_limit_exceeded"!==e.message&&r(fe("wm.kladde_error","Noget gik galt. Prøv igen."))}).finally(function(){f()})});var k=e.querySelector("#wm-kladde-commit");k&&k.addEventListener("click",function(){me(),ve()})}function ve(){U=!1;var t=document.querySelector(".correction-sidebar");t&&t.classList.remove("kladde-active");var n=document.getElementById("wm-kladde-container");n&&(n.style.display="none",n.innerHTML="",t&&n.parentElement!==t&&t.appendChild(n)),e()&&"function"==typeof window.closeMobileAiSheet&&window.closeMobileAiSheet(),Z()}function ye(e){t.setText("","silent"),t.clipboard.dangerouslyPasteHTML(0,function(e){for(var t=(new DOMParser).parseFromString(e,"text/html"),n=t.body.querySelectorAll("*"),r=0;r<n.length;r++){var o=n[r],i=o.tagName.toLowerCase();if(-1===["script","iframe","object","embed","form","style"].indexOf(i)){for(var a=[],l=0;l<o.attributes.length;l++)a.push(o.attributes[l].name);for(var s=0;s<a.length;s++)0!==a[s].indexOf("on")&&"srcdoc"!==a[s]&&"data"!==a[s]||o.removeAttribute(a[s])}else o.parentNode.removeChild(o)}return t.body.innerHTML}(e),"api")}});var k=null,S=se(),x=null,T=null,L=null;function E(e,t){if(e){var n=document.querySelectorAll(".wm-form .wm-mic-btn.ss-mic");"connecting"===t?(n.forEach(function(t){t===e?(t.setAttribute("data-mic-state","preparing"),t.removeAttribute("data-listening")):(t.removeAttribute("data-mic-state"),t.removeAttribute("data-listening"))}),L&&clearTimeout(L),L=setTimeout(function(){"preparing"===e.getAttribute("data-mic-state")&&e.removeAttribute("data-mic-state"),L=null},2e3)):"listening"===t?(L&&(clearTimeout(L),L=null),n.forEach(function(t){if(t===e){t.removeAttribute("data-mic-state"),t.setAttribute("data-listening","true"),t.setAttribute("aria-pressed","true");var n="wm-mic-task"===t.id;t.setAttribute("aria-label",n?"Stop diktering af opgave":"Stop diktering af stikord")}else t.removeAttribute("data-mic-state"),t.removeAttribute("data-listening"),t.setAttribute("aria-pressed","fal
3se")})):(L&&(clearTimeout(L),L=null),n.forEach(function(e){e.removeAttribute("data-mic-state"),e.removeAttribute("data-listening"),e.setAttribute("aria-pressed","false");var t="wm-mic-task"===e.id;e.setAttribute("aria-label",t?"function"==typeof SKT?SKT("wm.dictate_task"):"Dikter opgave":"function"==typeof SKT?SKT("wm.dictate_content"):"Dikter stikord")}))}}function C(e,t){x!==e?(x&&_(),x=e,T=t,k=le({button:e,idleAriaLabel:e.getAttribute("aria-label")||"Tale-til-tekst",service:"chat",lang:n(),onTranscript:function(e){S.remove();var t=T;if(t&&e){var n=t.selectionStart||t.value.length,o=t.value.substring(0,n),i=t.value.substring(t.selectionEnd||n),a=(!o||o.endsWith(" ")||o.endsWith("\n")?"":" ")+e;t.value=o+a+i;var l=n+a.length;t.selectionStart=t.selectionEnd=l,t.dispatchEvent(new Event("input",{bubbles:!0})),r(t)}},onPartial:function(e){T&&S.renderInField(T,e)},onError:function(){_()},onStateChange:function(e){E(x,e),"idle"!==e&&"error"!==e||(S.remove(),x=null,T=null)}}),k.start()):_()}function _(){k&&(k.stop(),k=null),x&&(E(x,"off"),x=null),T=null}function A(){!function(){var e=document.getElementById("calm-wm-form-polish");e&&e.remove();var t=document.getElementById("calm-wm-form-mic-trash");t&&t.remove();var n=document.createElement("style");n.id="calm-wm-form-polish",n.textContent='.text-area-container .wm-form { padding: 28px 22px !important; display: flex !important; flex-direction: column !important; justify-content: flex-start !important; align-items: center !important; }.text-area-container .wm-form .wm-form-inner { flex: 0 0 auto !important; width: 100% !important; max-width: 520px !important; }.text-area-container .wm-form .wm-form-header > span:first-of-type { font-size: 13px !important; font-weight: 600 !important; text-transform: none !important; letter-spacing: 0 !important; color: #5C4D43 !important; }.text-area-container .wm-form .wm-section-divider { display: block !important; font-size: 12px !important; font-weight: 600 !important; text-transform: none !important; letter-spacing: 0 !important; color: #5C4D43 !important; margin-top: 18px !important; margin-bottom: 8px !important; }.text-area-container .wm-form .wm-fields-card { background: var(--color-card, #FFFEFB) !important; border-radius: 14px !important; border: 1px solid rgba(58,47,38,0.06) !important; box-shadow: none !important; padding: 4px 0 !important; overflow: visible !important; }.text-area-container .wm-form .wm-fields-card .wm-field { padding: 12px 14px !important; }.text-area-container .wm-form .wm-fields-card .wm-field + .wm-field { border-top: 1px solid rgba(58,47,38,0.06) !important; }.text-area-container .wm-form .wm-field > label { font-size: 12px !important; font-weight: 600 !important; color: #5C4D43 !important; margin-bottom: 4px !important; display: block !important; }.text-area-container .wm-form .wm-tone-card { background: var(--color-card, #FFFEFB) !important; border-radius: 14px !important; border: 1px solid rgba(58,47,38,0.06) !important; box-shadow: none !important; padding: 14px 16px !important; }.text-area-container .wm-form .wm-tone-current { font-size: 14.5px !important; font-weight: 650 !important; color: #3A2F26 !important; }.text-area-container .wm-form .wm-tone-desc { font-size: 13px !important; font-weight: 400 !important; color: #9A8E82 !important; }.text-area-container .wm-form .wm-tone-endpoints span { font-size: 12px !important; font-weight: 400 !important; color: #9A8E82 !important; }.text-area-container .wm-form .wm-tone-track { height: 4px !important; background: rgba(154,142,130,0.25) !important; border-radius: 2px !important; position: relative !important; }.text-area-container .wm-form .wm-tone-progress { height: 100% !important; background: #6E8A7E !important; border-radius: 2px !important; }.text-area-container .wm-form .wm-tone-thumb { width: 18px !important; height: 18px !important; background: #fff !important; border: 2px solid #6E8A7E !important; border-radius: 50% !important; box-shadow: 0 1px 3px rgba(58,47,38,0.14) !important; position: absolute !important; top: 50% !important; transform: translateY(-50%) !important; margin-left: -9px !important; }.text-area-container .wm-form .wm-submit { min-height: 52px !important; border-radius: 16px !important; background: #6E8A7E !important; color: #fff !important; font-size: 14px !important; font-weight: 650 !important; box-shadow: 0 1px 2px rgba(58,47,38,0.06), 0 6px 18px rgba(110,138,126,0.22) !important; margin-top: 30px !important; }.text-area-container .wm-form .wm-submit:disabled { opacity: 0.4
3!important; }.text-area-container .wm-form .wm-submit:hover:not(:disabled) { background: #4A7A68 !important; }.text-area-container .wm-form .wm-lang-field .wm-language-row { width: 100% !important; margin: 0 !important; justify-content: flex-start !important; }.text-area-container .wm-form .wm-lang-compact-wrap { width: auto !important; }.text-area-container .wm-form .wm-lang-compact-btn { width: auto !important; background: transparent !important; border-radius: 12px !important; padding: 10px 12px !important; border: 1px solid rgba(58,47,38,0.08) !important; color: #9A8E82 !important; }.text-area-container .wm-form .wm-lang-compact-btn:hover { color: #5C4D43 !important; border-color: rgba(58,47,38,0.12) !important; }.text-area-container .wm-form .wm-collapse-btn { width: 32px !important; height: 32px !important; border-radius: 10px !important; background: transparent !important; border: none !important; color: #9A8E82 !important; display: flex !important; align-items: center !important; justify-content: center !important; }.text-area-container .wm-form .wm-collapse-btn:hover { background: rgba(58,47,38,0.04) !important; color: #5C4D43 !important; }.text-area-container .wm-form .wm-clear-btn, .text-area-container .wm-form .wm-clear-btn.visible { display: none !important; }.text-area-container .wm-form #wm-recording-indicator, .text-area-container .wm-form .wm-recording-indicator.visible, .text-area-container .wm-form #wm-recording-indicator.visible { display: none !important; }.text-area-container .wm-form .wm-textarea-wrap textarea { padding-right: 48px !important; padding-bottom: 12px !important; }.text-area-container .wm-form .wm-textarea-wrap .wm-mic-btn.ss-mic {position: absolute !important; top: 50% !important; right: 18px !important; bottom: auto !important;transform: translateY(-50%) !important;width: 32px !important; height: 32px !important; min-width: 32px !important; min-height: 32px !important;padding: 0 !important; border-radius: 10px !important;display: flex !important; align-items: center !important; justify-content: center !important;background: transparent !important; border: 1px solid transparent !important;color: #5C4D43 !important; box-shadow: none !important;transition: background 160ms ease, border-color 160ms ease, color 160ms ease, box-shadow 160ms ease !important;cursor: pointer !important; z-index: 1 !important;}.text-area-container .wm-form .wm-textarea-wrap .wm-mic-btn.ss-mic#wm-mic-content {top: auto !important; bottom: 22px !important; right: 18px !important; transform: none !important;}.text-area-container .wm-form .wm-textarea-wrap .wm-mic-btn.ss-mic::before,.text-area-container .wm-form .wm-textarea-wrap .wm-mic-btn.ss-mic::after { content: none !important; pointer-events: none !important; }.text-area-container .wm-form .wm-textarea-wrap .wm-mic-btn.ss-mic svg.lucide-mic { width: 16px !important; height: 16px !important; }.text-area-container .wm-form .wm-textarea-wrap .wm-mic-btn.ss-mic .wm-mic-label { display: none !important; }.text-area-container .wm-form .wm-textarea-wrap .wm-mic-btn.ss-mic:hover {background: rgba(58,47,38,0.05) !important; border-color: rgba(58,47,38,0.10) !important; color: #3A2F26 !important;}.text-area-container .wm-form .wm-textarea-wrap .wm-mic-btn.ss-mic:focus-visible {outline: 2px solid rgba(110,138,126,0.30) !important; outline-offset: 2px !important; border-color: #6E8A7E !important; box-shadow: none !important;}.text-area-container .wm-form .wm-textarea-wrap .wm-mic-btn.ss-mic[data-mic-state="preparing"] {background: rgba(110,138,126,0.06) !important; border-color: rgba(110,138,126,0.18) !important; color: #6E8A7E !important;}.text-area-container .wm-form .wm-textarea-wrap .wm-mic-btn.ss-mic[data-mic-state="preparing"] svg.lucide-mic { opacity: 0.4 !important; }.text-area-container .wm-form .wm-textarea-wrap .wm-mic-btn.ss-mic[data-mic-state="preparing"]::before {content: "" !important; position: absolute !important; inset: 4px !important; border-radius: 11px !important;border: 2px solid transparent !important; border-top-color: #6E8A7E !important;animation: calmWmMicSpin 0.8s linear infinite !important;}.text-area-container .wm-form .wm-textarea-wrap .wm-mic-btn.ss-mic[data-listening="true"] {background: rgba(110,138,126,0.10) !important; border-color: rgba(110,138,126,0.35) !important; color: #4A7A68 !important;}.text-area-container .wm-form .wm-textarea-wrap .wm-mic-btn.ss-mic[data-listening="true"]::after {content: "" !important; position: absolute !important; inset: 3px !important; border-radius: 12px !important;border: 1.5px solid rgba(110,138,126,0.30) !important;animation: calmWmMicPulse 2s ease-in-out infinite !important;}@keyframes calmWmMicSpin { to { transform: rotate(360deg); } }@keyframes calmWmMicPulse { 0%,100% { opacity:0.4; transform:scale(1); } 50% { opacity:1; transform:scale(1.06); } }.text-area-container .wm-form .wm-collapse-btn:focus-visible,.text-area-container .wm-form textarea:focus-visible,.text-area-container .wm-form .wm-tone-track:focus-visible,.text-area-container .wm-form .wm-submit:focus-visible,.text-area-container .wm-form .wm-lang-compact-btn:focus-visible {outline: 2px solid rgba(110,138,126,0.30) !important; outline-width: 2px !important; outline-style: solid !important; outline-color: rgba(110,138,126,0.30) !important; outline-offset: 2px !important; box-shadow: none !important;}.text-area-container .wm-form #wm-collapse:focus-visible,.text-area-container .wm-form #wm-tone-track:focus-visible {outline: 2px solid rgba(110,138,126,0.30) !important; outline-width: 2px !important; outline-style: solid !important; outline-color: rgba(110,138,126,0.30) !important; outline-offset: 2px !important; box-shadow: none !important;}.text-area-container .wm-form #wm-tone-track:focus {outline: 2px solid rgba(110,138,126,0.30) !important; outline-width: 2px !important; outline-style: solid !important; outline-color: rgba(110,138,126,0.30) !important; outline-offset: 2px !important; box-shadow: 0 0 0 2px rgba(110,138,126,0.30) !important;}@media (prefers-reduced-motion: reduce) {.text-area-container .wm-form .wm-textarea-wrap .wm-mic-btn.ss-mic[data-mic-state="preparing"]::before { animation: none !important; border-color: #6E8A7E !important; }.text-area-container .wm-form .wm-textarea-wrap .wm-mic-btn.ss-mic[data-listening="true"]::after { animation: none !important; opacity: 1 !important; }}@media (max-width: 768px) {.text-area-container .wm-form .wm-textarea-wrap .wm-mic-btn.ss-mic {width: 32px !important; height: 32px !important; min-width: 32px !important; min-height: 32px !important;padding: 0 !important; border-radius: 10px !important;background: transparent !important; border: 1px solid transparent !important;}.text-area-container .wm-form .wm-textarea-wrap .wm-mic-btn.ss-mic .wm-mic-label { display: none !important; }.text-area-container .wm-form .wm-textarea-wrap .wm-mic-btn.ss-mic
3svg.lucide-mic { width: 16px !important; height: 16px !important; }}[data-theme="dark"] .text-area-container .wm-form .wm-form-header > span:first-of-type { color: rgba(232,230,225,0.7) !important; }[data-theme="dark"] .text-area-container .wm-form .wm-section-divider { color: rgba(232,230,225,0.5) !important; }[data-theme="dark"] .text-area-container .wm-form .wm-fields-card { background: rgba(255,255,255,0.04) !important; border-color: rgba(255,255,255,0.08) !important; box-shadow: 0 1px 3px rgba(20,18,15,0.2), 0 2px 8px rgba(20,18,15,0.15) !important; }[data-theme="dark"] .text-area-container .wm-form .wm-fields-card .wm-field + .wm-field { border-color: rgba(255,255,255,0.06) !important; }[data-theme="dark"] .text-area-container .wm-form .wm-field > label { color: var(--color-text-secondary, #a3a19b) !important; }[data-theme="dark"] .text-area-container .wm-form .wm-tone-card { background: transparent !important; border: none !important; box-shadow: none !important; }[data-theme="dark"] .text-area-container .wm-form .wm-tone-current { color: #fff !important; }[data-theme="dark"] .text-area-container .wm-form .wm-tone-desc { color: rgba(232,230,225,0.55) !important; }[data-theme="dark"] .text-area-container .wm-form .wm-tone-endpoints span { color: rgba(232,230,225,0.45) !important; }[data-theme="dark"] .text-area-container .wm-form .wm-tone-track { background: rgba(255,255,255,0.10) !important; }[data-theme="dark"] .text-area-container .wm-form .wm-tone-progress { background: linear-gradient(90deg, rgba(255,255,255,0.25) 0%, rgba(255,255,255,0.4) 100%) !important; }[data-theme="dark"] .text-area-container .wm-form .wm-tone-thumb { background: var(--color-card, #2b2a27) !important; border-color: #a3a19b !important; box-shadow: 0 1px 4px rgba(20,18,15,0.3), 0 2px 8px rgba(163,161,155,0.25) !important; }[data-theme="dark"] .text-area-container .wm-form .wm-submit { background: rgba(110,138,126,0.25) !important; color: #fff !important; border: none !important; box-shadow: 0 1px 4px rgba(20,18,15,0.3) !important; }[data-theme="dark"] .text-area-container .wm-form .wm-submit:hover:not(:disabled) { background: rgba(110,138,126,0.35) !important; box-shadow: 0 2px 8px rgba(20,18,15,0.35) !important; }[data-theme="dark"] .text-area-container .wm-form .wm-lang-compact-btn { background: rgba(255,255,255,0.06) !important; border: 1px solid rgba(255,255,255,0.08) !important; border-radius: 18px !important; color: rgb(200,190,178) !important; }[data-theme="dark"] .text-area-container .wm-form .wm-lang-compact-btn:hover { background: rgba(212,168,154,0.12) !important; border-color: rgba(212,168,154,0.25) !important; color: #E8DDD4 !important; }[data-theme="dark"] .text-area-container .wm-form .wm-lang-compact-wrap.wm-lang-open .wm-lang-compact-btn { background: rgba(212,168,154,0.15) !important; border-color: rgba(212,168,154,0.3) !important; color: #E8DDD4 !important; }[data-theme="dark"] .text-area-container .wm-form .wm-collapse-btn { background: rgba(255,255,255,0.08) !important; color: rgba(232,230,225,0.6) !important; }[data-theme="dark"] .text-area-container .wm-form .wm-collapse-btn:hover { background: rgba(255,255,255,0.12) !important; }[data-theme="dark"] .text-area-container .wm-form .wm-textarea-wrap .wm-mic-btn.ss-mic { background: rgba(74,122,104,0.12) !important; border-color: rgba(74,122,104,0.25) !important; color: #6db89e !important; }',document.head.appendChild(n);var r=document.querySelector(".wm-form");r&&r.setAttribute("data-calm-applied","wm-form")}();var e=document.getElementById("wm-mic-task"),t=document.getElementById("wm-mic-content"),n=document.getElementById("wm-task"),r=document.getElementById("wm-content");[e,t].forEach(function(e){e&&e.setAttribute("aria-pressed","false")}),e&&n&&e.addEventListener("click",function(t){t.preventDefault(),C(e,n)}),t&&r&&t.addEventListener("click",function(e){e.preventDefault(),C(t,r)})}window.addEventListener("ss:lang-changed",function(){if("function"==typeof SKT){for(var e=0;e<o.length;e++)o[e].sktLabel&&(o[e].label=SKT(o[e].sktLabel)),o[e].sktDesc&&(o[e].desc=SKT(o[e].sktDesc));y=SKT("wm.content_ph");var t=document.querySelector("#wm-start-notes span");t&&(t.textContent=SKT("wm.start_notes"));var n=document.querySelector(".wm-form-header > span");n&&(n.textContent=SKT("wm.form_header"));var r=document.getElementById("wm-collapse");r&&(r.title=SKT("wm.close"));var i=document.querySelector('label[for="wm-task"]');i&&(i.textContent=SKT("wm.task_label"));var a=document.getElementById("wm-task");a&&(a.placeholder=SKT("wm.task_ph"));var l=document.querySelector('label[for="wm-content"]');l&&(l.textContent=SKT("wm.content_label"));var s=document.getElementById("wm-content");s&&(s.placeholder=SKT("wm.content_ph"));var c=document.getElementById("wm-mic-task");c&&(c.setAttribute("aria-label",SKT("wm.dictate_task")),c.title=SKT("wm.stt"));var d=document.getElementById("wm-mic-content");d&&(d.setAttribute("aria-label",SKT("wm.dictate_content")),d.title=SKT("wm.stt"));var u=document.querySelector(".wm-section-divider span");u&&(u.textContent=SKT("wm.tone_section"));var p=document.getElementById("wm-tone-value");if(p){var m=document.getElementById("wm-tone-track"),f=m?parseInt(m.getAttribute("aria-valuenow"))-1:4;o[f]&&(p.textContent=o[f].label)}var g=document.getElementById("wm-tone-desc");if(g){var h=document.getElementById("wm-tone-track"),v=h?parseInt(h.getAttribute("aria-valuenow"))-1:4;o[v]&&(g.textContent=o[v].desc)}var w=document.querySelectorAll(".wm-tone-endpoints span");
3w.length>=2&&(w[0].textContent=SKT("wm.tone_min"),w[1].textContent=SKT("wm.tone_max"));var b=document.querySelector(".wm-btn-text");b&&(b.textContent=SKT("wm.submit_text"));var k=document.querySelector(".wm-submit-desc");k&&(k.textContent=SKT("wm.submit_desc"));var S=document.getElementById("wm-lang-select");S&&S.setAttribute("aria-label",SKT("wm.lang_aria"));var x=document.querySelector(".wm-pill-more");x&&x.setAttribute("aria-label",SKT("wm.more_langs"));var T=document.getElementById("wm-lang-compact-label-el");T&&(T.textContent=SKT("wm.lang_label"));var L=document.querySelector(".wm-tpl-header > span");L&&(L.textContent=SKT("wm.tpl_header"));var E=document.querySelector(".wm-tpl-add > span");E&&(E.textContent=SKT("wm.tpl_add"));var C=document.querySelector(".wm-tpl-empty");C&&(C.textContent=SKT("wm.tpl_empty"));var _=document.querySelector(".wm-tpl-gallery-btn > span");_&&(_.textContent=SKT("wm.tpl_gallery"));var A=document.querySelector(".wm-tpl-form-header > span");A&&(A.textContent=B?SKT("wm.tpl_edit_title"):SKT("wm.tpl_new_title"));for(var q=document.querySelectorAll(".wm-tpl-form-body .wm-field > label"),M=["wm.tpl_name_label","wm.tpl_task_label","wm.tpl_content_label","wm.tpl_tone_label"],I=["Navn","Opgave","Stikord","Tonefald"],H=0;H<q.length&&H<M.length;H++)q[H].textContent=SKT(M[H])||I[H];var K=document.querySelector(".wm-tpl-save-text");K&&(K.textContent=SKT("wm.tpl_save"));for(var D=document.querySelectorAll('.wm-tpl-form-body input[type="text"], .wm-tpl-form-body textarea'),P=["wm.tpl_name_ph","wm.tpl_task_ph","wm.tpl_content_ph"],N=0;N<D.length&&N<P.length;N++){var j=SKT(P[N]);j&&(D[N].placeholder=j)}for(var R=document.querySelectorAll(".wm-tpl-tone-pill"),F=0;F<R.length&&F<o.length;F++)R[F].textContent=o[F].label;ve(),ue();var O=document.getElementById("wm-tone-track");O&&O.setAttribute("aria-label",SKT("wm.tone_range_aria")||"Tonefald")}});var q=setInterval(function(){document.getElementById("wm-mic-task")&&(clearInterval(q),A())},500),M=[],I=[],B=null,H=null,K=null,D=null,P={},N=null,j=[];function R(e){return t()?Promise.resolve({}):g().then(function(t){var n={"Content-Type":"application/json","X-SS-Version":"voksen"};t&&(n.Authorization="Bearer "+t);var r=new AbortController,o=setTimeout(function(){r.abort()},3e4);return fetch("/api/template-sharing-api.php",{method:"POST",headers:n,body:JSON.stringify(e),signal:r.signal}).finally(function(){clearTimeout(o)})}).then(function(e){return e.ok?e.json():{_silent_error:!0}}).then(function(e){if(e._silent_error)return{};if(e.error)throw new Error(e.error);return e})}function F(){return R({action:"received"}).then(function(e){return j=e.templates||[]})}function O(){var e=window.currentUser||null,t=(e&&e.app_metadata?e.app_metadata:{}).role||"";return"admin"===t||"school_admin"===t}function U(e,t){if("function"!=typeof SKT)return t;var n=SKT(e);return n&&n!==e?n:t}function $(e,n,r){return t()?Promise.resolve({templates:[]}):g().then(function(e){var t={"Content-Type":"application/json","X-SS-Version":"voksen"};e&&(t.Authorization="Bearer "+e);var n={action:"templates"};if(r)for(var o=Object.keys(r),i=0;i<o.length;i++)n[o[i]]=r[o[i]];var a=new AbortController,l=setTimeout(function(){a.abort()},3e4);return fetch("/api/writing-assistant-api.php",{method:"POST",headers:t,body:JSON.stringify(n),signal:a.signal}).finally(function(){clearTimeout(l)})}).then(function(e){return e.ok?e.json():{_silent_error:!0}}).then(function(e){if(e._silent_error)return{templates:[]};if(e.error)throw new Error(e.error);return e})}function z(){return $(0,0,{sub:"list"}).then(function(e){M=e.templates||[],I=[];for(var t=0;t<M.length;t++)M[t].pinned&&I.push(M[t].id);return M})}function G(e){return $(0,0,{sub:"create",template:e})}function V(e){return $(0,0,{sub:"reorder",ids:e})}function W(){var e=document.querySelector(".wm-tpl-list");if(e){if(e.innerHTML="",!M.length){var t=document.createElement("div");return t.className="wm-tpl-empty",t.textContent=U("wm.tpl_empty","Ingen skabeloner endnu. Opret din første!"),void e.appendChild(t)}for(var n=[],r=[],i=0;i<M.length;i++)M[i].pinned?n.push(M[i]):r.push(M[i]);for(var a=n.concat(r),l=!1,s=0;s<a.length;s++){var c=a[s];if(!l&&n.length>0&&!c.pinned){var d=document.createElement("div");d.className="wm-tpl-divider",e.appendChild(d),l=!0}var u=document.createElement("div");u.className="wm-tpl-card"+(c.pinned?" wm-tpl-pinned":""),u.setAttribute("role","listitem"),u.setAttribute("tabindex","0"),u.setAttribute("aria-label",h(c.title||U("wm.tpl_untitled","Uden navn"))),u.setAttribute("data-tpl-id",c.id),u.setAttribute("draggable","true");var p="";void 0!==c.tone&&null!==c.tone&&o[c.tone]&&(p=o[c.tone].label);var m=c.content||"";m.length>120&&(m=m.substring(0,120)+"...");
3var f=O()?'<button type="button" class="wm-tpl-share" aria-label="'+U("wm.tpl_share","Del")+'" tabindex="0" title="'+U("wm.tpl_share","Del")+'"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/></svg></button>':"";u.innerHTML='<div class="wm-tpl-drag-handle" aria-hidden="true"><svg viewBox="0 0 24 24" width="12" height="12" fill="currentColor" stroke="none"><circle cx="8" cy="4" r="1.5"/><circle cx="16" cy="4" r="1.5"/><circle cx="8" cy="10" r="1.5"/><circle cx="16" cy="10" r="1.5"/><circle cx="8" cy="16" r="1.5"/><circle cx="16" cy="16" r="1.5"/></svg></div><div class="wm-tpl-card-body"><div class="wm-tpl-title-row"><div class="wm-tpl-title">'+h(c.title||U("wm.tpl_untitled","Uden navn"))+"</div>"+(p?'<span class="wm-tpl-tone-badge">'+h(p)+"</span>":"")+'</div><div class="wm-tpl-preview">'+h(m)+'</div></div><div class="wm-tpl-card-actions">'+f+'<button type="button" class="wm-tpl-pin" aria-label="'+U("wm.tpl_pin","Fastgør")+'" tabindex="0" data-pinned="'+(c.pinned?"true":"false")+'"><svg viewBox="0 0 24 24" width="14" height="14" fill="'+(c.pinned?"currentColor":"none")+'" stroke="currentColor" stroke-width="2"><path d="M12 17v5"/><path d="M5 17h14v-1.76a2 2 0 00-1.11-1.79l-1.78-.89A2 2 0 0115 10.76V6h1a2 2 0 002-2H6a2 2 0 002 2h1v4.76a2 2 0 01-1.11 1.79l-1.78.89A2 2 0 005 15.24z"/></svg></button><button type="button" class="wm-tpl-edit" aria-label="'+U("wm.tpl_edit","Rediger")+'" tabindex="0"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z"/></svg></button><button type="button" class="wm-tpl-delete" aria-label="'+U("wm.tpl_delete","Slet")+'" tabindex="0"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2"/></svg></button></div>',J(u,c),e.appendChild(u)}!function(){for(var e=document.querySelectorAll(".wm-tpl-card"),t=0;t<e.length;t++)(function(e,t){e.addEventListener("dragstart",function(n){N=t,e.classList.add("wm-dragging"),n.dataTransfer.effectAllowed="move",n.dataTransfer.setData("text/plain",t.toString())}),e.addEventListener("dragover",function(t){t.preventDefault(),t.dataTransfer.dropEffect="move",e.classList.add("wm-drag-over")}),e.addEventListener("dragleave",function(){e.classList.remove("wm-drag-over")}),e.addEventListener("drop",function(n){n.preventDefault(),e.classList.remove("wm-drag-over");var r=N,o=t;if(null!==r&&r!==o){var i=M.splice(r,1)[0];M.splice(o,0,i);for(var a=[],l=0;l<M.length;l++)a.push(M[l].id);V(a).catch(function(e){console.error("Reorder error:",e)}),W()}}),e.addEventListener("dragend",function(){e.classList.remove("wm-dragging"),N=null;for(var t=document.querySelectorAll(".wm-tpl-card"),n=0;n<t.length;n++)t[n].classList.remove("wm-drag-over")})})(e[t],t)}()}}function J(e,t){var n=e.querySelector(".wm-tpl-card-body");n&&n.addEventListener("click",function(e){e.target.closest(".wm-tpl-card-actions")||pe(t)}),e.addEventListener("keydown",function(e){e.target.closest(".wm-tpl-card-actions")||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),pe(t))});var r=e.querySelector(".wm-tpl-share");r&&r.addEventListener("click",function(e){e.stopPropagation(),function(e){var t=document.querySelector(".wm-share-overlay");t&&t.remove();var n=document.createElement("div");n.className="wm-share-overlay",n.innerHTML='<div class="wm-share-modal" role="dialog" aria-label="'+U("wm.tpl_share_title","Del skabelon")+'" aria-modal="true"><div class="wm-share-header"><span>'+U("wm.tpl_share_title","Del skabelon")+'</span><button type="button" class="wm-share-close" aria-label="'+U("wm.close","Luk")+'">×</button></div><div class="wm-share-body"><p class="wm-share-tpl-name">'+h(e.title||"")+'</p><div class="wm-field"><label for="wm-share-emails">'+U("wm.tpl_share_emails","Email-adresser")+'</label><input type="email" id="wm-share-emails" inputmode="email" multiple placeholder="'+U("wm.tpl_share_emails_ph","[email protected], [email protected]")+'" autocomplete="off"><span class="wm-share-hint">'+U("wm.tpl_share_hint","Adskil med komma")+'</span></div><div class="wm-field"><label>'+U("wm.tpl_share_perm","Tilladelse")+'</label><div class="wm-share-perm-row"><button type="button" class="wm-share-perm-btn active" data-perm="read">'+U("wm.tpl_perm_read","Kan bruge")+'</button><button type="button" class="wm-share-perm-btn" data-perm="fork">'+U("wm.tpl_perm_fork","Kan gemme kopi")+'</button></div></div>
3<div class="wm-share-status hidden" role="status" aria-live="polite"></div></div><div class="wm-share-footer"><button type="button" class="wm-share-send-btn" disabled><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg><span>'+U("wm.tpl_share_send","Send invitation")+'</span><span class="wm-share-loader"></span></button></div></div>',document.body.appendChild(n),n.querySelector(".wm-share-modal");var r=n.querySelector(".wm-share-close"),o=n.querySelector("#wm-share-emails"),i=n.querySelector(".wm-share-send-btn"),a=n.querySelectorAll(".wm-share-perm-btn"),l=n.querySelector(".wm-share-status"),s="read";function c(){n.remove()}function d(e){l.innerHTML=e,l.classList.remove("hidden")}function u(e){var t=function(e){for(var t=String(e||"").split(/[,\n;]+/),n=[],r=[],o={},i=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,a=0;a<t.length;a++){var l=t[a].trim().toLowerCase();l&&(i.test(l)?o[l]||(o[l]=!0,n.push(l)):r.push(l))}return{emails:n,invalid:r}}(o.value),n=!!o.value.trim(),r=t.invalid.length>0;(o.setAttribute("aria-invalid",r?"true":"false"),i.disabled=!t.emails.length||r,!e||t.emails.length&&!r)?e||!n||r||l.classList.add("hidden"):d('<div class="wm-share-result wm-share-result-failed">'+h(r?U("wm.tpl_share_invalid_email","Ret ugyldige email-adresser: ")+t.invalid.join(", "):U("wm.tpl_share_invalid_empty","Skriv mindst én gyldig email-adresse."))+"</div>");return t}r.addEventListener("click",c),n.addEventListener("click",function(e){e.target===n&&c()}),n.addEventListener("keydown",function(e){"Escape"===e.key&&c()}),o.addEventListener("input",function(){u(!1)});for(var p=0;p<a.length;p++)(function(e){e.addEventListener("click",function(){s=e.getAttribute("data-perm");for(var t=0;t<a.length;t++)a[t].classList.toggle("active",a[t]===e)})})(a[p]);i.addEventListener("click",function(){var t=u(!0);t.emails.length&&!t.invalid.length&&(i.classList.add("loading"),i.disabled=!0,l.classList.add("hidden"),R({action:"share",template_id:e.id,emails:t.emails,permission:s}).then(function(e){for(var t=e.invitations||[],n="",r=0;r<t.length;
3r++){var i="pending"===t[r].status?"✓":"already_invited"===t[r].status?"↺":"✗",a="pending"===t[r].status?U("wm.tpl_share_sent","Sendt"):"already_invited"===t[r].status?U("wm.tpl_share_already","Allerede inviteret"):U("wm.tpl_share_failed","Fejl");n+='<div class="wm-share-result wm-share-result-'+t[r].status+'"><span>'+i+"</span> <span>"+h(t[r].email)+"</span> — <span>"+a+"</span></div>"}d(n),o.value="",u(!1)}).catch(function(e){d('<div class="wm-share-result wm-share-result-failed">'+h(e.message||U("wm.tpl_share_error","Kunne ikke dele skabelonen"))+"</div>")}).finally(function(){i.classList.remove("loading"),u(!1)}))}),requestAnimationFrame(function(){n.classList.add("visible"),o.focus()})}(t)});var o=e.querySelector(".wm-tpl-pin");o&&o.addEventListener("click",function(e){e.stopPropagation();var n,r,i="true"===o.getAttribute("data-pinned");(n=t.id,r=!i,$(0,0,{sub:"pin",id:n,pinned:r})).then(function(){if(t.pinned=!i,t.pinned)-1===I.indexOf(t.id)&&I.push(t.id);else{var e=I.indexOf(t.id);e>-1&&I.splice(e,1)}W(),ve()}).catch(function(e){console.error("Pin error:",e)})});var i=e.querySelector(".wm-tpl-edit");i&&i.addEventListener("click",function(e){e.stopPropagation(),he(t)});var a=e.querySelector(".wm-tpl-delete");a&&a.addEventListener("click",function(e){e.stopPropagation();var n,r=U("wm.tpl_delete_confirm","Er du sikker pÃ¥, at du vil slette denne skabelon?");confirm(r)&&(n=t.id,$(0,0,{sub:"delete",id:n})).then(function(){for(var e=0;e<M.length;e++)if(M[e].id===t.id){M.splice(e,1);break}var n=I.indexOf(t.id);n>-1&&I.splice(n,1),W(),ve()}).catch(function(e){console.error("Delete error:",e)})})}function Z(){var e=document.querySelector(".hk-dropdown-option.active");if(e){var t=document.getElementById("ai-panel"),n=document.getElementById("tone-panel");t&&(t.style.display="none"),n&&(n.style.display="none"),"option-tone"===e.id?(n&&(n.style.display="flex"),window._wf&&"function"==typeof window._wf.aiIsOpen&&window._wf.aiIsOpen(!1)):"option-ai"===e.id&&(t&&(t.style.display="flex"),window._wf&&"function"==typeof window._wf.aiIsOpen&&window._wf.aiIsOpen(!0))}}var Y={selectedId:null},Q={mail:'<rect x="2" y="4" width="20" height="16" rx="2"/><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/>',sparkle:'<path d="m12 3-1.9 5.8a2 2 0 0 1-1.3 1.3L3 12l5.8 1.9a2 2 0 0 1 1.3 1.3L12 21l1.9-5.8a2 2 0 0 1 1.3-1.3L21 12l-5.8-1.9a2 2 0 0 1-1.3-1.3z"/>',landmark:'<line x1="3" y1="22" x2="21" y2="22"/><line x1="6" y1="18" x2="6" y2="11"/><line x1="10" y1="18" x2="10" y2="11"/><line x1="14" y1="18" x2="14" y2="11"/><line x1="18" y1="18" x2="18" y2="11"/><polygon points="12 2 20 7 4 7"/>',brief:'<rect x="2" y="7" width="20" height="14" rx="2"/><path d="M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16"/>',cap:'<path d="M22 10 12 5 2 10l10 5 10-5z"/><path d="M6 12v5c0 1.7 2.7 3 6 3s6-1.3 6-3v-5"/>',pen:'<path d="M12 20h9"/><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4 12.5-12.5z"/>'};function X(e,t){if("function"!=typeof SKT)return t;var n=SKT(e);return n&&n!==e?n:t}var ee=[{id:"email",icon:"mail",tone:3,labelKey:"wm.cat_email_label",labelDa:"E-mail",promptKey:"wm.cat_email_prompt",promptDa:"Skriv en e-mail. Start med en venlig hilsen, kom hurtigt til det vigtigste, og slut pænt. Hold den kort og let at læse.",hintKey:"wm.cat_email_hint",hintDa:'Hvem skriver du til, og hvad skal de vide? F.eks. "til min chef â jeg er forsinket til mødet i morgen"'},{id:"improve",icon:"sparkle",tone:2,labelKey:"wm.cat_improve_label",labelDa:"Forbedr min tekst",promptKey:"wm.cat_improve_prompt",promptDa:"Gør min tekst klar og let at forstÃ¥. Ret stavning og grammatik, og gør sætningerne kortere og enklere. Behold min mening og mine oplysninger.",hintKey:"wm.cat_improve_hint",hintDa:"Indsæt din tekst her, sÃ¥ forbedrer jeg den."},{id:"public",icon:"landmark",tone:3,labelKey:"wm.cat_public_label",labelDa:"Det offentlige",promptKey:"wm.cat_public_prompt",promptDa:"Skriv en klar og høflig besked til en offentlig myndighed, fx kommunen, jobcenteret eller SKAT. Forklar min situation enkelt, og skriv tydeligt hvad jeg beder om.",hintKey:"wm.cat_public_hint",hintDa:'Hvilken myndighed, og hvad drejer det sig om? F.eks. "jobcenter â jeg vil klage over en afgørelse"'}
3,{id:"job",icon:"brief",tone:4,labelKey:"wm.cat_job_label",labelDa:"Jobansøgning",promptKey:"wm.cat_job_prompt",promptDa:"Skriv en jobansøgning. Fang hurtigt hvorfor jeg passer til jobbet, knyt min erfaring til det de søger, og hold en positiv og professionel tone.",hintKey:"wm.cat_job_hint",hintDa:"Hvilket job søger du, og hvad er dine stærkeste erfaringer? Indsæt gerne stillingsopslaget."},{id:"school",icon:"cap",tone:3,labelKey:"wm.cat_school_label",labelDa:"Besked til skolen",promptKey:"wm.cat_school_prompt",promptDa:"Skriv en kort og venlig besked til skolen eller institutionen, fx via Aula. Skriv tydeligt hvem det handler om, og hvad jeg vil sige eller spørge om.",hintKey:"wm.cat_school_hint",hintDa:'Hvem handler det om, og hvad vil du sige? F.eks. "min datter Emma i 3.b er syg i morgen"'}];function te(e,t){return'<svg viewBox="0 0 24 24" width="19" height="19" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">'+e+"</svg>"}var ne='<svg class="wm-cat-check" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="20 6 9 17 4 12"/></svg>';function re(){var e=document.getElementById("wm-task"),t=document.getElementById("wm-content"),n=document.getElementById("wm-submit");if(n){var r=Y.selectedId&&"self"!==Y.selectedId;n.disabled=r?!(t&&t.value.trim()):!(e&&e.value.trim()||t&&t.value.trim())}}function oe(){var e=document.getElementById("wm-content");e&&e.setAttribute("placeholder",y)}function ie(e){Y.selectedId=null;for(var t=e.querySelectorAll(".wm-cat-chip.active"),n=0;n<t.length;n++){t[n].classList.remove("active"),t[n].setAttribute("aria-pressed","false");var r=t[n].querySelector(".wm-cat-check");r&&r.remove()}}function ae(e,t){var n=document.getElementById("wm-form"),r=document.getElementById("wm-task"),o=document.getElementById("wm-content");if(n&&r){if(Y.selectedId===e.id)return ie(n),r.value="",oe(),void re();ie(n),n.classList.remove("wm-self-mode"),Y.selectedId=e.id,t.classList.add("active"),t.setAttribute("aria-pressed","true"),t.insertAdjacentHTML("beforeend",ne),r.value=X(e.promptKey,e.promptDa),v&&v(e.tone),o&&(o.setAttribute("placeholder",X(e.hintKey,e.hintDa)),o.focus()),re()}}function ce(e){var t=document.getElementById("wm-form"),n=document.getElementById("wm-task");t&&n&&("self"!==Y.selectedId?(ie(t),t.classList.add("wm-self-mode"),Y.selectedId="self",e.classList.add("active"),e.setAttribute("aria-pressed","true"),n.value="",oe(),r(n),re(),n.focus()):n.focus())}function de(){!function(){var e=document.getElementById("wm-cat-grid"),t=document.getElementById("wm-form");if(e&&t&&(!Y.selectedId||!e.children.length)){for(var n="",r=0;r<ee.length;r++){var o=ee[r];n+='<button type="button" class="wm-cat-chip" data-cat-id="'+o.id+'" aria-pressed="false">'+te(Q[o.icon])+"<span>"+h(X(o.labelKey,o.labelDa))+"</span></button>"}n+='<button type="button" class="wm-cat-chip wm-cat-chip-self" id="wm-cat-self" aria-pressed="false">'+te(Q.pen)+"<span>"+h(X("wm.start_write","Skriv selv"))+"</span></button>",e.innerHTML=n,e.classList.remove("hidden"),t.classList.add("wm-has-cats"),Y.selectedId=null,oe();for(var i=e.querySelectorAll(".wm-cat-chip"),a=0;a<i.length;a++)(function(e){e.addEventListener("click",function(){if("wm-cat-self"!==e.id){for(var t=e.getAttribute("data-cat-id"),n=0;n<ee.length;n++)if(ee[n].id===t)return void ae(ee[n],e)}else ce(e)})})(i[a])}}()}function ue(){var e=document.getElementById("wm-cat-grid");if(e){for(var t=0;t<ee.length;t++){var n=e.querySelector('.wm-cat-chip[data-cat-id="'+ee[t].id+'"] > span');n&&(n.textContent=X(ee[t].labelKey,ee[t].labelDa))}var r=e.querySelector("#wm-cat-self > span");if(r&&(r.textContent=X("wm.start_write","Skriv selv")),Y.selectedId&&"self"!==Y.selectedId)for(var o=0;o<ee.length;o++)if(ee[o].id===Y.selectedId){var i=document.getElementById("wm-task"),a=document.getElementById("wm-content");i&&(i.value=X(ee[o].promptKey,ee[o].promptDa)),a&&a.setAttribute("placeholder",X(ee[o].hintKey,ee[o].hintDa));break}}}function pe(e){var t=document.getElementById("wm-task"),n=document.getElementById("wm-content");t&&e.content&&(t.value=e.content,r(t)),void 0!==e.tone&&null!==e.tone&&v&&v(e.tone);for(var o=document.querySelectorAll(".sidebar-tpl-card"),i=0;i<o.length;i++)o[i].classList.remove("applied");var a=document.querySelector('.sidebar-tpl-card[data-tpl-id="'+e.id+'"]');a&&a.classList.add("applied");var l=document.getElementById("sidebar-tpl-swap");if(!(l&&"none"!==l.style.display)){fe();var s=document.getElementById("wm-nudge"),c=document.getElementById("wm-form"),d=document.querySelector(".grammar-page")||document.querySelector(".app-layout");s&&s.classList.add("hidden"),c&&(c.classList.remove("hidden"),document.body.classList.add("wm-form-open"),d&&d.classList.add("editor-empty"))}var u=document.getElementById("wm-submit");u&&(u.disabled=!(t&&t.value.trim()||n&&n.value.trim())),t&&t.focus()}function me(){var e=document.querySelector(".wm-tpl-panel");
3if(!e){var t=document.querySelector(".textarea-wrapper");if(!t)return;if(t.insertAdjacentHTML("beforeend",function(){for(var e="",t=0;t<o.length;t++)e+='<button type="button" class="wm-tpl-tone-pill" data-tone-idx="'+t+'" role="radio" aria-checked="false" tabindex="0" aria-label="'+h(o[t].label)+'">'+h(o[t].label)+"</button>";return'<div class="wm-tpl-panel hidden" role="dialog" aria-label="'+U("wm.tpl_header","Skabeloner")+'" aria-modal="true"><div class="wm-tpl-view" data-view="list"><div class="wm-tpl-header"><svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2"><path d="M19 21l-7-5-7 5V5a2 2 0 012-2h10a2 2 0 012 2z"/></svg><span>'+U("wm.tpl_header","Skabeloner")+'</span></div><button type="button" class="wm-tpl-add" aria-label="'+U("wm.tpl_add","Ny skabelon")+'"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg><span>'+U("wm.tpl_add","Ny skabelon")+'</span></button><div class="wm-tpl-list" role="list" aria-label="'+U("wm.tpl_header","Skabeloner")+'"></div><button type="button" class="wm-tpl-gallery-btn"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/></svg><span>'+U("wm.tpl_gallery","Udforsk skabeloner")+'</span></button></div><div class="wm-tpl-view wm-tpl-view-hidden" data-view="form"><div class="wm-tpl-form-header"><button type="button" class="wm-tpl-back-btn" aria-label="'+U("wm.tpl_back","Tilbage")+'"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><polyline points="15 18 9 12 15 6"/></svg></button><span>'+U("wm.tpl_new_title","Ny skabelon")+'</span></div><div class="wm-tpl-form-body"><div class="wm-field"><label>'+U("wm.tpl_name_label","Navn")+'</label><input type="text" data-tpl-field="title" placeholder="'+U("wm.tpl_name_ph","F.eks. Email til kunder")+'" autocomplete="off"></div><div class="wm-field"><label>'+U("wm.tpl_task_label","Opgave")+'</label><textarea data-tpl-field="content" rows="2" placeholder="'+U("wm.tpl_task_ph","Hvad skal teksten handle om?")+'" autocomplete="off"></textarea></div><div class="wm-field"><label>'+U("wm.tpl_tone_label","Tonefald")+'</label><div class="wm-tpl-tone-row">'+e+'</div></div><button type="button" class="wm-tpl-save-btn" disabled><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><path d="M19 21H5a2 2 0 01-2-2V5a2 2 0 012-2h11l5 5v11a2 2 0 01-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg><span class="wm-tpl-save-text">'+U("wm.tpl_save","Gem skabelon")+'</span><span class="wm-tpl-save-loader"></span></button></div></div></div>'}()),!(e=document.querySelector(".wm-tpl-panel")))return;!function(e){var t=e.querySelector(".wm-tpl-add");t&&t.addEventListener("click",function(){he(null)});var n=e.querySelector(".wm-tpl-back-btn");n&&n.addEventListener("click",function(){ge()});var r=e.querySelector(".wm-tpl-save-btn");r&&r.addEventListener("click",function(){!function(e){var t=e.querySelector('[data-tpl-field="title"]'),n=e.querySelector('[data-tpl-field="content"]'),r=e.querySelector(".wm-tpl-save-btn"),o=t?t.value.trim():"";if(!o)return;var i,a={title:o,content:n?n.value.trim():"",tone:H};r&&(r.classList.add("loading"),r.disabled=!0);i=B?function(e,t){return $(0,0,{sub:"update",id:e,template:t})}(B,a):G(a);i.then(function(e){return z()}).then(function(){W(),ge(),ve()}).catch(function(e){console.error("Save error:",e),alert(U("wm.tpl_save_error","Kunne ikke gemme skabelonen. Prøv igen."))}).finally(function(){r&&(r.classList.remove("loading"),r.disabled=!(t&&t.value.trim()))})}(e)});var o=e.querySelector('[data-tpl-field="title"]');o&&r&&o.addEventListener("input",function(){r.disabled=!o.value.trim()});for(var i=e.querySelectorAll(".wm-tpl-tone-pill"),a=0;a<i.length;a++)(function(t){t.addEventListener("click",function(){var n=parseInt(t.getAttribute("data-tone-idx"),10);H=H===n?null:n;for(var r=e.querySelectorAll(".wm-tpl-tone-pill"),o=0;o<r.length;o++){var i=parseInt(r[o].getAttribute("data-tone-idx"),10)===H;r[o].classList.toggle("active",i),r[o].setAttribute("aria-checked",i?"true":"false")}}),t.addEventListener("keydown",function(e){"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),t.click())})})(i[a]);var l=e.querySelector(".wm-tpl-gallery-btn");l&&l.addEventListener("click",function(){console.log("Gallery clicked")});var s=e.querySelector(".wm-tpl-list");s&&s.addEventListener("keydown",function(e){if("ArrowDown"===e.key||"ArrowUp"===e.key){var t=s.querySelectorAll(".wm-tpl-card");if(!t.length)return;for(var n=-1,r=0;r<t.length;r++)if(t[r]===document.activeElement){n=r;break}if("ArrowDown"===e.key)e.preventDefault(),t[(n+1)%t.length].focus();else if("ArrowUp"===e.key){e.preventDefault(),t[(n-1+t.length)%t.length].focus()}}})}(e)}e.classList.remove("hidden"),ge(),z().then(function(){W()}).catch(function(e){console.error("Template fetch error:",e),W()}),F().then(function(){we()}).catch(function(){}),function(e){K&&document.removeEventListener("keydown",K);K=function(t){if("Tab"===t.key){var n=e.querySelectorAll('button:not([disabled]), input:not([disabled]), textarea:not([disabled]), [tabindex="0"]');if(n.length){var r=n[0],o=n[n.length-1];t.shiftKey?document.activeElement===r&&(t.preventDefault(),o.focus()):document.activeElement===o&&(t.preventDefault(),r.focus())}}},document.addEventListener("keydown",K)}(e),D=function(e){"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),fe())},document.addEventListener("keydown",D),setTimeout(function(){var t=e.querySelector("button");t&&t.focus()},50)}function fe(){var e=document.querySelector(".wm-tpl-panel");e&&e.classList.add("hidden"),B=null,K&&(document.removeEventListener("keydown",K),K=null),D&&(document.removeEventListener("keydown",D),D=null)}function ge(){var e=document.querySelector(".wm-tpl-panel");
3if(e){var t=e.querySelector('[data-view="list"]'),n=e.querySelector('[data-view="form"]');t&&t.classList.remove("wm-tpl-view-hidden"),n&&n.classList.add("wm-tpl-view-hidden"),B=null}}function he(e){var t=document.querySelector(".wm-tpl-panel");if(t){var n=t.querySelector('[data-view="list"]'),r=t.querySelector('[data-view="form"]');n&&n.classList.add("wm-tpl-view-hidden"),r&&r.classList.remove("wm-tpl-view-hidden");var o=t.querySelector(".wm-tpl-form-header > span"),i=t.querySelector('[data-tpl-field="title"]'),a=t.querySelector('[data-tpl-field="content"]'),l=t.querySelector(".wm-tpl-save-btn");H=null,B=null,e?(B=e.id,o&&(o.textContent=U("wm.tpl_edit_title","Rediger skabelon")),i&&(i.value=e.title||""),a&&(a.value=e.content||""),void 0!==e.tone&&null!==e.tone&&(H=e.tone)):(o&&(o.textContent=U("wm.tpl_new_title","Ny skabelon")),i&&(i.value=""),a&&(a.value=""));for(var s=t.querySelectorAll(".wm-tpl-tone-pill"),c=0;c<s.length;c++){var d=parseInt(s[c].getAttribute("data-tone-idx"),10)===H;s[c].classList.toggle("active",d),s[c].setAttribute("aria-checked",d?"true":"false")}l&&(l.disabled=!(i&&i.value.trim())),i&&setTimeout(function(){i.focus()},50)}}function ve(){var e=document.querySelector(".wm-mobile-chips");if(!e){var t=document.querySelector(".textarea-wrapper");if(!t)return;var n=document.createElement("div");n.className="wm-mobile-chips",t.appendChild(n),e=n}e.innerHTML="";for(var r=0;r<M.length;r++)M[r].pinned&&function(t){var n=document.createElement("button");n.type="button",n.className="wm-chip",n.setAttribute("aria-label",h(t.title)),n.textContent=t.title,n.addEventListener("click",function(){pe(t)}),e.appendChild(n)}(M[r])}function ye(e,t,n){var r=(e||"").substring(0,50)+"|"+(void 0!==n?n:"");if(!P[r]){for(var o=0;o<M.length;o++)if(M[o].content===e&&M[o].tone===n)return;var i=function(){var e=document.querySelector(".wm-suggest-toast");if(e)return e;var t=document.createElement("div");return t.className="wm-suggest-toast",t.innerHTML='<div class="wm-suggest-content"><span class="wm-suggest-text">'+U("wm.tpl_suggest","Gem som skabelon?")+'</span><div class="wm-suggest-actions"><button type="button" class="wm-suggest-yes">'+U("wm.tpl_suggest_yes","Gem")+'</button><button type="button" class="wm-suggest-no">'+U("wm.tpl_suggest_no","Nej tak")+"</button></div></div>",document.body.appendChild(t),t}(),a=i.querySelector(".wm-suggest-yes"),l=i.querySelector(".wm-suggest-no"),s=a.cloneNode(!0);a.parentNode.replaceChild(s,a);var c=l.cloneNode(!0);l.parentNode.replaceChild(c,l),s.addEventListener("click",function(){i.classList.remove("visible"),me(),he(null);var t=document.querySelector(".wm-tpl-panel");if(t){var r=t.querySelector('[data-tpl-field="content"]');if(r&&e&&(r.value=e),null!=n){H=n;for(var o=t.querySelectorAll(".wm-tpl-tone-pill"),a=0;a<o.length;a++){var l=parseInt(o[a].getAttribute("data-tone-idx"),10)===n;o[a].classList.toggle("active",l),o[a].setAttribute("aria-checked",l?"true":"false")}}var s=t.querySelector(".wm-tpl-save-btn"),c=t.querySelector('[data-tpl-field="title"]');s&&c&&(s.disabled=!c.value.trim())}}),c.addEventListener("click",function(){i.classList.remove("visible"),P[r]=!0}),setTimeout(function(){i.classList.add("visible")},1500),setTimeout(function(){i.classList.contains("visible")&&i.classList.remove("visible")},11500)}}function we(){var e=document.querySelector(".wm-tpl-panel");if(e){var t=e.querySelector('[data-view="list"]');if(t){var n=t.querySelector(".wm-tpl-shared-section");if(n&&n.remove(),j.length){var r=document.createElement("div");r.className="wm-tpl-shared-section";var i=document.createElement("div");i.className="wm-tpl-shared-header",i.innerHTML='<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/></svg><span>'+U("wm.tpl_shared_header","Delt med dig")+'</span><button type="button" class="wm-tpl-shared-toggle" aria-expanded="true" aria-label="'+U("wm.tpl_collapse","Fold sammen")+'"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg></button>';var a=document.createElement("div");
3a.className="wm-tpl-shared-list",a.setAttribute("role","list");for(var l=0;l<j.length;l++)(function(e){var t=document.createElement("div");t.className="wm-tpl-card-shared",t.setAttribute("role","listitem"),t.setAttribute("tabindex","0"),t.setAttribute("aria-label",h(e.title||U("wm.tpl_untitled","Uden navn")));var n="";void 0!==e.tone&&null!==e.tone&&o[e.tone]&&(n=o[e.tone].label);var r=e.content||"";r.length>120&&(r=r.substring(0,120)+"...");var i=e.shared_by_name?'<span class="wm-tpl-shared-by">'+U("wm.tpl_from","Fra")+" "+h(e.shared_by_name)+"</span>":"",l=e.available?"":'<span class="wm-tpl-unavailable">'+U("wm.tpl_unavailable","Ikke tilgængelig")+"</span>",s="fork"===e.permission&&e.available?'<button type="button" class="wm-tpl-fork-btn" aria-label="'+U("wm.tpl_fork","Gem som min egen")+'" tabindex="0"><svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2"><path d="M16 17l5 5-5 5"/><path d="M21 22H9a2 2 0 01-2-2V4a2 2 0 012-2h5l7 7v6"/></svg><span>'+U("wm.tpl_fork","Gem som min egen")+"</span></button>":"";(t.innerHTML='<div class="wm-tpl-card-body"><div class="wm-tpl-title-row"><div class="wm-tpl-title">'+h(e.title||U("wm.tpl_untitled","Uden navn"))+"</div>"+(n?'<span class="wm-tpl-tone-badge">'+h(n)+"</span>":"")+"</div>"+i+l+'<div class="wm-tpl-preview">'+h(r)+'</div></div><div class="wm-tpl-card-actions">'+s+"</div>",e.available)&&(t.querySelector(".wm-tpl-card-body").addEventListener("click",function(){pe(e)}),t.addEventListener("keydown",function(t){t.target.closest(".wm-tpl-card-actions")||"Enter"!==t.key&&" "!==t.key||(t.preventDefault(),pe(e))}));var c=t.querySelector(".wm-tpl-fork-btn");c&&c.addEventListener("click",function(t){t.stopPropagation(),G({title:e.title,content:e.content||"",tone:e.tone}).then(function(){return z()}).then(function(){W(),ve(),c.textContent=U("wm.tpl_forked","Gemt!"),c.disabled=!0}).catch(function(e){console.error("Fork error:",e)})}),a.appendChild(t)})(j[l]);r.appendChild(i),r.appendChild(a);var s=i.querySelector(".wm-tpl-shared-toggle");s.addEventListener("click",function(){var e="true"===s.getAttribute("aria-expanded");s.setAttribute("aria-expanded",e?"false":"true"),a.classList.toggle("collapsed",e);var t=s.querySelector("svg");t&&(t.style.transform=e?"rotate(-90deg)":"")}),t.appendChild(r)}}}}function be(){var e=function(){var e="";try{e=new URLSearchParams(window.location.search).get("claim")||""}catch(e){}if(!e)try{e=sessionStorage.getItem("ss_tpl_claim_token")||""}catch(e){}return/^[0-9a-f]{64}$/i.test(e)?e:""}();if(e){try{var t=new URLSearchParams(window.location.search);if(t.has("claim")&&window.history&&window.history.replaceState){t.delete("claim");var n=t.toString(),r=window.location.pathname+(n?"?"+n:"")+window.location.hash;window.history.replaceState(null,"",r)}}catch(e){}window.SSAuth&&"function"==typeof window.SSAuth.waitUntilReady?window.SSAuth.waitUntilReady().then(o).catch(o):o()}function o(){R({action:"claim",token:e}).then(function(e){e.template&&(ke(e.already_had?U("wm.tpl_claim_already","Du har allerede denne skabelon."):U("wm.tpl_claim_success","Skabelon tilføjet!")+' "'+(e.template.title||"")+'"',"success"),F().then(function(){we()}))}).catch(function(e){ke(e.message||U("wm.tpl_claim_error","Kunne ikke hente skabelonen."),"error")}).finally(function(){!function(){try{sessionStorage.removeItem("ss_tpl_claim_token")}catch(e){}}()})}}function ke(e,t){var n=document.createElement("div");n.className="wm-claim-toast wm-claim-toast-"+t,n.setAttribute("role","alert"),n.textContent=e,document.body.appendChild(n),requestAnimationFrame(function(){n.classList.add("visible")}),setTimeout(function(){n.classList.remove("visible"),setTimeout(function(){n.remove()},300)},4e3)}document.addEventListener("wm-form-state",function(e){e.detail&&e.detail.open||function(){var e=document.getElementById("sidebar-tpl-swap");if(e){e.style.display="none";var t=document.querySelector(".sidebar-dropdown-items-container");t&&(t.style.display="");for(var n=[".correction-inner",".improv-inner",".style-inner"],r=0;r<n.length;r++){var o=document.querySelector(n[r]);o&&o.hasAttribute("data-pre-swap")&&(o.style.display=o.getAttribute("data-pre-swap")||"",o.removeAttribute("data-pre-swap"))}Z()}}()}),(window.requestIdleCallback||function(e){setTimeout(e,2e3)})(function(){de()});var Se=null;function xe(){var e=document.getElementById("wm-submit");
3if(e&&Se!==e){Se=e;var t=new(window.MutationObserver||function(){})(function(t){for(var n=0;n<t.length;n++)if("class"===t[n].attributeName){var r=t[n].oldValue&&t[n].oldValue.indexOf("loading")>-1,o=e.classList.contains("loading");if(r&&!o){var a=document.getElementById("wm-task"),l=document.getElementById("wm-content"),s=a?a.value.trim():"",c=l?l.value.trim():"";(s||c)&&setTimeout(function(){ye(s,0,i)},3e3)}}});t.observe(e,{attributes:!0,attributeOldValue:!0})}}var Te=setInterval(function(){document.querySelector(".textarea-wrapper")&&(clearInterval(Te),z().then(function(){ve()}).catch(function(){ve()}),F().catch(function(){}),be(),xe(),setTimeout(xe,2e3))},500)}();var uc={da:"danish",danish:"danish",en:"english",english:"english",ge:"german",de:"german",german:"german",fr:"french",french:"french",es:"spanish",spanish:"spanish",sv:"swedish",swedish:"swedish",no:"norwegian",nb:"norwegian",norwegian:"norwegian",fi:"finnish",finnish:"finnish",pl:"polish",polish:"polish",it:"italian",italian:"italian",pt:"portuguese",portuguese:"portuguese",nl:"dutch",dutch:"dutch",tr:"turkish",turkish:"turkish",ru:"russian",russian:"russian",ar:"arabic",arabic:"arabic",ja:"japanese",japanese:"japanese",ko:"korean",korean:"korean"},pc={english:["the","is","and","to","in","that","of","for","with","not","are","was","this","have","from","but","will","can","here","version","customer","wants","simple","update","before","friday"],danish:["og","er","det","til","en","med","for","har","den","ikke","kan","var","som","af","fra","her","version","kunden","vil","have","kort","opdatering","inden","fredag"],german:["und","ist","der","die","das","nicht","ein","von","zu","mit","auch","auf","fuer","fur","den","sich","werden","eine","haben"],french:["est","les","des","une","pas","dans","pour","que","sur","avec","sont","par","plus","tout","mais","cette","comme"],spanish:["que","los","las","por","con","una","del","para","como","pero","son","tiene","todo","hay","esta","desde"],swedish:["och","att","det","som","har","med","den","inte","till","var","kan","ska","ett","av","efter"],norwegian:["og","er","det","til","en","med","for","har","den","ikke","kan","var","som","av","fra","etter"],finnish:["ja","on","se","ei","etta","kun","myos","oli","ovat","tai","mutta","tama","nama"],polish:["jest","oraz","nie","dla","sie","ten","ta","to","jak","ale","przez","moze"],italian:["che","per","con","non","una","del","come","sono","questo","questa","anche","tra","piu"],portuguese:["que","para","com","uma","nao","como","sao","este","esta","tambem"],dutch:["het","een","niet","voor","met","dat","zijn","was","maar","ook","deze","door","over"],turkish:["ve","bir","bu","icin","degil","olarak","ile","daha","ama","sonra"]};function mc(e){var t=String(e||"").trim();if(!t)return"";if(/[\u0600-\u06ff]/.test(t))return"arabic";if(/[\u3040-\u30ff]/.test(t))return"japanese";if(/[\uac00-\ud7af]/.test(t))return"korean";if(/[\u0400-\u04ff]/.test(t))return"russian";var n=t.toLowerCase();"function"==typeof n.normalize&&(n=n.normalize("NFKD").replace(/[\u0300-\u036f]/g,""));var r=n.replace(/[^a-z\u00c0-\u024f\s]/g," ").split(/\s+/).filter(function(e){return e.length>1});if(r.length<4)return"";var o="",i=0,a=0;return Object.keys(pc).forEach(function(e){for(var t=pc[e],n=0,l=0;l<r.length;l++)-1!==t.indexOf(r[l])&&n++;n>i?(a=i,i=n,o=e):n>a&&(a=n)}),i>=2&&(i>a||i>=4)?o:""}function fc(e){var t=e||{};return mc(t.answer)||mc(t.sourceText)||function(e){var t=String(e||"").trim().toLowerCase();if(!t)return"";if(uc[t])return uc[t];var n=t.split(/[-_]/)[0];return uc[n]||""}(t.fallbackLanguage)||"danish"}function gc(e){var t=/:\s*$/.test(e),n=/^(selvf[oø]lgelig|klart|ja|her er|jeg har|nedenfor|forslag)/i.test(e)&&(/(version|forslag|tekst|kortere|omskrevet|rettet|udkast)/i.test(e)||t),r=/^(sure|here('s| is| are| you)|absolutely|of course|certainly|great|no problem)/i.test(e)&&(/(version|rewrite|rewritten|revised|rephrased|tone|draft|text|shorter|longer|professional|casual|formal|playful|funnier|concise|polished|updated)/i.test(e)||t);return n||r}function hc(e){var t=e.split("\n")[0].trim(),n=/^(would you like|let me know|i can also|feel free|shall i|happy to|i('d| would) be happy|want me to|do you want me)/i.test(t)||/^if you/i.test(t)&&/\b(i can|i could|i('d|'ll| would| will)|let me|shall i|want me)\b/i.test(t),r=/^(hvis du (vil|gerne|[oø]nsker)|vil du have|skal jeg|lad mig vide|du (kan|er velkommen))
3/i.test(t);return n||r}function vc(e){for(var t=e.split("\n");t.length&&!t[0].trim();)t.shift();if(!t.length)return"";if(gc(t[0].trim()))for(t.shift();t.length&&!t[0].trim();)t.shift();var n=t.join("\n").trim();if(!n)return"";for(var r=n.split(/\n\s*\n/);r.length>1&&hc(r[r.length-1].trim());)r.pop();return r.join("\n\n").trim()}function yc(e){var t=dc(e);return vc(t)||t}var wc="<<<SSREWRITE>>>";function bc(e){return String(e||"").replace(/<<<SSREWRITE>>>[\s\S]*?<<<SSREWRITE_SLUT>>>/g,"").replace(/<<<SSREWRITE>>>[\s\S]*$/g,"").replace(/```ssworkshop[\s\S]*?```/g,"").replace(/```ssworkshop[\s\S]*$/g,"").replace(/`ssworkshop\s*[\s\S]*?`/g,"").replace(/\n{3,}/g,"\n\n").trim()}function kc(e){var t=String(null==e?"":e),n=t.trim();if(n.length<2)return t;for(var r=[['"','"'],["â","â"],["â","â"],["â","â"],["â","â"],["»","«"],["«","»"]],o=n.charAt(0),i=n.charAt(n.length-1),a=null,l=0;l<r.length;l++)if(o===r[l][0]&&i===r[l][1]){a=r[l];break}if(!a)return t;var s=n.slice(1,-1);return s.trim()&&(/\n/.test(s)||s.trim().length>=80)?-1!==s.indexOf(a[0])||-1!==s.indexOf(a[1])?t:s.trim():t}function Sc(e){var t=String(null==e?"":e).trim();return/\b(send|giv|indsæt|indsend|indtast|del|upload|paste|sende|kopier|kopiér|læg|drop|share|give|type)\w*\b[\s\S]{0,45}\b(teksten|tekst|text|dokumentet|document)\b/i.test(t)||/\bs[Ã¥a]\s+\w+\s+jeg\b/i.test(t)?/\bteksten\b|\btekst\b|\bdokument/i.test(t)&&!/\btext\b/i.test(t)?"Her er din tekst â se den nedenfor.":"Here is your text â see it below.":e}function xc(e){var t=String(e||""),n=t.indexOf(wc);if(-1!==n){var r=t.slice(n+15),o=r.indexOf("<<<SSREWRITE_SLUT>>>"),i=function(e){var t=String(null==e?"":e).replace(/\r\n/g,"\n").replace(/\r/g,"\n");return(t=t.replace(/^\n+/,"").replace(/\n+$/,""))?t.split(/\n{2,}/).map(function(e){return(e=e.replace(/\n+$/,""))?"<p>"+(t=e,t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")).replace(/\n/g,"<br>")+"</p>":"";var t}).filter(Boolean).join(""):""}(-1!==o?r.slice(0,o):r);if(i)return{improved:i,display:Sc(bc(t)),complete:-1!==o}}var a=t.match(/```ssworkshop\s*\n?([\s\S]*?)\n?```/),l="",s="";if(a)l=a[1],s=t.replace(/```ssworkshop[\s\S]*?```/,"").replace(/\n{3,}/g,"\n\n").trim();else{var c=t.match(/`ssworkshop\s*([\s\S]*?)\s*`/);if(!c)return null;l=c[1],s=t.replace(/`ssworkshop\s*[\s\S]*?`/,"").replace(/\n{3,}/g,"\n\n").trim()}try{var d=JSON.parse(l.trim());if(d&&d.improved)return{improved:d.improved,display:Sc(s),complete:!0}}catch(e){}return null}function Tc(e){var t,n,r,o=e||{},i=o.labels||{},a=!!(o.selectionRange&&Number(o.selectionRange.length)>0&&String(o.selectedText||"").trim()),l=a?"selection":"document",s=o.docHash||ac(o.editorText||""),c=String(o.answer||"").trim(),d=String(o.query||"").trim(),u="rewrite"===o.forceResponseType||"draft"===o.forceResponseType?o.forceResponseType:sc(c,d),p=!!String(o.editorText||"").trim();"rewrite"===u?(t=a?i.apply_selection||"Anvend pÃ¥ markering":i.apply_document||"Anvend pÃ¥ dokument",n=i.preview||"Vis ændringer",r=i.insert_new||"Indsæt som ny tekst"):"draft"===u?(t=i.replace_draft||"Erstat med dette udkast",n=i.compare||"Sammenlign",r=i.insert||"Indsæt"):(t=a?i.try_selection||"Prøv pÃ¥ markering":i.try_document||"Prøv pÃ¥ dokument",n=i.preview_fallback||"ForhÃ¥ndsvis",r=i.insert||"Indsæt");var m="apply_rewrite",f="insert_at_cursor",g=r;return"draft"===u&&p&&(m="insert_at_cursor",t=r,f="apply_rewrite",g=i.replace_draft||"Erstat med dette udkast"),{version:2,responseType:u,scope:l,query:d,answer:c,insertText:yc(c),selectedText:a?String(o.selectedText||""):"",selectedHtml:a?String(o.selectedHtml||""):"",selectionRange:a?{index:Number(o.selectionRange.index)||0,length:Number(o.selectionRange.length)||0}:null,snapshot:{docHash:s,textLength:String(o.editorText||"").length},primary:{type:m,label:t},tertiary:{type:f,label:g},actions:[{type:"apply_rewrite",label:"apply_rewrite"===m?t:g,risk:a?"medium":"high"},{type:"preview_rewrite",label:n,risk:"low"},{type:"insert_at_cursor",label:"insert_at_cursor"===m?t:r,risk:"low"}]}}function Lc(e){var t=e.trim();if(0!==t.indexOf("data: "))return null;var n=t.substring(6);if("[DONE]"===n)return{type:"done"};try{var r=JSON.parse(n);return null===r?{type:"unparseable",raw:n}:{type:"chunk",data:r}}catch(e){return{type:"unparseable",raw:n}}}var Ec=null,Cc=null,_c=null;function Ac(e,t){if("function"!=typeof SKT)return t;var n=SKT(e);return n&&n!==e?n:t}var qc="idle",Mc="",Ic=!1,Bc=null,Hc=0,Kc=null,Dc=null,Pc=null,Nc=null,jc={words:[]},Rc=null,Fc=null,Oc="",Uc=parseFloat(localStorage.getItem("ss_tts_speed")||"1"),$c=[.75,1,1.25,1.5],zc=null,Gc=[],Vc="",Wc="",Jc=!1,Zc="",Yc=null,Qc=null,Xc=null,ed=se(),td=null,nd=null,rd=null,od=null,id=null,ad="",ld=0,sd=!1,cd="idle",dd='<span class="ai-typing-dots" aria-hidden="true"><span></span><span></span><span></span></span>';function ud(e,t,n){try{if(!window.ssOutcome)return;
3var r={type:t&&t.responseType||"",scope:t&&t.scope||"",cached:!(!t||!t._cachedRewrite&&!t._workshopImproved),forced:!(!t||!t._workshopImproved)};if(n)for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[o]=n[o]);window.ssOutcome.record("sofia","editor_action",e,r)}catch(e){}}var pd={},md=0,fd=null,gd=!1,hd=!1,vd=!1,yd=null,wd="",bd=!1,kd=null,Sd=!1,xd=null,Td=!1,Ld={},Ed="",Cd=null,_d={};function Ad(e){for(var t=0,n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t&=t;return t}var qd=!1,Md=null;function Id(){qd=!0,Md&&clearTimeout(Md),Md=setTimeout(function(){qd=!1,Md=null},1500)}function Bd(e){return"analyse"===e||"more-formal"===e||"shorten"===e||"rewrite"===e}function Hd(e){if(Bd(e)&&!bd&&Ec){var t=Ec.getLength()-1;t>0&&(_d[e]=Ad(Ec.getText(0,t).trim()),Id())}}var Kd=0;function Dd(e,t){try{var n={spelling:0,grammar:0,style:0,enhancement:0},r=[],o=0,i=t||{};for(var a in i)if(Object.prototype.hasOwnProperty.call(i,a)){o++;var l=i[a]||{},s=l.category,c=s&&"object"==typeof s?s.key||"":s||"",d=Object.prototype.hasOwnProperty.call(n,c)?c:"spelling";if(Object.prototype.hasOwnProperty.call(n,c)&&n[c]++,r.length<25){var u=(null!=l.original?String(l.original):"").slice(0,80),p=(null!=l.replacement?String(l.replacement):"").slice(0,80);u&&p&&r.push({o:u,r:p,c:d,e:(null!=l.explanation?String(l.explanation):"").slice(0,240)})}}var m=JSON.stringify({words_checked:parseInt(e,10)||0,corrections_total:o,category_counts:n,corrections:r,language:It()}),f={"Content-Type":"application/json"},g=function(e){fetch("/robots/skrivebord/grammar-api.php?action=record-writing-stats",{method:"POST",headers:e,body:m}).catch(function(){})};du().then(function(e){e&&(f.Authorization="Bearer "+e),g(f)}).catch(function(){g(f)})}catch(e){}}function Pd(e){return String(null==e?"":e).replace(/[&<>"]/g,function(e){return{"&":"&","<":"<",">":">",'"':"""}[e]})}function Nd(){var e=new Date;return e.getFullYear()+"-"+String(e.getMonth()+1).padStart(2,"0")}function jd(e){var t=String(null==e?"":e).match(/^(\d{4})-(\d{2})/);if(!t)return null;var n=parseInt(t[2],10);return n>=1&&n<=12?t[1]+"-"+t[2]:null}function Rd(e,t){var n="number"==typeof e?e:parseFloat(e);return isFinite(n)?Math.round(n).toLocaleString("da-DK"):"â"}function Fd(e,t,n){if(!e)return'<div class="calm-stat-empty"><p class="calm-stat-empty-title">'+SKT("stat.err_title")+'</p><p class="calm-stat-empty-body">'+SKT("stat.err_body")+'</p><button type="button" class="calm-stat-retry">'+SKT("stat.retry")+"</button></div>";var r=e.value||{},o=r.month||null,i=r.all||null,a=Array.isArray(e.rules)?e.rules:[],l=Array.isArray(e.patterns)?e.patterns:[];if(!i||0===(i.checks||0))return'<div class="calm-stat-empty"><p class="calm-stat-empty-title">'+SKT("stat.empty_title")+'</p><p class="calm-stat-empty-body">'+SKT("stat.empty_body")+"</p></div>";var s=t||jd(o&&o.since)||Nd(),c=n||[],d=c.indexOf(s),u=d>-1&&d+1<c.length?c[d+1]:-1===d&&c.length&&c[0]<s?c[0]:null,p=d>0?c[d-1]:null,m=!(!o||!((o.checks||0)>0||t)),f=m?o:i,g=function(e){try{var t=me()||"da";return new Intl.DateTimeFormat(t,{month:"long"}).format(e||new Date)}catch(e){return""}}(new Date(parseInt(s.slice(0,4),10),parseInt(s.slice(5,7),10)-1,1))+(s.slice(0,4)!==Nd().slice(0,4)?" "+s.slice(0,4):""),h=m?SKT("stat.value_month_title",{m:g}):SKT("stat.value_total_title"),v=function(e,t,n){return e?'<button type="button" class="calm-stat-monthnav" data-stat-month="'+Pd(e)+'" aria-label="'+Pd(n)+'"><span aria-hidden="true">'+("older"===t?"â¹":"âº")+"</span></button>":""},y=m?SKT("stat.value_line",{w:Rd(f.words),c:Rd(i.corrections)}):SKT("stat.value_line_total",{w:Rd(f.words)}),w='<div class="calm-stat-receipt"><div class="calm-stat-receipt-head"><p class="calm-stat-receipt-kicker">'+Pd(h)+"</p>"+(u||p?'<span class="calm-stat-monthnav-group">'+v(u,"older",SKT("stat.month_prev_aria"))+v(p,"newer",SKT("stat.month_next_aria"))+"</span>":"")+'</div><p class="calm-stat-receipt-num"><span class="calm-stat-bignum">'+Rd(f.corrections)+'</span> <span class="calm-stat-receipt-caught">'+Pd(SKT("stat.value_caught"))+'</span></p><p class="calm-stat-receipt-line">'+Pd(y)+"</p></div>",b=null;if(a.length){b=[];for(var k=0;k<a.length;k++){var S=String(a[k].rule||""),x=SKT("stat.rule_"+S);x&&x!=="stat.rule_"+S&&b.push({label:x,cnt:+a[k].cnt||0})}b.length||(b=null)}var T=b||t||!l.length?null:l;if(b||T){var L,E=b||T,C=0;for(L=0;L<E.length;L++)C+=+E[L].cnt||0;for(w+='<div class="calm-stat-rules"><div class="calm-stat-rules-title">
3'+Pd(SKT("stat.rules_title"))+"</div>",L=0;L<E.length;L++){var _=E[L],A=b?_.label:(_.example_original||"")+" â "+(_.example_replacement||""),q=+_.cnt||0,M=C>0?Math.max(6,Math.round(q/C*100)):6;w+='<div class="calm-stat-rulerow"><span class="calm-stat-rulename">'+Pd(A)+'</span><span class="calm-stat-rulebar" role="img" aria-label="'+Pd(SKT("stat.rules_row_aria",{n:q}))+'"><i style="width:'+M+'%"></i></span><span class="calm-stat-rulecnt">'+Rd(q)+"</span></div>"}w+="</div>"}return w+='<button type="button" class="ai-welcome-subtext ss-tip ss-learn-entry calm-stat-dict-entry" data-learn-entry="1"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg><span class="ss-tip-text">'+Pd(SKT("learn.entry"))+"</span></button>"}var Od=null,Ud=0;function $d(e){var t=wp||yp,n=document.getElementById(t.msgsId);if(n){"string"==typeof e&&/^\d{4}-\d{2}$/.test(e)?Od=e:null===e&&(Od=null),Od===Nd()&&(Od=null);var r=n.querySelector(".calm-statistik-panel");r||((r=document.createElement("div")).className="calm-statistik-panel",r.setAttribute("role","region"),r.setAttribute("aria-label","Din skrivestatistik"),n.appendChild(r)),r.innerHTML='<div class="calm-stat-loading" aria-live="polite">'+SKT("stat.loading")+"</div>";var o=++Ud,i=Od;!function(e,t){var n=function(e){try{t(e)}catch(e){}};try{var r="/robots/skrivebord/grammar-api.php?action=writing-stats"+(e&&/^\d{4}-\d{2}$/.test(e)?"&month="+e:""),o=function(e){fetch(r,{headers:e}).then(function(e){return e.json()}).then(function(e){n(e&&e.ok?e.data:null)}).catch(function(){n(null)})},i={};du().then(function(e){e&&(i.Authorization="Bearer "+e),o(i)}).catch(function(){o(i)})}catch(e){n(null)}}(i,function(e){if(!1!==r.isConnected&&o===Ud){var t=[];if(e&&Array.isArray(e.months))for(var n=0;n<e.months.length;n++){var a=jd(e.months[n]&&e.months[n].month_start);a&&t.push(a)}r.innerHTML=Fd(e,i,t);var l=r.querySelector(".calm-stat-retry");l&&l.addEventListener("click",function(){$d()});for(var s=r.querySelectorAll("[data-stat-month]"),c=0;c<s.length;c++)s[c].addEventListener("click",function(e){var t=e.currentTarget.getAttribute("data-stat-month");t&&$d(t)})}})}}var zd=/[^\p{Script=Latin}\p{Script=Common}\p{Script=Inherited}]/gu;function Gd(e,t){var n=e.match(zd);if(!n)return!1;var r=(t||"").match(zd)||[];return n.some(function(e){return-1===r.indexOf(e)})}function Vd(e,t,n){return!(!Ec||"function"!=typeof Ec.getText||t<=0||"string"!=typeof n)&&Ec.getText(e,t)===n}function Wd(e){for(var t=1;t<e.length;t++)if(e[t].index!==e[t-1].index+e[t-1].length)return!1;return!0}var Jd=0,Zd={};"undefined"!=typeof window&&(window.__editorActionStore=Zd);var Yd={spelling:{key:"spelling",sktKey:"corr.cat_spelling",color:"#DC2626"},grammar:{key:"grammar",sktKey:"corr.cat_grammar",color:"#2563EB"},style:{key:"style",sktKey:"corr.cat_style",color:"#7C3AED"},enhancement:{key:"enhancement",sktKey:"corr.cat_tone",color:"#0D9488"}};function Qd(e){if(Ec&&e&&!(e.length<=0)){var t=Ec.getText(e.index,e.length);t&&t.trim()&&(kd={index:e.index,length:e.length})}}function Xd(e){if(!Ec||!e||e.length<=0)return!1;var t=Ec.getText(e.index,e.length);if(!t||!t.trim())return!1;var n=t.length-t.replace(/^\s+/,"").length,r=t.length-t.replace(/\s+$/,"").length,o=e.length-n-r;if(o<=0)return!1;bd=!0,Vc=t.trim(),Qd(yd={index:e.index+n,length:o});try{wd=Ec.getSemanticHTML(yd.index,yd.length)}catch(e){wd=Vc}return!0}var eu=!1;function tu(){if(!eu){eu=!0;try{!function(){var e=document.getElementById("option-ai");if(!e)return;e.addEventListener("click",function(t){var n=e.classList.contains("active"),r=document.getElementById("ai-panel"),o=r&&"none"!==getComputedStyle(r).display,i=document.getElementById("ai-card-messages"),a=document.getElementById("ai-new-chat");if(n&&o&&i&&i.querySelector(".ai-msg")&&a){if(!t.isTrusted)return;a.click()}else{Iu();var l=document.getElementById("ai-panel");if(l)if(function(){if(!Ec)return;var e=Ec.getSelection();if(e&&e.length>0)Xd(e),Ju();else if(Xd(function(){if(!Ec||!kd)return null;var e=Math.max(0,Ec.getLength()-1);if(kd.index<0||kd.index>=e)return null;var t=Math.min(kd.length,e-kd.index);if(t<=0)return null;var n=Ec.getText(kd.index,t);return n&&n.trim()?{index:kd.index,length:t}:null}()))Ju();else{bd=!1;var t=Ec.getLength()-1;if(t>0){var n=Ec.getText(0,t),r=n.length-n.replace(/^\s+/,"").length,o=n.length-n.replace(/\s+$/,"").length;Vc=n.trim(),yd={index:r,length:t-r-o};try{wd=Ec.getSemanticHTML(r,t-r-o)}catch(e){wd=Vc}}else Vc="",wd="",yd=null}}(),l.querySelector(".ai-card")){var s=document.getElementById("ai-card-messages");if(s&&!gd){var c=s.querySelector(".ai-chips"),d=s.querySelector(".ai-msg"),u=s.querySelector(".ai-loading-icon, .ai-loading-bar");c||d||u||(s.innerHTML=vp())}Jc=!0}else Au(l),Jc=!0,Gc=[],function(){var e=window._supabase;if(!e)return;e.auth.getSession().then(function(t){var n=t&&t.data&&t.data.session;if(n){var r=new Date,o=new Date(r);o.setDate(o.getDate()+7),e.from("calendar_events").select("title, start_at, end_at, category, location, all_day").eq("user_id",n.user.id).gte("start_at",r.toISOString()).lte("start_at",o.toISOString()).order("start_at",{ascending:!0}).limit(20).then(function(e){if(!e.error&&e.data&&0!==e.data.length){var t=["[Min kalender â næste 7 dage]"];e.data.forEach(function(e){var n=new Date(e.start_at),r=function(e){var t=new Date(e);if(isNaN(t.getTime()))return e;var n=["jan","feb","mar","apr","maj","jun","jul","aug","sep","okt","nov","dec"];return["Søn","Man","Tirs","Ons","Tors","Fre","Lør"][t.getDay()]+" d. "+t.getDate()+". "+n[t.getMonth()]}(e.start_at),o="- "+r+" kl "+(e.all_day?"Hele dagen":String(n.getHours()).padStart(2,"0")+":"+String(n.getMinutes()).padStart(2,"0"))+": "+e.title;e.location&&(o+=" ("+e.location+")"),t.push(o)}),Wc=t.join("\n")}else Wc=""})}})}()}}),document.querySelectorAll(".hk-dropdown-option").forEach(function(e){"option-ai"!==e.id&&e.addEventListener("click",function(){var e=document.getElementById("ai-panel");
3e&&(e.style.display="none"),Zu(),Jc=!1,setTimeout(Mu,0)})})}()}catch(e){console.warn("[wow] initAiTab failed",e)}try{Yc&&Yc.init()}catch(e){console.warn("[wow] initToneTab failed",e)}try{Qc&&Qc.init()}catch(e){console.warn("[wow] initBedreTab failed",e)}try{!function(){var e=document.getElementById("sidebar-dropdown-items");if(!e||e.__ssTabGuard||"function"!=typeof MutationObserver)return;var t=function(){"function"==typeof window.SKT&&e.querySelectorAll("[data-i18n]").forEach(function(e){var t=e.getAttribute("data-i18n");if(t){var n=window.SKT(t);n&&n!==t&&e.textContent.trim()!==n&&(e.textContent=n)}})};try{var n=new MutationObserver(function(){t()});n.observe(e,{childList:!0,subtree:!0,characterData:!0}),e.__ssTabGuard=n,t()}catch(e){}}()}catch(e){console.warn("[wow] tablist i18n guard failed",e)}}var e=document.getElementById("option-ai");e&&e.classList.contains("active")&&setTimeout(function(){try{if(window.innerWidth<=767)return;if(!e.classList.contains("active"))return;if(document.body.classList.contains("ws-bedre-decision"))return;var t=document.getElementById("ai-panel");if(!t)return;try{Iu()}catch(e){t.style.display="flex"}t.querySelector(".ai-card")||(Au(t),Jc=!0,Gc=[])}catch(e){console.warn("[wow] early AI render failed",e)}},200)}var nu=!1;function ru(e){return e?(e.parentElement!==document.body&&document.body.appendChild(e),ou(e),e):null}function ou(e){e&&e.classList.toggle("bb-skrivebord",768===window.innerWidth)}function iu(e){document.body.classList.toggle("skrivebord-mobile-sheet-is-open",!!e)}function au(){return window.innerWidth<=767&&document.getElementById("skrivebord-mobile-sheet")}function lu(e){if(e){var t=au()&&document.getElementById("skrivebord-mobile-sheet-body");if(t)e.parentElement!==t&&t.appendChild(e);else if(e.parentElement&&"skrivebord-mobile-sheet-body"===e.parentElement.id){var n=document.querySelector(".correction-sidebar")||document.querySelector(".sidebar-controls");n&&n.appendChild(e)}}}function su(){var e=document.getElementById("ai-panel");if(!e){(e=document.createElement("div")).id="ai-panel",e.className="ai-panel-inner",e.style.display="flex";var t=au()&&document.getElementById("skrivebord-mobile-sheet-body")||document.querySelector(".correction-sidebar")||document.querySelector(".sidebar-controls");t?t.appendChild(e):document.body.appendChild(e)}return e.querySelector(".ai-card")||(Au(e),Jc=!0,Gc=[]),e}function cu(){lu(su()),Iu()}function du(){try{if(window.SSGrammarAuth&&"function"==typeof window.SSGrammarAuth.getAuthToken)return Promise.resolve(window.SSGrammarAuth.getAuthToken()).catch(function(){return""});if(window.SSAuth&&"function"==typeof window.SSAuth.token)return Promise.resolve(window.SSAuth.token()).catch(function(){return""});if(window._supabase&&window._supabase.auth&&"function"==typeof window._supabase.auth.getSession)return window._supabase.auth.getSession().then(function(e){var t=e&&e.data&&e.data.session;return t&&t.access_token?t.access_token:""}).catch(function(){return""})}catch(e){}return Promise.resolve("")}function uu(e,t,n){return!0===e&&!0===t&&("/robots/skrivebord/grammar-api.php?action=ai-text-analyse"===n||"/robots/skrivebord/grammar-api.php?action=ai-text-correct"===n)}function pu(e){var t={"Content-Type":"application/json"};return e&&(t.Authorization="Bearer "+e),t}function mu(e){if(window.handleSelectionTTS){if(e&&e._ttsLongPress)return e._ttsLongPress=!1,void Eu(e);if("idle"===qc){if(!Ec||!_c)return;var t=Ec.getLength()-1,n={index:_c.index,length:_c.length};if(t>0&&_c.length>=.9*t){var r=Ec.getSelection(!0),o=r?r.index:0,i=Ec.getLine(o),a=i?o-i[1]:o;a>0&&a<t&&(n={index:a,length:t-a})}var l=Ec.getText(n.index,n.length),s=l.trim();if(!s)return;var c=l.search(/\S/);c>0&&(n.index+=c),n.length=s.length,_c=n,Mc=s,window.updateSelectionTTSSelectedText&&window.updateSelectionTTSSelectedText(s);try{window.handleSelectionTTS()}catch(t){return console.warn("TTS bundle error:",t),qc="idle",void hu(e,"idle")}qc="loading",hu(e,"loading"),Cu(e),yu(e),xu()}else"loading"===qc?(window.stopSelectionTTS&&window.stopSelectionTTS(),qc="idle",hu(e,"idle"),clearInterval(vu),vu=null,Tu()):"playing"===qc?(window.pauseSelectionTTS&&window.pauseSelectionTTS(),qc="paused",hu(e,"paused"),clearInterval(vu),vu=null,Fc&&(cancelAnimationFrame(Fc),Fc=null)):"paused"===qc&&(window.resumeSelectionTTS&&window.resumeSelectionTTS(),qc="playing",hu(e,"playing"),yu(e),Lu(),setTimeout(function(){if("playing"===qc){var t=null;try{t=window.getSelectionTTSState&&window.getSelectionTTSState()}catch(e){}!(!t||!(t.isPlaying||t.currentAudio&&!t.currentAudio.paused))||(Mc&&window.updateSelectionTTSSelectedText&&window.handleSelectionTTS?(window.updateSelectionTTSSelectedText(Mc),window.handleSelectionTTS(),qc="loading",hu(e,"loading"),Tu(),xu()):(qc="idle",hu(e,"idle"),clearInterval(vu),vu=null,Tu()))}},600))}}function fu(e){Cc&&Cc.classList.toggle("is-paused",!!e)}function gu(){"idle"!==qc&&window.stopSelectionTTS&&window.stopSelectionTTS(),qc="idle",Mc="",Ic=!1,Kc=null,clearTimeout(Bc),clearInterval(vu),vu=null;var e=Cc&&Cc.querySelector('[data-action="tts"]');e&&hu(e,"idle"),fu(!1),Tu()}function hu(e,t){if(e){var n=e.querySelector("svg");n&&(e.classList.remove("hte-btn--active","hte-btn--loading"),"loading"===t?(n.innerHTML='<path d="M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"/><path d="M16 9a5 5 0 0 1 0 6"/>',e.classList.add("hte-btn--loading"),e.title=SKT("tts.loading_audio")||"Indlæser lydâ¦"):"playing"===t?(n.innerHTML='<rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/>',e.classList.add("hte-btn--active"),e.title=SKT("tts.pause")||"Pause"):"paused"===t?(n.innerHTML='<polygon points="5 3 19 12 5 21 5 3"/>',e.classList.add("hte-btn--active"),e.title=SKT("tts.resume")||"Fortsæt"):(n.innerHTML='<path d="M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"/><path d="M16 9a5 5 0 0 1 0 6"/><path d="M19.364 18.364a9 9 0 0 0 0-12.728"/>',e.title=SKT("tts.play")||"Læs markeret tekst op"),"paused"===t?function(){var e=null;try{e=window.getSelectionTTSState&&window.getSelectionTTSState()}catch(e){}fu(!(!e||!0!==e.isPaused))}():fu(!1))}}var vu=null;function yu(e){clearInterval(vu),vu=setInterval(function(){if("idle"===qc)return clearInterval(vu),void(vu=null);var t=null;try{t=window.getSelectionTTSState&&window.getSelectionTTSState()}catch(e){}if(t){var n=!!(t.isPlaying||t.currentAudio&&!t.currentAudio.paused),r=!!(t.isProcessing||t.isFetching||t.isWaitingForNextChunk||t.currentChunkRequest);"loading"===qc&&n?(qc="playing",hu(e,"playing"),Lu()):r||n||"playing"!==qc&&"loading"!==qc||(qc="idle",hu(e,"idle"),clearInterval(vu),vu=null,Tu(),setTimeout(function(){"idle"===qc&&Qg()},600))}},400)}function wu(e){for(var t,n=[],r=/\S+/g;null!==(t=r.exec(e||""));)n.push({word:t[0],offset:t.index,length:t[0].length});return n}function bu(e){return wu(String(e||"")).length}function ku(e,t){if(!t||!t.duration||isNaN(t.duration))return!1;var n=function(e){var t=e&&Array.isArray(e.allChunks)?e.allChunks:[],n=e&&"number"==typeof e.currentPlayingChunkIndex?e.currentPlayingChunkIndex:-1;if(!t.length||n<0||n>=t.length)return{chunkIndex:-1,wordStartIndex:0,wordCount:null};for(var r=0,o=0;o<n;o++)r+=bu(t[o]);return{chunkIndex:n,wordStartIndex:r,wordCount:bu(e.currentPlayingChunkText||t[n])}}(e),r=[n.chunkIndex,n.wordStartIndex,null===n.wordCount?"all":n.wordCount,t.duration].join(":");return r!==Oc&&(jc=function(e,t,n){var r=wu(e),o=r,i=[];if(!e||!t)return{words:o,sentences:i};if(n&&null!==n.wordCount&&(o=r.slice(n.wordStartIndex,n.wordStartIndex+n.wordCount)),!o.length)return{words:o,sentences:i};for(var a=0,l=0;l<o.length;l++)a+=o[l].length;for(var s=0,c=0;c<o.length;c++){var d=o[c].length/a;o[c].start=s,o[c].duration=d*t,s+=o[c].duration}for(var u,p=/[^.!?]+[.!?]*/g;null!==(u=p.exec(e));){for(var m=u.index,f=m+u[0].length,g=null,h=null,v=0;v<o.length;v++)o[v].offset>=m&&o[v].offset<f&&(g||(g=o[v]),h=o[v]);
3g&&h&&i.push({start:g.start,end:h.start+h.duration,textOffset:m,textLength:u[0].length})}return!i.length&&o.length&&i.push({start:o[0].start,end:o[o.length-1].start+o[o.length-1].duration,textOffset:0,textLength:e.length}),{words:o,sentences:i}}(Mc,t.duration,n),Oc=r),!(!jc.words||!jc.words.length)}function Su(){if(Ec&&Rc&&"playing"===qc){var e=null,t=null;try{t=(e=window.getSelectionTTSState&&window.getSelectionTTSState())&&e.currentAudio}catch(e){}if(t&&!t.paused&&ku(e,t)){for(var n=t.currentTime,r=null,o=jc.words,i=0;i<o.length;i++)if(n>=o[i].start&&n<o[i].start+o[i].duration){r=o[i];break}!r&&o.length&&n>=o[o.length-1].start&&(r=o[o.length-1]);var a=Rc.index;if(r&&Pc){var l=Ec.getBounds(a+r.offset,r.length);if(l){Pc.style.left=l.left+"px",Pc.style.top=l.top+"px",Pc.style.width=l.width+"px",Pc.style.height=l.height+"px",Pc.style.opacity="1";var s=Ec.container.querySelector(".ql-editor")||Ec.container,c=s.scrollTop,d=s.clientHeight;l.top+l.height>d+c-40?s.scrollTop=l.top-d/3:l.top<c+40&&(s.scrollTop=l.top-40)}}if(r){var u=Ec.getLine(a+r.offset);if(u&&u[0]&&u[0].domNode){var p=u[0].domNode;Nc!==p&&(Nc&&Nc.classList.remove("tts-active-line"),p.classList.add("tts-active-line"),Nc=p)}}Fc=requestAnimationFrame(Su)}else"playing"===qc&&(Fc=requestAnimationFrame(Su))}}function xu(){if(Ec&&_c&&Mc){Rc={index:_c.index,length:_c.length},function(){if(Tu(),!Ec||!Ec.container)return null;var e=Ec.container.querySelector(".ql-editor");e||(e=Ec.container);var t=document.createElement("div");t.id="tts-highlight-layer",e.appendChild(t);var n=document.createElement("div");n.className="tts-word-highlight",n.style.opacity="0",t.appendChild(n),Dc=t,Pc=n}();var e=function(){var t=null;try{t=window.getSelectionTTSState&&window.getSelectionTTSState()}catch(e){}var n=t&&t.currentAudio;n&&n.duration&&!isNaN(n.duration)?(ku(t,n),1!==Uc&&(n.playbackRate=Uc,window.setSelectionTTSpeed&&window.setSelectionTTSpeed(Uc)),Fc=requestAnimationFrame(Su)):"loading"!==qc&&"playing"!==qc||setTimeout(e,200)};setTimeout(e,300)}}function Tu(){Fc&&(cancelAnimationFrame(Fc),Fc=null),Pc&&Pc.classList.add("tts-fade-out"),Nc&&(Nc.classList.remove("tts-active-line"),Nc=null);var e=Dc;e&&setTimeout(function(){e.parentNode&&e.parentNode.removeChild(e)},550),Dc=null,Pc=null,jc={words:[],sentences:[]},Rc=null,Oc=""}function Lu(){Dc&&(Fc&&cancelAnimationFrame(Fc),Fc=requestAnimationFrame(Su))}function Eu(e){for(var t=-1,n=0;n<$c.length;n++)if(Math.abs($c[n]-Uc)<.01){t=n;break}Uc=$c[t=(t+1)%$c.length],localStorage.setItem("ss_tts_speed",String(Uc));try{var r=window.getSelectionTTSState&&window.getSelectionTTSState();r&&r.currentAudio&&(r.currentAudio.playbackRate=Uc),window.setSelectionTTSpeed&&window.setSelectionTTSpeed(Uc)}catch(e){}if(Mc)try{var o=window.getSelectionTTSState&&window.getSelectionTTSState();o&&o.currentAudio&&o.currentAudio.duration&&(Oc="",ku(o,o.currentAudio))}catch(e){}Cu(e)}function Cu(e){if(e){var t=e.querySelector(".tts-speed-badge");1!==Uc?(t||(e.style.position="relative",(t=document.createElement("span")).className="tts-speed-badge",e.appendChild(t)),t.textContent=Uc+"x",t.style.opacity="1"):t&&(t.style.opacity="0")}}function _u(e,t){if(e)if(t=t||0,"function"==typeof SKT){var n=!1;e.querySelectorAll("[data-i18n]").forEach(function(e){var t=e.getAttribute("data-i18n");if(t){var r=SKT(t);r&&r!==t?e.textContent=r:n=!0}}),e.querySelectorAll("[data-i18n-placeholder]").forEach(function(e){var t=e.getAttribute("data-i18n-placeholder"),n=SKT(t);n&&n!==t&&(e.placeholder=n)}),e.querySelectorAll("[data-i18n-title]").forEach(function(e){var t=e.getAttribute("data-i18n-title"),n=SKT(t);n&&n!==t&&(e.title=n)}),e.querySelectorAll("[data-i18n-aria-label]").forEach(function(e){var t=e.getAttribute("data-i18n-aria-label"),n=SKT(t);n&&n!==t&&e.setAttribute("aria-label",n)}),n&&t<15&&setTimeout(function(){_u(e,t+1)},120)}else t<15&&setTimeout(function(){_u(e,t+1)},120)}function Au(e){sp(),e.innerHTML=['<div class="ai-card ai-card--sidebar" id="ai-card">','<div class="ai-card-header">','<button class="ai-new-chat-btn" id="ai-new-chat" type="button" data-i18n-title="chip.back_to_options" title="'+SKT("chip.back_to_options")+'" data-i18n-aria-label="chip.back_to_options" aria-label="'+SKT("chip.back_to_options")+'">','<svg viewBox="0 0 24 24">
3<path d="M15 18l-6-6 6-6"/><path d="M9 12h10"/></svg>','<span class="ai-new-chat-label" data-i18n="tone.back">'+SKT("tone.back")+"</span>","</button>","</div>",'<div class="ai-card-messages" id="ai-card-messages" role="log" aria-label="Sofia">',vp(),"</div>",'<div class="ai-card-input-row">','<div class="ai-card-input-wrap">','<textarea id="ai-card-input" class="ai-card-input" data-i18n-placeholder="ai.placeholder.default" placeholder="'+(SKT("ai.placeholder.default")||SKT("ai.placeholder"))+'" data-i18n-aria-label="ai.placeholder.default" aria-label="'+(SKT("ai.placeholder.default")||SKT("ai.placeholder"))+'" autocomplete="off" rows="1"></textarea>','<button type="button" class="ai-card-mic ss-mic" id="ai-card-mic" data-i18n-title="stt.dictate" title="'+SKT("stt.dictate")+'" data-i18n-aria-label="stt.dictateAi" aria-label="'+SKT("stt.dictateAi")+'">','<svg viewBox="0 0 24 24"><path d="M12 23V20M12 20C9.87827 20 7.84344 19.1571 6.34315 17.6569C4.84285 16.1566 4 14.1217 4 12M12 20C14.1217 20 16.1566 19.1571 17.6569 17.6569C19.1571 16.1566 20 14.1217 20 12M12 17C9.25 17 7 14.828 7 12.172V5.828C7 3.172 9.25 1 12 1C14.75 1 17 3.172 17 5.828V12.172C17 14.828 14.75 17 12 17Z"/></svg>',"</button>",'<button type="button" class="ai-card-send" id="ai-card-send" data-i18n-title="action.send" title="'+SKT("action.send")+'" data-i18n-aria-label="action.send" aria-label="'+SKT("action.send")+'">','<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><line x1="12" y1="20" x2="12" y2="5"></line><polyline points="6 11 12 5 18 11"></polyline></svg>',"</button>","</div>","</div>","</div>"].join(""),function(e){e.querySelector("#ai-card-send").addEventListener("click",function(){var t=e.querySelector("#ai-card-input");if(t&&t.value.trim())try{lm(t.value.trim()),t.value="","TEXTAREA"===t.tagName&&(t.style.height="auto",t.style.overflowY="hidden");var n=e.querySelector("#ai-card-send");n&&(n.disabled=!0,n.style.opacity="0.3")}catch(t){console.error("Send error:",t);var r=document.getElementById("ai-card-messages");r&&!r.querySelector(".ai-chips")&&(r.innerHTML=vp());var o=e.querySelector("#ai-card-send");o&&(o.disabled=!1,o.style.opacity=""),Pp=!1}});var t=e.querySelector("#ai-new-chat");t&&t.addEventListener("click",function(){var e=document.getElementById("ai-card-messages");if(e&&e.querySelector("[data-learn-panel]"))return gd&&Pg(wp||yp)&&Object.keys(pd).length>0?(jg(document.body.classList.contains("corrections-statistik-mode")?"statistik":"liste"),lp(),void cp()):(document.body.classList.contains("corrections-statistik-mode")?(e.innerHTML="",$d()):e.innerHTML=vp(),lp(),void cp());Gc=[],tp(),Pp=!1,zp(yp),gd&&Mg(),t.classList.remove("visible"),Mu();var n=document.getElementById("ai-card-messages");n&&(n.style.opacity="0",setTimeout(function(){n.innerHTML=vp(),n.style.opacity="1",lp(),cp()},150));var r=document.getElementById("ai-card-input");r&&(r.value="",r.style.height="auto",r.style.overflowY="hidden",r.focus())});var n=e.querySelector("#ai-card-input");n&&"TEXTAREA"===n.tagName&&n.addEventListener("input",function(){this.style.height="auto";var e=84,t=Math.min(this.scrollHeight,e);this.style.height=t+"px",this.style.overflowY=this.scrollHeight>e?"auto":"hidden"});var r=e.querySelector("#ai-card-send");function o(){if(r&&n){var e=n.value.trim().length>0;r.disabled=!e,r.style.opacity=e?"":"0.3"}}o(),n.addEventListener("input",o),n.addEventListener("keydown",function(e){if("Enter"===e.key&&!e.shiftKey&&this.value.trim())return e.preventDefault(),lm(this.value.trim()),this.value="",this.style.height="auto",this.style.overflowY="hidden",void o();var t=this;setTimeout(function(){t.style.height="auto";var e=84,n=Math.min(t.scrollHeight,e);t.style.height=n+"px",t.style.overflowY=t.scrollHeight>e?"auto":"hidden"},0)});var i=e.querySelector("#ai-card-mic");i&&i.addEventListener("click",function(){gf()});e.addEventListener("click",function(t){var n=t.target.closest("#ai-chips-toggle");if(n){var r=e.querySelector("#ai-chips-more");if(r){var o="none"!==r.style.display;r.style.display=o?"none":"flex",n.querySelector(".ai-chips-toggle-text").textContent=o?"Flere muligheder â¾":"Færre â´"}}else{if(t.target.closest("[data-learn-entry]"))!function(e){var t=document.getElementById(e.msgsId);if(!t)return;ag=!1,ig=[],t.innerHTML=dg(),pg(e,t),lp();var n=window._supabase||window.supabase;if(!n||!n.from)return ig=null,void ug(e);var r=Rf,o=Jf;Promise.all([n.from("korrektur_learning_prefs").select("enabled").limit(1),n.from("korrektur_suppress_rules").select("id,rule_type,params,label_da,status,created_by,updated_at").eq("status","active").gt("expires_at",(new Date).toISOString()).order("updated_at",{ascending:!1}).limit(50)]).then(function(t){var n=t[0],i=t[1];r===Rf&&n&&!n.error&&Array.isArray(n.data)&&(jf=!(n.data.length&&n.data[0]&&!1===n.data[0].enabled)),o===Jf&&(ig=i&&!i.error&&Array.isArray(i.data)?i.data:null),ug(e)}).catch(function(){o===Jf&&(ig=null),ug(e)})}(yp);else{var i=t.target.closest(".ai-chip")||t.target.closest(".ai-action-item");if(i){var a=i.dataset.action;if(a){if("true"===i.dataset.processing)return;Vp(a)}}}}}),e.addEventListener("input",function(e){var t=e.target.closest?e.target.closest(".ai-level-range"):null;if(t){var n=parseInt(t.value,10);if(1===n||2===n||3===n){try{localStorage.setItem(mp,String(n))}catch(e){}!function(e,t){var n=t||document.querySelector("#ai-card-messages .ai-level-chip");if(!n)return;var r=fp[e];if(!r)return;n.setAttribute("data-level",String(e));var o=n.querySelector(".ai-level-run");o&&o.setAttribute("data-action",r.action);var i=n.querySelector(".ai-chip-label");i&&(i.setAttribute("data-i18n",r.labelKey),i.textContent=SKT(r.labelKey));var a=n.querySelector(".ai-chip-desc");a&&(a.setAttribute("data-i18n",r.descKey),a.textContent=SKT(r.descKey));var l=n.querySelector(".ai-sparkle-icon");if(l){l.setAttribute("data-bars",String(e));for(var s=l.querySelectorAll("rect"),c=0;c<s.length;c++)s[c].setAttribute("fill",c<e?"currentColor":"none")}var d=n.querySelector(".ai-level-range");
3d&&String(d.value)!==String(e)&&(d.value=String(e))}(n,t.closest(".ai-level-chip"))}}})}(zc=e.querySelector("#ai-card"));var t=e.querySelector("#ai-card-messages");if(t&&(t.style.transition="opacity 0.15s ease"),t&&!t.__ssBackSync&&"function"==typeof MutationObserver)try{var n=null,r=new MutationObserver(function(){n&&clearTimeout(n),n=setTimeout(function(){n=null,lp()},80)});r.observe(t,{childList:!0,subtree:!0}),t.__ssBackSync=r}catch(e){}ap(),cp(),_u(e),function(e){if(e&&!e.__ssI18nObs&&"function"==typeof MutationObserver){var t=function(e){if(e&&"function"==typeof window.SKT){var t=e.getAttribute("data-i18n");if(t){var n=window.SKT(t);n&&n!==t&&e.textContent.trim()!==n&&(e.textContent=n)}}},n=function(e){e&&1===e.nodeType&&(e.hasAttribute&&e.hasAttribute("data-i18n")&&t(e),e.querySelectorAll&&e.querySelectorAll("[data-i18n]").forEach(t))};try{var r=new MutationObserver(function(e){for(var t=0;t<e.length;t++)for(var r=e[t].addedNodes,o=0;o<r.length;o++)n(r[o])});r.observe(e,{childList:!0,subtree:!0}),e.__ssI18nObs=r,n(e)}catch(e){}}}(e)}function qu(e,t){return!!function(e){if(!e)return!1;try{return"none"!==getComputedStyle(e).display}catch(e){return!1}}(e)&&((!t||!e.querySelector(".bedre-result-wrap"))&&!!e.querySelector(".ai-new-chat-btn.visible"))}function Mu(){var e=qu(document.getElementById("ai-panel"),!1)||qu(document.getElementById("tone-panel"),!1)||qu(document.getElementById("bedre-panel"),!0);document.body.classList.contains("corrections-review-mode")&&(e=!1),document.body.classList.toggle("sk-ai-conversation-active",!!e)}function Iu(){if(au()&&!nu&&window.openMobileAiSheet)window.openMobileAiSheet("ai");else{document.querySelectorAll(".hk-dropdown-option").forEach(function(e){e.classList.remove("active")});var e=document.getElementById("option-ai");e&&e.classList.add("active"),Zg(),(gd||Object.keys(pd).length>0)&&Bp(),Kp("tone"),Hp("ai"),Dp("ai");[".improv-inner",".correction-inner",".style-inner","#chat-view","#bedre-panel","#tone-panel"].forEach(function(e){var t=document.querySelector(e);t&&(t.style.display="none")});var t=document.getElementById("ai-panel");t&&(t.style.display="flex"),Yc&&Yc.isOpen(!1),Qc&&Qc.isOpen(!1);var n=document.getElementById("chat-reset-link");n&&(n.style.display="none"),function(){var e=document.getElementById("ai-panel");if(e){if(!e.querySelector(".ai-card"))return Au(e),Jc=!0,void(Gc=[]);var t=document.getElementById("ai-card-messages");t&&(t.querySelector(".ai-msg")||t.querySelector(".ai-welcome")||t.querySelector(".ai-loading-icon, .ai-loading-bar")||t.querySelector(".calm-corrections-list")||t.querySelector("[data-learn-panel]")||t.querySelector(".ai-empty-state")||ap()||(t.innerHTML=vp()))}}(),Mu()}}function Bu(e,t){var n=e.querySelector(".mobile-tab-toggle");if(n){var r=n.querySelector('.mobile-tab-btn[data-tab="kladde"]');if(t&&!r){var o=document.createElement("button");o.className="mobile-tab-btn",o.setAttribute("data-tab","kladde"),o.setAttribute("data-i18n","wm.kladde_title"),o.setAttribute("type","button"),o.textContent=("function"==typeof SKT?SKT("wm.kladde_title"):"")||"Kladde",n.appendChild(o),o.addEventListener("click",function(){Ku("kladde")})}else!t&&r&&r.remove()}}function Hu(e){return"tone"===e||"ai"===e?"corrections":e||"corrections"}function Ku(e){var t=ru(document.getElementById("skrivebord-mobile-sheet"));if(t){var n="kladde"===(e=Hu(e||"corrections"));Bu(t,n);var r=t.querySelector('.mobile-tab-btn[data-tab="'+e+'"]');r&&"none"!==getComputedStyle(r).display||(e="corrections");var o="ai"===e;t.querySelectorAll(".mobile-tab-btn").forEach(function(t){t.classList.toggle("active",t.getAttribute("data-tab")===e)});var i=document.getElementById("skrivebord-mobile-sheet-body");if(i){lu(su()),function(e){e&&[".improv-inner",".correction-inner",".style-inner"].forEach(function(t){var n=document.querySelector(t);n&&n.parentElement!==e&&e.appendChild(n)})}(i);var a=i.querySelector("#ai-panel"),l=document.getElementById("tone-panel"),s=i.querySelector(".improv-inner"),c=i.querySelector(".correction-inner"),d=i.querySelector(".style-inner"),u=i.querySelector("#wm-kladde-container");n&&u&&u.parentElement===i&&i.firstElementChild!==u&&i.insertBefore(u,i.firstElementChild);var p,m=(!(p=window.quill1)||"function"!=typeof p.getText||0===p.getText().replace(/\s/g,"").length)&&"corrections"===e,f=o||"corrections"===e&&!m,g=!1;if(s&&s.children.length>0&&(g=!0),!g&&a){a.querySelector(".ai-loading, .ai-spinner")&&(g=!0);var h=a.querySelector("#ai-card-messages");if(h){var v=h.textContent||"";(v.indexOf("Sofia")>=0||v.indexOf("Annuller")>=0)&&(g=!0),(h.querySelector(".correction-summary-badges")||h.querySelector(".calm-corrections-list")||h.querySelector("#accept-all-btn"))&&(g=!0),h.querySelector("[data-learn-panel]")&&(g=!0)}}a&&(a.style.display=f?"":"none");var y=a?a.querySelector(".ai-card-input-row"):null;if(y&&(y.style.display=o?"":"none"),f&&!g&&a){var w=a.querySelector("#ai-card-messages");!w||w.querySelector(".ai-msg")||w.querySelector(".ai-loading-icon")||(w.innerHTML=vp())}if(l&&(l.style.display="none"),s){var b=s.children.length>0;s.style.display=o||"corrections"!==e||m||!b?"none":"flex"}c&&(o||"corrections"!==e||m)&&(c.style.display="none"),d&&(d.style.display="none"),n&&(a&&(a.style.display="none"),s&&(s.style.display="none"),c&&(c.style.display="none")),u&&(u.style.display=n?"flex":"none");var k=document.getElementById("sk-mobile-empty-state");if(k){k.style.display=!o&&m?"flex":"none",n&&(k.style.display="none");var S=k.querySelector(".sk-mobile-empty-desc");if(S){var x="function"==typeof SKT&&SKT("empty.body")||"Skriv eller indsæt tekst i editoren, så kan jeg hjælpe dig.";S.textContent=x}}}}}window._wf={registerTone:function(e){if(Yc=e,eu)try{e.init()}catch(e){}},registerBedre:function(e){if(Qc=e,eu)try{e.init()}catch(e){}},registerActions:function(e){for(var t in window._aiActions||(window._aiActions={}),e)e.hasOwnProperty(t)&&(window._aiActions[t]=e[t])},handleChipAction:function(e,t){return Vp(e,t)},runGrammarCheck:function(e){try{cu()}catch(e){}Np=null;var t=Vp("analyse",null,e);return Np||(!1===t?"unavailable":"started")},handleAiSend:function(e,t,n,r){lm(e,t,n,r)},syncAiConversationChrome:function(){Mu()},cancelAiPanelConversation:function(e){zp(e)},cancelActiveCorrection:function(){km()},escapeHtml:function(e){return rh(e)},toggleStt:function(e){gf(e)},clearChatStorage:function(){tp()},resetChatForDocumentChange:function(e){!function(e){var t=e?ep(e):null;tm(Gc=t||[]),t||tp();Pp=!1;var n=document.getElementById("ai-card-messages");n&&(t&&t.length>0?ip(t,n):n.innerHTML=vp());lp()}(e)},clearCorrections:function(){Mg()},hideCorrectionPopup:function(){Zg()},saveCorrections:function(){Bp()},loadCorrections:function(e){Hp(e)},hideMarks:function(e){Kp(e)},showMarks:function(e){Dp(e)},chipInFlight:function(e){return void 0!==e&&(Pp=e),Pp},aiHistory:function(e){return void 0!==e&&(Gc=e),Gc},correctionMode:function(){return gd},hasCorrectionMap:function(){return Object.keys(pd).length>0},correctionCount:function(){return Object.keys(pd).length},voiceApplyResult:function(){return jp},aiIsOpen:function(e){return void 0!==e&&(Jc=e),Jc},acceptAllCorrectionsMobile:function(){Cg()},hasForeignScript:function(e,t){return Gd(e,t)},setEditorRobotLoading:function(e,t){Mm(e,t)},getSelectionRange:function(){return yd},wasSelectionExplicit:function(){return bd}};var Du=null,Pu=0;
3window.openMobileAiSheet=function(e){var t=ru(document.getElementById("skrivebord-mobile-sheet"));if(t){if(e=Hu(e||"corrections"),nu=!0,Pu&&(clearTimeout(Pu),Pu=0),Du){var n=t.querySelector(".skrivebord-mobile-sheet-content");n&&n.removeEventListener("animationend",Du),Du=null}var r=document.querySelector(".mobile-ai-wrap.open");r&&r.classList.remove("open"),t.classList.remove("closing"),ou(t),t.classList.add("open"),t.removeAttribute("inert"),t.setAttribute("aria-hidden","false"),iu(!0),Ku(e),nu=!1}},window.closeMobileAiSheet=function(){var e=ru(document.getElementById("skrivebord-mobile-sheet")),t=document.querySelector(".sk-tb-active");if(t&&t.classList.remove("sk-tb-active"),e&&e.classList.contains("open")){if(iu(!1),!e.classList.contains("closing")){e.classList.add("closing");var n=e.querySelector(".skrivebord-mobile-sheet-content");if(n){var r=!1;Du=function t(){r||(r=!0,Pu&&(clearTimeout(Pu),Pu=0),Du=null,e.classList.remove("open","closing"),e.setAttribute("inert",""),e.setAttribute("aria-hidden","true"),n.removeEventListener("animationend",t))},n.addEventListener("animationend",Du,{once:!0}),Pu=setTimeout(Du,300)}else e.classList.remove("open","closing"),e.setAttribute("inert",""),e.setAttribute("aria-hidden","true")}}else iu(!1)},window.startMobileGrammarCheck=function(){var e=window.quill1;if(e&&"function"==typeof e.getText&&0!==e.getText().replace(/\s/g,"").length){var t=document.getElementById("skrivebord-mobile-sheet");if(t){!t.classList.contains("open")||t.classList.contains("closing")?window.openMobileAiSheet("corrections"):Ku("corrections");var n=su();n&&(n.style.display=""),setTimeout(function(){Vp("analyse")},80)}}};var Nu=!1;function ju(e){var t=document.getElementById("sk-tb-check");t&&(e?(t.classList.add("sk-tb-loading"),t.setAttribute("aria-busy","true"),t.disabled=!0):(t.classList.remove("sk-tb-loading"),t.removeAttribute("aria-busy"),t.disabled=!1))}function Ru(){Nu=!1,function(){var e=document.getElementById("inputText");if(e){e.classList.remove("sk-mobile-grammar-loading");var t=e.querySelector(".sk-mobile-grammar-skeleton");t&&t.remove()}}(),ju(!1);var e=document.getElementById("ai-card-messages");if(e){var t=e.querySelector(".ai-loading-icon");if(t){var n=t.closest(".ai-empty-state");n&&n.remove()}}}var Fu={};function Ou(e,t){try{e[t.id||"m"+Object.keys(e).length]={original:t.original,replacement:t.replacement,category:"sentence"===t.scope?Yd.style:yf(t.original,t.replacement,Ed),explanation:""}}catch(e){}}function Uu(){var e=ru(document.getElementById("skrivebord-mobile-sheet"));if(e){var t=e.querySelector(".skrivebord-mobile-sheet-backdrop");t&&t.addEventListener("click",window.closeMobileAiSheet),e.querySelectorAll(".mobile-tab-btn").forEach(function(e){e.addEventListener("click",function(){Ku(Hu(this.getAttribute("data-tab")))})}),document.addEventListener("keydown",function(t){"Escape"===t.key&&e.classList.contains("open")&&window.closeMobileAiSheet()});var n=e.querySelector(".skrivebord-mobile-sheet-handle");if(n){var r=0;n.addEventListener("touchstart",function(e){r=e.touches[0].clientY},{passive:!0}),n.addEventListener("touchend",function(e){e.changedTouches[0].clientY-r>40&&window.closeMobileAiSheet()},{passive:!0})}}}function $u(){var e=document.getElementById("sk-fix-all-pill");e&&e.addEventListener("click",function(){Cg()})}window.startMobileDirectCheck=function(){var e=window.quill1;e&&"function"==typeof e.getText&&(0!==e.getText().replace(/\s/g,"").length&&(Pp||(lu(su()),Nu=!0,function(){var e=document.getElementById("inputText");if(e&&!e.querySelector(".sk-mobile-grammar-skeleton")){e.classList.add("sk-mobile-grammar-loading");var t=document.createElement("div");t.className="sk-mobile-grammar-skeleton",t.setAttribute("aria-hidden","true"),e.appendChild(t)}}(),ju(!0),setTimeout(function(){Vp(fp[gp()].action)},80))))},"loading"===document.readyState?document.addEventListener("DOMContentLoaded",Uu):Uu(),"loading"===document.readyState?document.addEventListener("DOMContentLoaded",$u):$u();var zu=window.innerWidth<=767;window.addEventListener("resize",function(){var e=window.innerWidth<=767;if(ou(document.getElementById("skrivebord-mobile-sheet")),e!==zu&&(zu=e,!e)){var t=ru(document.getElementById("skrivebord-mobile-sheet"));if(Pu&&(clearTimeout(Pu),Pu=0),Du&&t){var n=t.querySelector(".skrivebord-mobile-sheet-content");n&&n.removeEventListener("animationend",Du),Du=null}t&&(ou(t),t.classList.remove("open","closing"),t.setAttribute("inert",""),t.setAttribute("aria-hidden","true")),iu(!1),function(){var e=document.querySelector(".correction-sidebar");
3if(e){[".improv-inner",".correction-inner",".style-inner"].forEach(function(t){var n=document.querySelector(t);n&&n.parentElement&&"skrivebord-mobile-sheet-body"===n.parentElement.id&&e.appendChild(n)});var t=document.getElementById("wm-kladde-container");t&&t.parentElement&&"skrivebord-mobile-sheet-body"===t.parentElement.id&&e.appendChild(t);var n=document.getElementById("skrivebord-mobile-sheet");n&&Bu(n,!1)}}(),lu(document.getElementById("ai-panel")),lu(document.getElementById("tone-panel"))}});var Gu=0,Vu=window.openMobileAiSheet;if(window.openMobileAiSheet=function(e){return Gu=Date.now(),Vu(e)},window.visualViewport){var Wu=window.visualViewport.height;window.visualViewport.addEventListener("resize",function(){var e=document.getElementById("skrivebord-mobile-sheet");if(e&&e.classList.contains("open")){var t=Wu-window.visualViewport.height;Wu=window.visualViewport.height,t>150&&Date.now()-Gu>600&&window.closeMobileAiSheet()}else Wu=window.visualViewport.height})}function Ju(){if(Ec&&yd&&!Sd){hd=!0;try{Ec.formatText(yd.index,yd.length,{background:"rgba(234,179,8,0.08)"})}catch(e){console.warn("highlightSelection error:",e.message)}finally{hd=!1}Sd=!0}}function Zu(){if(Ec&&yd&&Sd){hd=!0;try{Ec.formatText(yd.index,yd.length,{background:!1})}catch(e){console.warn("unhighlightSelection error:",e.message)}finally{hd=!1}Sd=!1}}var Yu="skrivsikkert_ai_chat";function Qu(){return window.SkrivebordApp&&window.SkrivebordApp.currentDocId||null}function Xu(){try{var e=Qu();if(!e)return;var t={docContext:e,messages:Gc.slice(-20)};localStorage.setItem(Yu,JSON.stringify(t))}catch(e){}}function ep(e){try{var t=localStorage.getItem(Yu);if(!t&&(t=sessionStorage.getItem(Yu)))try{localStorage.setItem(Yu,t)}catch(e){}if(!t)return null;var n=JSON.parse(t);if(n&&"object"==typeof n&&!Array.isArray(n)&&n.messages){var r=e||Qu();return r?n.docContext!==r?null:Array.isArray(n.messages)&&n.messages.length>0?n.messages:null:null}if(Array.isArray(n))return tp(),null}catch(e){}return null}function tp(){try{localStorage.removeItem(Yu)}catch(e){}try{sessionStorage.removeItem(Yu)}catch(e){}}var np=/\[EMBED:\w+:\w+:\{[\s\S]*?\}\]/g,rp=/\[EMBED:[^\]]*$/;function op(e){return String(null==e?"":e).replace(np,"").replace(rp,"")}function ip(e,t){if(!t)return!1;t.innerHTML="";for(var n=0;n<e.length;n++){var r=e[n];if("user"===r.role)ih(t,"user",rh(r.content));else if("assistant"===r.role){var o=xc(r.content),i=bc(op(r.content)),a=(i=kc(i))?ah(i):"",l=e[n-1]&&"user"===e[n-1].role?e[n-1].content:"",s=null,c=sm(),d=!(!o||!wm(o.improved)),u=i||(o?wm(o.improved):"");l&&(d||cc({hasQuill:!!Ec,answer:u,editorText:c,query:l,isCorrection:!1,chipAction:null}))&&(s=bm(Tc({answer:u,query:l,editorText:c,selectedText:"",selectedHtml:"",selectionRange:null,docHash:ac(c),forceResponseType:o&&o.improved?"rewrite":"",labels:{apply_selection:SKT("ea.apply_selection"),apply_document:SKT("ea.apply_document"),preview:SKT("ea.preview"),insert_new:SKT("ea.insert_new"),replace_draft:SKT("ea.replace_draft"),compare:SKT("ea.compare"),insert:SKT("ea.insert"),try_selection:SKT("ea.try_selection"),try_document:SKT("ea.try_document"),preview_fallback:SKT("ea.preview_fallback")}}))),s&&o&&(!1!==o.complete?(s._workshopImproved=Fm(o.improved),s._cachedRewrite=s._workshopImproved):s._rewriteTruncated=!0),s&&(s._restoredFromStorage=!0),!a&&o&&(a="<p>"+rh(SKT("ea.kicker")||"Sofia har et forslag")+"</p>"),tf(i||"",null,null,ih(t,"assistant",'<div class="ai-msg-wrapper"><div class="ai-msg-content">'+a+"</div>"+ef(i||"",s)+"</div>"))}}return!0}function ap(){var e=ep();return!(!e||0===e.length)&&(tm(Gc=e),!!ip(e,document.getElementById("ai-card-messages"))&&(lp(),!0))}function lp(){var e=document.getElementById("ai-new-chat");if(e){var t=document.getElementById("ai-card-messages");if(t){var n=t.querySelector(".ai-msg")||t.querySelector("[data-learn-panel]");document.body.classList.contains("corrections-review-mode")&&(n=null),n?e.classList.add("visible"):e.classList.remove("visible")}}var r=document.getElementById("tone-new-chat"),o=document.getElementById("tone-card-messages");r&&o&&(o.querySelector(".ai-msg")?r.classList.add("visible"):r.classList.remove("visible"));Mu()}function sp(){if(!Ec)return Zc="";try{var e=Ec.getLength()-1;Zc=e>0?Ec.getText(0,e).trim():""}catch(e){Zc=""}return Zc}function cp(){var e=document.getElementById("ai-card-input");if(e){var t="ai.placeholder.default",n=SKT(t);n&&n!==t||(n="Spørg Sofia om din tekst..."),e.getAttribute("placeholder")!==n&&e.setAttribute("placeholder",n),e.setAttribute("data-i18n-placeholder",t)}}var dp=null,up=null;function pp(){dp&&clearTimeout(dp),dp=setTimeout(function(){dp=null;var e=window.SKT&&window.SKT.lang?window.SKT.lang():null;if(!e||e!==up){up=e,cp();var t=document.querySelector("#ai-card-messages .ai-welcome");t?t.outerHTML=vp():document.querySelector("#ai-card-messages [data-learn-panel]")&&ug(yp)}},0)}"undefined"!=typeof window&&(window.addEventListener("ss:lang-changed",pp),window.addEventListener("ss:lang-ui-ready",pp));var mp="sk_proof_level",fp={1:{action:"rewrite",labelKey:"chip.rewrite",descKey:"chip.basic_desc"},2:{action:"shorten",labelKey:"chip.shorten",descKey:"chip.full_desc"},3:{action:"analyse",labelKey:"chip.check_all",descKey:"chip.check_desc"}};function gp(){var e=null;try{e=parseInt(localStorage.getItem(mp),10)}catch(e){}return 1===e||2===e||3===e?e:3}
3function hp(e){return'<svg class="ai-sparkle-icon" viewBox="0 0 24 24" width="20" height="20" aria-hidden="true" data-bars="'+e+'"><rect x="4" y="13" width="4" height="8" rx="1" fill="'+(e>=1?"currentColor":"none")+'" stroke="currentColor" stroke-width="1.5"/><rect x="10" y="8" width="4" height="13" rx="1" fill="'+(e>=2?"currentColor":"none")+'" stroke="currentColor" stroke-width="1.5"/><rect x="16" y="3" width="4" height="18" rx="1" fill="'+(e>=3?"currentColor":"none")+'" stroke="currentColor" stroke-width="1.5"/></svg>'}function vp(){var e=function(){var e=arguments[0],t=String(Zc||"").trim();return e&&t.length>e?t.substring(0,e):t}(),t=!!e,n=gp(),r=fp[n];return['<div class="ai-welcome ai-welcome--correction">','<div class="ai-level-chip" data-level="'+n+'">','<button type="button" class="ai-chip ai-chip--primary ai-level-run" data-action="'+r.action+'"'+(t?"":" disabled")+">",hp(n),'<div class="ai-chip-text">','<span class="ai-chip-label" data-i18n="'+r.labelKey+'">'+SKT(r.labelKey)+"</span>",'<span class="ai-chip-desc" data-i18n="'+r.descKey+'">'+SKT(r.descKey)+"</span>","</div>","</button>",'<div class="ai-level-slider">','<span class="ai-level-dot" aria-hidden="true"></span>','<span class="ai-level-dot" aria-hidden="true"></span>','<span class="ai-level-dot" aria-hidden="true"></span>','<input type="range" class="ai-level-range" min="1" max="3" step="1" value="'+n+'" data-i18n-aria-label="chip.level_aria" aria-label="'+SKT("chip.level_aria")+'">',"</div>","</div>",'<div class="sk-under-chip">','<div class="sk-under-divider" aria-hidden="true"></div>','<button type="button" class="ai-welcome-subtext ss-tip ss-learn-entry" data-learn-entry="1">','<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg>','<span class="ss-tip-text" data-i18n="learn.entry">'+SKT("learn.entry")+"</span>","</button>","</div>","</div>"].join("")}var yp={msgsId:"ai-card-messages",sendId:"ai-card-send",buildChips:function(){return vp()}};var wp=null,bp={ai:null,tone:null},kp={ai:null,tone:null},Sp=null,xp=null;function Tp(e){return e&&"tone-card-messages"===e.msgsId?"tone":"ai"}function Lp(){return wp?Tp(wp):"ai"}function Ep(){if(!Ec||"function"!=typeof Ec.getContents)return"";for(var e=Ec.getContents(),t=e&&e.ops?e.ops:[],n=[],r=0;r<t.length;r++){var o=t[r]||{},i={};if(Object.prototype.hasOwnProperty.call(o,"insert")&&(i.insert=o.insert),Object.prototype.hasOwnProperty.call(o,"delete")&&(i.delete=o.delete),Object.prototype.hasOwnProperty.call(o,"retain")&&(i.retain=o.retain),o.attributes){for(var a={},l=!1,s=Object.keys(o.attributes),c=0;c<s.length;c++){var d=s[c];"inline-correction"===d&&Object.prototype.hasOwnProperty.call(pd,String(o.attributes[d]))||(a[d]=o.attributes[d],l=!0)}l&&(i.attributes=a)}var u=n.length?n[n.length-1]:null;!u||"string"!=typeof u.insert||"string"!=typeof i.insert||Object.prototype.hasOwnProperty.call(u,"delete")||Object.prototype.hasOwnProperty.call(u,"retain")||Object.prototype.hasOwnProperty.call(i,"delete")||Object.prototype.hasOwnProperty.call(i,"retain")||JSON.stringify(u.attributes||null)!==JSON.stringify(i.attributes||null)?n.push(i):u.insert+=i.insert}return JSON.stringify(n)}function Cp(){return kp[Lp()]||null}function _p(e){if(!e||!Ec||!e.delta)return!1;var t=window.SkrivebordApp||null,n=t&&t.currentDocId?String(t.currentDocId):null,r=t&&"number"==typeof t._ctxGen?t._ctxGen:null;return e.docId===n&&e.contextGen===r&&e.expectedSignature===Ep()}function Ap(e){if(!e||!Ec||!window.Quill)return!1;hd=!0;try{var t=window.Quill.import("delta");return!!t&&(Ec.history&&"function"==typeof Ec.history.cutoff&&Ec.history.cutoff(),Ec.setContents(new t(e.delta.ops||[]),"user"),Ec.history&&"function"==typeof Ec.history.cutoff&&Ec.history.cutoff(),_d={},!0)}catch(e){return console.warn("Correction review undo restore failed:",e.message),!1}finally{hd=!1}}function qp(){var e=Lp(),t=kp[e];kp[e]=null,Sp===t&&Mp(t)}function Mp(e){if(!e||Sp===e){xp&&(clearTimeout(xp),xp=null);var t=document.querySelector('.ai-undo-toast[data-correction-review-undo="true"]');t&&t.parentNode&&t.parentNode.removeChild(t),Sp=null}}function Ip(e){return"tone"===Tp(e)}function Bp(){var e=wp?Tp(wp):null;e&&(bp[e]={map:pd,mode:gd,panel:wp,flight:Pp})}function Hp(e){var t=bp[e];t&&t.mode?(pd=t.map,gd=t.mode,wp=t.panel,Pp=t.flight,bp[e]=null):(pd={},gd=!1,Pp=!1,kp[e]=null)}function Kp(e){if(Ec)for(var t=Ec.container.querySelectorAll('mark.inline-correction[data-panel="'+e+'"]'),n=0;n<t.length;n++)t[n].classList.add("panel-hidden")}function Dp(e){if(Ec)for(var t=Ec.container.querySelectorAll('mark.inline-correction[data-panel="'+e+'"]'),n=0;n<t.length;n++)t[n].classList.remove("panel-hidden")}var Pp=!1,Np=null,jp=null,Rp=null,Fp=null,Op={};function Up(e){return e&&e.msgsId||"ai-card-messages"}function $p(e){var t=Up(e);return Op[t]=(Op[t]||0)+1,Op[t]}function zp(e){$p(e)}function Gp(e,t){return Op[Up(e)]===t}
3function Vp(e,t,n){var r=t||yp,o=document.getElementById(r.msgsId);if(!o)return Ru(),!1;if(window.MarketingAdapter&&!MarketingAdapter.canUse("skrivebord"))return Np="demo_limit",window._showDemoLimit&&window._showDemoLimit(),Ru(),!1;if(Pp)return Np="in_flight",Ru(),!1;Pp=!0;var i,a=!1;if(Ec){var l=Ec.getSelection();if(l&&l.length>0){a=!0,bd=!0;var s=Ec.getText(l.index,l.length),c=s.length-s.replace(/^\s+/,"").length,d=s.length-s.replace(/\s+$/,"").length;Vc=s.trim(),yd={index:l.index+c,length:l.length-c-d};try{wd=Ec.getSemanticHTML(l.index+c,l.length-c-d)}catch(e){wd=Vc}Zu(),Ju()}else{bd=!1,Zu();var u=Ec.getLength()-1;if(u>0){var p=Ec.getText(0,u),m=p.length-p.replace(/^\s+/,"").length,f=p.length-p.replace(/\s+$/,"").length;Vc=p.trim(),yd={index:m,length:u-m-f};try{wd=Ec.getSemanticHTML(m,u-m-f)}catch(e){wd=Vc}}else Vc="",wd="",yd=null}}if(!a&&Bd(e)&&Vc){var g=Ad(Vc);if(i=g,_d.analyse===i||_d["more-formal"]===i||_d.shorten===i||_d.rewrite===i)return Pp=!1,Np="no_changes",qf(o),Ru(),!1}if(!Vc||!Vc.trim()){o.innerHTML='<div class="ai-empty-state"><svg class="ai-empty-icon ai-empty-icon--bird" viewBox="0 0 19 17" fill="none" aria-hidden="true"><path d="M13.75 4.8125C13.75 4.99792 13.695 5.17918 13.592 5.33335C13.489 5.48752 13.3426 5.60768 13.1713 5.67864C13 5.74959 12.8115 5.76816 12.6296 5.73199C12.4477 5.69581 12.2807 5.60652 12.1496 5.47541C12.0185 5.3443 11.9292 5.17726 11.893 4.9954C11.8568 4.81354 11.8754 4.62504 11.9464 4.45373C12.0173 4.28243 12.1375 4.13601 12.2917 4.033C12.4458 3.92998 12.6271 3.875 12.8125 3.875C13.0611 3.875 13.2996 3.97377 13.4754 4.14959C13.6512 4.3254 13.75 4.56386 13.75 4.8125ZM18.75 5.75C18.7501 5.85292 18.7247 5.95427 18.6762 6.04504C18.6277 6.13581 18.5575 6.21319 18.4719 6.27031L16.875 7.33437V8.875C16.8727 11.0292 16.016 13.0945 14.4927 14.6177C12.9695 16.141 10.9042 16.9977 8.75 17H1.875C1.6395 17 1.40879 16.9335 1.20945 16.8081C1.01011 16.6827 0.85024 16.5035 0.748266 16.2913C0.646292 16.079 0.606358 15.8422 0.633065 15.6082C0.659771 15.3743 0.752033 15.1526 0.89922 14.9688L0.907032 14.9594L7.5 7.04922V5.50703C7.5 2.89609 9.59297 0.7625 12.1648 0.75H12.1875C13.1833 0.749704 14.1533 1.06652 14.9569 1.65451C15.7605 2.24251 16.356 3.07115 16.657 4.02031L18.4719 5.22969C18.5575 5.28681 18.6277 5.36419 18.6762 5.45496C18.7247 5.54573 18.7501 5.64708 18.75 5.75ZM16.9984 5.75L15.7734 4.93281C15.6457 4.84782 15.5536 4.7188 15.5148 4.57031C15.3229 3.83405 14.8921 3.18228 14.29 2.71713C13.6878 2.25199 12.9484 1.99977 12.1875 2H12.1703C10.2844 2.00938 8.75 3.58203 8.75 5.50703V7.275C8.75025 7.4214 8.6991 7.56324 8.60547 7.67578L1.875 15.75H3.97656L9.51875 9.1C9.57069 9.03512 9.63504 8.98125 9.70805 8.94154C9.78106 8.90184 9.86125 8.87709 9.94394 8.86875C10.0266 8.86041 10.1101 8.86864 10.1896 8.89297C10.2691 8.91729 10.3429 8.95722 10.4067 9.01042C10.4706 9.06362 10.5232 9.12902 10.5615 9.20279C10.5997 9.27656 10.6229 9.35722 10.6296 9.44006C10.6363 9.52289 10.6265 9.60624 10.6006 9.68521C10.5747 9.76419 10.5333 9.83721 10.4789 9.9L5.60547 15.75H8.75C10.5727 15.7479 12.3202 15.0229 13.6091 13.7341C14.8979 12.4452 15.6229 10.6977 15.625 8.875V7C15.6249 6.89708 15.6503 6.79573 15.6988 6.70496C15.7473 6.61419 15.8175 6.53681 15.9031 6.47969L16.9984 5.75Z" fill="currentColor"/></svg><div class="ai-empty-headline">'+SKT("empty.title")+'</div><div class="ai-empty-body">'+SKT("empty.body")+'</div><button type="button" class="ai-empty-btn" id="no-text-back-btn">'+SKT("tone.back")+"</button></div>";var h=document.getElementById("no-text-back-btn");return h&&h.addEventListener("click",function(){Pp=!1,o.innerHTML=r.buildChips()}),Pp=!1,Ru(),!1}if(o.innerHTML="",Ed=e,window._aiActions||(window._aiActions={}),!window._aiActions["fix-language"]){var v={"fix-language":{type:"inline",category:"spelling"},analyse:{type:"inline",category:"spelling"},"more-formal":{type:"inline",category:"enhancement"},shorten:{type:"inline",category:"style"},rewrite:{type:"inline",category:"style"},simplify:{type:"inline",category:"style"},elaborate:{type:"rewrite",category:"enhancement"},friendlier:{type:"inline",category:"enhancement"},bulletize:{type:"transform",category:"style"},"add-quotes":{type:"inline",category:"enhancement"}};for(var y in v)v.hasOwnProperty(y)&&(window._aiActions[y]=v[y])}return"tone-analyse"===e?(lm("tone-analyse",e,void 0,r),!0):window._aiActions[e]?(lm(e,e,void 0,r,n
3),!0):(Pp=!1,Ru(),!1)}function Wp(){try{return"0"!==localStorage.getItem("ss_sofia_readonce")}catch(e){return!0}}function Jp(){var e=String(Vc||"").trim();if(!Ec||!bd)return e;try{var t=Ec.getSelection();if(t&&t.length>0){var n=Ec.getText(t.index,t.length).trim();if(n)return n}var r=yd;if(r&&Number(r.length)>0){var o=Math.max(0,Ec.getLength()-1),i=Math.min(Math.max(0,Number(r.index)||0),o),a=Math.min(Number(r.length)||0,o-i);if(a>0){var l=Ec.getText(i,a).trim();if(l)return l}}return e}catch(t){return e}}function Zp(){var e=String(wd||"");if(!Ec||!bd)return e;try{var t=Ec.getSelection();if(t&&t.length>0){var n=Ec.getSemanticHTML(t.index,t.length);if(n)return n}var r=yd;if(r&&Number(r.length)>0){var o=Math.max(0,Ec.getLength()-1),i=Math.min(Math.max(0,Number(r.index)||0),o),a=Math.min(Number(r.length)||0,o-i);if(a>0){var l=Ec.getSemanticHTML(i,a);if(l)return l}}return e}catch(t){return e}}function Yp(){var e=[],t=!!bd,n=t?Jp():"";if(!n&&Ec){var r=Ec.getLength()-1;r>0&&(n=Ec.getText(0,r).trim()),t=!1}if(n){var o=n.substring(0,5e4),i=t?function(){if(!Ec||!yd)return"";try{for(var e=Ec.getContents(yd.index,yd.length),t=[],n=!1,r=!1,o=!1,i=!1,a=0;a<e.ops.length;a++){var l=e.ops[a].attributes;l&&(l.bold&&(n=!0),l.italic&&(r=!0),l.list&&(o=!0),l.header&&(i=!0))}return n&&t.push("fed tekst"),r&&t.push("kursiv"),o&&t.push("punktliste"),i&&t.push("overskrift"),t.join(", ")}catch(e){return""}}():"",a=t?"Markeret tekst":"Tekst i editoren";e.push({role:"user",content:"[KONTEKST] Se teksten herunder."}),e.push({role:"assistant",content:"ForstÃ¥et."});var l="["+a+"]\n<<<TEKST>>>\n"+o+"\n<<<SLUT>>>";i&&(l+="\n[Format: "+i+"]"),e.push({role:"user",content:l}),e.push({role:"assistant",content:"Jeg har din tekst foran mig og arbejder direkte i den â du behøver ikke sende, indsætte eller skrive den igen."})}return Wc&&(e.push({role:"user",content:Wc}),e.push({role:"assistant",content:"Jeg kan ogsÃ¥ se din kalender. Spørg om hvad som helst."})),e}var Qp={},Xp=null;function em(e){return kc(bc(String(e||""))).trim()}function tm(e){if(Array.isArray(e))for(var t=0;t<e.length;t++)e[t]&&(e[t]._restored=!0)}function nm(e,t){if(Pp||gd)return!1;if(!Ec)return!1;var n,r=document.getElementById(t.msgsId);if(!r)return!1;if(function(e){var t=String(e||"").trim();return!t||t.length>40||/\?\s*$/.test(t)?null:/^(fortryd|fortryd\s+(det|den|ændring(en)?|sidste|det\s+sidste|seneste|den\s+sidste\s+ændring)|undo|undo\s+(it|that|last|the\s+(change|last)))[\s!.]*$/i.test(t)?{intent:"undo",confidence:"high"}:null}(e)&&((n=Xp)&&n._undoHtml&&"selection"!==n._undoScope&&!(fm()!==n._undoHash?(th('<svg viewBox="0 0 24 24" width="18" height="18" stroke="#9B6050" fill="none" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 8v4l2 2"/></svg><span>'+rh(SKT("ea.toast_undo_expired"))+"</span>"),0):!Vm(n._undoHtml)||(n._undoHtml=null,n.snapshot&&(n.snapshot.docHash=fm(),n.snapshot.textLength=sm().length),Xp=null,th('<svg viewBox="0 0 24 24" width="18" height="18" stroke="#4A7A68" fill="none" stroke-width="2"><path d="M3 10h4l3-7 4 14 3-7h4"/></svg><span>'+rh(SKT("ea.toast_undone"))+"</span>"),0))))return!0;var o=r.querySelectorAll(".ai-editor-actions[data-editor-action-model]"),i=o.length?o[o.length-1]:null,a=i?Zd[i.getAttribute("data-editor-action-model")||""]:null,l=function(e){for(var t=Array.isArray(e)?e:[],n=t.length-1;n>=0;n--){var r=t[n]||{};if("assistant"===r.role&&!r._restored){var o=String(r.content||"").trim();if(o){for(var i="",a=n-1;a>=0;a--)if(t[a]&&"user"===t[a].role){i=String(t[a].content||"");break}/^\[(KONTEKST|Tekst|Markeret)/.test(i)&&(i="");var l=sc(o,i);if("rewrite"===l||"draft"===l)return{answer:o,query:i,responseType:l};if("question"!==l&&"clarification"!==l&&"summary"!==l&&o.length>=60&&!/\?\s*$/.test(o))return{answer:o,query:i,responseType:l}}}}return null}(Gc),s=function(e){var t=String(e||"").trim();if(!t||t.length>60)return null;if(/\?\s*$/.test(t))return null;var n=t.toLowerCase();return/\b(komma|punktum|afsnit|tone|formel|uformel|kortere|l[æa]ngere|stavning|grammatik|omskriv|forkort|udvid|oversæt|paragraph|comma|period|spelling|grammar|rewrite|shorten|expand|translat|formal|casual|shorter|longer)\b/i.test(n)||/^(nej\b|ikke\b|vent\b|stop\b|annull|fortryd|no\b|don'?t\b|wait\b|stop\b|cancel|undo)/i.test(n)?null:/^(inds[æae]+t(\s+(det|den|teksten?))?|s[æae]+t\s+((det|den|teksten?)\s+)?ind|smid\s+((det|den|teksten?)\s+)?ind|putt?\s+((det|den|teksten?)\s+)?ind|tilf[øo]+j\s+(det|den|teksten?)\s+(til|i)\s+(quill|editor|dokument))(\s+tak)?[\s!.]*$/i.test(t)||/^(insert(\s+(it|this|that|the\s+text))?|put\s+(it|this|that)\s+in|paste\s+(it|this|that)(\s+in)?)(\s+please)?[\s!.]*$/i.test(t)?{intent:"insert_at_cursor",confidence:"high"}:/^(anvend(\s+(det|den|teksten?))?|brug\s+(det|den|teksten?)|erstat(\s+(det|den|teksten?)|\s+med\s+(det|den|teksten?))?)(\s+tak)?[\s!.]*$/i.test(t)||/^(apply(\s+(it|this|that))?|replace(\s+(it|this|that|the\s+text)|\s+with\s+(it|this|that|the\s+text))?)(\s+please)?[\s!.]*$/i.test(t)?{intent:"apply_rewrite",confidence:"high"}:null}(e),c=null,d=null;if(s&&l)if(a&&!a._restoredFromStorage&&em(a.answer)===em(l.answer))c=a,d=s;else{i=null;var u=ac(l.answer);if(!(c=Zd[Qp[u]||""])){var p=sm();if(!(c=bm(Tc({answer:l.answer,query:l.query||e,editorText:p,selectedText:"",selectedHtml:"",selectionRange:null,docHash:ac(p),labels:{apply_selection:SKT("ea.apply_selection"),apply_document:SKT("ea.apply_document"),preview:SKT("ea.preview"),insert_new:SKT("ea.insert_new"),replace_draft:SKT("ea.replace_draft"),compare:SKT("ea.compare"),insert:SKT("ea.insert"),try_selection:SKT("ea.try_selection"),try_document:SKT("ea.try_document"),preview_fallback:SKT("ea.preview_fallback")}}))))return!1;Qp[u]=c.id}d=s}else{if(!a)return!1;if(!(d=function(e){var t=e||{};if(!t.hasLatestModel)return null;var n=String(t.query||"").trim();if(!n||n.length>60)return null;if(/\?\s*$/.test(n))return null;var r=n.toLowerCase(),o="rewrite"===t.latestModelResponseType||"draft"===t.latestModelResponseType?t.latestModelResponseType:"";return/\b(komma|punktum|afsnit|tone|formel|uformel|kortere|l[æa]ngere|stavning|grammatik|omskriv|forkort|udvid|oversæt|paragraph|comma|period|spelling|grammar|rewrite|shorten|expand|translat|formal|casual|shorter|longer)\b/i.test(r)||/^(nej\b|ikke\b|vent\b|stop\b|annull|fortryd|no\b|don'?t\b|wait\b|stop\b|cancel|undo)/i.test(r)?null:/^(inds[æae]+t(\s+(det|den|teksten?))?|s[æae]+t\s+((det|den|teksten?)\s+)?ind|smid\s+((det|den|teksten?)\s+)?ind|putt?\s+((det|den|teksten?)\s+)?ind|tilf[øo]+j\s+(det|den|teksten?)\s+(til|i)\s+(quill|editor|dokument))(\s+tak)?[\s!.]*$/i.test(n)||/^(insert(\s+(it|this|that|the\s+text))?|put\s+(it|this|that)\s+in|paste\s+(it|this|that)(\s+in)?)(\s+please)?[\s!.]*$/i.test(n)?{intent:"insert_at_cursor",confidence:"high"}:/^(anvend(\s+(det|den|teksten?))?|brug\s+(det|den|teksten?)|erstat(\s+(det|den|teksten?)|\s+med\s+(det|den|teksten?))?)(\s+tak)?[\s!.]*$/i.test(n)||/^(apply(\s+(it|this|that))?|replace(\s+(it|this|that|the\s+text)|\s+with\s+(it|this|that|the\s+text))?)(\s+please)?[\s!.]*$/i.test(n)?{intent:"apply_rewrite",confidence:"high"}:/^(i\s+quill|ind\s+i\s+(quill|editor|dokumentet))[\s!.]*$/i.test(n)?o?{intent:"rewrite"===o?"apply_rewrite":"insert_at_cursor",confidence:"high"}:null:(/^(g[øo]+r\s+det|ja(\s+tak)?|ok(ay)?|fint|perfekt|g[øo]+r\s+det\s+bare|k[øo]+r\s+p[Ã¥a]+)[\s!.]*$/i.test(n)||/^(do\s+it|yes(\s+please)?|go(\s+ahead)?|ok(ay)?|perfect|sure|lgtm|looks\s+good)[\s!.]*$/i.test(n))&&o?{intent:"rewrite"===o?"apply_rewrite":"insert_at_cursor",confidence:"medium"}:null}({query:e,latestModelResponseType:a.responseType,hasLatestModel:!0})))return!1;c=a}if(c._followupInFlight)return!0;function m(e,t,n){try{window.dispatchEvent(new CustomEvent("skrivebord:editor-action-followup",{detail:{modelId:c.id||"",intent:d.intent,success:!!e,reason:t||"",_followupMutationChanged:!!n}}))}catch(e){}}function f(e,t,n){var r=SKT(t);return c._followupInFlight=!1,e?(c._followupConsumed=d.intent,Nm(i,r,"success"),th('<svg viewBox="0 0 24 24" width="18" height="18" stroke="#4A7A68" fill="none" stroke-width="2"><path d="M20 6L9 17l-5-5"/></svg><span>'+rh(r)+"</span>")):Nm(i,r,"info"),m(e,t,n),!0}if(r.querySelectorAll(".ai-welcome, .ai-chips, .ai-chips--more, .ai-chips-toggle").forEach(function(e){e.remove()}),lp(),c._restoredFromStorage)return f(!1,"ea.followup_no_pending",!1);if(c._followupConsumed===d.intent)return f(!1,"ea.followup_no_pending",!1);if(c._followupInFlight=!0,"insert_at_cursor"===d.intent){var g=!!Qm(c);return f(g,g?"ea.followup_inserted":"ea.followup_no_pending",g)}if("apply_rewrite"===d.intent){if(lc(c.snapshot,fm()))return Nm(i,SKT("ea.followup_stale"),"warning"),th('<svg viewBox="0 0 24 24" width="18" height="18" stroke="#9B6050" fill="none" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 8v4l2 2"/></svg><span>'+rh(SKT("ea.followup_stale"))+"</span>"),c._followupInFlight=!1,m(!1,"ea.followup_stale",!1),!0;if(c._cachedRewrite&&!mm(c,c._cachedRewrite)){var h=!!Gm(c,c._cachedRewrite);return f(h,h?"ea.followup_applied":"ea.followup_no_pending",h)}var v=jm();return Pm(i,!0,SKT("ea.busy_apply")),i||Mm(!0,SKT("ea.busy_apply")),Rm(c,v.signal).then(function(e){if(v.done(),Pm(i,!1),i||Mm(!1),v.isCancelled())return c._followupInFlight=!1,!0;c._cachedRewrite=e;var t=!!Gm(c,e);f(t,t?"ea.followup_applied":"ea.followup_no_pending",t)}).catch(function(e){if(v.done(),Pm(i,!1),i||Mm(!1),v.isCancelled()||e&&"AbortError"===e.name)return c._followupInFlight=!1,!0;var t,n;t=e&&e.message||SKT("ea.error_apply_fail"),n=t||SKT("ea.error_apply_fail"),c._followupInFlight=!1,Nm(i,n,"error"),th('<svg viewBox="0 0 24 24" width="18" height="18" stroke="#B85450" fill="none" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 8v5"/><path d="M12 16h.01"/></svg><span>'+rh(n)+"</span>"),m(!1,"error",!1)}),!0}return c._followupInFlight=!1,!1}function rm(e){Pp=!1;var t=document.getElementById(e.sendId);if(t){var n=document.getElementById(e.sendId.replace("-send","-input")),r=n&&n.value.trim().length>0;t.disabled=!r,t.style.opacity=r?"":"0.3"}}function om(e,t){return ih(e,"assistant",'<div class="ai-msg-wrapper"><div class="ai-msg-content">'+rh(t)+"</div></div>")}function im(e,t){var n=document.getElementById(e.msgsId);if(n){!function(e,t,n){t.querySelectorAll(".ai-welcome, .ai-chips, .ai-chips--more, .ai-chips-toggle").forEach(function(e){e.remove()}),"function"==typeof e.clearChatLanding&&e.clearChatLanding(t),ih(t,"user",rh(n)),lp()}(e,n,t);var r=sm();if(!r||!r.trim())return om(n,SKT("aq.none","Jeg fandt ingen replikker at sætte anførselstegn ved.")),void rm(e);var o=ih(n,"assistant",'<div class="ai-msg-wrapper"><div class="ai-msg-content">'+rh(SKT("aq.propose","Jeg kan sætte anførselstegn ved replikkerne i din tekst."))+'</div><div class="ai-editor-actions" role="group" aria-label="'+rh(SKT("ea.toolbar_aria"))+'"><div class="ai-editor-actions-row"><button type="button" class="ai-editor-action-btn ai-editor-action-btn--primary ai-aq-appl
3y-btn"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3l1.6 4.4L18 9l-4.4 1.6L12 15l-1.6-4.4L6 9l4.4-1.6L12 3z"/><path d="M19 14l.8 2.2L22 17l-2.2.8L19 20l-.8-2.2L16 17l2.2-.8L19 14z"/></svg><span>'+rh(SKT("aq.apply","Sæt anførselstegn"))+'</span></button></div><div class="ai-editor-actions-scope">'+rh(SKT("ea.scope_document_active"))+"</div></div></div>").querySelector(".ai-aq-apply-btn");o&&o.addEventListener("click",function(){!function(e,t){if(!Ec)return;var n=document.getElementById(e.msgsId),r=t&&t.querySelector("span");t&&(t.disabled=!0,t.setAttribute("aria-busy","true"),r&&(r.textContent=SKT("aq.applying","Sætter anførselstegnâ¦")));function o(){var e=t&&t.closest(".ai-editor-actions");e&&e.remove()}var i=Math.max(0,Ec.getLength()-1),a=i>0?Ec.getText(0,i):"",l=a.length-a.replace(/^\s+/,"").length,s=a.trim();if(!s)return o(),void om(n,SKT("aq.error","Beklager, det gik galt. Prøv igen."));du().then(function(e){if(!e)throw new Error("no session");return fetch("/robots/skrivebord/grammar-api.php?action=ai-text-correct",{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+e},body:JSON.stringify({chip:"add-quotes",text:s})})}).then(function(e){return e.json()}).then(function(e){var t=[];if(e&&e._m)try{t=JSON.parse(atob(e._m))}catch(e){}if(o(),t.length){t.sort(function(e,t){return t.i-e.i});var r=0;t.forEach(function(e){var t=l+e.i;try{Ec.getText(t,e.l)===e.o&&(Ec.deleteText(t,e.l,"user"),Ec.insertText(t,e.r,"user"),r++)}catch(e){}}),om(n,r>0?SKT("aq.done","Anførselstegnene er sat ind. Du kan fortryde med Ctrl+Z."):SKT("aq.none","Jeg fandt ingen replikker at sætte anførselstegn ved."))}else om(n,SKT("aq.none","Jeg fandt ingen replikker at sætte anførselstegn ved."))}).catch(function(){t&&(t.disabled=!1,t.removeAttribute("aria-busy"),r&&(r.textContent=SKT("aq.apply","Sæt anførselstegn"))),om(n,SKT("aq.error","Beklager, det gik galt. Prøv igen."))})}(e,o)}),rm(e)}}var am=260;function lm(e,t,n,r,o){n||hf();var i=r||yp,a=!(!o||!o.autoApply),l=document.getElementById(i.msgsId);if(l){if(!t&&!n){if(nm(e,i))return;if(function(e){if(!e)return!1;var t=String(e).toLowerCase();return!!/(anf[øo]rselstegn|g[Ã¥a]se[øo]jne|citationstegn)/.test(t)&&/(s[æa]t|s[æa]tte|tilf[øo]j|inds[æa]t|lav\b|f[Ã¥a] |omkring|\breplik|dialog|direkte tale|citat)/.test(t)}(e))return void im(i,e)}var s=!!t,c=n||0;s&&Bd(t)&&eg(),a&&!c&&(jp=null);var d=null,u=s?0:$p(i),p=!1;if(s&&(!Vc||!Vc.trim())&&Ec){var m=Ec.getLength()-1;if(m>0){var f=Ec.getText(0,m),g=f.length-f.replace(/^\s+/,"").length,h=f.length-f.replace(/\s+$/,"").length;Vc=f.trim(),yd={index:g,length:m-g-h},bd=!1;try{wd=Ec.getSemanticHTML(g,m-g-h)}catch(e){wd=Vc}}if(!Vc||!Vc.trim())return l.innerHTML=i.buildChips(),void th('<svg viewBox="0 0 24 24" width="18" height="18" stroke="#f59e0b" fill="none" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg><span>'+SKT("empty.title")+"</span>")}var v=document.getElementById(i.sendId);v&&(v.disabled=!0,v.style.opacity="0.5");var y=new AbortController;l.querySelectorAll(".ai-welcome, .ai-chips, .ai-chips--more, .ai-chips-toggle").forEach(function(e){e.remove()});var w=null;if(s){wp=i,bd&&"analyse"===t&&yd&&window.innerWidth>767?Km(!0,yd):Mm(!0);var b=function(e){var t="loading."+e,n=SKT(t);return n&&n!==t||(n=SKT("loading.default")),n&&"loading.default"!==n||(n="Analyserer tekst"),n}(t),k={analyse:'<rect x="4" y="13" width="4" height="8" rx="1" fill="currentColor"/><rect x="10" y="8" width="4" height="13" rx="1" fill="currentColor"/><rect x="16" y="3" width="4" height="18" rx="1" fill="currentColor"/>',rewrite:'<rect x="4" y="13" width="4" height="8" rx="1" fill="currentColor"/><rect x="10" y="8" width="4" height="13" rx="1" fill="currentColor" opacity=".3"/><rect x="16" y="3" width="4" height="18" rx="1" fill="currentColor" opacity=".3"/>',shorten:'<rect x="4" y="13" width="4" height="8" rx="1" fill="currentColor"/><rect x="10" y="8" width="4" height="13" rx="1" fill="currentColor"/><rect x="16" y="3" width="4" height="18" rx="1" fill="currentColor" opacity=".3"/>',"more-formal":'<rect x="2" y="7" width="20" height="14" rx="2" ry="2"/><path d="M16 7V4a2 2 0 00-2-2h-4a2 2 0 00-2 2v3"/>',"tone-smart":'<path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/>',"tone-analyse":'<line x1="4" y1="21" x2="4" y2="14"/><line x1="4" y1="10" x2="4" y2="3"/><line x1="12" y1="21" x2="12" y2="12"/><line x1="12" y1="8" x2="12" y2="3"/><line x1="20" y1="21" x2="20" y2="16"/><line x1="20" y1="12" x2="20" y2="3"/><circle cx="4" cy="12" r="2" fill="currentColor"/><circle cx="12" cy="10" r="2" fill="currentColor"/><circle cx="20" cy="14" r="2" fill="currentColor"/>',"tone-rewrite":'<path d="M17 3a2.83 2.83 0 114 4L7.5 20.5 2 22l1.5-5.5z"/>',"tone-confident":'<circle cx="12" cy="8" r="7"/><path d="M8.21 13.89L7 23l5-3 5 3-1.21-9.12"/>',"tone-diplomatic":'<path d="M16 16l3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1z"/><path d="M2 16l3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1z"/><path d="M7 21h10"/><path d="M12 3v18"/>
3<path d="M3 7h2c2 0 5-1 7-2 2 1 5 2 7 2h2"/>',"tone-professional":'<rect x="2" y="7" width="20" height="14" rx="2" ry="2"/><path d="M16 7V4a2 2 0 00-2-2h-4a2 2 0 00-2 2v3"/>',"tone-unify":'<path d="M16 3h5v5"/><path d="M8 3H3v5"/><path d="M12 22V8"/><path d="M21 3l-9 9"/><path d="M3 3l9 9"/>',"tone-friendly":'<path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/>',simplify:'<path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/>',friendlier:'<path d="M20.84 4.61a5.5 5.5 0 00-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 00-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 000-7.78z"/>'}[t]||'<path d="M9.937 15.5A2 2 0 008.5 14.063l-6.135-1.582a.5.5 0 010-.962L8.5 9.936A2 2 0 009.937 8.5l1.582-6.135a.5.5 0 01.962 0L14.063 8.5A2 2 0 0015.5 9.937l6.135 1.582a.5.5 0 010 .962L15.5 14.063a2 2 0 00-1.437 1.437l-1.582 6.135a.5.5 0 01-.962 0z"/>',S=Math.ceil(String(Vc||"").length/600),x="analyse"===t&&S>=2&&!(!window.ssStagedProgress||!window.ssStagedProgress.start),T=t&&0===t.indexOf("tone-")&&"function"==typeof window._toneGarmentSvg?window._toneGarmentSvg():'<svg aria-hidden="true" viewBox="0 0 24 24">'+k+"</svg>";if(l.innerHTML='<div class="ai-empty-state ai-completion-state" role="status" aria-live="polite" aria-busy="true"><div class="ss-chip-wait"><div class="ss-chip-wait-row"><div class="ai-loading-icon" aria-hidden="true">'+T+'</div><span class="ss-chip-wait-text"><span class="ai-empty-headline">'+b+'</span><span class="calm-loading-sub">'+(SKT("loading.subtitle")||"")+"</span></span></div>"+(x?"":'<div class="ss-chip-wait-track ss-chip-wait-track--fill" aria-hidden="true"><span class="ss-chip-wait-fill"></span></div>')+'</div><button class="ai-empty-btn ai-cancel-btn" id="ai-cancel-btn" tabindex="-1" aria-label="'+(SKT("ai.cancel_aria")||"")+'">'+SKT("ai.cancel_request")+"</button></div>",x)try{var L=l.querySelector(".ai-completion-state"),E=L?L.querySelector(".ai-empty-headline"):null,C=L?L.querySelector(".ss-chip-wait"):null,_=window.ssStagedProgress.makeBar();C&&C.appendChild(_),w=window.ssStagedProgress.start({lineEl:E,barEl:_,readText:b,workText:String(SKT("loading.stage_fix")||"Retter {n} afsnit").replace("{n}",S),gatherText:SKT("loading.stage_gather")||"Samler det hele",estimateMs:Math.min(9e4,6e3+900*S)})}catch(e){w=null}var A=document.getElementById("ai-cancel-btn");if(A)A.addEventListener("click",function(){y.abort(),Rp=null,l.innerHTML=i.buildChips(),Pp=!1,H()}),window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches?A.removeAttribute("tabindex"):setTimeout(function(){document.body.contains(A)&&A.removeAttribute("tabindex")},1500);Rp=function(){y.abort(),Rp=null;var e=document.getElementById(i.msgsId);e&&e.querySelector(".ai-completion-state")&&(e.innerHTML=i.buildChips()),Pp=!1,H()}}else{if(gd){if(Mg(),!(l=document.getElementById(i.msgsId)))return;l.querySelectorAll(".ai-empty-state").forEach(function(e){e.remove()})}"function"==typeof i.clearChatLanding&&i.clearChatLanding(l),ih(l,"user",rh(e)),lp();d="ai-stream-"+Date.now();var q=ih(l,"assistant",'<div class="ai-msg-wrapper"><div class="ai-msg-content ai-streaming" id="'+d+'" aria-busy="true">'+dd+"</div></div>")}var M=null,I=Yp(),B=s?function(e){return"analyse"===e?"/robots/skrivebord/grammar-api.php?action=ai-text-analyse":"string"==typeof e&&0===e.indexOf("tone-")?"/robots/skrivebord/grammar-api.php?action="+e:"/robots/skrivebord/grammar-api.php?action=ai-text-correct"}(t):"/api/chat-api.php";(uu(!0===window.__SS_PUBLIC_MODE,s,B)?Promise.resolve(""):du()).then(function(n){if(n||uu(!0===window.__SS_PUBLIC_MODE,s,B)){var r,o=I.concat(Gc);if(s)if("analyse"===t){r={text:Vc||"",language:It()};var m=ym(wd);m&&(r.html=m)}else if("tone-analyse"===t){var f="undefined"!=typeof SKT&&SKT.lang?SKT.lang():"da-DK";r={text:Vc||"",language:It(),ui_lang:f}}else if("tone-smart"===t){var g="undefined"!=typeof SKT&&SKT.lang?SKT.lang():"da-DK",h=[];p=!0===window._toneSmartForceWholeEditor;var v=Vc||"";if(Ec&&(!bd||p)){var b=Ec.getLength()-1;b>0&&(v=Ec.getText(0,b).trim())}var k=v.split("\n").filter(function(e){return e.trim()});if(k.length>0){var S=k[0].trim().substring(0,120);if(/^(hej|kære|dear|hi|hey|til|an|hello|hallo)\b/i.test(S)){var x=S.match(/^(?:hej|kære|dear|hi|hey|til|an|hello|hallo)\s+(.{1,60})/i);x&&h.push("Modtager: "+x[1].replace(/[,!.]+$/,"").trim())}}if(k.length>1){var T=k[k.length-1].trim().substring(0,80);/^(mvh|venlig|hilsen|regards|best|med venlig|vh|kærlig)/i.test(T)&&h.push("Signatur: "+T)}
3var L=v.split(/\s+/).filter(Boolean).length;if(L>0&&h.push("Tekstlængde: "+L+" ord"),Wc){var E=Wc.split("\n").filter(function(e){return e.trim()&&"-"===e.charAt(0)}).slice(0,5).map(function(e){return e.replace(/^-\s*/,"").substring(0,120)});E.length>0&&h.push("Kalender: "+E.join("; "))}r={text:v||"",target:window._toneSmartTarget||"auto",ui_lang:g,selection:{has_selection:!p&&!!bd},context_facts:h};var C=function(e){var t=ym(function(e){if(!e)return"";try{var t=document.createElement("div");t.innerHTML=e;for(var n=t.querySelectorAll("ol"),r=0;r<n.length;r++){for(var o=n[r],i=o.children,a=0,l=0,s=0;s<i.length;s++)"LI"===i[s].tagName&&(a++,"bullet"===(i[s].getAttribute("data-list")||"")&&l++);if(a>0&&l===a){for(var c=document.createElement("ul");o.firstChild;)c.appendChild(o.firstChild);o.parentNode.replaceChild(c,o)}}return t.innerHTML}catch(t){return e}}(e));if(!t)return"";if("function"!=typeof TurndownService)return"";try{var n=new TurndownService({headingStyle:"atx",bulletListMarker:"-",codeBlockStyle:"fenced",emDelimiter:"*"}),r=String(n.turndown(t)||"").trim();return vm.test(r)?r:""}catch(e){return""}}(!Ec||bd&&!p?wd:Ec.root.innerHTML);C&&(r.markdown=C),window._toneSmartTarget=null,window._toneSmartForceWholeEditor=!1}else if("tone-rewrite"===t)r={text:Vc||"",target:window._toneRewriteTarget||"diplomatic",diagnosis:window._toneRewriteDiagnosis||{}};else if(t&&0===t.indexOf("tone-"))r={text:Vc||""};else{r={chip:t,text:Vc||""};var _=ym(wd);_&&(r.html=_)}else{var A=o.map(function(e){return{role:e&&e.role,content:e&&e.content}});A.push({role:"user",content:e}),r={messages:A,tutor_id:"advisor-sofia",locale:me(),ss_workshop_emit:Wp(),client_embeds:!1}}if(M=setTimeout(function(){if(s||Gp(i,u)){var e=document.getElementById(i.msgsId);!e||gd||e.querySelector(".ai-chips")||e.querySelector(".ai-msg--assistant")||(e.innerHTML=i.buildChips()),H()}},s&&-1!==B.indexOf("action=ai-text-")?19e4:55e3),s)fetch(B,{method:"POST",headers:pu(n),body:JSON.stringify(r),signal:y.signal}).then(function(e){if((429===e.status||413===e.status)&&window.SSWordLimit){var t=413===e.status&&window.__SS_PUBLIC_MODE?{silent:!0}:void 0;return window.SSWordLimit.handleResponse(e,t).then(function(t){if(t)throw window.SSWordLimit.createError(t);throw new Error("Server svarede "+e.status)})}if(!e.ok)throw new Error(e.status>=500?"Serveren er overbelastet â prøv igen om et øjeblik":"Server svarede "+e.status);return e.json()}).then(function(e){return y.signal.aborted?e:function(e){var t=e&&e.querySelector?e.querySelector(".ss-chip-wait-fill"):null;if(!t||!t.parentNode)return Promise.resolve();var n=window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{var r=t.parentNode.getBoundingClientRect().width,o=r>0?t.getBoundingClientRect().width/r*100:0;t.style.width=o+"%",t.style.animation="none",t.offsetWidth,t.classList.add("is-complete"),t.style.width="100%"}catch(e){return Promise.resolve()}return n?Promise.resolve():new Promise(function(e){setTimeout(e,am)})}(l).then(function(){return e})}).then(function(n){if(!y.signal.aborted){if(M&&(clearTimeout(M),M=null),w)try{w.gather()}catch(e){}if(window.MarketingAdapter&&MarketingAdapter.track("skrivebord"),"word_limit_exceeded"===n.error)return l.innerHTML=i.buildChips(),a&&(jp={failed:!0,reason:"too_long"}),H(),void(window.SSWordLimit?window.SSWordLimit.show({data:n}):window._showWordLimitModal&&window._showWordLimitModal(n.used,n.limit||15e3,n.reset_date||null));if(n.error)K(n.error);else{if("tone-smart"===t&&n.success&&n.improved_text)return Yc&&Yc.renderSmartResult&&Yc.renderSmartResult(n,i,{wholeEditor:p}),void H();if("tone-analyse"===t&&n.detected)return function(e,t){Yc&&Yc.renderAnalysis(e,t)}(n,i),void H();var r,o=n.answer||n.reply||"";if(s&&Vc&&o&&yd){var c,d=function(e){if(!(e=(e=(e=e.replace(/^<<<(?:TEKST|TEXT|TEXTE|TEXTO)>>>\s*/i,"")).replace(/\s*<<<(?:SLUT|END|ENDE|FIN)>>>\s*$/i,"")).replace(/\n{3,}/g,"\n\n")))return"";var t=(e=(e=(e=(e=(e=(e=e.replace(/\*\*(.+?)\*\*/g,"$1")).replace(/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g,"$1")).replace(/^(?:Her er (?:den )?(?:rettede|forkortede|omskrevne|forenklede|justerede|forsimplede) tekst:?\s*\n?)/i,"")).replace(/^(?:Den (?:rettede|forkortede|omskrevne|forenklede|justerede|forsimplede) tekst:?\s*\n?)/i,"")).replace(/^(?:Here is the (?:corrected|shortened|rewritten|simplified|adjusted) text:?\s*\n?)/i,"")).replace(/^(?:The (?:corrected|shortened|rewritten|simplified|adjusted) text:?\s*\n?)/i,"")).lastIndexOf("\n\n");if(t>20){e.substring(t+2).trim().match(/^(?:Rettelser|Ãndringer|Bemærk|Note|Forklaring|Kommentar|Jeg har (?:rettet|ændret|fjernet|tilføjet|korrigeret)|Changes|Corrections|Note:|I have (?:corrected|changed|removed|added|fixed))/i)&&(e=e.substring(0,t))}return e.trim()}(o);if("transform"===(window._aiActions&&window._aiActions[t]?window._aiActions[t].type:"inline")){Zu();var u=d.split("\n").filter(function(e){return e.trim().length>0});if(u.length>0&&Ec&&yd){hd=!0,Ec.deleteText(yd.index,yd.length);for(var m=yd.index,f=0;f<u.length;f++){var g=u[f].replace(/^[\u2022\-\*]\s*/,"").trim();Ec.insertText(m,g+"\n"),Ec.formatLine(m,1,"list","bullet"),m+=g.length+1}hd=!1,th('<svg viewBox="0 0 24 24" width="18" height="18" stroke="#4a5768" fill="none" stroke-width="2"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg><span>
3Tekst omformet</span>'),l.innerHTML=i.buildChips()}return void H()}var h=null;if(n._m)try{h=JSON.parse(atob(n._m))}catch(e){}if(h&&h.length>0){c=[];for(var v=0;v<h.length;v++){var b=h[v];md++,c.push({id:"c"+md,index:b.i,length:b.l,original:b.o,replacement:b.r})}}else c=function(e,t){if(!window.diff_match_patch)return console.warn("diff_match_patch not available"),null;var n=window._aiActions&&window._aiActions[Ed];if(n&&"rewrite"===n.type)return function(e,t){for(var n=e.split("\n"),r=t.split("\n"),o=[],i=0,a=0;a<n.length;a++){var l=n[a],s=a<r.length?r[a]:"";if(l!==s&&l.trim().length>0){var c=.2;"tone-rewrite"===Ed?c=.08:Ed&&0===Ed.indexOf("tone-")&&(c=.25);var d=Math.max(l.length,s.length),u=vf(l,s);if(d>0&&u/d<c){i+=l.length+1;continue}md++,o.push({id:"s"+md,index:i,length:l.length,original:l,replacement:s,scope:"sentence"})}i+=l.length+1}return o}(e,t);var r=t.replace(/\r\n/g,"\n"),o=e.replace(/\r\n/g,"\n");-1===o.indexOf("\n\n")&&r.indexOf("\n\n")>-1&&(r=r.replace(/\n{2,}/g,"\n"));r=r.replace(/[ \t]+\n/g,"\n");var i=Cf(o,r);if(!i)return null;for(var a=[],l=0,s=0;s<i.length;s++){var c=i[s][0],d=i[s][1];if(0===c)l+=d.length;else if(-1===c){var u="";s+1<i.length&&1===i[s+1][0]&&(u=i[s+1][1],s++),md++,a.push({id:"c"+md,index:l,length:d.length,original:d,replacement:u}),l+=d.length}else 1===c&&(md++,a.push({id:"c"+md,index:l,length:0,original:"",replacement:d}))}return a}(Vc,d);if(c&&c.length>0){h||(c=function(e,t){for(var n=0;n<e.length;n++){var r=e[n];if(0===r.length&&r.replacement)if(r.index>0){for(var o=r.index-1;o>0&&" "!==t[o-1]&&"\n"!==t[o-1];)o--;var i=t.substring(o,r.index);r.index=o,r.length=i.length,r.original=i,r.replacement=i+r.replacement}else if(r.index<t.length){for(var a=r.index+1;a<t.length&&" "!==t[a]&&"\n"!==t[a];)a++;var l=t.substring(r.index,a);r.length=l.length,r.original=l,r.replacement=r.replacement+l}if(r.original&&r.replacement){for(var s=r.original,c=r.replacement;s.length>0&&c.length>0&&" "===s[0]&&" "===c[0];)s=s.substring(1),c=c.substring(1);for(;s.length>0&&c.length>0&&" "===s[s.length-1]&&" "===c[c.length-1];)s=s.substring(0,s.length-1),c=c.substring(0,c.length-1);r.displayOriginal=s,r.displayReplacement=c}}return e}(c,Vc)),c=(c=c.filter(function(e){return e.length>0&&!(""===e.original.trim()&&""===(e.replacement||"").trim())})).filter(function(e){return e.original.trim()!==(e.replacement||"").trim()});for(var k=[],S=0;S<c.length;S++){var x=c[S];if(-1===x.original.indexOf("\n")&&-1===(x.replacement||"").indexOf("\n"))k.push(x);else for(var T=x.original.split("\n"),L=(x.replacement||"").split("\n"),E=0,C=0;C<T.length;C++){var _=T[C],A=C<L.length?L[C]:"";_!==A&&_.length>0&&(md++,k.push({id:"c"+md,index:x.index+E,length:_.length,original:_,replacement:A})),E+=_.length+1}}c=function(e,t){try{if(!Bd(t))return e;if(!1===jf)return e;if(!Df||!Df.length)return e;if(!e||!e.length)return e;for(var n=[],r=0;r<e.length;r++){for(var o=e[r],i=null,a=0;a<Df.length;a++)if(og(Df[a],o)){i=Df[a];break}if(i){var l=Nf[i.id]=(Nf[i.id]||0)+1,s="active"===i.status&&"user"!==i.created_by&&l%10==0,c="active"===i.status?s?"probe":"live":"shadow";try{window.ssOutcome&&window.ssOutcome.record("korrektur","correction","suppressed",{rule:i.id,rt:i.rule_type,sc:i.scope||"user",o:String(o.original||"").slice(0,80),r:String(o.replacement||"").slice(0,80),mode:c})}catch(e){}"live"!==c&&n.push(o)}else n.push(o)}return n}catch(t){return e}}(c=k,t)}if(r=String(Vc||""||"").trim(),Kd=r?r.split(/\s+/).filter(function(e){return e.length>0}).length:0,c&&c.length>0){if(Nu){var q=function(e,t){if(!Ec||!t||0===t.length)return 0;var n=window.Quill,r=n?n.import("delta"):null;hd=!0,Mg(),hd=!0,Zu();var o=t.slice().sort(function(e,t){return e.index-t.index}),i=0;if(Fu={},r){for(var a=new r,l=0,s=0;s<o.length;s++){var c=o[s];if(!(c.length<=0||null==c.replacement||Gd(c.replacement,c.original||""))){var d=e+c.index;if(!(d<l)&&Vd(d,c.length,c.original)){var u=Ec.getFormat(d,c.length);delete u["inline-correction"],u["mobile-corrected"]=!0,d>l&&a.retain(d-l),a.delete(c.length),c.replacement.length>0&&a.insert(c.replacement,u),l=d+c.length,Ou(Fu,c),i++}}}Ec.updateContents(a,"silent")}else{o.reverse();for(var p=0;p<o.length;p++){var m=o[p];if(!(m.length<=0||null==m.replacement||Gd(m.replacement,m.original||""))){var f=e+m.index;Vd(f,m.length,m.original)&&(Ec.deleteText(f,m.length,"silent"),m.replacement.length>0&&(Ec.insertText(f,m.replacement,"silent"),Ec.formatText(f,m.replacement.length,"mobile-corrected",!0,"silent")),Ou(Fu,m),i++)}}}return gd=!1,hd=!1,i}(yd.index,c);return Dd(Kd,Fu),a&&(jp={applied:q}),Ru(),(I=window.getSelection())&&I.removeAllRanges(),H(),void(Bd(t)&&Hd(t))}var I,B=function(e,t){if(!Ec||!t||0===t.length)return 0;hd=!0,Mg(),hd=!0,Zu(),function(){if(Ec&&"function"==typeof Ec.getContents){Mp();var e=Ec.getContents(),t=window.SkrivebordApp||null,n=Lp(),r=Ep();kp[n]={delta:JSON.parse(JSON.stringify(e)),initialSignature:r,expectedSignature:r,appliedCount:0,panelKey:n,docId:t&&t.currentDocId?String(t.currentDocId):null,contextGen:t&&"number"==typeof t._ctxGen?t._ctxGen:null}}}(),hd=!0,gd=!0;for(var n=0,r=0;r<t.length;r++){var o=t[r];if(o.length>0){var i=e+o.index,a="sentence"===o.scope,l=a?Yd.style:yf(o.original,o.replacement,Ed);if(Ld[l.key])continue;if(o.replacement&&Gd(o.replacement,o.original||""))continue;if(!Vd(i,o.length,o.original))continue;Ec.formatText(i,o.length,"inline-correction",o.id);var s=o.original&&o.replacement?"«"+o.original+"» â «"+o.replacement+"»":SKT("corr.single"),c=a?{short:SKT("corr.rewritten"),detail:SKT("corr.rewritten_detail")}:{short:s,detail:""};pd[o.id]={original:o.original,replacement:o.replacement,displayOriginal:o.displayOriginal||o.original,displayReplacement:o.displayReplacement||o.replacement,type:""===o.replacement?"delete":"replace",category:l,explanation:c.short,explanationDetail:c.detail,scope:o.scope||"word"},n++}}var d=wp?Tp(wp):"ai";
3Object.keys(pd).forEach(function(e){for(var t=Ec.container.querySelectorAll('[data-cid="'+e+'"]'),n=0;n<t.length;n++){var r=pd[e];t[n].setAttribute("data-type","sentence"===r.scope?"sentence":r.category.key),t[n].setAttribute("data-panel",d),t[n].classList.add("just-appeared")}}),setTimeout(function(){for(var e=Ec.container.querySelectorAll(".just-appeared"),t=0;t<e.length;t++)e[t].classList.remove("just-appeared")},900),0===n&&qp();return hd=!1,n}(yd.index,c);!function(e,t,n){if(!e||0===e.length)return;var r=window._aiActions&&window._aiActions[t];if(r&&r.category&&"fix-language"!==t&&"analyse"!==t&&"shorten"!==t&&"rewrite"!==t)return;for(var o=me(),i=yt(),a=[],l=[],s=[],c=0;c<e.length;c++){var d=e[c];if(d.id&&pd[d.id]){var u=d.displayOriginal||d.original,p=d.displayReplacement||d.replacement,m=wf(d.id);a.push({original:u,replacement:p,context:m}),l.push(d.id),s.push(Sf(o,i,t||"fix-language",u,p,m))}}if(0===a.length)return;for(var f=[],g=[],h=[],v=0;v<l.length;v++){var y=xf(s[v]);if(y)Lf(l[v],y);else{pd[l[v]]&&(pd[l[v]].explanationPending=!0);for(var w=document.querySelectorAll('mark.inline-correction[data-cid="'+l[v]+'"]'),b=0;b<w.length;b++)w[b].setAttribute("data-classifying","1");f.push(a[v]),g.push(l[v]),h.push(s[v])}}if($g(),0===f.length)return void Ef(l,n);var k=JSON.stringify({corrections:f,action:t||"fix-language",uiLang:o,documentLang:i}),S=function(e){var t="undefined"!=typeof AbortController?new AbortController:null,r=t?setTimeout(function(){try{t.abort()}catch(e){}},6e4):null;fetch("/robots/skrivebord/grammar-api.php?action=classify-corrections",{method:"POST",headers:e,body:k,signal:t?t.signal:void 0}).then(function(e){return r&&clearTimeout(r),e.json()}).then(function(e){var t=e&&e.data&&e.data.corrections;if(t&&t.length===g.length){for(var r=0;r<g.length;r++){var o=g[r],i=t[r];if(pd[o]&&i){var a={category:i.category,short:i.short,detail:i.detail};Lf(o,a),i.enriched&&Tf(h[r],a)}}Ef(l,n)}else{for(var s=0;s<g.length;s++){pd[g[s]]&&(pd[g[s]].explanationPending=!1);for(var c=document.querySelectorAll('mark.inline-correction[data-cid="'+g[s]+'"]'),d=0;d<c.length;d++)c[d].removeAttribute("data-classifying")}$g()}}).catch(function(){r&&clearTimeout(r);for(var e=0;e<g.length;e++){pd[g[e]]&&(pd[g[e]].explanationPending=!1);for(var t=document.querySelectorAll('mark.inline-correction[data-cid="'+g[e]+'"]'),n=0;n<t.length;n++)t[n].removeAttribute("data-classifying")}$g()})},x={"Content-Type":"application/json"};du().then(function(e){e&&(x.Authorization="Bearer "+e),S(x)}).catch(function(){S(x)})}(c,t,Kd),(I=window.getSelection())&&I.removeAllRanges(),_f(B)}else Nu&&Ru(),qf(l),Dd(Kd,{});if(a){var D=Object.keys(pd).length;D>0?(Cg(),jp={applied:D}):jp={no_changes:!0}}Bd(t)&&Hd(t),H()}else{var P=xc(o),N=bc(o);if(!(N=kc(N))&&!P)return l.innerHTML=i.buildChips(),void H();var j=n.citations||[];Gc.push({role:"user",content:e}),Gc.push({role:"assistant",content:o}),Gc.length>50&&(Gc=Gc.slice(-50)),Xu();var R=!(!P||!wm(P.improved)),F=N||(P?wm(P.improved):""),O=null,U=sm();(R||cc({hasQuill:!!Ec,answer:F,editorText:U,query:e,isCorrection:s,chipAction:t}))&&(O=bm(Tc({answer:F,query:e,editorText:U,selectedText:bd?Jp():"",selectedHtml:bd?Zp():"",selectionRange:bd?yd:null,docHash:ac(U),forceResponseType:P&&P.improved?"rewrite":"",labels:{apply_selection:SKT("ea.apply_selection"),apply_document:SKT("ea.apply_document"),preview:SKT("ea.preview"),insert_new:SKT("ea.insert_new"),replace_draft:SKT("ea.replace_draft"),compare:SKT("ea.compare"),insert:SKT("ea.insert"),try_selection:SKT("ea.try_selection"),try_document:SKT("ea.try_document"),preview_fallback:SKT("ea.preview_fallback")}}))),O&&P&&(!1!==P.complete?(O._workshopImproved=Fm(P.improved),O._cachedRewrite=O._workshopImproved):O._rewriteTruncated=!0),O&&ud("shown",O);var $=N?ah(N):"<p>"+rh(SKT("ea.kicker")||"Sofia har et forslag")+"</p>";j.length>0&&($+=lh(j));var z=function(e,t,n){var r=document.getElementById(e);if(r){var o=r.closest(".ai-msg");if(o){o.className="ai-msg ai-msg--"+t,o.innerHTML=n;var i=document.getElementById("ai-card-messages");return i&&(i.scrollTop=i.scrollHeight),o}}return null}(null,"assistant",'<div class="ai-msg-wrapper"><div class="ai-msg-content">'+$+"</div>"+ef(N||"",O)+"</div>");tf(N||"",t,i,z),lp(),H()}}}}).catch(function(e){return"AbortError"===e.name?(Ru(),H(),void(a&&(jp={failed:!0,reason:"cancelled"}))):e.wordLimitExceeded||"word_limit_exceeded"===e.message?(M&&(clearTimeout(
3M),M=null),l.innerHTML=i.buildChips(),a&&(jp={failed:!0,reason:"too_long"}),void H()):(console.error("AI error:",e),void K("Kunne ikke kontakte AI. Prøv igen."))});else{var D=document.getElementById(d);!function(e,t,n,r,o,i,a){fetch(e,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer "+n,Accept:"text/event-stream"},body:JSON.stringify(Object.assign({},t,{stream:!0})),signal:a}).then(function(e){if(e.ok){var t=(e.headers.get("content-type")||"").toLowerCase();if(e.body&&-1===t.indexOf("application/json")){var n=e.body.getReader(),a=new TextDecoder,l="",s="",c=!1;p()}else e.text().then(function(e){var t=null,n=!1;try{t=JSON.parse(e),n=!0}catch(e){n=!1}if(n){if(t&&t.error)return void i(t.error);var a=t&&(t.answer||t.reply)||"";return r(a),void o(a,t||{})}if(e&&-1!==e.indexOf("data:")){for(var l="",s=function(e){for(var t=e.split("\n"),n=[],r=0;r<t.length;r++){var o=Lc(t[r]);if(o&&(n.push(o),"done"===o.type))break}return n}(e),c=0;c<s.length;c++){var d=s[c];if("done"===d.type)break;if("chunk"===d.type){var u=d.data;if("word_limit_exceeded"===u.error)return void i("word_limit_exceeded");if(u.error)return void i(u.error);var p=u.delta||u.content||u.text||"";p&&r(l+=p)}}o(l,{})}else i("Kunne ikke parse svar")}).catch(function(e){e&&"AbortError"===e.name||i("Kunne ikke parse svar")})}else{if((429===e.status||413===e.status)&&window.SSWordLimit){var d=413===e.status&&window.__SS_PUBLIC_MODE?{silent:!0}:void 0;return void window.SSWordLimit.handleResponse(e,d).then(function(t){i(t?"word_limit_exceeded":"Server svarede "+e.status)})}i("Server svarede "+e.status)}function u(e){c||(c=!0,o(s,e||{}))}function p(){n.read().then(function(e){if(e.done)u({});else{var t=function(e){for(var t=e.split("\n"),n=t.pop(),r=[],o=0;o<t.length;o++){var i=Lc(t[o]);i&&r.push(i)}return{events:r,rest:n}}(l+=a.decode(e.value,{stream:!0}));l=t.rest;for(var n=0;n<t.events.length;n++){var o=t.events[n];if("done"===o.type)return void u({});if("unparseable"!==o.type){var c=o.data;if("word_limit_exceeded"===c.error)return void i("word_limit_exceeded");if(c.error)return void i(c.error);var d=c.delta||c.content||c.text||"";d&&r(s+=d)}else s+=o.raw,r(s)}p()}}).catch(function(e){"AbortError"!==e.name&&i("Stream afbrudt")})}}).catch(function(e){"AbortError"!==e.name&&i("Kunne ikke kontakte AI")})}(B,r,n,function(e){if(Gp(i,u)&&D){var t=Sc(bc(op(e)));D.innerHTML=t?ah(t)+'<span class="ai-stream-cursor" aria-hidden="true"></span>':dd,l.scrollTop=l.scrollHeight}},function(t,n){if(Gp(i,u)){M&&(clearTimeout(M),M=null),window.MarketingAdapter&&MarketingAdapter.track("skrivebord");var r=xc(t),o=Sc(r&&null!=r.display?op(r.display):bc(op(t)));if(!(o=kc(o))&&!r){if(D){var a=D.closest(".ai-msg");a&&a.remove()}return l.innerHTML=i.buildChips(),void H()}var s=n&&n.citations?n.citations:[];Gc.push({role:"user",content:e}),Gc.push({role:"assistant",content:t}),Gc.length>50&&(Gc=Gc.slice(-50)),Xu();var c=!(!r||!wm(r.improved)),d=o||(r?wm(r.improved):""),p=null,m=sm();(c||cc({hasQuill:!!Ec,answer:d,editorText:m,query:e,isCorrection:!1,chipAction:null}))&&(p=bm(Tc({answer:d,query:e,editorText:m,selectedText:bd?Jp():"",selectedHtml:bd?Zp():"",selectionRange:bd?yd:null,docHash:ac(m),forceResponseType:r&&r.improved?"rewrite":"",labels:{apply_selection:SKT("ea.apply_selection"),apply_document:SKT("ea.apply_document"),preview:SKT("ea.preview"),insert_new:SKT("ea.insert_new"),replace_draft:SKT("ea.replace_draft"),compare:SKT("ea.compare"),insert:SKT("ea.insert"),try_selection:SKT("ea.try_selection"),try_document:SKT("ea.try_document"),preview_fallback:SKT("ea.preview_fallback")}}))),p&&r&&(!1!==r.complete?(p._workshopImproved=Fm(r.improved),p._cachedRewrite=p._workshopImproved):p._rewriteTruncated=!0),p&&ud("shown",p);var f=o?ah(o):"<p>"+rh(SKT("ea.kicker")||"Sofia har et forslag")+"</p>";if(s.length>0&&(f+=lh(s)),D){D.classList.remove("ai-streaming"),D.removeAttribute("aria-busy");var g=D&&D.closest?D.closest(".ai-msg"):q,h=D.closest(".ai-msg-wrapper")||D.parentNode;h&&(h.innerHTML='<div class="ai-msg-content">'+f+"</div>"+ef(o||"",p)),tf(o||"",null,i,g)}lp(),H()}}
3,function(t){if(Gp(i,u)){if(M&&(clearTimeout(M),M=null),"word_limit_exceeded"===t){if(D){var n=D.closest(".ai-msg");n&&n.remove()}return l.innerHTML=i.buildChips(),window.SSWordLimit?window.SSWordLimit.show({data:{error:"word_limit_exceeded"}}):window._showWordLimitModal&&window._showWordLimitModal(null,15e3,null),void H()}if(D){D.classList.remove("ai-streaming"),D.removeAttribute("aria-busy");var r=document.createElement("div");r.className="ai-error-recovery",r.setAttribute("role","alert"),r.innerHTML='<p class="ai-error-text">'+rh(t||SKT("ea.error_stream"))+'</p><button type="button" class="ai-editor-action-btn ai-error-retry" data-editor-retry aria-label="'+rh(SKT("ea.retry"))+'"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M1 4v6h6"/><path d="M3.51 15a9 9 0 105.3-9.24L1 10"/></svg><span>'+rh(SKT("ea.retry"))+"</span></button>",D.appendChild(r);var o=r.querySelector("[data-editor-retry]");o&&o.addEventListener("click",function(){r.remove(),lm(e,null,c+1,i)})}H()}},y.signal)}}else K("Session udløbet â genindlæs siden.")}).catch(function(e){console.error("Session error:",e),K("Session kunne ikke hentes. Prøv at genindlæse siden.")})}else a&&(jp={failed:!0});function H(){if(Pp=!1,Rp=null,Ru(),Mm(!1),Km(!1),w){try{w.stop()}catch(e){}w=null}M&&(clearTimeout(M),M=null);var e=document.getElementById(i.sendId);if(e){var t=document.getElementById(i.sendId.replace("-send","-input")),n=t&&t.value.trim().length>0;e.disabled=!n,e.style.opacity=n?"":"0.3",t&&!t.matches(":focus")&&setTimeout(function(){t.focus()},100)}}function K(n){if(s)return c<1?(console.warn("Correction error, retrying:",n),void setTimeout(function(){lm(e,t,c+1,i,o)},800)):(l.innerHTML=i.buildChips(),th('<svg viewBox="0 0 24 24" width="18" height="18" stroke="#ef4444" fill="none" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg><span>Kunne ikke rette teksten â prøv igen</span>'),a&&(jp={failed:!0}),void H());ih(l,"error",n),lp(),H()}}
3function sm(){if(!Ec)return"";var e=Math.max(0,Ec.getLength()-1);return e>0?Ec.getText(0,e):""}function cm(e){return String(e||"").replace(/\u00A0/g," ").replace(/ /gi," ")}function dm(){if(!Ec)return"";var e=Math.max(0,Ec.getLength()-1);if(e<=0)return"";try{return cm(Ec.getSemanticHTML(0,e))}catch(e){var t=document.querySelector("#inputText .ql-editor");return t?cm(t.innerHTML):""}}function um(e){return e?"selection"===e.scope?cm(e.selectedHtml||gm(e.selectedText)):dm():""}function pm(e){return(String(e||"").replace(/<p\b[^>]*>(?:\s| |<br\s*\/?>)*<\/p>/gi,"").match(/<\/?(?:p|br|strong|b|em|i|u|s|ol|ul|li|h1|h2|h3|blockquote|code|pre|span|a)\b[^>]*>/gi)||[]).map(function(e){var t=/^<\//.test(e),n=e.match(/^<\/?\s*([a-z0-9]+)/i),r=n?n[1].toLowerCase():"";return"b"===r&&(r="strong"),"i"===r&&(r="em"),"br"===r&&(t=!1),(t?"/":"")+r}).filter(Boolean).join("|")}function mm(e,t){var n=pm(um(e));return!!n&&n!==pm(t)}function fm(){return ac(sm())}function gm(e){var t=String(e||"").split(/\n{2,}/);return t.length?t.map(function(e){return"<p>"+e.split("\n").map(rh).join("<br>")+"</p>"}).join(""):""}function hm(e){var t=cm(e).trim();return t?window.DOMPurify&&"function"==typeof window.DOMPurify.sanitize?window.DOMPurify.sanitize(t,{ALLOWED_TAGS:["p","br","strong","b","em","i","u","s","ol","ul","li","h1","h2","h3","blockquote","code","pre","span","a"],ALLOWED_ATTR:["href","target","rel","class"]}):t.replace(/<script[\s\S]*?>[\s\S]*?<\/script>/gi,""):""}var vm=/(^|\n)\s*(#{1,6}\s|[-*]\s|\d+\.\s)|\*\*[^*\n]+\*\*/;function ym(e){var t=cm(e).trim();return t?(t=(t=(t=t.replace(/<span[^>]*class="[^"]*ql-ui[^"]*"[^>]*>[\s\S]*?<\/span>/gi,"")).replace(/\s*style="[^"]*"/gi,"")).replace(/\s*data-[a-z-]+="[^"]*"/gi,""),window.DOMPurify&&"function"==typeof window.DOMPurify.sanitize?window.DOMPurify.sanitize(t,{ALLOWED_TAGS:["p","br","strong","b","em","i","u","ol","ul","li","h1","h2","h3","blockquote","a"],ALLOWED_ATTR:["href"]}):t.replace(/<script[\s\S]*?>[\s\S]*?<\/script>/gi,"")):""}function wm(e){var t=document.createElement("div");t.innerHTML=hm(e);for(var n=t.querySelectorAll("br"),r=0;r<n.length;r++)n[r].parentNode.replaceChild(document.createTextNode("\n"),n[r]);for(var o=t.querySelectorAll("p, div, li, h1, h2, h3, blockquote, pre"),i=0;i<o.length;i++)o[i].appendChild(document.createTextNode("\n"));return(t.textContent||t.innerText||"").replace(/[ \t]+\n/g,"\n").replace(/\n{3,}/g,"\n\n").trim()}function bm(e){return e?(Jd++,e.id="seoa-"+Jd,Zd[e.id]=e,e):null}function km(){if(Rp){try{Rp()}catch(e){}Rp=null}if(Fp){try{Fp.abort()}catch(e){}Fp=null}if(Qc&&"function"==typeof Qc.cancelActiveImprovement)try{Qc.cancelActiveImprovement()}catch(e){}}function Sm(){km(),"function"==typeof window.cancelAllRequests&&window.cancelAllRequests(),Mm(!1),Km(!1)}function xm(e){var t=document.querySelector(".sk-editor-ai-loading-lock");if(t){if("Escape"===e.key)return e.preventDefault(),void Sm();if("Tab"===e.key){var n=t.querySelector(".calm-ai-cancel-btn");if(!n)return;e.preventDefault();try{n.focus({preventScroll:!0})}catch(e){n.focus()}}}}var Tm=".sidebar-dropdown-items-container, .ai-card-input-wrap";function Lm(e){var t;e?(t=[],document.querySelectorAll(Tm).forEach(function(e){e.querySelectorAll('button, textarea, input, select, a[href], [role="tab"], [tabindex]').forEach(function(e){t.push(e)})}),t).forEach(function(e){e.hasAttribute("data-sk-gen-gated")||(e.setAttribute("data-sk-gen-gated","1"),"disabled"in e&&"DIV"!==e.tagName&&(e.disabled?e.setAttribute("data-sk-gen-was-disabled","1"):e.disabled=!0),e.hasAttribute("tabindex")&&e.setAttribute("data-sk-gen-tabindex",e.getAttribute("tabindex")),e.setAttribute("tabindex","-1"),e.setAttribute("aria-disabled","true"))}):document.querySelectorAll("[data-sk-gen-gated]").forEach(function(e){"disabled"in e&&"DIV"!==e.tagName&&!e.hasAttribute("data-sk-gen-was-disabled")&&(e.disabled=!1),e.removeAttribute("data-sk-gen-was-disabled"),e.hasAttribute("data-sk-gen-tabindex")?(e.setAttribute("tabindex",e.getAttribute("data-sk-gen-tabindex")),e.removeAttribute("data-sk-gen-tabindex")):e.removeAttribute("tabindex"),e.removeAttribute("aria-disabled"),e.removeAttribute("data-sk-gen-gated")})}function Em(){return!!document.querySelector(".sk-editor-ai-loading-lock, .sk-selection-ai-loading")}function Cm(){var e=Em();document.body&&document.body.classList.toggle("sk-ai-generating",e),Lm(e)}function _m(e){if(document.body&&document.body.classList.contains("sk-ai-generating")){var t=e.target;t&&t.closest&&t.closest(Tm)&&("keydown"===e.type&&"Escape"===e.key||(e.preventDefault(),e.stopPropagation()))}}window.syncAiGenerationGate=Cm,["click","mousedown","keydown","paste"].forEach(function(e){document.addEventListener(e,_m,!0)});var Am=null;function qm(){!Am&&"function"==typeof MutationObserver&&document.body&&(Am=ne
3w MutationObserver(function(){(Em()||document.body.classList.contains("sk-ai-generating"))&&Cm()})).observe(document.body,{childList:!0,subtree:!0})}function Mm(e,t){var n=document.querySelector(".textarea-wrapper");if(n){var r=n.querySelector(".sk-editor-ai-loading-lock");if(!e)return r&&r.remove(),document.removeEventListener("keydown",xm,!0),n.style.overflowY="",void Cm();if(r){if(t){var o=r.querySelector(".calm-cancel-label");o&&(o.textContent=t)}Cm()}else{var i=document.createElement("div");i.className="sk-editor-ai-loading-lock loader-backdrop",i.setAttribute("role","status"),i.setAttribute("aria-live","polite"),i.setAttribute("aria-busy","true");var a=document.createElement("div");a.className="skeleton-loader",a.setAttribute("aria-hidden","true");for(var l=0;l<15;l++){var s=document.createElement("div");s.className="skeleton-line",a.appendChild(s)}var c=document.createElement("div");c.className="loader-text",c.setAttribute("data-calm-cancel-row","1");var d=document.createElement("div");d.className="gradient-loader",d.setAttribute("aria-hidden","true"),c.appendChild(d);var u=document.createElement("span");u.className="calm-cancel-label",u.textContent=t||SKT("loading.editor_lock"),c.appendChild(u);var p=document.createElement("button");p.type="button",p.className="calm-ai-cancel-btn",p.setAttribute("aria-label",SKT("ai.cancel_aria")||"Annuller AI-behandling"),p.title="Escape",p.innerHTML='<svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true"><path d="M3.5 3.5L10.5 10.5M10.5 3.5L3.5 10.5" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg><span>'+(SKT("ai.cancel_request")||"Annuller")+"</span>",p.addEventListener("click",function(){Sm()}),c.appendChild(p),i.appendChild(a),i.appendChild(c),n.scrollTop=0,n.style.overflow="hidden",n.appendChild(i),document.addEventListener("keydown",xm,!0),Cm()}}}function Im(e){var t=document.querySelector(".sk-selection-ai-loading");if(t){if("Escape"===e.key)return e.preventDefault(),void Sm();if("Tab"===e.key){var n=t.querySelector(".sk-sel-cancel");if(!n)return;e.preventDefault();try{n.focus({preventScroll:!0})}catch(e){n.focus()}}}}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",qm,{once:!0}):qm(),window.setEditorRobotLoading=Mm;var Bm=null;function Hm(e,t,n,r){if(!(e&&t&&n&&Ec&&r&&r.length))return!1;var o=Ec.getBounds(r.index,0),i=Ec.getBounds(r.index+r.length,0);if(!o||!i)return!1;var a=n.getBoundingClientRect(),l=t.getBoundingClientRect(),s=a.top-l.top+t.scrollTop+o.top,c=Math.max(i.top+i.height-o.top,36);return e.style.top=s-4+"px",e.style.height=c+8+"px",!0}function Km(e,t,n){var r=document.querySelector(".textarea-wrapper");if(r){var o=document.querySelector(".sk-selection-ai-loading");if(!e)return o&&o.remove(),document.removeEventListener("keydown",Im,!0),Bm&&(Bm(),Bm=null),void Cm();if(!o)if(Ec&&t&&t.length){var i=Ec.root,a=document.createElement("div");a.className="sk-selection-ai-loading",a.setAttribute("role","status"),a.setAttribute("aria-live","polite"),a.setAttribute("aria-busy","true");var l=document.createElement("div");l.className="sk-sel-status-row";var s=document.createElement("div");s.className="gradient-loader",s.setAttribute("aria-hidden","true"),l.appendChild(s);var c=document.createElement("span");c.className="sk-sel-label",c.textContent=SKT("loading.selection_check")||"Tjekker markeringâ¦",l.appendChild(c);var d=document.createElement("button");if(d.type="button",d.className="sk-sel-cancel",d.setAttribute("aria-label",SKT("ai.cancel_aria")||"Annuller"),d.innerHTML='<svg width="10" height="10" viewBox="0 0 14 14" fill="none" aria-hidden="true"><path d="M3.5 3.5L10.5 10.5M10.5 3.5L3.5 10.5" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg><span>'+(SKT("ai.cancel_request")||"Annuller")+"</span>",d.addEventListener("click",function(){Sm()}),l.appendChild(d),a.appendChild(l),Hm(a,r,i,t)){r.appendChild(a);var u=function(){document.body.contains(a)&&Hm(a,r,i,t)};i.addEventListener("scroll",u,{passive:!0}),Bm=function(){i.removeEventListener("scroll",u)},document.addEventListener("keydown",Im,!0),Cm()}else Mm(!0,n)}else Mm(!0,n)}}function Dm(e){if(!e)return null;var t=e.querySelector(".ai-editor-actions-status");return t||((t=document.createElement("div")).className="ai-editor-actions-status",e.appendChild(t)),t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.setAttribute("aria-atomic","true"),t}function Pm(e,t,n){if(e){Mm(!!t),e.querySelectorAll("[data-editor-action]").forEach(function(e){e.disabled=!!t,t?e.setAttribute("aria-busy","true"):e.removeAttribute("aria-busy")});var r=Dm(e);r&&(r.textContent=t?n||SKT("ea.busy_apply"):"",r.setAttribute("data-state",t?"busy":"idle"))}}function Nm(e,t,n){if(e){Pm(e,!1);var r=Dm(e);r&&(r.textContent=t||"",r.setAttribute("data-state",n||"info"))}}function jm(){var e=new AbortController,t={cancelled:!1};return e.signal.addEventListener("abort",function(){t.cancelled=!0}),Fp=e,{signal:e.signal,isCancelled:function(){return t.cancelled},done:function(){Fp===e&&(Fp=null)}}}function Rm(e,t){return new Promise(function(n,r){Ec?t&&t.aborted?r(new DOMException("Aborted","AbortError")):!function(e){if(!e)return!1;if(lc(e.snapshot,fm())){if(e.snapshot=e.snapshot||{},e.snapshot.docHash=fm(),e.snapshot.textLength=sm().length,e._cachedRewrite=null,"selection"===e.scope){e.scope="document",e.selectionRange=null,e.selectedText="",e.selectedHtml="";var t=document.querySelector('.ai-editor-actions[data-editor-action-model="'+e.id+'"]');if(t){var n=t.querySelector('[data-editor-action="apply_rewrite"] span'),r=t.querySelector(".ai-editor-actions-scope");n&&(n.textContent=SKT("ea.apply_document")),r&&(r.textContent=SKT("ea.scope_document_active"))}}th('<svg viewBox="0 0 24 24" width="18" height="18" stroke="#9B6050" fill="none" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 8v4l2 2"/></svg><span>'+rh(SKT("ea.toast_stale"))+"</span>")}return!0}
3(e)?r(new Error("stale")):du().then(function(o){if(t&&t.aborted)r(new DOMException("Aborted","AbortError"));else if(o){var i=um(e),a="selection"===e.scope?e.selectedText:sm(),l=new FormData;l.append("action","hgf_grammar_bot_edit"),l.append("quillContent",i),l.append("quillText",a),l.append("userMessage",e.query),l.append("scope",e.scope||"document"),l.append("aiResponseMessage",e.answer),l.append("language",fc({answer:e.answer,sourceText:a,fallbackLanguage:It()})),fetch("/robots/skrivebord/grammar-api.php",{method:"POST",headers:{Authorization:"Bearer "+o},body:l,signal:t}).then(function(e){if((413===e.status||429===e.status)&&window.SSWordLimit){var t=413===e.status&&window.__SS_PUBLIC_MODE?{silent:!0}:void 0;return window.SSWordLimit.handleResponse(e,t).then(function(t){if(t)throw window.SSWordLimit.createError(t);throw new Error(SKT("ea.error_server",{code:e.status}))})}if(413===e.status)return e.json().catch(function(){return{}}).then(function(t){if(t&&("word_limit_exceeded"===t.error||t.login_required))throw new Error("word_limit_exceeded");throw new Error(SKT("ea.error_server",{code:e.status}))});if(!e.ok)throw new Error(SKT("ea.error_server",{code:e.status}));return e.json()}).then(function(e){if(!e||!1===e.success){var t=e&&e.data&&(e.data.message||e.data);throw new Error(t||SKT("ea.error_ai_fail"))}var r=e.content||e.data&&e.data.content||"";if(!r)throw new Error(SKT("ea.error_empty"));n(Fm(r))}).catch(r)}else r(new Error(SKT("ea.error_session")))}).catch(r):r(new Error(SKT("ea.error_no_editor")))})}function Fm(e){var t=String(e||"");return t&&/\*\*|__|(^|\n)\s*(#{1,3}\s|[-*]\s|>\s)|(^|[\s>(])\*\S[^*\n]*\*($|[\s<).,!?;:])|(^|[\s>(])_\S[^_\n]*_($|[\s<).,!?;:])/.test(t)?/<(p|br|strong|em|b|i|u|s|a|span|code|pre|ol|ul|li|h[1-3]|blockquote|div)\b/i.test(t)?t.split(/(<[^>]*>)/).map(function(e){return"<"===e.charAt(0)?e:e.replace(/\*\*(\S(?:[^*\n]*\S)?)\*\*/g,"<strong>$1</strong>").replace(/(^|[\s(])__(\S(?:[^_\n]*\S)?)__(?=$|[\s).,!?;:])/gm,"$1<strong>$2</strong>").replace(/(^|[\s(])\*(\S(?:[^*\n]*\S)?)\*(?=$|[\s).,!?;:])/gm,"$1<em>$2</em>").replace(/(^|[\s(])_(\S(?:[^_\n]*\S)?)_(?=$|[\s).,!?;:])/gm,"$1<em>$2</em>")}).join(""):ah(t):t}function Om(e){if(!e)return"";var t=function(e){var t=String(e||"").trim().replace(/\r\n/g,"\n");return t?vc(t)||t:""}(e);return t?hm(ah(t)):""}function Um(){return{docHash:fm(),text:sm()}}function $m(e){return!!e&&(e.docHash!==fm()||e.text!==sm())}function zm(e,t,n,r,o){var i=window.SSGhostPreview;if(!(i&&"function"==typeof i.open&&Ec&&Ec.container&&t))return!1;try{if(lc(t.snapshot,fm()))return!1;var a=hm(Fm(n));if(!a)return!1;var l=cm("selection"===t.scope&&(t.selectedHtml||t.selectedText)?t.selectedHtml||String(t.selectedText||"").split(/\n+/).map(function(e){return e.trim()}).filter(Boolean).map(function(e){return"<p>"+rh(e)+"</p>"}).join(""):dm());return i.open({host:Ec.container,originalHtml:l,proposedHtml:a,t:SKT,onOpenChange:function(e){try{o&&o.hasAttribute("aria-pressed")&&o.setAttribute("aria-pressed",e?"true":"false")}catch(e){}try{Ec.enable(!e)}catch(e){}try{(Ec.container.closest(".grammar-page")||document).querySelectorAll(".ql-toolbar, .skv2-action-controls, .format-toolbar").forEach(function(t){if(e){if(t.hasAttribute("inert"))return void(t.dataset.ghostPriorInert="1");t.setAttribute("inert","")}else{if(t.dataset.ghostPriorInert)return void delete t.dataset.ghostPriorInert;t.removeAttribute("inert")}})}catch(e){}},onApply:function(){var o=Gm(t,n),i=r||{};i.success=!!o,i.ghost=!0,ud("apply",t,i),o?Ym(e,t):Nm(e,SKT("ea.stat_none"),"info")},onDismiss:function(){ud("ghost_dismiss",t,r||{})}})}catch(e){try{window.SSGhostPreview&&window.SSGhostPreview.close&&window.SSGhostPreview.close()}catch(e){}return!1}}function Gm(e,t){if(!Ec||!e)return!1;if(lc(e.snapshot,fm()))return th('<svg viewBox="0 0 24 24" width="18" height="18" stroke="#9B6050" fill="none" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 8v4l2 2"/></svg><span>'+rh(SKT("ea.followup_stale"))+"</span>"),!1;var n=hm(Fm(t));if(!n)return!1;var r=dm(),o=fm(),i=Um();Mg(),Zu(),hd=!0;try{if("selection"===e.scope&&e.selectionRange)Ec.deleteText(e.selectionRange.index,e.selectionRange.length,"user"),Ec.clipboard&&Ec.clipboard.dangerouslyPasteHTML?Ec.clipboard.dangerouslyPasteHTML(e.selectionRange.index,n,"user"):Ec.insertText(e.selectionRange.index,wm(n),"user"),Ec.setSelection(e.selectionRange.index,0,"silent");else{var a=Math.max(0,Ec.getLength()-1);a>0&&Ec.deleteText(0,a,"user"),Ec.clipboard&&Ec.clipboard.dangerouslyPasteHTML?Ec.clipboard.dangerouslyPasteHTML(0,n,"user"):Ec.insertText(0,wm(n),"user"),Ec.setSelection(Math.max(0,Ec.getLength()-1),0,"silent")}}finally{hd=!1}return!!$m(i)&&(Ec.focus(),e.snapshot.docHash=fm(),e.snapshot.textLength=sm().length,e._undoHtml=r,e._undoScope=e.scope||"document",e._undoHash=e.snapshot.docHash,e._preApplyHash=o,Xp=e,!0)}function Vm(e){if(!Ec)return!1;var t=hm(e);if(!t)return!1;Mg(),Zu(),hd=!0;try{var n=Math.max(0,Ec.getLength()-1);n>0&&Ec.deleteText(0,n,"user"),Ec.clipboard&&Ec.clipboard.dangerouslyPasteHTML?Ec.clipboard.dangerouslyPasteHTML(0,t,"user"):Ec.insertText(0,wm(t),"user"),Ec.setSelection(Math.max(0,Ec.getLength()-1),0,"silent")}finally{hd=!1}return Ec.focus(),!0}var Wm=null,Jm=null;function Zm(){Jm=null;var e=Wm;if(e){var t=e.card,n=e.status;if(t&&t.isConnected&&n&&n.isConnected&&t.hasAttribute("data-applied")){var r=fm();if(r!==e.undoHash){if(e.preApplyHash&&r===e.preApplyHash)e.model&&(e.model._undoHtml=null),t.removeAttribute("data-applied"),n.textContent="",n.removeAttribute("data-state");else{var o=n.querySelector(".ai-editor-undo-btn");o&&o.remove()}Wm=null}}else Wm=null}}function Ym(e,t){if(e)if(!(!t||!t._undoHtml||"selection"===t._undoScope)){Pm(e,!1),e.setAttribute("data-applied","1");var n=Dm(e);if(n){n.setAttribute("data-state","applied"),n.textContent="";var r=document.createElement("span");r.className="ai-editor-applied-msg",r.innerHTML='<svg class="ai-editor-applied-check" viewB
3ox="0 0 16 16" width="16" height="16" aria-hidden="true"><circle cx="8" cy="8" r="7.25" fill="#4A7A68"></circle><path d="M4.8 8.2l2.1 2.1 4.3-4.6" fill="none" stroke="#ffffff" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path></svg>',r.appendChild(document.createTextNode(SKT("ea.followup_applied")));var o=document.createElement("button");o.type="button",o.className="ai-editor-undo-btn",o.setAttribute("aria-label",SKT("ea.toast_undo_aria")),o.innerHTML='<svg viewBox="0 0 16 16" width="13" height="13" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M6.2 3.4 2.6 7l3.6 3.6"></path><path d="M3 7h6.2a4.2 4.2 0 1 1 0 8.4H6.8"></path></svg><span>'+rh(SKT("ea.toast_undo_label"))+"</span>",n.appendChild(r),n.appendChild(o);var i=t._undoHtml,a=t._undoHash;Wm={model:t,card:e,status:n,undoHash:a,preApplyHash:t._preApplyHash||null};var l=function(e,t){n&&(n.textContent=e||"",t?n.setAttribute("data-state",t):n.removeAttribute("data-state"))};o.addEventListener("click",function(){if(Wm=null,fm()!==a)return ud("undo_stale",t),void l(SKT("ea.toast_undo_expired"),"warning");var n=Vm(i);ud("undo",t,{success:!!n}),n?(t._undoHtml=null,t.snapshot&&(t.snapshot.docHash=fm(),t.snapshot.textLength=sm().length),e.removeAttribute("data-applied"),l("",null)):l(SKT("ea.toast_undo_expired"),"warning")})}}else Nm(e,SKT("ea.followup_applied"),"success")}function Qm(e){if(!Ec||!e)return!1;var t=Fm(e._workshopImproved||e._cachedRewrite||"");if(!t&&e._rewriteTruncated)return!1;var n=Om(e.answer),r=e.insertText||dc(e.answer);if(!t&&!n&&!r)return!1;var o=Um(),i=Ec.getSelection(),a=i?i.index:Math.max(0,Ec.getLength()-1);if(i&&i.length>0&&(Ec.deleteText(i.index,i.length,"user"),a=i.index),t&&Ec.clipboard&&Ec.clipboard.dangerouslyPasteHTML)a>0&&!(i&&i.length>0)&&(Ec.insertText(a,"\n","user"),a++),Ec.clipboard.dangerouslyPasteHTML(a,hm(t),"user");else if(t){var l=a>0&&!(i&&i.length>0)?"\n":"";Ec.insertText(a,l+wm(t),"user")}else if(n&&Ec.clipboard&&Ec.clipboard.dangerouslyPasteHTML)a>0&&!(i&&i.length>0)&&(Ec.insertText(a,"\n","user"),a++),Ec.clipboard.dangerouslyPasteHTML(a,hm(n),"user");else{var s=a>0&&!(i&&i.length>0)?"\n":"";Ec.insertText(a,s+r,"user")}return Ec.setSelection(Math.max(0,Ec.getLength()-1),0,"silent"),!!$m(o)&&(Ec.focus(),!0)}function Xm(e,t,n){if(e){var r=e.parentNode&&e.parentNode.querySelector(".ai-editor-preview");r&&r.remove();var o=wm(n),i=t&&"selection"===t.scope&&t.selectedText?String(t.selectedText):sm(),a=window._wf;if(a&&a.skCompare&&"function"==typeof a.skCompare.open){var l="";if(t&&"selection"===t.scope&&(t.selectedHtml||t.selectedText))l=t.selectedHtml||String(t.selectedText||"").split(/\n+/).map(function(e){return e.trim()}).filter(Boolean).map(function(e){return"<p>"+rh(e)+"</p>"}).join("");else if(Ec)try{l=Ec.getSemanticHTML(0,Ec.getLength())}catch(e){l=""}l=cm(l);var s=e.querySelector(".ai-editor-action-btn--primary")||e.querySelector(".ai-editor-action-btn");s&&!s.id&&(s.id="ea-return-"+(t&&t.id?String(t.id):"card"));try{return void a.skCompare.open(l,m(),{returnFocusId:s?s.id:null,footerAction:{label:SKT("ea.preview_apply"),onClick:function(){var r=Gm(t,n);ud("modal_apply",t,{success:!!r}),r?Ym(e,t):Nm(e,SKT("ea.stat_none"),"info")}}})}catch(e){}}var c=document.createElement("div");c.className="ai-editor-preview",c.setAttribute("role","group"),c.setAttribute("aria-label",SKT("ea.preview_label")),c.setAttribute("tabindex","-1"),c.innerHTML='<div class="ai-editor-preview-header"><div class="ai-editor-preview-label">'+rh(SKT("ea.preview_label"))+'</div></div><div class="ai-editor-preview-body">'+m()+'</div><div class="ai-editor-preview-actions"><button type="button" class="ai-editor-action-btn ai-editor-preview-apply-btn" data-editor-preview-apply>'+rh(SKT("ea.preview_apply"))+'</button><button type="button" class="ai-editor-action-btn" data-editor-preview-cancel>'+rh(SKT("ea.preview_close"))+"</button></div>",e.insertAdjacentElement("afterend",c);var d=c.querySelector(".ai-editor-preview-body");oh(function(){try{var e=function(e,t){var n=Cf(String(e||""),String(t||""));if(!n||!n.length)return null;for(var r=0,o=0,i=0;i<n.length;i++){var a=(n[i][1]||"").length;o+=a,0!==n[i][0]&&(r+=a)}if(0===o||r/o>.85)return null;function l(e){return e.length<=220?rh(e):rh(e.slice(0,90))+'<span style="color:#B4A89C"> ⦠</span>'+rh(e.slice(-90))}for(var s="",c=0;c<n.length;c++){var d=n[c][0],u=n[c][1];u&&(s+=0===d?l(u):-1===d?'<del style="color:#9A8E82;text-decoration:line-through;margin-right:0.18em">'+rh(u)+"</del>":'<ins style="color:#4A7A68;font-weight:500;text-decoration:none">'+rh(u)+"</ins>")}return'<div class="ai-editor-diff" style="white-space:pre-wrap;line-height:1.65;color:#5C4D43">'+s+"</div>"}(i,o);e&&d&&(d.innerHTML=e)}catch(e){}}),e.style.display="none";var u=function(){e.style.display=""};try{c.scrollIntoView({behavior:"smooth",block:"nearest"})}catch(e){}try{c.focus()}catch(e){}var p=function(){c.remove(),u();try{var t=e.querySelector(".ai-editor-action-btn--primary");t&&t.focus()}catch(e){}};c._ssClosePreview=p,c.addEventListener("keydown",function(e){"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),p())}),c.querySelector("[data-editor-preview-apply]").addEventListener("click",function(){var r=Gm(t,n);ud("preview_apply",t,{success:!!r}),r?(c.remove(),u(),Ym(e,t)):(c.remove(),u(),Nm(e,SKT("ea.stat_none"),"info"))}),c.querySelector("[data-editor-preview-cancel]").addEventListener("click",p)}function m(){var e=hm(n);return e&&/<(p|br|li|h[1-3]|ul|ol|blockquote|pre)\b/i.test(e)?e:o.split(/\n+/).map(function(e){return e.trim()}
3).filter(Boolean).map(function(e){return"<p>"+rh(e)+"</p>"}).join("")}}function ef(e,t){var n=function(e){if(!e||!e.id)return"";var t="selection"===e.scope?SKT("ea.scope_selection_active"):SKT("ea.scope_document_active"),n=e.actions||[],r=e.primary||n[0]||{type:"apply_rewrite",label:SKT("ea.apply_document")},o=e.tertiary||n.find(function(e){return"insert_at_cursor"===e.type})||{type:"insert_at_cursor",label:SKT("ea.insert")},i=r.type||"apply_rewrite",a=o.type||"insert_at_cursor";function l(e){return"insert_at_cursor"===e?'<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3v12"/><path d="M7 10l5 5 5-5"/><path d="M5 20h14"/></svg>':"apply_rewrite"===e?'<svg viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="5" width="7.5" height="14" rx="1.5"/><rect x="13.5" y="5" width="7.5" height="14" rx="1.5" stroke-dasharray="3 2.4"/></svg>':'<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3l1.6 4.4L18 9l-4.4 1.6L12 15l-1.6-4.4L6 9l4.4-1.6L12 3z"/><path d="M19 14l.8 2.2L22 17l-2.2.8L19 20l-.8-2.2L16 17l2.2-.8L19 14z"/></svg>'}"apply_rewrite"===i&&(r=Object.assign({},r,{label:SKT("ea.ghost_see_diff")}));var s="scope-"+e.id,c="apply_rewrite"===i?' aria-pressed="false"':"";return'<div class="ai-editor-actions" role="toolbar" aria-label="'+rh(SKT("ea.toolbar_aria"))+'" data-editor-action-model="'+rh(e.id)+'"><div class="ai-editor-actions-row"><button type="button" class="ai-editor-action-btn ai-editor-action-btn--primary" data-editor-action="'+rh(i)+'" data-editor-action-model="'+rh(e.id)+'"'+c+' aria-describedby="'+rh(s)+'">'+l(i)+"<span>"+rh(r.label)+'</span></button><button type="button" class="ai-editor-action-btn ai-editor-action-btn--quiet" data-editor-action="'+rh(a)+'" data-editor-action-model="'+rh(e.id)+'" aria-describedby="'+rh(s)+'">'+l(a)+"<span>"+rh(o.label)+'</span></button></div><div class="ai-editor-actions-scope" id="'+rh(s)+'">'+rh(t)+"</div></div>"}(t),r=rh(SKT("toolbar.copy")),o=rh(SKT("toolbar.tts"));return n+='<div class="ai-msg-actions"><button type="button" class="ai-msg-action-btn" data-copy title="'+r+'" aria-label="'+r+'"><svg viewBox="0 0 24 24"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/></svg></button><button type="button" class="ai-msg-action-btn" data-tts data-tts-status="idle" title="'+o+'" aria-label="'+o+'"><svg viewBox="0 0 24 24"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><path d="M15.54 8.46a5 5 0 010 7.07"/></svg></button><span class="ai-msg-action-status" data-tts-status-text role="status" aria-live="polite" aria-atomic="true"></span></div>'}function tf(e,t,n,r){setTimeout(function(){var o=function(e){var t=Up(e);return document.getElementById(t)||document.getElementById("ai-card-messages")}(n),i=o?o.querySelectorAll(".ai-msg"):[],a=r||(i.length>0?i[i.length-1]:null);if(a&&(!o||o.contains(a))){if(function(e){e&&e.querySelectorAll("[data-editor-action]").forEach(function(e){e.dataset.wired||(e.dataset.wired="true",e.addEventListener("click",function(){var t=Zd[e.getAttribute("data-editor-action-model")||""],n=e.getAttribute("data-editor-action"),r=e.closest(".ai-editor-actions");if(t&&n){if("insert_at_cursor"===n){var o=Qm(t);return ud("insert",t,{success:!!o}),void(o?Nm(r,SKT("ea.followup_inserted"),"success"):Nm(r,SKT("ea.followup_no_pending"),"info"))}if("apply_rewrite"===n&&"true"===e.getAttribute("aria-pressed")&&window.SSGhostPreview&&"function"==typeof window.SSGhostPreview.isOpen&&window.SSGhostPreview.isOpen()){try{window.SSGhostPreview.close()}catch(e){}ud("ghost_dismiss",t,{via:"toggle"})}else{var i=t._cachedRewrite&&mm(t,t._cachedRewrite);if(t._cachedRewrite&&!lc(t.snapshot,fm())&&!i){if("preview_rewrite"===n)return ud("preview",t),void Xm(r,t,t._cachedRewrite);if(zm(r,t,t._cachedRewrite,{cached:!0},e))return void ud("ghost_open",t,{cached:!0});var a=Gm(t,t._cachedRewrite);return ud("apply",t,{success:!!a}),void(a?(e.classList.add("done"),Ym(r,t),setTimeout(function(){e.classList.remove("done")},1800)):Nm(r,SKT("ea.stat_none"),"info"))}var l=Date.now(),s=jm();Pm(r,!0,"preview_rewrite"===n?SKT("ea.busy_preview"):SKT("ea.busy_apply")),Rm(t,s.signal).then(function(o){if
3(s.done(),s.isCancelled())Pm(r,!1);else{var a={cached:!1,format_refresh:!!i,refetch_ms:Date.now()-l};if(Pm(r,!1),t._cachedRewrite=o,"preview_rewrite"===n)return ud("preview",t,a),void Xm(r,t,o);if(zm(r,t,o,a,e))ud("ghost_open",t,a);else{var c=Gm(t,o);a.success=!!c,ud("apply",t,a),c?(e.classList.add("done"),Ym(r,t),setTimeout(function(){e.classList.remove("done")},1800)):Nm(r,SKT("ea.stat_none"),"info")}}}).catch(function(e){s.done(),Pm(r,!1),s.isCancelled()||e&&"AbortError"===e.name||(!e||!e.wordLimitExceeded&&"word_limit_exceeded"!==e.message?e&&"stale"===e.message?Nm(r,SKT("ea.followup_stale"),"warning"):(Nm(r,e&&e.message||SKT("ea.error_apply_fail"),"error"),th('<svg viewBox="0 0 24 24" width="18" height="18" stroke="#B85450" fill="none" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 8v5"/><path d="M12 16h.01"/></svg><span>'+rh(e&&e.message||SKT("ea.error_apply_fail"))+"</span>")):Nm(r,SKT("ea.error_word_limit"),"warning"))})}}}))})}(a),n){var l=a.querySelector(".ai-editor-actions[data-editor-action-model]");l&&o&&function(e,t){e&&e.querySelectorAll(".ai-editor-actions[data-editor-action-model]").forEach(function(e){e!==t&&"1"!==e.getAttribute("data-superseded")&&(e.setAttribute("data-superseded","1"),e.querySelectorAll('[data-editor-action="apply_rewrite"], [data-editor-action="preview_rewrite"]').forEach(function(e){e.disabled=!0,e.setAttribute("aria-disabled","true")}))})}(o,l),function(e){try{var t=document.getElementById("sk-sofia-sr-announcer");t||((t=document.createElement("div")).id="sk-sofia-sr-announcer",t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.setAttribute("aria-atomic","true"),t.style.cssText="position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap;border:0;",document.body.appendChild(t));var n=SKT("ea.sr_replied")||"Sofia svarede",r=e&&e.querySelector(".ai-editor-actions[data-editor-action-model]");if(r){var o=[];r.querySelectorAll("[data-editor-action] span").forEach(function(e){var t=(e.textContent||"").trim();t&&o.push(t)}),o.length&&(n+=". "+o.join(", "))}t.textContent="",setTimeout(function(){t.textContent=n},60)}catch(e){}}(a)}a.querySelectorAll("[data-copy]").forEach(function(t){t.dataset.wired||(t.dataset.wired="true",t.addEventListener("click",function(){var n=ah(e),r=e.replace(/\*\*(.+?)\*\*/g,"$1").replace(/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g,"$1").replace(/__(.+?)__/g,"$1").replace(/`(.+?)`/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/^#{1,6}\s+/gm,"").replace(/^[\s]*[-*+â¢]\s+/gm,"⢠").replace(/^[\s]*(\d+)\.\s+/gm,"$1. ").trim(),o=function(){t.classList.add("done"),t.innerHTML='<svg viewBox="0 0 24 24" width="13" height="13" stroke="currentColor" fill="none" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg>',setTimeout(function(){t.classList.remove("done"),t.innerHTML='<svg viewBox="0 0 24 24"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/></svg>'},2e3)};if(navigator.clipboard&&"undefined"!=typeof ClipboardItem)navigator.clipboard.write([new ClipboardItem({"text/html":new Blob([n],{type:"text/html"}),"text/plain":new Blob([r],{type:"text/plain"})})]).then(o).catch(function(){navigator.clipboard.writeText(r).then(o)});else{var i=document.createElement("div");i.contentEditable="true",i.innerHTML=n,i.style.position="fixed",i.style.left="-9999px",document.body.appendChild(i);var a=document.createRange();a.selectNodeContents(i);var l=window.getSelection();l.removeAllRanges(),l.addRange(a);try{document.execCommand("copy")}catch(e){}l.removeAllRanges(),document.body.removeChild(i),o()}}))}),a.querySelectorAll("[data-tts]").forEach(function(t){t.dataset.wired||(t.dataset.wired="true",t.addEventListener("click",function(){var n,r,o;df(t,(r=e,sf((o=(n=a)&&n.querySelector?n.querySelector(".ai-msg-content"):null)&&o.textContent?o.textContent:"")||r||""))}))}),a.querySelectorAll("[data-insert]").forEach(function(t){t.dataset.wired||(t.dataset.wired="true",t.addEventListener("click",function(){if(Ec){var n=ah(e);n=n.replace(/<span class="ai-cite-ref">\[\d+\]<\/span>/g,"").replace(/<h[23] class="ai-md-heading">/g,"<p><strong>").replace(/<\/h[23]>/g,"</strong></p>");var r,o=Ec.getSelection();o&&o.length>0?(Ec.deleteText(o.index,o.length),r=o.index):o?r=o.index:(r=Ec.getLength()-1,Ec.insertText(r,"\n"),r+=1);var i=Ec.getModule("clipboard");if(i&&i.dangerouslyPasteHTML)i.dangerouslyPasteHTML(r,n);else{var a=e.replace(/\*\*(.+?)\*\*/g,"$1").replace(/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g,"$1").replace(/`(.+?)`/g,"$1").trim();Ec.insertText(r,a)}t.classList.add("done"),t.innerHTML='<svg viewBox="0 0 24 24" width="13" height="13" stroke="currentColor" fill="none" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg>',th('<svg viewBox="0 0 24 24" width="18" height="18" stroke="#4a5768" fill="none" stroke-width="2"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg><span>'+rh(SKT("ea.toast_inserted"))+"</span>"),setTimeout(function(){t.classList.remove("done"),t.innerHTML='<svg viewBox="0 0 24 24">
3<path d="M15 3h6v6"/><path d="M10 14L21 3"/><path d="M18 13v6a2 2 0 01-2 2H5a2 2 0 01-2-2V8a2 2 0 012-2h6"/></svg>'},2e3)}}))}),a.querySelectorAll("[data-retry]").forEach(function(e){e.dataset.wired||(e.dataset.wired="true",e.addEventListener("click",function(){if(!(Gc.length<2)){var t=Gc[Gc.length-2];if(t&&"user"===t.role){Gc.pop(),Gc.pop();var n=e.closest(".ai-msg");n&&n.remove(),lm(t.content)}}}))});var s=a.querySelector("[data-email-copy]");if(s&&"email-compose"===t){if(s.dataset.wired)return;s.dataset.wired="true",s.addEventListener("click",function(){navigator.clipboard.writeText(e).then(function(){window.open("/email/#compose","_blank"),th('<svg viewBox="0 0 24 24" width="18" height="18" stroke="#4a5768" fill="none" stroke-width="2"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg><span>E-mail kopieret â indsæt i e-mailen</span>')})})}}},50)}function nf(e,t){var n=e&&e.closest?e.closest(".ai-msg-actions"):null,r=n&&n.querySelector?n.querySelector("[data-tts-status-text]"):null;r&&(r.textContent=t||"",t?r.classList.add("visible"):r.classList.remove("visible"))}function rf(){return window.HGF_ajax_object&&window.HGF_ajax_object.ajax_url||window.ajaxurl||"/robots/skrivebord/grammar-api.php"}function of(){var e="da-DK";try{e=me&&me()||"da-DK"}catch(e){}return function(e){if(!e)return"";var t=String(e).trim();if(!t)return"";var n=null;if("undefined"!=typeof TTSEngine&&TTSEngine&&"function"==typeof TTSEngine.normalizeLanguage?n=TTSEngine:"undefined"!=typeof window&&window.TTSEngine&&"function"==typeof window.TTSEngine.normalizeLanguage&&(n=window.TTSEngine),n&&"function"==typeof n.normalizeLanguage){var r="__unknown_tts_language__",o=n.normalizeLanguage(t,r);if(o&&o!==r)return o}var i={da:"Danish",danish:"Danish",en:"English",english:"English",de:"German",ge:"German",german:"German",fr:"French",french:"French",es:"Spanish",spanish:"Spanish",sv:"Swedish",swedish:"Swedish",no:"Norwegian",nb:"Norwegian",nn:"Norwegian",norwegian:"Norwegian",fi:"Finnish",finnish:"Finnish",pl:"Polish",polish:"Polish",it:"Italian",italian:"Ital
3ian",pt:"Portuguese",portuguese:"Portuguese",nl:"Dutch",dutch:"Dutch",tr:"Turkish",turkish:"Turkish",ru:"Russian",russian:"Russian",ar:"Arabic",arabic:"Arabic",uk:"Ukrainian",ukrainian:"Ukrainian",ja:"Japanese",japanese:"Japanese",ko:"Korean",korean:"Korean",zh:"Chinese",chinese:"Chinese"};return i[t.split("-")[0].toLowerCase()]||i[t.toLowerCase()]||""}(e)||"Danish"}function af(e,t){if(e){if(cd=t,e.classList.remove("active","loading","paused","failed"),e.removeAttribute("aria-busy"),e.removeAttribute("data-tts-status"),e.removeAttribute("data-tts-error"),e.setAttribute("data-tts-status",t||"idle"),nf(e,""),"loading"===t){e.classList.add("active","loading"),e.setAttribute("aria-busy","true");var n=("function"==typeof SKT?SKT("tts.loading_audio"):"")||"Loading audio...",r=("function"==typeof SKT?SKT("toolbar.tts_stop"):"")||"Stop";return e.title=r,e.setAttribute("aria-label",r),e.innerHTML='<svg viewBox="0 0 24 24" width="13" height="13" stroke="currentColor" fill="none" stroke-width="2" class="spin-icon"><path d="M21 12a9 9 0 11-6.219-8.56"/></svg>',void nf(e,n)}if("playing"===t){e.classList.add("active");var o=("function"==typeof SKT?SKT("tts.pause"):"")||"Pause";return e.title=o,e.setAttribute("aria-label",o),void(e.innerHTML='<svg viewBox="0 0 24 24" width="13" height="13" stroke="currentColor" fill="none" stroke-width="2"><rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/></svg>')}if("paused"===t){e.classList.add("active","paused");var i=("function"==typeof SKT?SKT("tts.resume"):"")||"Resume";return e.title=i,e.setAttribute("aria-label",i),void(e.innerHTML='<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="5 3 19 12 5 21 5 3"/></svg>')}if("failed"===t){e.classList.add("failed"),e.setAttribute("data-tts-status","failed"),e._ssTtsErrorCategory&&e.setAttribute("data-tts-error",e._ssTtsErrorCategory);var a=("function"==typeof SKT?SKT("tts.read_failed"):"")||"Read-aloud failed",l=("function"==typeof SKT?SKT("ea.retry"):"")||a;return e.title=l,e.setAttribute("aria-label",l),e.innerHTML='<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><line x1="19" y1="5" x2="5" y2="19"/></svg>',void nf(e,a)}var s=("function"==typeof SKT?SKT("toolbar.tts"):"")||"Read aloud";e.title=s,e.setAttribute("aria-label",s),e.innerHTML='<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><path d="M15.54 8.46a5 5 0 0 1 0 7.07"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14"/></svg>'}}function lf(e,t,n){var r=new FormData;r.append("action","hgf_important_secure_bots_text_to_speech"),r.append("nonce",window.HGF_ajax_object&&window.HGF_ajax_object.nonce||""),r.append("text",t.substring(0,3e3)),r.append("lang",of()),r.append("gender","Female");var o={method:"POST",body:r};return(id=window.AbortController?new AbortController:null)&&(o.signal=id.signal),fetch(rf(),o).then(function(e){if(!e.ok)throw new Error("TTS HTTP "+e.status);var t=e.headers&&e.headers.get&&e.headers.get("content-type")||"";if(t&&-1===t.indexOf("audio")&&-1===t.indexOf("octet-stream"))throw new Error("TTS returned non-audio response");return e.blob()}).then(function(t){if(n!==ld)return null;ad=URL.createObjectURL(t);var r=new Audio(ad);g(r),nd=r,r.addEventListener("ended",function(){uf()}),r.addEventListener("error",function(){n===ld&&cf(e,new Error("TTS audio playback failed"))});var o=r.play();return o&&"function"==typeof o.then?o.then(function(){n===ld&&af(e,"playing")}):(af(e,"playing"),null)})}function sf(e){if(!e)return"";var t=String(e).trim();return(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=(t=t.replace(/^#{1,6}\s+/gm,"")).replace(/\*\*(.+?)\*\*/g,"$1")).replace(/__(.+?)__/g,"$1")).replace(/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g,"$1")).replace(/(?<!_)_(?!_)(.+?)(?<!_)_(?!_)/g,"$1")).replace(/~~(.+?)~~/g,"$1")).replace(/`([^`]+)`/g,"$1")).replace(/```[\s\S]*?```/g,"")).replace(/\[([^\]]+)\]\([^)]+\)/g,"$1")).replace(/^[\s]*[-*+â¢]\s+/gm,"")).replace(/^[\s]*\d+[.)]\s+/gm,"")).replace(/^>\s*/gm,"")).replace(/\n\s*\n/g,"\n")).replace(/[ \t]+/g," ")).trim()}function cf(e,t){var n=function(e){var t=e&&e.name?String(e.name):"",n=e&&e.message?String(e.message):"";if("AbortError"===t)return"aborted";if(/timeout/i.test(t)||/timeout/i.test(n))return"timeout";if(/non-audio/i.test(n))return"non_audio";var r=n.match(/TTS HTTP\s+(\d{3})/i);return r&&r[1]?"http_"+r[1]:/network|fetch/i.test(n)?"network":"unknown"}(t);uf(),e&&"aborted"!==n&&(e._ssTtsErrorCategory=n,af(e,"failed"),e._ssTtsErrorCategory="",setTimeout(function(){"failed"===e.getAttribute("data-tts-status")&&af(e,"idle")},3500))}function df(e,t){if(rd===e){if("playing"===cd)return void(nd?(nd.pause(),af(rd,"paused")):od&&"function"==typeof od.pause&&(od.pause(),af(rd,"paused")));if("paused"===cd)return void function(){if(nd){var e=nd.play();e&&"function"==typeof e.then?e.then(function(){af(rd,"playing")}):af(rd,"playing")}else if(od&&"function"==typeof od.resume)od.resume(),af(rd,"playing")}();if("loading"===cd)return void uf()}uf();var n=sf(t);if(e&&n){rd=e;var r=++ld;af(e,"loading");var o=!(!window.TtsModule||"function"!=typeof window.TtsModule.fetchAudio||"function"!=typeof window.TtsModule.createPlayer)?function(e,t,n){var r=window.TtsModule.createPlayer({onStateChange:function(t){n===ld&&("playing"===t&&af(e,"playing"),"idle"!==t||sd||uf())}});return od=r,"function"==typeof r.prime&&r.prime({volume:p()}),id=window.AbortController?new AbortController:null,window.TtsModule.fetchAudio({text:t,lang:of(),gender:"Female",quality:"premium",endpoint:rf(),signal:id?id.signal:null,maxLength:3e3}).then(function(e){if(n!==ld){try{URL.revokeObjectURL(e)}catch(e){}return null}return ad=e,r.play(e,{volume:p()})})}(e,n,r):lf(e,n,r);Promise.resolve(o).then(function(){r!==ld||nd||od||uf()}).catch(function(t){r===ld&&cf(e,t)})}}function uf(){if(!sd){if(sd=!0,ld++,id){try{id.abort()}catch(e){}id=null}if(od){try{od.stop()}catch(e){}od=null}if(nd&&(nd.pause(),nd.onended=null,nd.onerror=null,nd.src="",nd=null),ad){try{URL.revokeObjectURL(ad)}catch(e){}ad=""}rd&&(af(rd,"idle"),rd=null),cd="idle",sd=!1}}function pf(e,t){var n=t&&t.button?t.button:document.getElementById("ai-card-m
3ic");n&&(n.classList.add("denied"),n.title=e||SKT("stt.micBlocked"),setTimeout(function(){n.classList.remove("denied"),n.title=SKT("stt.dictate")},3e3))}document.addEventListener("skrivebord:tts-stop-all",function(){uf()});var mf="sk:mic-claim",ff="ai-card";function gf(e){uf();var t=function(e){var t=e||{},n={buttonId:t.buttonId||"ai-card-mic",inputId:t.inputId||"ai-card-input"};return n.button=t.button||document.getElementById(n.buttonId),n.key=n.buttonId+"::"+n.inputId,n}(e);if(navigator.mediaDevices&&"function"==typeof navigator.mediaDevices.getUserMedia){var n=function(){try{var e=localStorage.getItem("sb_ui_lang");if(e)return String(e).split("-")[0].toLowerCase()}catch(e){}return"da"}(),r=t.key+"::"+n;if(Xc&&td!==r&&(Xc.stop(),Xc=null,td=null),!Xc){var o=t.button,i=t.inputId;td=r,Xc=le({button:o,idleAriaLabel:o&&o.getAttribute("aria-label")||SKT("stt.dictateAi"),service:"chat",lang:n,onTranscript:function(e){ed.remove();var t=document.getElementById(i);t&&e&&(t.value+=e+" ",t.dispatchEvent(new Event("input",{bubbles:!0})))},onPartial:function(e){var t=document.getElementById(i);if(t){if(e&&!ed.isShowing())try{var n=(t.value||"").length;t.setSelectionRange(n,n)}catch(e){}ed.renderInField(t,e)}},onError:function(){pf(null,t)},onStateChange:function(e){"idle"!==e&&"error"!==e||ed.remove(),o&&(o.title="listening"===e?SKT("stt.stop"):"connecting"===e?SKT("stt.connecting"):SKT("stt.dictate"))}})}try{!("function"==typeof Xc.isActive&&Xc.isActive())&&function(){try{window.dispatchEvent(new CustomEvent(mf,{detail:{owner:ff}}))}catch(e){}}(),Xc.toggle()}catch(e){Xc=null,td=null,pf(null,t)}}else pf(SKT("stt.micRequiresHttps"),t)}function hf(){Xc&&Xc.stop(),Xc=null,td=null}function vf(e,t){if(0===e.length)return t.length;if(0===t.length)return e.length;for(var n=[],r=0;r<=t.length;r++)n[r]=[r];for(var o=0;o<=e.length;o++)n[0][o]=o;for(var i=1;i<=t.length;i++)for(var a=1;a<=e.length;a++){var l=t.charAt(i-1)===e.charAt(a-1)?0:1;n[i][a]=Math.min(n[i-1][a]+1,n[i][a-1]+1,n[i-1][a-1]+l)}return n[t.length][e.length]}function yf(e,t,n){var r=window._aiActions&&window._aiActions[n];return r&&r.category?"fix-language"===n||"analyse"===n?Yd.grammar:Yd[r.category]||Yd.style:Yd.grammar}function wf(e){var t=document.querySelector('mark.inline-correction[data-cid="'+e+'"]');if(!t)return"";var n=t.closest("p, li, h1, h2, h3, blockquote")||t.parentElement;if(!n)return"";var r=n.textContent||"";if(!r||!r.trim())return"";var o=t.textContent||"",i=-1;try{if(document.createRange){var a=document.createRange();a.setStart(n,0),a.setEndBefore(t),i=a.toString().length,a.detach&&a.detach()}}catch(e){i=-1}-1===i&&(i=o?r.indexOf(o):-1),-1===i&&(i=0);for(var l=0,s=i-1;s>=0;s--){var c=r.charAt(s);if("."===c||"!"===c||"?"===c){l=s+1;break}}for(var d=r.length,u=i+o.length;u<r.length;u++){var p=r.charAt(u);if("."===p||"!"===p||"?"===p){d=u+1;break}}return function(e,t,n){if(!e)return"";var r=240,o="number"==typeof t?Math.max(0,t):0,i="number"==typeof n?Math.max(o,n):o;if(e.length>r){var a=Math.max(1,i-o),l=Math.floor((r-Math.min(a,r))/2),s=Math.max(0,o-l),c=s+r;c>e.length&&(c=e.length,s=Math.max(0,c-r)),e=e.slice(s,c)}return(e=e.replace(/\s+/g," ").trim()).length>r&&(e=e.slice(0,r).trim()),e}(r.slice(l,d),i-l,i-l+o.length)}"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener(mf,function(e){e&&e.detail&&e.detail.owner===ff||hf()});var bf="undefined"!=typeof Map?new Map:null,kf=800;function Sf(e,t,n,r,o,i){function a(e){var t=String(null==e?"":e);return t.length+":"+t}return a(e)+a(t)+a(n)+a(r)+a(o)+a(i)}function xf(e){return bf&&bf.has(e)?bf.get(e):null}function Tf(e,t){if(bf){if(bf.size>=kf){var n=bf.keys().next().value;void 0!==n&&bf.delete(n)}bf.set(e,t)}}function Lf(e,t){var n=pd[e];if(n&&t){var r=Yd[t.category]||n.category;n.category=r,"string"==typeof t.short&&""!==t.short&&(n.explanation=t.short),"string"==typeof t.detail&&(n.explanationDetail=t.detail),n.explanationPending=!1;for(var o=document.querySelectorAll('mark.inline-correction[data-cid="'+e+'"]'),i=0;i<o.length;i++)o[i].removeAttribute("data-classifying"),r&&r.key&&o[i].setAttribute("data-type",r.key),r&&r.color&&!o[i].closest("h1, h2, h3")&&(o[i].style.borderBottomColor=r.color)}}function Ef(e,t){var n=Object.keys(pd).length,r=Cd;if(n>0&&(_f(n),r&&Mf(r)),Dd(t,pd),xd&&-1!==e.indexOf(xd)){var o=document.getElementById("correction-popup"),i=document.querySelector('mark.inline-correction[data-cid="'+xd+'"]');o&&i&&!Lg()&&Wg(xd,i)}}function Cf(e,t){var n=window.diff_match_patch;if(!n)return null;function r(e){return e.match(/\S+|\s+/g)||[]}var o=r(e),i=r(t),a=[""],l={},s=1;function c(e){for(var t="",n=0;n<e.length;n++){var r=e[n];l.hasOwnProperty(r)?t+=String.fromCharCode(l[r]):(l[r]=s,a[s]=r,t+=String.fromCharCode(s),s++)}return t}var d=c(o),u=c(i),p=new n,m=p.diff_main(d,u,!1);p.diff_cleanupSemantic(m),p.diff_cleanupMerge(m);for(var f=0;f<m.length;f++){for(var g=m[f][1],h=[],v=0;v<g.length;v++)h.push(a[g.charCodeAt(v)]);m[f][1]=h.join("")}return m}function _f(e){var t=wp||yp,n=document.getElementById(t.msgsId);if(n){for(var r={},o=Object.keys(pd),i=0;i<o.length;i++){var a=pd[o[i]].category;a&&(r[a.key]=(r[a.key]||0)+1)}Cd=null;for(var l='<div class="correction-summary-badges">
3',s=["spelling","grammar","style","enhancement"],c=0;c<s.length;c++){var d=s[c];r[d]&&(l+='<span class="correction-badge correction-badge--'+d+'" data-category="'+d+'" role="button" tabindex="0">'+r[d]+" "+(Yd[d]?SKT(Yd[d].sktKey):d)+"</span>")}l+="</div>",n.innerHTML='<div class="ai-empty-state ai-completion-state" role="status" aria-live="polite"><div class="ai-completion-icon"><svg viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg></div><div class="ai-empty-headline" id="correction-count">'+SKT(1===e?"corr.count_one":"corr.count_other",{n:e})+'</div><div class="calm-review-sub">'+SKT("corr.review_hint")+"</div>"+l+'<div class="ai-empty-body">'+SKT("corr.instructions")+'</div><div class="correction-summary-actions"><button class="ai-action-btn ai-action-btn--primary" id="accept-all-btn"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg> '+SKT("corr.accept_all")+'</button><button class="ai-action-btn" id="reject-all-btn">'+SKT("corr.undo")+"</button></div></div>";var u=document.getElementById("accept-all-btn"),p=document.getElementById("reject-all-btn");u?u.addEventListener("click",function(){Cd?function(e){for(var t=Object.keys(pd),n=[],r=0;r<t.length;r++){var o=pd[t[r]];o.category&&o.category.key===e&&n.push(t[r])}for(var i=0;i<n.length;i++)kg(n[i]);If();var a=Object.keys(pd).length;a>0&&_f(a)}(Cd):xg()}):console.warn("[wow-features] #accept-all-btn not found after rendering correction summary"),p?p.addEventListener("click",function(){Mg(),If(),Pp=!1,n&&(n.innerHTML=t.buildChips())}):console.warn("[wow-features] #reject-all-btn not found after rendering correction summary");for(var m=document.querySelectorAll(".correction-badge[data-category]"),f=0;f<m.length;f++)m[f].setAttribute("aria-pressed","false"),m[f].addEventListener("click",function(){Mf(this.getAttribute("data-category"))}),m[f].addEventListener("keydown",function(e){"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),Mf(this.getAttribute("data-category")))});Eg(),function(){Ig||(Ig=!0);document.body.classList.add("corrections-review-mode");var e=wp||yp,t=Ip(e),n=Pg(e);document.body.classList.toggle("tone-review-markeret-only",t);var r="liste";if(n){try{r=localStorage.getItem("skriv:corrections-view-mode")||"liste"}catch(e){}"liste"!==r&&"statistik"!==r&&(r="liste")}var o=document.getElementById("sidebar-dropdown-items");if(o){var i=t?"corr.review_tone":"corr.review_korrektur",a=Dg(i,t?"TONE":"KORREKTUR"),l=o.querySelector(".calm-review-status-row");if(l){var s=l.querySelector(".calm-review-label");s&&(s.setAttribute("data-i18n",i),s.textContent=a)}else(l=document.createElement("div")).className="calm-review-status-row",l.innerHTML='<svg class="calm-review-status-icon" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.582a.5.5 0 0 1 0 .963L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"/></svg><span class="calm-review-label" data-i18n="'+i+'">'+a+'</span><span class="calm-review-count" id="calm-review-count"></span><span class="calm-review-cat-dots" id="calm-review-dots"></span>',o.appendChild(l);var c=o.querySelector(".calm-mode-toggle");if(t&&c&&c.remove(),n){var d=c;d||((d=document.createElement("div")).className="calm-mode-toggle",d.setAttribute("role","tablist"),d.setAttribute("aria-label",Dg("corr.toggle_aria","Vis tilstand")),d.setAttribute("data-i18n-aria-label","corr.toggle_aria"),d.innerHTML='<button role="tab" id="calm-tab-liste" data-i18n="format.list" aria-selected="'+("statistik"!==r?"true":"false")+'" tabindex="'+("statistik"!==r?"0":"-1")+'">'+Dg("format.list","Liste")+'</button><button role="tab" id="calm-tab-statistik" data-i18n="corr.tab_statistik" aria-selected="'+("statistik"===r?"true":"false")+'" tabindex="'+("statistik"===r?"0":"-1")+'">'+Dg("corr.tab_statistik","Statistik")+"</button>",o.appendChild(d),d.addEventListener("click",function(e){var t=e.target.closest('[role="tab"]');t&&jg("calm-tab-statistik"===t.id?"statistik":"liste")}),d.addEventListener("keydown",function(e){var t=d.querySelectorAll('[role="tab"]'),n=Array.prototype.indexOf.call(t,document.activeElement);if(!(n<0)){var r=-1;"ArrowRight"===e.key||"ArrowDown"===e.key?r=(n+1)%t.length:"ArrowLeft"===e.key||"ArrowUp"===e.key?r=(n-1+t.length)%t.length:"Home"===e.key?r=0:"End"===e.key&&(r=t.length-1),r>=0&&(e.preventDefault(),t[r].focus(),jg("calm-tab-statistik"===t[r].id?"statistik":"liste"))}}))}}if(n)Rg();else{var u=document.getElementById(e.msgsId);if(u){var p=u.querySelector(".calm-corrections-list");p&&p.remove()}}var m=document.querySelector(".ai-card--sidebar .ai-card-input-row");if(m&&!m.querySelector(".calm-review-footer-host")){var f=document.createElement("div");
3f.className="calm-review-footer-host",f.innerHTML='<button class="calm-footer-accept-all" id="calm-accept-all"></button><button class="calm-footer-undo" id="calm-undo"></button>',m.appendChild(f),document.getElementById("calm-accept-all").addEventListener("click",function(){!function(){if(0===Object.keys(pd).length){Ng();var e=wp||yp,t=document.getElementById(e.msgsId);return t&&(t.innerHTML=e.buildChips()),void(Pp=!1)}Bg.acceptAll&&clearTimeout(Bg.acceptAll);xg()}()}),document.getElementById("calm-undo").addEventListener("click",function(){!function(e){if(e.classList.contains("calm-confirming")){Bg.undo&&clearTimeout(Bg.undo),e.classList.remove("calm-confirming");var t=Cp(),n=_p(t);Mg();var r=n&&Ap(t);t&&!r&&(t.appliedCount||0)>0&&th('<svg viewBox="0 0 24 24" width="18" height="18" stroke="#9B6050" fill="none" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 8v4l2 2"/></svg><span>'+rh(SKT("ea.toast_undo_expired"))+"</span>"),If(),Pp=!1;var o=wp||yp,i=document.getElementById(o.msgsId);return void(i&&(i.innerHTML=o.buildChips()))}e.classList.add("calm-confirming"),e.textContent=SKT("corr.undo_confirm")||"Tryk igen for at fortryde",Bg.undo=setTimeout(function(){e.classList.remove("calm-confirming"),e.textContent=SKT("corr.undo")||"Fortryd"},3e3)}(this)})}n&&"statistik"===r?(document.body.classList.add("corrections-statistik-mode"),document.body.classList.remove("corrections-list-mode"),Ug(),$d()):n&&"liste"===r?(document.body.classList.add("corrections-list-mode"),document.body.classList.remove("corrections-statistik-mode")):(document.body.classList.remove("corrections-list-mode","corrections-statistik-mode"),Ug());Og()}()}}function Af(){for(var e={},t=Object.keys(pd),n=0;n<t.length;n++){var r=pd[t[n]].category;r&&(e[r.key]=(e[r.key]||0)+1)}for(var o=document.querySelectorAll(".correction-badge[data-category]"),i=o.length-1;i>=0;i--){var a=o[i].getAttribute("data-category"),l=e[a]||0;if(l<=0)o[i].parentNode&&o[i].parentNode.removeChild(o[i]);else{var s=Yd[a]?SKT(Yd[a].sktKey):a;o[i].textContent=l+" "+s;var c=Cd&&a===Cd;o[i].classList.toggle("correction-badge--active",!!c),o[i].setAttribute("aria-pressed",c?"true":"false")}}return e}function qf(e){var t=wp||yp;Zu(),e.innerHTML='<div class="ai-empty-state ai-completion-state" role="status" aria-live="polite"><div class="ai-completion-icon"><svg viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="#4a5768" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg></div><div class="ai-empty-headline">'+SKT("corr.none_title")+'</div><div class="ai-empty-body">'+SKT("corr.none_body")+'</div><button class="ai-empty-btn" id="no-corr-done-btn">'+SKT("corr.none_btn")+"</button></div>";var n=function(){Pp=!1,e.innerHTML=t.buildChips()},r=setTimeout(function(){document.getElementById("no-corr-done-btn")&&n()},3500),o=document.getElementById("no-corr-done-btn");o&&o.addEventListener("click",function(){clearTimeout(r),n()})}function Mf(e){Cd=Cd===e?null:e;for(var t=document.querySelectorAll(".correction-badge[data-category]"),n=0;n<t.length;n++){Cd&&t[n].getAttribute("data-category")===Cd?(t[n].classList.add("correction-badge--active"),t[n].setAttribute("aria-pressed","true")):(t[n].classList.remove("correction-badge--active"),t[n].setAttribute("aria-pressed","false"))}if(Cd&&xd){var r=pd[xd];r&&r.category&&r.category.key!==Cd&&Zg()}if(Ec){for(var o=Ec.container.querySelectorAll("mark.inline-correction[data-cid]"),i=0,a=0;a<o.length;a++){var l=o[a].getAttribute("data-cid"),s=pd[l];if(s){var c=s.category?s.category.key:"";Cd&&c!==Cd?o[a].classList.add("correction-dimmed"):(o[a].classList.remove("correction-dimmed"),i++)}}var d=document.getElementById("correction-count");if(d){var u=Object.keys(pd).length;if(Cd){var p=Yd[Cd]?SKT(Yd[Cd].sktKey):Cd;d.textContent=SKT("corr.filtered",{n:i,cat:p,total:u})}else d.textContent=SKT(1===u?"corr.count_one":"corr.count_other",{n:u})}var m=document.getElementById("accept-all-btn");if(m)if(Cd){var f=Yd[Cd]?SKT(Yd[Cd].sktKey):"";m.innerHTML='<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg> '+SKT("corr.accept_n",{n:i,cat:f.toLowerCase()})}
3else m.innerHTML='<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg> '+SKT("corr.accept_all")}}function If(){Cd=null;for(var e=document.querySelectorAll(".correction-badge[data-category]"),t=0;t<e.length;t++)e[t].classList.remove("correction-badge--active");for(var n=Ec?Ec.container.querySelectorAll("mark.inline-correction[data-cid]"):[],r=0;r<n.length;r++)n[r].classList.remove("correction-dimmed")}function Bf(){var e=Object.keys(pd).length;Ig&&Fg(SKT(1===e?"corr.remaining_one":"corr.remaining_other",{n:e}));var t=document.getElementById("correction-count");if(0===e){gd=!1,Pp=!1;var n=Cp();if(Bd(Ed)){if(!bd){var r=Ec.getLength()-1;r>0&&(_d[Ed]=Ad(Ec.getText(0,r).trim()))}Id()}if(Ig){Ng();var o=wp||yp;return(i=document.getElementById(o.msgsId))&&(i.innerHTML=o.buildChips()),Eg(),void function(e){if(e&&e.initialSignature!==e.expectedSignature){Mp();var t=document.querySelector(".ai-undo-toast");t&&t.parentNode&&t.parentNode.removeChild(t);var n=document.createElement("div");n.className="ai-undo-toast",n.setAttribute("data-correction-review-undo","true"),n.setAttribute("role","status"),n.setAttribute("aria-live","polite");var r=e.appliedCount||1,o=Ac(1===r?"corr.sweep_applied_one":"corr.sweep_applied_many",1===r?"{n} rettelse anvendt":"{n} rettelser anvendt").replace("{n}",r);n.innerHTML="<span>"+rh(o)+'</span><button type="button" class="ai-undo-btn" aria-label="'+rh(SKT("ea.toast_undo_aria"))+'">'+rh(SKT("ea.toast_undo_label"))+"</button>",document.body.appendChild(n),Sp=e,requestAnimationFrame(function(){n.classList.add("ai-undo-toast--visible")}),n.querySelector(".ai-undo-btn").addEventListener("click",function(){var t=Sp===e&&kp[e.panelKey]===e&&_p(e)&&Ap(e);kp[e.panelKey]===e&&(kp[e.panelKey]=null),Mp(e),th(t?'<svg viewBox="0 0 24 24" width="18" height="18" stroke="#4a5768" fill="none" stroke-width="2"><path d="M3 10h4l3-7 4 14 3-7h4"/></svg><span>'+rh(SKT("ea.toast_undone"))+"</span>":'<svg viewBox="0 0 24 24" width="18" height="18" stroke="#9B6050" fill="none" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 8v4l2 2"/></svg><span>'+rh(SKT("ea.toast_undo_expired"))+"</span>")}),xp=setTimeout(function(){kp[e.panelKey]===e&&(kp[e.panelKey]=null),Mp(e)},1e4)}else e&&kp[e.panelKey]===e&&(kp[e.panelKey]=null)}(n)}qp();var i,a=wp||yp;if(i=document.getElementById(a.msgsId)){i.innerHTML='<div class="ai-empty-state ai-completion-state" style="transition:opacity 0.3s ease"><div class="ai-completion-icon"><svg viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="#4a5768" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg></div></div>';var l=i.querySelector(".ai-completion-state");setTimeout(function(){l&&l.isConnected&&(l.style.opacity="0",setTimeout(function(){l&&l.isConnected&&i&&(i.innerHTML=a.buildChips())},300))},1500)}}else if(t){var s=Af();if(Cd){var c=s[Cd]||0;if(0===c)return If(),void _f(e);var d=Yd[Cd]?SKT(Yd[Cd].sktKey):Cd;t.textContent=SKT("corr.filtered",{n:c,cat:d,total:e});var u=document.getElementById("accept-all-btn");u&&(u.innerHTML='<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg> '+SKT("corr.accept_n",{n:c,cat:d.toLowerCase()}))}else{t.textContent=SKT(1===e?"corr.remaining_one":"corr.remaining_other",{n:e});var p=document.getElementById("accept-all-btn");p&&(p.innerHTML='<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg> '+SKT("corr.accept_all"))}}Eg(),Ig&&Og()}function Hf(e){try{if(!(e&&e.length&&window.Quill&&Ec))return null;var t=window.Quill.find(e[0]);if(!t)return null;var n=Ec.getIndex(t),r=0;try{r=t.length()}catch(e){}var o=Ec.getText(),i=Math.max(0,n-80),a=o.slice(i,Math.min(o.length,n+r+80));return(a=a.replace(/\s+/g," ").trim())?a.slice(0,200):null}catch(e){return null}}SKT("done.analyse_h"),SKT("done.analyse_b"),SKT("done.rewrite_h"),SKT("done.rewrite_b"),SKT("done.shorten_h"),SKT("done.shorten_b"),SKT("done.formal_h"),SKT("done.formal_b"),SKT("done.tone_rewrite_h"),SKT("done.tone_rewrite_b"),SKT("done.tone_diplomatic_h"),SKT("done.tone_diplomatic_b"),SKT("done.tone_confident_h"),SKT("done.tone_confident_b"),SKT("done.tone_professional_h"),SKT("done.tone_professional_b"),SKT("done.tone_unify_h"),SKT("done.tone_unify_b");var Kf=!0,Df=null,Pf=null,Nf={},jf=null,Rf=0,Ff=2,Of=8e3,Uf=null,$f=null,zf={},Gf=(new Date).toISOString(),Vf=null,Wf={},Jf=0,Zf=200,Yf=2e3;function Qf(e){var t=[],n=(new Date).toISOString();return function r(o){return e.from("korrektur_suppress_rules").select("id,rule_type,params,status,scope,created_by",{count:"exact"}).in("status",["shadow","active"]).gt("expires_at",n).order("id",{ascending:!0}).range(o,o+Zf-1).then(function(e){if(!e||e.error||!Array.isArray(e.data))return{data:null,error:e&&e.error||{message:"rule fetch failed"}};t=t.concat(e.data);var n="number"==typeof e.count?e.count:null;return(null!=n?t.length>=n:e.data.length<Zf)?{data:t,error:null}:t.length>=Yf?{data:null,error:{message:"rule window exceeds safe client maximum"}}:r(t.length)})}(0)}function Xf(e){return"user"===e?0:"org"===e?1:"domain"===e?2:"global"===e?3:4}function eg(){try{if(!Kf||Pf)return;var e=window._supabase||window.supabase;if(!e||!e.from)return;var t=Rf;Pf=Promise.all([e.from("korrektur_learning_prefs").select("enabled").limit(1),Qf(e)]).then(function(e){if(t===Rf){var n=e[0],r=e[1];if(!(n&&!n.error&&Array.isArray(n.data)))return jf=null,Df=null,void(Pf=null);if(jf=!(n.data.length&&n.data[0]&&!1===n.data[0].enabled)){var o=r&&!r.error&&Array.isArray(r.data);Df=o?r.data.slice().sort(function(e,t){var n=Xf(e&&e.scope||"user")-Xf(t&&t.scope||"user");return n||String(e&&e.id||"").localeCompare(String(t&&t.id||""))}):null,o||(Pf=null)}else Df=[]}else Pf=null}).catch(function(){Df=null,Pf=null})}catch(e){}}function tg(e){return String(null==e?"":e).replace(/^[\s.,;:!?"'«»ââââ()\[\]{}\-ââ\/]+|[\s.,;:!?"'«»ââââ()\[\]{}\-ââ\/]+$/g,"").toLowerCase()}function ng(e){var t=String(null==e?"":e);try{t=t.normalize("NFC")}catch(e){}return t.replace(/[\u00A0\u202F]/g," ").replace(/\s+/g," ").toLocaleLowerCase("da-DK")}function rg(e){var t=String(null==e?"":e);try{t=t.normalize("NFC")}catch(e){}return t.replace(/^[\s.,;:!?"'«»âââââ()\[\]{}\-ââ\/]+|[\s.,;:!?"'«»âââââ()\[\]{}\-ââ\/]+$/g,"")}function og(e,t){try{var n=String(t.original||""),r=String(t.replacement||""),o=e&&e.params||{};switch(e.rule_type){case"exact_pair":return n===String(o.o||"")&&r===String(o.r||"");case"word_swap":return""!==tg(n)&&tg(n)===tg(o.from)&&tg(r)===tg(o.to);case"comma_to_semicolon":return-1!==n.indexOf(",")&&n.split(",").join(";")===r;case"comma_add_off":return r!==n&&r.split(",").join("")===n.split(",").join("")&&(r.match(/,/g)||[]).length>(n.match(/,/g)||[]).length;case"article_add_off":return r!==n&&function(e,t){var n=String(null==e?"":e).split(/\s+/).filter(
3Boolean),r=String(null==t?"":t).split(/\s+/).filter(Boolean);if(r.length<=n.length)return!1;for(var o=0,i=0;i<r.length;i++)if(o<n.length&&r[i]===n[o])o++;else{var a=r[i].toLocaleLowerCase("da-DK").replace(/[.,;:!?"'«»()]+$/g,"");if("den"!==a&&"det"!==a&&"en"!==a&&"et"!==a)return!1}return o===n.length}(n,r);case"insert_off":return r!==n&&function(e,t,n){if(!Array.isArray(n)||!n.length)return!1;for(var r={},o=0;o<n.length;o++){var i=String(null==n[o]?"":n[o]).trim().toLocaleLowerCase("da-DK");i&&(r[i]=!0)}var a=String(null==e?"":e).split(/\s+/).filter(Boolean),l=String(null==t?"":t).split(/\s+/).filter(Boolean);if(l.length<=a.length)return!1;for(var s=0,c=0;c<l.length;c++)if(s<a.length&&l[c]===a[s])s++;else if(!r[l[c].toLocaleLowerCase("da-DK").replace(/[.,;:!?"'«»()]+$/g,"")])return!1;return s===a.length}(n,r,o.words);case"caps_keep":return((c=String(n||"").match(/[A-Za-zÃÃÃ
æøå]/g))?c.length:0)>=3&&n===n.toUpperCase()&&n!==r&&n.toLowerCase()===r.toLowerCase();case"hyphen_compound":return r!==n&&(r.match(/-/g)||[]).length>(n.match(/-/g)||[]).length&&r.split("-").join(" ").split(/\s+/).join(" ")===n.split("-").join(" ").split(/\s+/).join(" ")&&(!o.token||-1!==n.indexOf(o.token));case"protect_token":return function(e,t,n){var r=String(null==e?"":e),o=String(null==t?"":t),i=String(null==n?"":n);if(!i||-1===r.indexOf(i)||r===o)return!1;for(var a=0;a<r.length&&a<o.length&&r.charAt(a)===o.charAt(a);)a++;for(var l=0;l<r.length-a&&l<o.length-a&&r.charAt(r.length-1-l)===o.charAt(o.length-1-l);)l++;for(var s=a,c=r.length-l,d=r.indexOf(i);-1!==d;){if(s<=d+i.length+1&&c>=d-1)return!0;d=r.indexOf(i,d+1)}return!1}(n,r,o.token);case"protect_phrase":var i=ng(o.phrase||o.token||"");return""!==i&&-1!==ng(n).indexOf(i)&&-1===ng(r).indexOf(i);case"case_keep":var a=Array.isArray(o.forms)?o.forms:o.token?[o.token]:[],l=rg(n),s=rg(r);return a.some(function(e){var t=String(null==e?"":e);try{t=t.normalize("NFC")}catch(e){}return t===l})&&l!==s&&l.toLocaleLowerCase("da-DK")===s.toLocaleLowerCase("da-DK")&&ng(n)===ng(r);default:return!1}}catch(e){return!1}var c}var ig=null,ag=!1,lg=!1;function sg(e,t,n){var r=SKT(e);return r&&r!==e?r.replace(/\{a\}|\{b\}/g,function(e){var r="{a}"===e?t:n;return"<b>"+rh(null==r?"":String(r))+"</b>"}):null}function cg(e){try{var t=e&&e.params||{},n=null;switch(e.rule_type){case"exact_pair":n=null==t.r||""===t.r?sg("learn.rule_keeps",t.o):sg("learn.rule_pair",t.o,t.r);break;case"word_swap":n=sg("learn.rule_pair",t.from,t.to);break;case"comma_to_semicolon":n=sg("learn.rule_semicolon");break;case"comma_add_off":n=sg("learn.rule_comma");break;case"caps_keep":n=sg("learn.rule_caps");break;case"hyphen_compound":n=t.token?sg("learn.rule_hyphen_token",t.token):sg("learn.rule_hyphen");break;case"protect_token":n="user"===e.created_by?sg("learn.rule_user_word",t.token):sg("learn.rule_protect",t.token);break;case"protect_phrase":n=sg("learn.rule_protect",t.phrase||t.token);break;case"case_keep":n=sg("learn.rule_case",Array.isArray(t.forms)?t.forms.join(" / "):t.token);break;case"article_add_off":n=sg("learn.rule_articles");break;case"insert_off":n=sg("learn.rule_inserts",Array.isArray(t.words)?t.words.join(", "):"")}return n||rh(String(e&&e.label_da||""))}catch(e){return""}}function dg(){var e=!1!==jf,t='<div class="ss-learn-panel" data-learn-panel="1"><div class="ss-learn-head"><div class="ss-learn-head-text"><p class="ss-learn-title" data-i18n="learn.title">'+rh(SKT("learn.title"))+"</p>"+(e?'<p class="ss-learn-sub" data-i18n="learn.sub">'+rh(SKT("learn.sub"))+"</p>":'<p class="ss-learn-sub ss-learn-sub--off" data-i18n="learn.off_note">'+rh(SKT("learn.off_note"))+"</p>")+'</div><button type="button" class="ss-learn-toggle'+(e?"":" ss-learn-toggle--off")+'" role="switch" aria-checked="'+(e?"true":"false")+'" data-learn-toggle="1" aria-label="'+rh(SKT(e?"learn.turn_off":"learn.turn_on"))+'" title="'+rh(SKT(e?"learn.turn_off":"learn.turn_on"))+'"></button></div>';return e&&(t+='<div class="ss-learn-add"><input type="text" class="ss-learn-add-input" data-learn-add-input="1" maxlength="40" autocomplete="off" spellcheck="false" enterkeyhint="done" placeholder="'+rh(SKT("learn.add_placeholder"))+'" aria-label="'+rh(SKT("learn.add_placeholder"))+'"><button type="button" class="ss-learn-add-btn" data-learn-add="1" aria-label="'+rh(SKT("learn.add_btn"))+'" title="'+rh(SKT("learn.add_btn"))+'"><svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg></button></div>'),null===ig?t+='<div class="ss-learn-empty" data-learn-state="error" data-i18n="learn.error">
3'+rh(SKT("learn.error"))+"</div>":ig.length?t+=function(e){for(var t=ig||[],n=ag?t:t.slice(0,4),r='<div class="ss-learn-rows'+(e?"":" ss-learn-rows--off")+'">',o=0;o<n.length;o++){var i=n[o];r+='<div class="ss-learn-row"><span class="ss-learn-row-text">'+cg(i)+"</span>"+(e?'<button type="button" class="ss-learn-x" data-learn-dismiss="'+rh(String(i.id))+'" aria-label="'+rh(SKT("learn.delete"))+'" title="'+rh(SKT("learn.delete"))+'"><svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M18 6L6 18M6 6l12 12"/></svg></button>':"")+"</div>"}if(r+="</div>",!ag&&t.length>4){var a=SKT("learn.show_all");a&&"learn.show_all"!==a||(a="Vis alle ({n})"),r+='<button type="button" class="ss-learn-more" data-learn-more="1">'+rh(a.replace("{n}",String(t.length)))+"</button>"}return r}(e):t+='<div class="ss-learn-empty" data-learn-state="empty" data-i18n="learn.empty">'+rh(SKT("learn.empty"))+"</div>",t+="</div>"}function ug(e){var t=document.getElementById(e.msgsId);t&&t.querySelector("[data-learn-panel]")&&(t.innerHTML=dg(),pg(e,t))}function pg(e,t){var n=t.querySelector("[data-learn-panel]");n&&(n.addEventListener("click",function(t){if(t.target.closest("[data-learn-more]"))return ag=!0,void ug(e);if(t.target.closest("[data-learn-toggle]"))!function(e,t){if(lg)return;var n=window._supabase||window.supabase;if(!n||!n.auth)return;lg=!0,Rf++;var r=jf;jf=t,ug(e),n.auth.getUser().then(function(e){var r=e&&e.data&&e.data.user&&e.data.user.id;if(!r)throw new Error("no-user");return n.from("korrektur_learning_prefs").upsert({user_id:r,enabled:t,updated_at:(new Date).toISOString()},{onConflict:"user_id"})}).then(function(e){if(e&&e.error)throw e.error;t?(Df=null,Pf=null,eg()):Df=[]}).catch(function(){jf=r,ug(e)}).then(function(){lg=!1})}(e,!1===jf);else if(t.target.closest("[data-learn-add]"))wg(e);else{var n=t.target.closest("[data-learn-dismiss]");n&&function(e,t){if(lg||!t)return;var n=window._supabase||window.supabase;if(!n||!n.rpc)return;lg=!0,n.rpc("korrektur_rule_dismiss",{p_rule_id:t}).then(function(n){if(!n||!n.error){Jf++;var r=function(e){return e?e.filter(function(e){return String(e.id)!==String(t)}):e};ig=r(ig),Df=r(Df),ug(e)}}).catch(function(){}).then(function(){lg=!1})}(e,n.getAttribute("data-learn-dismiss"))}}),n.addEventListener("keydown",function(t){"Enter"===t.key&&t.target&&t.target.closest&&t.target.closest("[data-learn-add-input]")&&(t.preventDefault(),wg(e))}),n.addEventListener("input",function(e){var t=e.target&&e.target.closest&&e.target.closest("[data-learn-add-input]");t&&(t.classList.remove("ss-learn-add-input--invalid"),t.removeAttribute("aria-invalid"))}))}function mg(e){return!(!e||/\s/.test(e)||/[<>]/.test(e)||!/[\p{L}\p{N}]/u.test(e)||/[\u00AD\u00A0\u1680\u2000-\u200A\u200B-\u200F\u202A-\u202E\u202F\u205F\u2060-\u2064\u2066-\u2069\u3000\uFEFF]/.test(e)||e.length<2||e.length>40||2===e.length&&e===e.toLocaleLowerCase("da-DK")&&!/[0-9&]/.test(e))}function fg(e){var t=window._supabase||window.supabase;if(!t||!t.rpc)return Promise.resolve(null);try{return t.rpc("korrektur_word_add",{p_word:e}).then(function(t){var n=t&&!t.error&&t.data?t.data:null;if(!n||"added"!==n.r&&"exists"!==n.r||!n.id)return null;Rf++,Jf++;var r={id:n.id,rule_type:"protect_token",params:{token:e},label_da:null,status:"active",scope:"user",created_by:"user",updated_at:(new Date).toISOString()},o=function(e){return Array.isArray(e)?e.filter(function(e){return String(e.id)!==String(n.id)}):e};return Array.isArray(ig)?(ig=o(ig)).unshift(r):ig=[r],Array.isArray(Df)&&(Df=o(Df)).unshift(r),{out:n,row:r}}).catch(function(){return null})}catch(e){return Promise.resolve(null)}}function gg(e){$f&&(clearTimeout($f),$f=null),Uf=null;try{$g()}catch(e){}}function hg(e){$f&&clearTimeout($f),Uf=e,$f=setTimeout(function(){gg()},Of);try{$g()}catch(e){}}function vg(e){try{if(!1===jf)return;var t=String(e&&e.original||"").trim();try{t=t.normalize("NFC")}catch(e){}if(!mg(t))return;var n=tg(t);if(!n||zf[n])return;Wf[n]=(Wf[n]||0)+1;var r=Wf[n];(function(){if(Vf)return Vf;var e=window._supabase||window.supabase;if(!e||!e.from)return Promise.resolve(null);var t=new Date(Date.now()-7776e6).toISOString();return Vf=e.from("ai_outcomes").select("meta").eq("surface","korrektur").eq("ai_action","correction").eq("outcome","rejected").gte("created_at",t).lt("created_at",Gf).order("created_at",{ascending:!1}).limit(500).then(function(e){if(!e||e.error||!Array.isArray(e.data))return Vf=null,null;for(var t={},n=0;n<e.data.length;n++){var r=e.data[n]&&e.data[n].meta;
3if(r&&r.o&&!r.s&&!(String(r.o).length>=80)){var o=String(r.o).trim();if(!/\s/.test(o)){var i=tg(o);i&&(t[i]=(t[i]||0)+1)}}}return t}).catch(function(){return Vf=null,null})})().then(function(e){var o=(e&&e[n]||0)+r;o<Ff||zf[n]||function(e){for(var t=Array.isArray(Df)?Df:[],n=0;n<t.length;n++){var r=t[n];if(r&&("protect_token"===r.rule_type||"protect_phrase"===r.rule_type)){var o=r.params&&(r.params.token||r.params.phrase);if(o&&tg(String(o))===e)return Promise.resolve(!0)}}var i=window._supabase||window.supabase;if(!i||!i.from)return Promise.resolve(!0);var a=new Date(Date.now()-2592e6).toISOString();return i.from("korrektur_suppress_rules").select("params").eq("rule_type","protect_token").eq("status","killed").gte("updated_at",a).order("updated_at",{ascending:!1}).limit(100).then(function(t){if(!t||t.error||!Array.isArray(t.data))return!0;for(var n=0;n<t.data.length;n++){var r=t.data[n]&&t.data[n].params&&t.data[n].params.token;if(r&&tg(String(r))===e)return!0}return!1}).catch(function(){return!0})}(n).then(function(e){if(!e&&!zf[n]){zf[n]=!0,hg({word:t,norm:n,state:"offer"});try{window.ssOutcome&&window.ssOutcome.record("korrektur","never_chip","shown",{o:t,n:o})}catch(e){}}})})}catch(e){}}function yg(){if(!Uf)return"";var e=rh(Uf.word);if("offer"===Uf.state||"busy"===Uf.state){var t=sg("never.add",Uf.word)||"Ret aldrig »"+e+"«";return'<div class="calm-never-chip" data-never-chip="offer" role="status"><span class="calm-never-chip-note" data-i18n="never.before">'+rh(SKT("never.before"))+'</span><button type="button" class="calm-never-chip-add" data-action="never-add">'+t+"</button></div>"}return'<div class="calm-never-chip calm-never-chip--added" data-never-chip="added" role="status"><svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" aria-hidden="true"><polyline points="20 6 9 17 4 12"/></svg><span class="calm-never-chip-note">'+(sg("never.added",Uf.word)||"Sofia retter aldrig »"+e+"«")+'</span><button type="button" class="calm-never-chip-undo" data-action="never-undo" data-i18n="never.undo">'+rh(SKT("never.undo"))+"</button></div>"}function wg(e){if(!lg){var t=document.getElementById(e.msgsId),n=t&&t.querySelector("[data-learn-add-input]");if(n){var r=String(n.value||"").trim();try{r=r.normalize("NFC")}catch(e){}var o=function(){try{n.classList.add("ss-learn-add-input--invalid"),n.setAttribute("aria-invalid","true")}catch(e){}};mg(r)?(lg=!0,fg(r).then(function(t){t?ug(e):o()}).catch(function(){}).then(function(){lg=!1})):o()}}}function bg(e,t){var n={type:e&&e.type};if(!e)return n;try{var r=e.category,o=r&&"object"==typeof r?r.key||"":r||"";null!=e.original&&(n.o=String(e.original).slice(0,80)),null!=e.replacement&&(n.r=String(e.replacement).slice(0,80)),e.explanation&&(n.e=String(e.explanation).slice(0,240)),o&&(n.c=o),"sentence"===e.scope&&(n.s="sentence"),t&&(n.sx=String(t).slice(0,200))}catch(e){}return n}function kg(e){var t=pd[e];if(t){var n=Ec.container.querySelectorAll('[data-cid="'+e+'"]');if(!n.length)return delete pd[e],Zg(),void Bf();var r=Hf(n),o=window.Quill,i="delete"===t.type?"":t.replacement||"";hd=!0;try{for(var a=[],l=0;l<n.length;l++){var s=o&&o.find(n[l]);if(s)try{a.push({blot:s,index:Ec.getIndex(s),length:s.length()})}catch(e){}}if(!a.length)return void Sg(e,!0);if(a.sort(function(e,t){return e.index-t.index}),!Wd(a))return void Sg(e,!0);var c=a[0].index,d=a[a.length-1].index+a[a.length-1].length-c;if(!Vd(c,d,t.original))return void Sg(e,!0);var u=Ec.getFormat(c,d);delete u["inline-correction"];var p=(new(o.import("delta"))).retain(c).delete(d);i&&(p=p.insert(i,u)),Ec.updateContents(p,"user"),function(){var e=kp[Lp()];e&&(e.expectedSignature=Ep(),e.appliedCount=(e.appliedCount||0)+1)}();for(var m=Ec.container.querySelectorAll('[data-cid="'+e+'"]'),f=0;f<m.length;f++){var g=m[f];if(g&&g.parentNode){for(;g.firstChild;)g.parentNode.insertBefore(g.firstChild,g);g.parentNode.removeChild(g)}}}catch(e){console.warn("acceptCorrection quill error:",e.message)}finally{hd=!1}try{window.ssOutcome&&window.ssOutcome.record("korrektur","correction","accepted",bg(t,r))}catch(e){}delete pd[e],Zg(),Bf()}}function Sg(e,t){var n=pd[e],r=Ec.container.querySelectorAll('[data-cid="'+e+'"]'),o=t?null:Hf(r);if(r.length){hd=!0;try{for(var i=window.Quill,a=0;a<r.length;a++){var l=r[a],s=i&&i.find(l);if(s){var c=Ec.getIndex(s),d=s.length();Ec.formatText(c,d,"inline-correction",!1,"silent")}else if(l&&l.parentNode){for(;l.firstChild;)l.parentNode.insertBefore(l.firstChild,l);l.parentNode.removeChild(l)}}}catch(e){console.warn("rejectCorrection error:",e.message);for(var u=0;u<r.length;u++){var p=r[u];if(p&&p.parentNode){for(;p.firstChild;)p.parentNode.insertBefore(p.firstChild,p);p.parentNode.removeChild(p)}}}finally{hd=!1}}
3try{!t&&window.ssOutcome&&window.ssOutcome.record("korrektur","correction","rejected",bg(n,o))}catch(e){}if(!t)try{vg(n)}catch(e){}delete pd[e],Zg(),Bf()}function xg(){var e=window.Quill,t=e?e.import("delta"):null,n=Object.keys(pd);if(e&&t&&0!==n.length){try{window.ssOutcome&&window.ssOutcome.record("korrektur","correction","accepted",{n:n.length,bulk:!0})}catch(h){}for(var r=[],o=0;o<n.length;o++){var i=n[o],a=pd[i];if(a){var l=Ec.container.querySelectorAll('[data-cid="'+i+'"]');if(l.length){for(var s=[],c=0;c<l.length;c++){var d=e.find(l[c]);if(d)try{s.push({blot:d,index:Ec.getIndex(d),length:d.length()})}catch(e){}}if(s.length&&(s.sort(function(e,t){return e.index-t.index}),Wd(s)))try{var u=s[0].index,p=s[s.length-1].index+s[s.length-1].length-u;if(!Vd(u,p,a.original))continue;r.push({index:u,length:p,replacement:"delete"===a.type?"":a.replacement||"",formats:function(e){return delete e["inline-correction"],e}(Ec.getFormat(u,p)),id:i})}catch(h){console.warn("acceptAll: could not get index for",i)}}}}if(0!==r.length){r.sort(function(e,t){return e.index-t.index}),hd=!0;try{for(var m=new t,f=0,g=0;g<r.length;g++){var h=r[g];h.index<f?console.warn("Overlap skip:",h.id,"idx",h.index,"<",f):(h.index>f&&m.retain(h.index-f),m.delete(h.length),h.replacement&&m.insert(h.replacement,h.formats||{}),f=h.index+h.length)}Ec.updateContents(m,"user");for(var v=Ec.container.querySelectorAll("mark.inline-correction"),y=v.length-1;y>=0;y--){var w=v[y];if(w.parentNode){for(;w.firstChild;)w.parentNode.insertBefore(w.firstChild,w);w.parentNode.removeChild(w)}}}finally{hd=!1}if(pd={},Zg(),gd=!1,qp(),Cd=null,Hd(Ed),Ig){Fg(SKT("corr.remaining_other",{n:0})),Ng();var b=wp||yp,k=document.getElementById(b.msgsId);k&&(k.innerHTML=b.buildChips()),Pp=!1,Eg(),lp()}else Bf()}else{hd=!0;try{for(var S=Ec.container.querySelectorAll("mark.inline-correction"),x=S.length-1;x>=0;x--){var T=S[x];if(T.parentNode){for(;T.firstChild;)T.parentNode.insertBefore(T.firstChild,T);T.parentNode.removeChild(T)}}}finally{hd=!1}if(pd={},Zg(),gd=!1,qp(),Cd=null,Ig){Ng();var L=wp||yp,E=document.getElementById(L.msgsId);E&&(E.innerHTML=L.buildChips()),Pp=!1,Eg(),lp()}else Bf()}}}var Tg=null;function Lg(){return window.innerWidth<=767}function Eg(){var e=document.getElementById("sk-fix-all-pill");if(e){var t=Object.keys(pd).length;if(t>0&&Lg()&&gd){var n=e.querySelector(".sk-fix-all-label");n&&(n.textContent=Ac("corr.fix_all_label","Ret alle")),e.querySelector(".sk-fix-all-count").textContent="("+t+")",e.style.display="flex",requestAnimationFrame(function(){e.classList.add("sk-fix-all-pill--visible")})}else e.classList.remove("sk-fix-all-pill--visible"),Tg&&clearTimeout(Tg),Tg=setTimeout(function(){e&&(e.style.display="none"),Tg=null},300)}}function Cg(){var e=Object.keys(pd).length;if(0!==e){var t=dm();xg(),function(e,t,n){var r=document.getElementById("sk-undo-toast");r&&r.classList.remove("sk-undo-toast--visible");_g&&(clearTimeout(_g),_g=null);var o=document.getElementById("sk-undo-toast");if(!o)return;o.querySelector(".sk-undo-text").textContent=Ac(1===e?"corr.sweep_applied_one":"corr.sweep_applied_many",1===e?"{n} rettelse anvendt":"{n} rettelser anvendt").replace("{n}",e);var i=o.querySelector(".sk-undo-btn");i&&(i.textContent=Ac("corr.undo","Fortryd"));o.style.display="flex",requestAnimationFrame(function(){o.classList.add("sk-undo-toast--visible")});var a=o.querySelector(".sk-undo-btn"),l=function(){if(Ec){if(n&&fm()!==n)return o.classList.remove("sk-undo-toast--visible"),void setTimeout(function(){o.style.display="none"},300);hd=!0;try{var e=Math.max(0,Ec.getLength()-1);e>0&&Ec.deleteText(0,e,"user"),Ec.clipboard&&Ec.clipboard.dangerouslyPasteHTML?Ec.clipboard.dangerouslyPasteHTML(0,t||"<p><br></p>","user"):Ec.insertText(0,wm(t),"user")}finally{hd=!1}o.classList.remove("sk-undo-toast--visible"),setTimeout(function(){o.style.display="none"},300),a.removeEventListener("click",l)}};a.removeEventListener("click",a._sweepHandler),a._sweepHandler=l,a.addEventListener("click",l),_g=setTimeout(function(){o.classList.remove("sk-undo-toast--visible"),setTimeout(function(){o.style.display="none"},300),_g=null},1e4)}(e,t,fm())}}var _g=null;function Ag(e){if(Lg()){var t=pd[e];if(t){var n=document.querySelector(".sk-mobile-corr-card");n&&n.remove();var r=document.createElement("div");r.className="sk-mobile-corr-card",r.setAttribute("data-corr-id",e);var o=rh(t.original||""),i="delete"===t.type?"(slet)":rh(t.replacement||"");r.innerHTML='<div class="sk-mobile-corr-card-body"><span class="sk-mobile-corr-original">'+o+'</span><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><path d="M5 12h14M12 5l7 7-7 7"/></svg><span class="sk-mobile-corr-replacement">'+i+'</span></div><div class="sk-mobile-corr-card-actions"><button class="sk-mobile-corr-accept" type="button" aria-label="Accepter"><svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg></button><button class="sk-mobile-corr-dismiss" type="button" aria-label="Afvis"><svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button></div>',document.body.appendChild(r),requestAnimationFrame(function(){r.classList.add("sk-mobile-corr-card--visible")}),r.querySelector(".sk-mobile-corr-accept").addEventListener("click",function(){kg(e),qg(r)}),r.querySelector(".sk-mobile-corr-dismiss").addEventListener("click",function(){Sg(e),qg(r)})}}}function qg(e){e.classList.remove("sk-mobile-corr-card--visible"),setTimeout(function(){e.parentNode&&e.remove()},200);var t=Object.keys(pd);if(Eg(),t.length>0){var n=Ec.container.querySelector('[data-cid="'+t[0]+'"]');if(n){var r=window.Quill&&window.Quill.find(n);if(r){var o=Ec.getIndex(r);Ec.setSelection(o,0,"silent")}setTimeout(function(){Ag(t[0])},250)}}}function Mg(){Cd=null,Td=!1;var e=document.querySelector(".sk-mobile-corr-card");if(e&&e.remove(),!Ec)return pd={},gd=!1,qp(),void Eg();var t=wp?Tp(wp):null,n=t?'.inline-correction[data-panel="'+t+'"]':".inline-correction";hd=!0;try{for(var r=Ec.container.querySelectorAll(n),o=window.Quill,i=r.length-1;i>=0;i--){var a=o&&o.find(r[i]);if(a)try{var l=Ec.getIndex(a),s=a.length();Ec.formatText(l,s,"inline-correction",!1)}catch(e){console.warn("Failed to clear blot, unwrapping DOM:",e.message)}}for(var c=t?'mark.inline-correction[data-panel="'+t+'"]':"mark.inline-correction",d=Ec.container.querySelectorAll(c),u=d.length-1;u>=0;u--){var p=d[u],m=p.parentNode;if(m){for(;p.firstChild;)m.insertBefore(p.firstChild,p);m.removeChild(p)}}}finally{hd=!1}t&&(bp[t]=null),pd={},gd=!1,Zg(),Eg(),qp(),Ng()}var Ig=!1,Bg={};function Hg(e){var t=e&&e.category?e.category.key:"";return"spelling"===t||"grammar"===t||"style"===t||"enhancement"===t?t:"spelling"}function Kg(e){var t=Yd[e];if(t&&"function"==typeof SKT){var n=SKT(t.sktKey);if(n&&n!==t.sktKey)return n}return"grammar"===e?"Grammatik":"spelling"===e?"Stavning":"style"===e?"Klarhed":"enhancement"===e?"Tone":"Stavning"}function Dg(e,t){if("function"==typeof SKT){var n=SKT(e);if(n&&n!==e)return n}return t}function Pg(e){return!Ip(e)&&("tone-rewrite"!==Ed&&"more-formal"!==Ed&&(!Ed||0!==Ed.indexOf("tone-")))}function Ng(){if(Ig){for(var e in Ig=!1,Ug(),document.body.classList.remove("corrections-review-mode","corrections-list-mode","corrections-statistik-mode","tone-review-markeret-only"),Bg)Bg[e]&&clearTimeout(Bg[e]);Bg={};var t=document.getElementById("sidebar-dropdown-items");if(t){var n=t.querySelector(".calm-review-status-row");n&&n.remove();var r=t.querySelector(".calm-mode-toggle");r&&r.remove()}var o=wp||yp,i=document.getElementById(o.msgsId);if(i){var a=i.querySelector(".calm-corrections-list");a&&a.remove();var l=i.querySelector(".calm-review-empty");l&&l.remove()}var s=document.querySelector(".ai-card--sidebar .ai-card-input-row");if(s){var c=s.querySelector(".calm-review-footer-host");c&&c.remove()}}}function jg(e){if(!Pg(wp||yp))return document.body.classList.remove("corrections-list-mode","corrections-statistik-mode"),void Ug();"liste"!==e&&"statistik"!==e&&(e="liste");var t="liste"===e,n="statistik"===e;document.body.classList.toggle("corrections-list-mode",t),document.body.classList.toggle("corrections-statistik-mode",n);try{localStorage.setItem("skriv:corrections-view-mode",e)}catch(e){}Ug();var r=document.getElementById("calm-tab-liste"),o=document.getElementById("calm-tab-statistik");r&&(r.setAttribute("aria-selected",t?"true":"false"),r.tabIndex=t?0:-1),o&&(o.setAttribute("aria-selected",n?"true":"false"),o.tabIndex=n?0:-1);var i=document.getElementById((wp||yp).msgsId),a=i&&i.querySelector("[data-learn-panel]");a&&(a.remove(),lp()),t&&(Rg(),$g()),n&&$d()}function Rg(){var e=wp||yp;if(Pg(e)){var t=document.getElementById(e.msgsId);if(t&&!t.querySelector(".calm-corrections-list")){var n=document.createElement("div");
3n.className="calm-corrections-list",n.addEventListener("click",Vg),n.addEventListener("keydown",function(e){if(("Enter"===e.key||" "===e.key)&&!e.target.closest("[data-action]")){var t=e.target.closest(".calm-corr-card");t&&e.target===t&&(e.preventDefault(),e.stopPropagation(),t.click())}}),t.appendChild(n),Gg=!1}!function(){if(Gg)return;var e=wp||yp,t=document.getElementById(e.msgsId);if(!t)return;var n=t.querySelector(".calm-corrections-list");if(!n)return;Gg=!0;var r=null,o=window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;function i(){r&&(r.classList.remove("calm-hover-target"),r=null)}function a(e){if(i(),e){var t=document.querySelector('#inputText mark.inline-correction[data-cid="'+e+'"], .ql-editor mark.inline-correction[data-cid="'+e+'"]');t&&(t.style.removeProperty("background"),t.style.removeProperty("background-color"),t.style.removeProperty("box-shadow"),t.classList.add("calm-hover-target"),r=t,t.scrollIntoView({behavior:o?"instant":"smooth",block:"nearest"}))}}n.addEventListener("mouseover",function(e){var t=e.target.closest(".calm-corr-card");t&&a(t.getAttribute("data-cid"))}),n.addEventListener("mouseout",function(e){var t=e.target.closest(".calm-corr-card"),n=e.relatedTarget?e.relatedTarget.closest(".calm-corr-card"):null;t&&t!==n&&i()}),n.addEventListener("focusin",function(e){var t=e.target.closest(".calm-corr-card");t&&a(t.getAttribute("data-cid"))}),n.addEventListener("focusout",function(e){(e.relatedTarget?e.relatedTarget.closest(".calm-corr-card"):null)||i()})}(),lp()}}function Fg(e){var t=document.getElementById("calm-review-live");t||((t=document.createElement("div")).id="calm-review-live",t.setAttribute("aria-live","polite"),t.setAttribute("aria-atomic","true"),t.style.cssText="position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);white-space:nowrap;border:0;padding:0;margin:-1px;",document.body.appendChild(t)),t.textContent=e}function Og(){var e=Object.keys(pd).length,t=function(){for(var e={spelling:0,grammar:0,style:0,enhancement:0},t=Object.keys(pd),n=0;n<t.length;n++){var r=Hg(pd[t[n]]);e[r]=(e[r]||0)+1}return e}(),n=wp||yp,r=Pg(n);if(!r){document.body.classList.remove("corrections-list-mode");var o=document.getElementById(n.msgsId),i=o&&o.querySelector(".calm-corrections-list");i&&i.remove()}var a=r&&document.body.classList.contains("corrections-list-mode");Ug();var l=document.getElementById("calm-review-count");l&&(l.textContent=e);var s=document.getElementById("calm-review-dots");if(s){for(var c="",d=["spelling","grammar","style","enhancement"],u=0;u<d.length;u++)t[d[u]]>0&&(c+='<span class="calm-cat-dot calm-cat-dot--'+d[u]+'">'+t[d[u]]+"</span>");s.innerHTML=c}var p=document.getElementById("calm-accept-all");p&&(0===e?(p.textContent=SKT("corr.none_btn")||"Færdig",p.setAttribute("data-done","true")):(p.textContent=(SKT("corr.accept_all")||"Godkend alle")+" "+e,p.removeAttribute("data-done")),p.classList.remove("calm-confirming"));var m=document.getElementById("calm-undo");m&&(m.textContent=SKT("corr.undo")||"Fortryd",m.classList.remove("calm-confirming")),a&&(Rg(),$g())}function Ug(e){for(var t=document.querySelectorAll("#inputText mark.inline-correction, .ql-editor mark.inline-correction"),n=0;n<t.length;n++){var r=t[n];r.style.removeProperty("background"),r.style.removeProperty("background-color"),r.style.removeProperty("border-color"),r.style.removeProperty("border-bottom-color"),r.style.removeProperty("border-left-color"),r.style.removeProperty("box-shadow"),r.style.removeProperty("cursor")}}function $g(){var e=wp||yp;if(Pg(e)){var t=document.getElementById(e.msgsId);if(t){var n=t.querySelector(".calm-corrections-list");if(n){var r=Object.keys(pd);if(0!==r.length){var o=t.querySelector(".calm-review-empty");o&&o.remove();for(var i=yg(),a=0;a<r.length;a++){var l=r[a],s=pd[l];if(s){var c=Hg(s),d=s.displayOriginal||s.original||"",u=s.displayReplacement||s.replacement||"",p=s.explanation||"";d.length>80&&(d=d.substring(0,80)+"â¦"),u.length>80&&(u=u.substring(0,80)+"â¦"),i+='<div class="calm-corr-card" data-cid="'+rh(l)+'" role="group" tabindex="0" aria-haspopup="dialog" aria-label="'+rh(d)+" â "+rh(u)+'"><div class="calm-corr-card-cat calm-corr-card-cat--'+c+'" title="'+Kg(c)+'"></div><div class="calm-corr-card-body"><span class="calm-corr-card-original">'+rh(d)+"</span>"+("delete"!==s.type&&u?'<span class="calm-corr-card-replacement">'+rh(u)+"</span>":"")+(s.explanationPending?'<span class="calm-corr-card-explanation calm-corr-card-explanation--loading" aria-hidden="true"></span>':p?'<span class="calm-corr-card-explanation">'+rh(p)+"</span>":"")+'</div><div class="calm-corr-card-actions"><button class="calm-corr-card-accept" data-action="accept" data-cid="'+rh(l)+'" aria-label="'+(SKT("corr.accept")||"Godkend")+": "+rh(u||d)+'" title="'+(SKT("corr.accept")||"Godkend")+'"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg></button><button class="calm-corr-card-skip" data-action="skip" data-cid="'+rh(l)+'" aria-label="'+(SKT("corr.skip")||"Spring over")+": "+rh(d)+'" title="'+(SKT("corr.skip")||"Spring over")+'"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button></div></div>'}}n.innerHTML=i,zg(fd?xd:null)}else{n.innerHTML=yg();var m=t.querySelector(".calm-review-empty");
3m||((m=document.createElement("div")).className="calm-review-empty",m.innerHTML='<svg class="calm-review-empty-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg><div class="calm-review-empty-headline">'+(SKT("corr.none_title")||"Alt er gennemgÃ¥et")+'</div><div class="calm-review-empty-body">'+(SKT("corr.none_body")||"Ingen korrekturer tilbage.")+"</div>",t.appendChild(m))}}}}}function zg(e){var t=wp||yp,n=t&&document.getElementById(t.msgsId),r=n&&n.querySelector(".calm-corrections-list");if(r){e?r.classList.add("calm-corr-list--focused"):r.classList.remove("calm-corr-list--focused");for(var o=r.querySelectorAll(".calm-corr-card"),i=0;i<o.length;i++)e&&o[i].getAttribute("data-cid")===e?o[i].classList.add("calm-corr-card--active"):o[i].classList.remove("calm-corr-card--active")}}var Gg=!1;function Vg(e){var t=e.target.closest("[data-action]");if(t){e.stopPropagation();var n=t.getAttribute("data-cid"),r=t.getAttribute("data-action");if("never-add"===r)return void function(){if(Uf&&"offer"===Uf.state){var e=Uf.word,t=Uf.norm;Uf.state="busy",$f&&(clearTimeout($f),$f=null),fg(e).then(function(n){if(Uf&&Uf.word===e)if(n){hg({word:e,norm:t,state:"added",ruleId:n.out.id});try{window.ssOutcome&&window.ssOutcome.record("korrektur","never_chip","accepted",{o:e,rule:n.out.id})}catch(e){}}else gg()})}}();if("never-undo"===r)return void function(){if(Uf&&"added"===Uf.state&&Uf.ruleId){var e=Uf.ruleId,t=Uf.word,n=Uf.norm,r=window._supabase||window.supabase;r&&r.rpc&&(gg(),r.rpc("korrektur_rule_dismiss",{p_rule_id:e}).then(function(r){if(r&&r.error)hg({word:t,norm:n,state:"added",ruleId:e});else{Jf++;var o=function(t){return Array.isArray(t)?t.filter(function(t){return String(t.id)!==String(e)}):t};ig=o(ig),Df=o(Df);try{window.ssOutcome&&window.ssOutcome.record("korrektur","never_chip","undone",{o:t,rule:e})}catch(e){}}}).catch(function(){hg({word:t,norm:n,state:"added",ruleId:e})}))}}();if(!n)return;var o=r,i=-1;(d=t.closest(".calm-corr-card"))&&d.parentNode&&(i=Array.prototype.indexOf.call(d.parentNode.querySelectorAll(".calm-corr-card"),d)),"accept"===r?kg(n):Sg(n);var a=e.currentTarget.querySelectorAll(".calm-corr-card"),l=i>=0?a[i]:null;if(l&&l.classList.contains("calm-corr-card")){var s=l.querySelector('[data-action="'+o+'"]');s&&s.focus()}else{var c=document.getElementById("calm-accept-all");c&&c.focus()}}else{var d;if(d=e.target.closest(".calm-corr-card"))if(n=d.getAttribute("data-cid"))Wg(n,document.querySelector('#inputText mark.inline-correction[data-cid="'+n+'"], .ql-editor mark.inline-correction[data-cid="'+n+'"]')||d)}}function Wg(e,t){if(Lg())Ag(e);else{Zg();var n=pd[e];if(n){xd=e;var r=Ec&&Ec.container;r&&(r.classList.add("correction-focused"),t.classList.add("correction-active")),zg(e);var o=document.createElement("div");o.className="correction-popup",o.id="correction-popup",o.setAttribute("role","dialog"),o.setAttribute("aria-label",SKT("corr.popup_label")),o.addEventListener("touchstart",function(e){e.stopPropagation()}),o.addEventListener("touchend",function(e){e.stopPropagation()});var i=n.displayOriginal||n.original,a=n.displayReplacement||n.replacement;if("sentence"===n.scope){i.length>60&&(i=i.substring(0,60)+"â¦"),a.length>60&&(a=a.substring(0,60)+"â¦")}else if(n.original.length<=2&&"replace"===n.type){var l=function(e){if(!Ec||!e)return null;var t=window.Quill,n=t&&t.find(e);if(!n)return null;var r=Ec.getIndex(n),o=n.length(),i=Ec.getText(Math.max(0,r-15),Math.min(15,r)),a=Ec.getText(r+o,15),l=i.match(/(?:^|\s)(\S+)$/),s=a.match(/^(\S+)/);return{before:l?l[1]:"",after:s?s[1]:""}}(t);l&&(i=l.before+n.original+l.after,a=l.before+n.replacement+l.after)}var s=n.category||Yd.spelling,c="";"replace"===n.type?c='<span class="correction-popup-old">'+rh(i)+'</span>
3<svg class="correction-popup-arrow" viewBox="0 0 24 24" width="14" height="14"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg><span class="correction-popup-new">'+rh(a)+"</span>":"delete"===n.type&&(c='<span class="correction-popup-old">'+rh(n.original)+'</span><svg class="correction-popup-arrow" viewBox="0 0 24 24" width="14" height="14"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg><span class="correction-popup-label">'+SKT("corr.popup_remove")+"</span>");var d,u=n.explanation||"",p=n.explanationDetail||"";o.innerHTML='<div class="correction-popup-category"><span class="correction-popup-badge correction-popup-badge--'+s.key+'"><svg viewBox="0 0 24 24" width="12" height="12">'+({spelling:'<circle cx="12" cy="12" r="10"/><path d="M8 12h8"/>',grammar:'<path d="M4 7V4h16v3"/><path d="M9 20h6"/><path d="M12 4v16"/>',style:'<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>',enhancement:'<circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/>'}[s.key]||"")+"</svg>"+SKT(s.sktKey)+'</span></div><div class="correction-popup-preview">'+c+"</div>"+(u?'<div class="correction-popup-explanation"><div class="correction-popup-explain-row"><span class="correction-popup-explain-text">'+rh(u)+'</span><span class="correction-popup-explain-actions">'+(p?'<button class="correction-popup-expand-btn" id="corr-expand" type="button" aria-label="'+SKT("corr.popup_expand")+'" aria-expanded="false"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg></button>':"")+'<button class="correction-popup-tts-btn" id="corr-tts" type="button" aria-label="'+SKT("corr.popup_read_aloud")+'"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><path d="M15.54 8.46a5 5 0 0 1 0 7.07"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14"/></svg></button></span></div>'+(p?'<div class="correction-popup-detail" id="corr-detail"><p>'+rh(p)+"</p></div>":"")+"</div>":"")+'<div class="correction-popup-actions"><button class="correction-popup-btn correction-popup-btn--accept" id="corr-accept"><svg viewBox="0 0 24 24" width="14" height="14"><polyline points="20 6 9 17 4 12"/></svg> '+SKT("corr.popup_accept")+'<kbd class="correction-popup-kbd" aria-hidden="true">Enter</kbd></button><button class="correction-popup-btn correction-popup-btn--reject" id="corr-reject"><svg viewBox="0 0 24 24" width="14" height="14"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg> '+SKT("corr.popup_skip")+'<kbd class="correction-popup-kbd" aria-hidden="true">Tab</kbd></button></div>'+(((d=Object.keys(pd).length)>1?'<div class="correction-popup-accept-all"><button class="correction-popup-btn correction-popup-btn--accept-all" id="corr-accept-all"><svg viewBox="0 0 24 24" width="14" height="14"><polyline points="20 6 9 17 4 12"/></svg> '+SKT("corr.fix_all",{n:d})+"</button></div>":"")+'<div class="correction-popup-footer"><button class="correction-popup-link" id="corr-ignore-rule"><svg viewBox="0 0 24 24" width="12" height="12"><circle cx="12" cy="12" r="10"/><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/></svg> '+SKT("corr.ignore_type")+"</button></div>"),document.body.appendChild(o);var m=t.getBoundingClientRect(),f=o.offsetWidth,g=o.offsetHeight,h=window.innerWidth,v=window.innerHeight;if(h>480){var y=m.left,w=m.bottom+8;w+g>v-8&&(w=m.top-g-8,o.style.transformOrigin="bottom left"),y+f>h-8&&(y=h-f-8),y<8&&(y=8);var b=v-16;g>b&&(o.style.maxHeight=b+"px",o.style.overflowY="auto",g=o.offsetHeight);var k=Math.max(8,v-g-8);w<8&&(w=8),w>k&&(w=k);var S=document.getElementById("ai-card");if(S&&S.offsetParent){var x=S.getBoundingClientRect();y+f>x.left&&y<x.right&&w<x.bottom&&w+g>x.top&&(y=Math.max(8,x.left-f-8))}o.style.left=y+"px",o.style.top=w+"px"}fd=o;var T=o.querySelector("#corr-accept"),L=o.querySelector("#corr-reject");T.addEventListener("mousedown",I),T.addEventListener("click",I),L.addEventListener("mousedown",B),L.addEventListener("click",B),o.querySelector("#corr-ignore-rule").addEventListener("mousedown",function(e){e.preventDefault(),e.stopPropagation(),function(e){Ld[e]=!0;for(var t=Object.keys(pd),n=0;n<t.length;n++){var r=pd[t[n]];if(r.category&&r.category.key===e){for(var o=Ec.container.querySelectorAll('[data-cid="'+t[n]+'"]'),i=0;i<o.length;i++){var a=o[i],l=window.Quill,s=l&&l.find(a);if(s){hd=!0;try{Ec.formatText(Ec.getIndex(s),s.length(),"inline-correction",!1,"silent")}catch(e){console.warn("ignoreRuleType format error:",e.message)}finally{hd=!1}}}delete pd[t[n]]}}if(Zg(),Cd===e){If();var c=Object.keys(pd).length;if(c>0)return void _f(c)}Bf()}(s.key)});var E=o.querySelector("#corr-accept-all");E&&E.addEventListener("click",function(e){e.preventDefault(),e.stopPropagation(),xg()});var C=o.querySelector("#corr-expand"),_=o.querySelector(".correction-popup-explain-text"),A=!1;C&&(C.addEventListener("mousedown",H),C.addEventListener("click",H),C.addEventListener("touchend",H)),_&&C&&(_.style.cursor="pointer",_.addEventListener("mousedown",H),_.addEventListener("click",H),_.addEventListener("touchend",H));var q=o.querySelector("#corr-tts");if(q){var M=!1;function K(e){if(e.preventDefault(),e.stopPropagation(),!M){M=!0,setTimeout(function(){M=!1},300);var t=n.explanation||"";n.explanationDetail&&(t+=". "+n.explanationDetail),df(q,t)}}q.addEventListener("mousedown",K),q.addEventListener("click",K),q.addEventListener("touchend",K)}setTimeout(function(){var e=o.querySelector("#corr-accept");e&&e.focus()},50)}}function I(t){t.preventDefault(),t.stopPropagation(),T.removeEventListener("click",I),T.removeEventListener("mousedown",I),kg
3(e),Jg()}function B(t){t.preventDefault(),t.stopPropagation(),L.removeEventListener("click",B),L.removeEventListener("mousedown",B),Sg(e),Jg()}function H(e){if(e.preventDefault(),e.stopPropagation(),C&&!A){A=!0,setTimeout(function(){A=!1},300);var t=o.querySelector("#corr-detail"),n="true"===C.getAttribute("aria-expanded");if(C.setAttribute("aria-expanded",n?"false":"true"),C.classList.toggle("open",!n),t&&t.classList.toggle("open",!n),!n&&window.innerWidth>480){var r=function(){if(o.isConnected){var e=o.getBoundingClientRect(),t=window.innerHeight;e.height>t-16&&(o.style.maxHeight=t-16+"px",o.style.overflowY="auto",e=o.getBoundingClientRect());var n=e.bottom-(t-8);n>0&&(o.style.top=Math.max(8,e.top-n)+"px")}},i=Date.now();if(function e(){r(),Date.now()-i<320&&o.isConnected&&requestAnimationFrame(e)}(),t){var a=function(e){e.target===t&&"max-height"===e.propertyName&&(t.removeEventListener("transitionend",a),r())};t.addEventListener("transitionend",a)}setTimeout(r,350)}}}}function Jg(){if(0!==Object.keys(pd).length){for(var e=Ec.container.querySelectorAll("mark.inline-correction[data-cid]"),t=null,n=null,r=0;r<e.length;r++){var o=e[r].getAttribute("data-cid");if(pd[o]){if(Cd){var i=pd[o];if(i.category&&i.category.key!==Cd)continue}t=e[r],n=o;break}}t&&n?(t.scrollIntoView({behavior:"smooth",block:"center"}),setTimeout(function(){Wg(n,t),Td=!1},150)):Td=!1}else Td=!1}function Zg(){if(rd&&fd&&fd.contains(rd)&&uf(),fd){var e=Ec&&Ec.container;if(e){e.classList.remove("correction-focused");for(var t=e.querySelectorAll(".correction-active"),n=0;n<t.length;n++)t[n].classList.remove("correction-active")}zg(null);var r=fd;fd=null,xd=null,r.classList.add("correction-popup--exiting"),r.addEventListener("animationend",function(){r.remove()}),setTimeout(function(){r.parentNode&&r.remove()},200)}}function Yg(e){if(Cc&&Ec){Qd(_c={index:e.index,length:e.length});var t=Ec.getText(e.index,e.length).trim();window.updateSelectionTTSSelectedText&&window.updateSelectionTTSSelectedText(t);var n,r=window.getSelection();if(r&&r.rangeCount>0)n=r.getRangeAt(0).getBoundingClientRect();else{var o=Ec.getBounds(e.index,e.length),i=Ec.container.getBoundingClientRect();n={left:i.left+o.left,right:i.left+o.left+o.width,top:i.top+o.top,bottom:i.top+o.top+o.height,width:o.width,height:o.height}}Cc.style.left="-9999px",Cc.style.top="-9999px",Cc.classList.add("visible");var a=Cc.offsetWidth,l=Cc.offsetHeight,s=n.left+n.width/2,c=Math.max(8,Math.min(s-a/2,window.innerWidth-a-8)),d=n.top-l-8;d<8&&(d=n.bottom+8);var u=window.innerHeight-l-8;d>u&&(d=u),Cc.style.left=c+"px",Cc.style.top=d+"px"}}function Qg(){Cc&&"playing"!==qc&&"loading"!==qc&&"paused"!==qc&&(Cc.classList.remove("visible","is-paused"),Cc.style.top="-9999px",Cc.style.left="-9999px",_c=null)}function Xg(){Cc&&(Cc.classList.remove("visible","is-paused"),Cc.style.top="-9999px",Cc.style.left="-9999px",_c=null)}var eh=null;function th(e){nh();var t=document.createElement("div");t.className="hte-toast",t.id="hte-toast",t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),document.body.appendChild(t),t.innerHTML=e,t.offsetHeight,t.classList.add("visible"),eh=setTimeout(nh,6e3)}function nh(){clearTimeout(eh);var e=document.getElementById("hte-toast");e&&(e.classList.remove("visible"),setTimeout(function(){e.parentNode&&e.remove()},200))}function rh(e){return String(null==e?"":e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function oh(e){if(window.diff_match_patch)e();else{var t=document.createElement("script");t.src="/assets/lib/ss_diff.js",t.onload=e,t.onerror=function(){console.warn("diff_match_patch not found"),e()},document.head.appendChild(t)}}function ih(e,t,n){var r=document.createElement("div");return r.className="ai-msg ai-msg--"+t,r.innerHTML=n,e.appendChild(r),e.scrollTop=e.scrollHeight,r}function ah(e){if(!e)return"";var t=e.split("\n"),n=[],r=null;function o(){r&&(n.push(r),r=null)}function i(e){return e=(e=(e=(e=(e=rh(e)).replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>")).replace(/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g,"<em>$1</em>")).replace(/`(.+?)`/g,"<code>$1</code>")).replace(/\[(\d+)\]/g,'<span class="ai-cite-ref">[$1]</span>')}for(var a=0;a<t.length;a++){var l=t[a].trim();if(/^-{3,}$/.test(l)||/^\*{3,}$/.test(l))o(),n.push({type:"hr"});else{var s=l.match(/^(#{2,3})\s+(.+)/);if(s){o();var c=s[1].length;n.push({type:"heading",level:c,text:i(s[2])})}else{var d=l.match(/^(\d+)[.)\]]\s+(.+)/);if(d)r&&"ol"===r.type||(o(),r={type:"ol",items:[]}),r.items.push(i(d[2]));else{var u=l.match(/^[\-\*\+\u2022]\s+(.+)/);u?(r&&"ul"===r.type||(o(),r={type:"ul",items:[]}),r.items.push(i(u[1]))):">"!==l.charAt(0)?""!==l?(r&&"p"===r.type||(o(),r={type:"p",lines:[]}),r.lines.push(i(l))):o():(r&&"bq"===r.type||(o(),r={type:"bq",lines:[]}),r.lines.push(i(l.replace(/^>\s?/,""))))}}}}o();for(var p="",m=0;m<n.length;m++){var f=n[m];if("hr"===f.type)p+="<hr>";else if("heading"===f.type)p+="<h"+f.level+' class="ai-md-heading">'+f.text+"</h"+f.level+">";else if("ol"===f.type){p+="<ol>";for(var g=0;g<f.items.length;g++)p+="<li>"+f.items[g]+"</li>";p+="</ol>"}else if("ul"===f.type){p+="<ul>";
3for(var h=0;h<f.items.length;h++)p+="<li>"+f.items[h]+"</li>";p+="</ul>"}else"bq"===f.type?p+="<blockquote>"+f.lines.join("<br>")+"</blockquote>":"p"===f.type&&(p+="<p>"+f.lines.join("<br>")+"</p>")}return p||"<p>"+rh(e)+"</p>"}function lh(e){if(!e||0===e.length)return"";var t='<div class="ai-citations"><span class="ai-citations-label">Kilder:</span>';return e.forEach(function(e,n){var r=e.subject||e.from_name||"Kilde "+(n+1);t+='<span class="ai-cite-item">['+(n+1)+"] "+rh(r)+"</span>"}),t+="</div>"}!function e(t,n){n=n||0,document.getElementById("ai-panel")?setTimeout(function(){t()},0):n>120||setTimeout(function(){e(t,n+1)},500)}(tu),function e(t,n){n=n||0,window.quill1?setTimeout(function(){t(window.quill1)},0):n>120?console.warn("[wow] waitForQuill timed out; quill1 not initialized after 60s"):setTimeout(function(){e(t,n+1)},500)}(function(e){Ec=e,sp(),cp();var t=document.getElementById("grammar-bot-container");if(t){t.querySelectorAll("span").forEach(function(e){"Korrektur"!==e.textContent.trim()||e.getAttribute("data-i18n")||e.setAttribute("data-i18n","tab.korrektur")});var n=t.querySelector("#ai-card-input");n&&!n.getAttribute("data-i18n-placeholder")&&n.setAttribute("data-i18n-placeholder","ai.placeholder.default"),n&&!n.getAttribute("data-i18n-aria-label")&&n.setAttribute("data-i18n-aria-label","ai.placeholder.default")}Cc=function(){var e=document.createElement("div");function t(){if("function"==typeof SKT){var t={analyse:"toolbar.check_selected",tts:"toolbar.tts_selected",overflow:"toolbar.more"};e.querySelectorAll(".hte-btn[data-action]").forEach(function(e){var n=t[e.dataset.action];n&&(e.title=SKT(n))});var n=e.querySelector(".hte-btn--close");n&&(n.title=Ac("wm.close","Luk"),n.setAttribute("aria-label",Ac("toolbar.tts_close","Luk oplæsning"))),e.querySelectorAll(".hte-overflow-item [data-i18n]").forEach(function(e){var t=e.getAttribute("data-i18n");t&&(e.textContent=SKT(t))}),e.querySelectorAll(".hte-btn-label[data-i18n]").forEach(function(e){var t=e.getAttribute("data-i18n");t&&(e.textContent=SKT(t))})}}function n(t){var n=t.target.closest&&t.target.closest('[data-action="tts"]');n&&e.contains(n)&&(Kc=n,Ic=!0,clearTimeout(Bc),Bc=setTimeout(function(){Ic=!1,Kc=null},1200))}function r(t){var n=t.target.closest&&t.target.closest('[data-action="tts"]');if(n&&e.contains(n)||!Ic||!Kc||!function(e,t){if(!t||"number"!=typeof e.clientX||"number"!=typeof e.clientY)return!1;var n=t.getBoundingClientRect();return e.clientX>=n.left-12&&e.clientX<=n.right+12&&e.clientY>=n.top-12&&e.clientY<=n.bottom+12}(t,Kc)||(n=Kc),n&&e.contains(n)){t.stopImmediatePropagation(),t.preventDefault();var r=Date.now();r-Hc<350||(Hc=r,Kc=null,mu(n))}}e.className="hte-toolbar",e.id="hte-toolbar",e.innerHTML=['<button class="hte-btn hte-btn--util" data-action="tts" title="Læs markeret tekst op">','<svg viewBox="0 0 24 24"><path d="M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"/><path d="M16 9a5 5 0 0 1 0 6"/><path d="M19.364 18.364a9 9 0 0 0 0-12.728"/></svg>',"</button>",'<button class="hte-btn hte-btn--ai-star" data-action="analyse" title="Tjek markeret tekst">','<span class="calm-analyse-ico" aria-hidden="true"><svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/><path d="m8 11 2 2 4-4"/></svg></span>','<span class="hte-btn-label" data-i18n="toolbar.check_selected">Tjek markeret</span>',"</button>",'<div class="hte-divider"></div>','<button class="hte-btn hte-btn--action hte-btn--more" data-action="overflow" title="Mere">','<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="1.5"/><circle cx="6" cy="12" r="1.5"/><circle cx="18" cy="12" r="1.5"/></svg>',"</button>",'<div class="hte-overflow-menu" id="hte-overflow-menu">','<div class="calm-hte-group" data-group="korrektur">','<span class="calm-hte-label" aria-hidden="true">Korrektur</span>','<button class="hte-overflow-item" data-action="rewrite">','<span class="calm-hte-ico" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="M17 3a2.83 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5z"/><path d="m15 5 4 4"/></svg></span>','<span data-i18n="hte.rewrite">Grundlæggende</span>',"</button>",'<button class="hte-overflow-item" data-action="shorten">','<span class="calm-hte-ico" aria-hidden="true"><svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/><path d="m8 11 2 2 4-4"/></svg></span>','<span data-i18n="hte.shorten">Fuld</span>',"</button>","</div>",'<div class="calm-hte-sep" aria-hidden="true"></div>','<div class="calm-hte-group" data-group="tonefald">','<span class="calm-hte-label" aria-hidden="true">Tonefald</span>','<button class="hte-overflow-item" data-action="more-formal">','<span class="calm-hte-ico" aria-hidden="true"><svg viewBox="0 0 24 24">
3<path d="M12 22c-2 0-4-6-4-8l2-2 2 1 2-1 2 2c0 2-2 8-4 8z"/><path d="M8 6l4-4 4 4-2 2h-4z"/></svg></span>','<span data-i18n="chip.more_formal">Mere formel</span>',"</button>",'<button class="hte-overflow-item" data-action="friendlier">','<span class="calm-hte-ico" aria-hidden="true"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="M8 14s1.5 2 4 2 4-2 4-2"/><line x1="9" y1="9" x2="9.01" y2="9"/><line x1="15" y1="9" x2="15.01" y2="9"/></svg></span>','<span data-i18n="chip.friendlier">Venligere</span>',"</button>",'<button class="hte-overflow-item" data-action="simplify">','<span class="calm-hte-ico" aria-hidden="true"><svg viewBox="0 0 24 24"><circle cx="6" cy="6" r="3"/><path d="M8.12 8.12 12 12"/><circle cx="6" cy="18" r="3"/><path d="m8.12 15.88 11.88-11.88"/><path d="m14.47 14.48 5.53 5.52"/></svg></span>','<span data-i18n="chip.simplify">Forenkl</span>',"</button>","</div>",'<div class="calm-hte-sep" aria-hidden="true"></div>','<div class="calm-hte-group" data-group="forklar">','<button class="hte-overflow-item" data-action="explain">','<span class="calm-hte-ico" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5"/><path d="M9 18h6"/><path d="M10 22h4"/></svg></span>','<span data-i18n="chip.explain">Forklar</span>',"</button>","</div>","</div>",'<button type="button" class="hte-btn hte-btn--util hte-btn--close" data-action="tts-close" title="Luk" aria-label="Luk oplæsning">','<svg viewBox="0 0 24 24" aria-hidden="true">','<line x1="6" y1="6" x2="18" y2="18"></line>','<line x1="18" y1="6" x2="6" y2="18"></line>',"</svg>","</button>"].join(""),document.body.appendChild(e),t(),window.addEventListener("ss:lang-changed",t),e.addEventListener("pointerdown",n,!0),e.addEventListener("mousedown",n,!0),e.addEventListener("touchstart",n,!0),e.addEventListener("mousedown",function(t){var n=t.target.closest&&t.target.closest('[data-action="tts-close"]');n&&e.contains(n)&&t.stopPropagation(),t.preventDefault()}),document.addEventListener("pointerup",r,!0),document.addEventListener("mouseup",r,!0),document.addEventListener("touchend",r,!0),document.addEventListener("click",function(t){var n=t.target.closest('[data-action="tts"]'),r=t.target.closest&&t.target.closest('[data-action="tts-close"]');if(r&&e.contains(r))return t.stopImmediatePropagation(),t.preventDefault(),gu(),void Xg();if(n&&e.contains(n)){if(t.stopImmediatePropagation(),t.preventDefault(),Date.now()-Hc<350)return;return Hc=Date.now(),void mu(n)}Ic&&(t.stopImmediatePropagation(),t.preventDefault())},!0),document.addEventListener("selectionchange",function(e){(Ic||"idle"!==qc)&&e.stopImmediatePropagation()},!0);var o=e.querySelector("#hte-overflow-menu");function i(){o&&o.classList.remove("visible")}return document.addEventListener("click",function(t){o&&o.classList.contains("visible")&&!e.contains(t.target)&&i()}),e.addEventListener("click",function(e){var t=e.target.closest(".hte-btn")||e.target.closest(".hte-overflow-item");if(t){e.preventDefault(),e.stopPropagation();var n=t.dataset.action;if("overflow"!==n){if(i(),"tts-close"===n)return gu(),void Xg();if("tts"!==n){if("ask-ai"===n){if(_c&&Ec&&(r=Ec.getText(_c.index,_c.length).trim())){Vc=r,yd={index:_c.index,length:_c.length};try{wd=Ec.getSemanticHTML(_c.index,_c.length)}catch(e){}}return Qg(),cu(),void setTimeout(function(){var e=document.getElementById("ai-card-input");e&&e.focus()},200)}if("explain"===n){if(_c&&Ec){if(!(r=Ec.getText(_c.index,_c.length).trim()))return;Vc=r,yd={index:_c.index,length:_c.length};try{wd=Ec.getSemanticHTML(_c.index,_c.length)}catch(e){}bd=!0}return Qg(),cu(),void setTimeout(function(){lm(SKT("chip.explain_query")||"Forklar den markerede tekst")},100)}var r;if(_c&&Ec&&(r=Ec.getText(_c.index,_c.length).trim())){Vc=r,yd={index:_c.index,length:_c.length};try{wd=Ec.getSemanticHTML(_c.index,_c.length)}catch(e){}}Qg(),cu(),setTimeout(function(){Vp(n)},100)}else mu(t)}else o&&o.classList.toggle("visible")}}),e.addEventListener("contextmenu",function(e){var t=e.target.closest('[data-action="tts"]');t&&(e.preventDefault(),Eu(t))}),e}(),function(){var e=window.Quill;if(e){var t=e.import("blots/inline");class n extends t{static create(e){var t=super.create();return e&&t.setAttribute("data-cid",e),t}static formats(e){return e.getAttribute("data-cid")||!1}}n.blotName="inline-correction",n.tagName="mark",n.className="inline-correction",e.register(n,!0);class r extends t{static create(){return super.create()}static formats(){return!0}}r.blotName="mobile-corrected",r.tagName="mark",r.className="sk-mobile-corrected-mark",e.register(r,!0)}}(),oh(function(){}),Ec.container.addEventListener("click",function(e){var t=e.target.closest(".inline-correction");if(t){var n=t.getAttribute("data-cid");if(n&&pd[n])return e.preventDefault(),e.stopPropagation(),void Wg(n,t);e.preventDefault(),e.stopPropagation();var r=t.parentNode;if(r){for(;t.firstChild;)r.insertBefore(t.firstChild,t);r.removeChild(t),r.normalize()}}else Zg()});var r=!1;document.addEventListener("visibilitychange",function(){r=!0,setTimeout(function(){r=!1},500)}),Ec.on("text-change",function(e,t,n){sp(),cp();var o=document.getElementById("ai-card-messages");if(o&&o.querySelector(".ai-welcome")&&!o.querySelector(".ai-msg")&&(o.innerHTML=vp()),!hd&&!r&&!qd){var i=!1;if(e&&e.ops)for(var a=0;a<e.ops.length;a++){var l=e.ops[a];if(l.insert||l.delete){i=!0;break}}i&&(_d={},Wm&&(Jm&&clearTimeout(Jm),Jm=setTimeout(Zm,250)))}if(gd&&!hd){var s=wp||yp;if("user"===n){if(r)return;var c=!1;if(e&&e.ops)for(var d=0;d<e.ops.length;d++){var u=e.ops[d];if(u.insert||u.delete){c=!0;break}}if(!c)return;for(var p=Object.keys(pd),m=0,f=0;f<p.length;f++){var g=p[f];Ec.container.querySelector('mark.inline-correction[data-cid="'+g+'"]')||(delete pd[g],m++)}if(0===Object.keys(pd).length){Mg();var h=document.getElementById(s.msgsId);h&&(h.innerHTML=s.buildChips())}else m>0&&(Ig?Og():document.getElementById("correction-count")?Af():_f(Object.keys(pd).length))}else"api"===n&&setTimeout(function(){if(gd){var e=wp?Tp(wp):null,t=e?'mark.inline-correction[data-panel="'+e+'"]':"mark.inline-correction";if(0===Ec.container.querySelectorAll(t).length){pd={},gd=!1,Zg();var n=document.getElementById(s.msgsId);n&&(n.innerHTML=s.buildChips())}}},100)}if(gd||hd||"user"!==n||vd||!Ec.container.querySelector("mark.inline-correction:not(.panel-hidden)")||(vd=!0,setTimeout(function(){if(vd=!1,!gd&&!hd&&Ec){var e=Ec.container.querySelectorAll("mark.inline-correction:not(.panel-hidden)");if(e.length){hd=!0;try{for(var t=window.Quill,n=e.length-1;n>=0;n--){var r=e[n],o=t&&t.find(r);if(o)try{Ec.formatText(Ec.getIndex(o),o.length(),"inline-correction",!1,"silent");continue}catch(e){}var i=r.parentNode;if(i){for(;r.firstChild;)i.insertBefore(r.firstChild,r);i.removeChild(r)}}}finally{hd=!1}}}},0)),window.innerWidth<=767&&!hd){var v=document.getElementById("skrivebord-mobile-sheet");if(v&&v.classList.contains("open")&&!v.classList.contains("closing")){var y=v.querySelector(".mobile-tab-btn.active");Ku(y?y.getAttribute("data-tab"):"corrections")}}});var o=null,i=null;function a(e){!fd||fd.contains(e.target)||e.target.closest(".inline-correction")||e.target.closest(".correction-popup")||Zg()}Ec.container.addEventListener("pointerup",function(){clearTimeout(i),clearTimeout(o),o=setTimeout(function(){var e=Ec.getSelection();e&&e.length>0&&Ec.getText(e.index,e.length).trim().length>0&&Yg(e)},0)}),document.addEventListener("selectionchange",function(){clearTimeout(o),o=setTimeout(function(){if(Ec.hasFocus()){var e=Ec.getSelection();e&&e.length>0&&Ec.getText(e.index,e.length).trim().length>0?Yg(e):e&&0===e.length&&Qg()}},150)}),Ec.on("selection-change",function(e,t,n){e&&e.length>0?Qd(e):"user"===n&&Ec.hasFocus&&Ec.hasFocus()&&(kd=null),e&&0!==e.length||(clearTimeout(o),Qg())}),document.addEventListener("mousedown",function(e){a(e),!Cc||Cc.contains(e.target)||zc&&zc.contains(e.target)||(clearTimeout(o),i=setTimeout(Qg,300))}),document.addEventListener("touchstart",function(e){a(e)},{passive:!0});var l=Ec.container.closest(".ql-editor-wrap")||Ec.container.parentElement;l&&l.addEventListener("scroll",function(){if(Cc&&Cc.classList.contains("visible")&&_c){var e=Ec.getSelection();e&&e.length>0?Yg(e):Qg()}},{passive:!0});var s=!1;document.addEventListener("keydown",function(e){if("Enter"===e.key||"Tab"===e.key||"Escape"===e.key){if(s&&("Enter"===e.key||"Tab"===e.key))return e.preventDefault(),void e.stopImmediatePropagation();if(!e.repeat||"Enter"!==e.key&&"Tab"!==e.key){if(Td&&("Enter"===e.key||"Tab"===e.key))return e.preventDefault(),void e.stopImmediatePropagation();if(gd&&!fd&&("Enter"===e.key||"Tab"===e.key)&&!e.shiftKey)return e.preventDefault(),void e.stopImmediatePropagation();
3if(fd&&xd){if("Enter"===e.key&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey)return e.preventDefault(),e.stopImmediatePropagation(),s=!0,Td=!0,kg(xd),void Jg();if("Tab"===e.key&&!e.shiftKey)return e.preventDefault(),e.stopImmediatePropagation(),s=!0,Td=!0,Sg(xd),void Jg()}if("Escape"===e.key){var t=document.querySelector(".ai-editor-preview");if(t){if(e.preventDefault(),"function"==typeof t._ssClosePreview)t._ssClosePreview();else{var n=t.previousElementSibling;t.remove(),n&&n.style&&"none"===n.style.display&&(n.style.display="")}return}fd?Zg():Jc?function(){hf(),uf(),Mg(),Zu();var e=document.getElementById("ai-panel");if(e&&e.querySelector(".ai-card--sidebar")){var t=document.getElementById("ai-card-messages");return t&&(t.innerHTML=vp()),Jc=!1,void(Gc=[])}zc&&(zc.classList.add("closing"),setTimeout(function(){zc&&(zc.remove(),zc=null)},200)),Jc=!1,Gc=[]}():Qg(),nh()}}else(gd||Td)&&(e.preventDefault(),e.stopImmediatePropagation())}},!0),document.addEventListener("keyup",function(e){"Enter"!==e.key&&"Tab"!==e.key||!s||(s=!1)},!0),tu()}),function(){var e=window._wf;if(e){var t=!1,n=null,r={ukendt:!0,"ukendt tone":!0,"ukendt tonalitet":!0,unknown:!0,"unknown tone":!0,unbekannt:!0,"unbekannter ton":!0,inconnu:!0,"ton inconnu":!0,desconocido:!0,"tono desconocido":!0,"okänd":!0,"okänd ton":!0,okand:!0,"okand ton":!0,undefined:!0,null:!0,"n/a":!0},o={msgsId:"tone-card-messages",sendId:"tone-card-send",buildChips:U},i=null,a=null,l={professional:{action:"tone-professional",sktKey:"tone.make_professional",svg:'<svg viewBox="0 0 24 24"><rect x="2" y="7" width="20" height="14" rx="2" ry="2"/><path d="M16 7V4a2 2 0 00-2-2h-4a2 2 0 00-2 2v3"/></svg>'},confident:{action:"tone-confident",sktKey:"tone.make_confident",svg:'<svg viewBox="0 0 24 24"><circle cx="12" cy="8" r="7"/><path d="M8.21 13.89L7 23l5-3 5 3-1.21-9.12"/></svg>'},diplomatic:{action:"tone-diplomatic",sktKey:"tone.make_diplomatic",svg:'<svg viewBox="0 0 24 24"><path d="M16 16l3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1z"/><path d="M2 16l3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1z"/><path d="M7 21h10"/><path d="M12 3v18"/><path d="M3 7h2c2 0 5-1 7-2 2 1 5 2 7 2h2"/></svg>'},unify:{action:"tone-unify",sktKey:"tone.unify_label",svg:'<svg viewBox="0 0 24 24"><path d="M16 3h5v5"/><path d="M8 3H3v5"/><path d="M12 22V8"/><path d="M21 3l-9 9"/><path d="M3 3l9 9"/></svg>'}},s=!1,c=["uformel","personlig","neutral","hoeflig","professionel"],d="sk_tone_level",u=function(){var e=null;try{e=parseInt(localStorage.getItem(d),10)}catch(e){}return e>=0&&e<=4?e:2}();"undefined"!=typeof window&&(window._toneGarmentSvg=function(){return O(u)});var p=[],m=!1,f=!1,g=["friendly","message","mail","professional","marketing","warm","creative","direct","calm","objective","personal","favourite"],h={friendly:{labelKey:"tone.byot.icon_friendly",label:"Venlig",svg:'<circle cx="12" cy="12" r="9"/><path d="M8.5 10h.01"/><path d="M15.5 10h.01"/><path d="M8 14c1 1.2 2.3 1.8 4 1.8s3-.6 4-1.8"/>'},message:{labelKey:"tone.byot.icon_message",label:"Besked",svg:'<path d="M21 15a4 4 0 0 1-4 4H8l-5 3V7a4 4 0 0 1 4-4h10a4 4 0 0 1 4 4Z"/>'},mail:{labelKey:"tone.byot.icon_mail",label:"Mail",svg:'<rect x="3" y="5" width="18" height="14" rx="2"/><path d="m3 7 9 6 9-6"/>'},professional:{labelKey:"tone.byot.icon_professional",label:"Professionel",svg:'<rect x="3" y="7" width="18" height="13" rx="2"/><path d="M9 7V5a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2"/><path d="M3 12h18"/><path d="M12 12v2"/>'},marketing:{labelKey:"tone.byot.icon_marketing",label:"Marketing",svg:'<path d="m3 11 14-5v12L3 13Z"/><path d="M17 9.5h2.5a1.5 1.5 0 0 1 0 3H17"/><path d="M6 14l1.5 5"/>'},warm:{labelKey:"tone.byot.icon_warm",label:"Varm",svg:'<path d="M20.8 4.6a5.4 5.4 0 0 0-7.6 0L12 5.8l-1.2-1.2a5.4 5.4 0 0 0-7.6 7.6L12 21l8.8-8.8a5.4 5.4 0 0 0 0-7.6Z"/>'},creative:{labelKey:"tone.byot.icon_creative",label:"Kreativ",svg:'<path d="M12 3l1.5 5 5 1.5-5 1.5-1.5 5-1.5-5-5-1.5 5-1.5Z"/><path d="M19 15l.8 2.2L22 18l-2.2.8L19 21l-.8-2.2L16 18l2.2-.8Z"/>'},direct:{labelKey:"tone.byot.icon_direct",label:"Direkte",svg:'<path d="M13 2 4 14h7l-1 8 9-12h-7Z"/>'}
3,calm:{labelKey:"tone.byot.icon_calm",label:"Rolig",svg:'<path d="M5 21c8 0 14-6 14-14V3h-4C7 3 3 7 3 13c0 3 2 5 5 5"/><path d="M3 21c3-5 7-8 12-9"/>'},objective:{labelKey:"tone.byot.icon_objective",label:"Objektiv",svg:'<path d="M12 3v18"/><path d="M5 21h14"/><path d="M7 6h10"/><path d="M6 6l-3 7h6Z"/><path d="M18 6l-3 7h6Z"/>'},personal:{labelKey:"tone.byot.icon_personal",label:"Personlig",svg:'<path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/>'},favourite:{labelKey:"tone.byot.icon_favourite",label:"Favorit",svg:'<path d="m12 3 2.8 5.7 6.2.9-4.5 4.4 1.1 6.2L12 17.2l-5.6 3 1.1-6.2L3 9.6l6.2-.9Z"/>'}},v=null,y=null,w=null,b=se(),k="",S=null,x=/^rgba\(\s*234\s*,\s*179\s*,\s*8\s*,\s*0\.08\s*\)$/i,T="auto",L=null,E=0,C=!1,_=!1;document.addEventListener("skrivebord:tts-stop-all",function(){Fe()});var A=null,q=null;window.addEventListener("ss:lang-changed",ze),window.addEventListener("ss:lang-ui-ready",ze),e.registerTone({PANEL:o,init:function(){var e=document.getElementById("option-tone");e&&(e.addEventListener("click",function(){if(window.innerWidth>767){var e=document.getElementById("tone-panel");e&&(e.style.display="flex")}setTimeout(function(){$e()},0)}),document.querySelectorAll(".hk-dropdown-option").forEach(function(e){"option-tone"!==e.id&&e.addEventListener("click",function(){B(),Te();var e=document.getElementById("tone-panel");e&&(e.style.display="none"),t=!1})}))},ensureReady:$e,renderAnalysis:Ue,renderSmartResult:function(t,n,r){var o=document.getElementById(n.msgsId);if(o){i=t,T=t&&t.target?t.target:"auto",_=!1,Fe();var l=t&&t.improved_text?String(t.improved_text):"",s=function(){if(window.quill1&&"function"==typeof window.quill1.getText)return window.quill1.getText().trim();var e=document.querySelector("#inputText .ql-editor")||document.querySelector(".ql-editor");return e?(e.textContent||"").trim():""}();e.hasForeignScript&&e.hasForeignScript(l,s)?function(t,n){Te();var r=e.escapeHtml(n||H("bedre.error_foreign_script","Resultatet indeholdt uventede tegn - prov igen"));t.innerHTML='<div class="ai-error-text tone-smart-error" role="status">'+r+"</div>"+U(),N(t),j();var o=t.querySelector(".tone-slider-apply")||t.querySelector('[data-action="tone-smart"]')||t.querySelector(".ai-chip");o&&o.focus()}(o,H("bedre.error_foreign_script","Resultatet indeholdt uventede tegn - prov igen")):(function(e,t,n){var r=window._wf,o=!t&&r&&r.getSelectionRange?r.getSelectionRange():null,i=!(t||!r||!r.wasSelectionExplicit)&&r.wasSelectionExplicit();if(window.quill1&&"function"==typeof window.quill1.getText)if(k=window.quill1.getText().trim(),i&&o&&null!=o.index&&o.length>0)S={index:o.index,length:o.length},a=function(e,t){if(!e||!Array.isArray(e.ops)||!t||t.length<=0)return e;var n=t.index,r=n+t.length,o=0,i=!1,a=e.ops.map(function(e){var t,a="string"==typeof e.insert?e.insert.length:1,l=o<r&&o+a>n;if(o+=a,!l||!e.attributes||("string"!=typeof(t=e.attributes.background)||!x.test(t)))return e;var s={};return Object.keys(e).forEach(function(t){s[t]="attributes"===t?Object.assign({},e.attributes):e[t]}),delete s.attributes.background,0===Object.keys(s.attributes).length&&delete s.attributes,i=!0,s});return i?{ops:a}:e}(window.quill1.getContents(),S),window.quill1.deleteText(o.index,o.length),window.quill1.insertText(o.index,e);else{a=window.quill1.getContents(),S=null;var l=n&&"markdown"===n.format?function(e){if(!e||"undefined"==typeof marked||"function"!=typeof marked.parse)return null;if(!window.quill1||!window.quill1.clipboard||"function"!=typeof window.quill1.clipboard.convert)return null;try{var t=marked.parse(String(e),{breaks:!0});window.DOMPurify&&"function"==typeof window.DOMPurify.sanitize&&(t=window.DOMPurify.sanitize(t,{ALLOWED_TAGS:["p","br","strong","b","em","i","u","ol","ul","li","h1","h2","h3","blockquote","a"],ALLOWED_ATTR:["href"]}));var n=window.quill1.clipboard.convert({html:t});return n&&n.ops&&n.ops.length?n:null}catch(e){return null}}(e):null;l?window.quill1.setContents(l):window.quill1.setText(e)}else{var s=document.querySelector(".ql-editor");s&&(a=s.innerHTML,k=(s.textContent||"").trim(),S=null,s.textContent=e)}}(l,r&&r.wholeEditor,{format:t&&t.format}),function(t,n){var r=ke(n),o=e.escapeHtml(H("tone.result.tts_play","Læs resumé op")).replace(/"/g,""");xe(),t.innerHTML='<div class="tone-completion-state tone-smart-state"><div class="tone-result-wrap bedre-result-wrap">'+e.skResultCard.build({escapeHtml:e.escapeHtml,iconSvg:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="20 6 9 17 4 12"/></svg>',titleAttrs:' id="tone-card-title" data-i18n="tone.result.title"',titleText:SKT("tone.result.title"),extraHeadRow:Se(n),undoAttrs:' id="tone-undo" data-i18n="tone.result.undo"',undoText:SKT("tone.result.undo"),acceptAttrs:' id="tone-done" data-i18n="tone.result.keep"',acceptText:SKT("tone.result.keep"),showCompare:!0,compareAttrs:' id="tone-compare-btn" data-i18n="tone.result.compare"',compareText:SKT("tone.result.compare"),hasSummary:!0,summaryText:r,summaryPlayAttrs:' id="tone-summary-play"',summaryPlayAriaPressed:!0,summarySvgAriaHidden:!0,ttsPlayLabel:o,summaryLabelHtml:'<span class="ws-summary-label" data-i18n="tone.result.listen">'+SKT("tone.result.listen")+"</span>",summaryLiveRegionHtml:'<span class="sr-only tone-result-live" aria-live="polite"></span>',dividerAttrs:' data-i18n="tone.result.adjust"',dividerText:SKT("tone.result.adjust"),rerunAttrs:' id="tone-rerun"',rerunTitleAttrs:' data-i18n="tone.result.rerun.title"',rerunTitleText:SKT("tone.result.rerun.title"),rerunHintAttrs:' data-i18n="tone.result.rerun.hint"',rerunHintText:SKT("tone.result.rerun.hint"),changeAttrs:' id="tone-c
3hange-focus"',changeTitleAttrs:' data-i18n="tone.result.change.title"',changeTitleText:SKT("tone.result.change.title"),changeHintAttrs:' data-i18n="tone.result.change.hint"',changeHintText:SKT("tone.result.change.hint")})+"</div></div>",function(t){e.skResultCard.wire(t,{undo:"tone-undo",accept:"tone-done",compareBtn:"tone-compare-btn",rerun:"tone-rerun",changeFocus:"tone-change-focus",summaryPlay:"tone-summary-play"},{onUndo:Ce,onKeep:Ee,onCompare:Me,onRerun:_e,onChangeFocus:Ae,onToggleTts:je})}(t)}(o,t))}},restoreLastAnalysis:function(){var t=document.getElementById("tone-card-messages");if(t){B(),e.aiHistory([]),e.clearChatStorage(),e.chipInFlight(!1);var r=document.getElementById("tone-new-chat");r&&r.classList.remove("visible");var i=document.getElementById("tone-card-input");i&&(i.value=""),n&&n.detected?Ue(n,o):(n=null,Te(),t.innerHTML=U())}},isOpen:function(e){return void 0!==e&&(t=e),t}}),e.registerActions({"tone-professional":{type:"inline",category:"enhancement"},"tone-confident":{type:"inline",category:"enhancement"},"tone-diplomatic":{type:"inline",category:"enhancement"},"tone-rewrite":{type:"inline",category:"enhancement"},"tone-unify":{type:"inline",category:"enhancement"},"tone-smart":{type:"smart",category:"enhancement"}})}else console.error("[tone-tab] bridge (window._wf) not found");function M(e,t){var n,o=e&&"string"==typeof e.label?e.label.trim():"";return(n=(n=String(o||"").trim().toLowerCase()).replace(/[.!?â¦]+$/g,"").trim())&&!r[n]?o:SKT(function(e){switch(String(e||"").toLowerCase()){case"diplomatic":return"tone.fallback_diplomatic";case"confident":return"tone.fallback_confident";case"unify":return"tone.fallback_unify";case"none":return"tone.appropriate";default:return"tone.can_improve"}}(t))}function I(e,t){for(var n=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,null,!1),r=[],o="";n.nextNode();)r.push({node:n.currentNode,start:o.length}),o+=n.currentNode.textContent;var i=o.toLowerCase().indexOf(t.toLowerCase());if(-1!==i)for(var a=i+t.length,l=0;l<r.length;l++){var s=r[l],c=s.node.textContent.length;if(!(s.start+c<=i)){if(s.start>=a)break;var d=Math.max(0,i-s.start),u=Math.min(c,a-s.start);try{var p=document.createRange();p.setStart(s.node,d),p.setEnd(s.node,u);var m=document.createElement("span");m.className="tone-hl",p.surroundContents(m)}catch(e){}}}}function B(){for(var e=document.querySelectorAll("#inputText .tone-hl"),t=0;t<e.length;t++){for(var n=e[t],r=n.parentNode;n.firstChild;)r.insertBefore(n.firstChild,n);r.removeChild(n),r.normalize()}}function H(e,t){if("function"!=typeof SKT)return t;var n=SKT(e);return n&&n!==e?n:t}function K(){var t=e.escapeHtml(H("tone.reset","Nulstil tone")).replace(/"/g,""");return'<button type="button" class="tone-reset-x" data-i18n-title="tone.reset" data-i18n-aria-label="tone.reset" aria-label="'+t+'" title="'+t+'"><svg viewBox="0 0 16 16" aria-hidden="true" focusable="false"><path d="M4 4 L12 12 M12 4 L4 12" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" fill="none"/></svg></button>'}function D(){return 0===function(){if(window.quill1&&"function"==typeof window.quill1.getText)return window.quill1.getText().trim();var e=document.querySelector(".ql-editor");return e?(e.textContent||"").trim():""}().length}function P(){var e=D();return' data-tone-requires-text="true" aria-disabled="'+(e?"true":"false")+'"'+(e?" disabled":"")}function N(e){var t=e||document,n=D();t.querySelectorAll('[data-tone-requires-text="true"]').forEach(function(e){e.disabled=n,e.setAttribute("aria-disabled",n?"true":"false")})}function j(){if(!s){if(window.quill1&&"function"==typeof window.quill1.on)return window.quill1.on("text-change",function(){N()}),void(s=!0);var e=document.querySelector(".ql-editor");e&&(e.addEventListener("input",function(){N()}),s=!0)}}function R(e){return H("wm.tone_"+e,["Uformel","Personlig","Neutral","Høflig","Professionel"][e]||"Neutral")}function F(e){return H("wm.tone_"+e+"d",["Afslappet og venlig","Varm og personlig","Klar og direkte","Respektfuld og venlig","Formel og autoritativ"][e]||"Klar og direkte")}function O(e){var t=Math.max(0,Math.min(4,parseInt(e,10)||0)),n="M6.8 3.6 L3.6 6.8 L5.6 9.4 L7.2 8.2 L7.2 20.4 L16.8 20.4 L16.8 8.2 L18.4 9.4 L20.4 6.8 L17.2 3.6 L14.6 3.6 C14 5.4 10 5.4 9.4 3.6 Z",r="M8.6 3.6 L4.4 6 L4.4 19.6 L7.3 19.6 L7.3 20.6 L16.7 20.6 L16.7 19.6 L19.6 19.6 L19.6 6 L15.4 3.6 L12 6.2 Z",o='<line x1="7.3" y1="7.6" x2="7.3" y2="19.6" stroke="#4A7A68" stroke-width="1" opacity="0.75"/>
3<line x1="16.7" y1="7.6" x2="16.7" y2="19.6" stroke="#4A7A68" stroke-width="1" opacity="0.75"/>',i='<svg width="26" height="26" viewBox="0 0 24 24" data-garment="'+t+'" aria-hidden="true">',a="</svg>";return 0===t?i+'<path d="'+n+'" fill="#FDFCF9"/>'+a:1===t?i+'<path d="'+n+'" fill="#FDFCF9"/><path d="M9.8 4 L12 7.2 L14.2 4" stroke="#4A7A68" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/><circle cx="12" cy="9.2" r="0.9" fill="#4A7A68"/>'+a:2===t?i+'<path d="'+r+'" fill="#FDFCF9"/>'+o+'<path d="M9.4 3.9 L12 6.9 L14.6 3.9" stroke="#4A7A68" stroke-width="1.4" fill="none" stroke-linecap="round" stroke-linejoin="round"/><line x1="12" y1="6.9" x2="12" y2="20.6" stroke="#4A7A68" stroke-width="1.1"/><circle cx="12" cy="10" r="0.8" fill="#4A7A68"/><circle cx="12" cy="13.6" r="0.8" fill="#4A7A68"/><circle cx="12" cy="17.2" r="0.8" fill="#4A7A68"/>'+a:3===t?i+'<path d="'+r+'" fill="#FDFCF9"/>'+o+'<path d="M9.4 3.9 L12 6.9 L14.6 3.9" stroke="#4A7A68" stroke-width="1.4" fill="none" stroke-linecap="round" stroke-linejoin="round"/><path d="M11.1 6.9 L12.9 6.9 L12.55 8.4 L11.45 8.4 Z" fill="#4A7A68"/><path d="M11.45 8.4 L11.05 10.2 L11.35 15.6 L12 17.4 L12.65 15.6 L12.95 10.2 L12.55 8.4 Z" fill="#4A7A68"/>'+a:i+'<path d="M8.6 3.6 L4.4 6 L4.4 19.6 L7.3 19.6 L7.3 20.6 L16.7 20.6 L16.7 19.6 L19.6 19.6 L19.6 6 L15.4 3.6 Z M9.4 3.8 L14.6 3.8 L12 16 Z" fill="#FDFCF9" fill-rule="evenodd"/>'+o+'<path d="M10 8.6 L12 15.6 L14 8.6 L13 7.6 L12 8.8 L11 7.6 Z" fill="#FDFCF9" opacity="0.42"/><circle cx="12" cy="13.9" r="0.45" fill="#FDFCF9" opacity="0.75"/><path d="M9.4 3.8 L12 9.4 L12 13.8 L10.1 7 Z" fill="#FDFCF9" opacity="0.85"/><path d="M14.6 3.8 L12 9.4 L12 13.8 L13.9 7 Z" fill="#FDFCF9" opacity="0.85"/><path d="M11.05 5.2 L12 6.3 L12.95 5.2 L12 4.4 Z" fill="#FDFCF9"/><path d="M11.35 6.3 L12.65 6.3 L12.4 7.4 L11.6 7.4 Z" fill="#FDFCF9"/><path d="M11.6 7.4 L11.3 8.8 L11.55 12.6 L12 13.9 L12.45 12.6 L12.7 8.8 L12.4 7.4 Z" fill="#FDFCF9"/><circle cx="8.9" cy="17.5" r="0.6" fill="#4A7A68"/>'+a}function U(){ie();for(var t=P(),n=u,r=e.escapeHtml(R(n)),o=e.escapeHtml(H("wm.tone_range_aria","Tonefald")).replace(/"/g,"""),i=e.escapeHtml(H("tone.apply","Anvend tone")),a="",l=0;l<c.length;l++)a+="<span></span>";return['<div class="ai-welcome tone-slider-welcome">','<div class="tone-slider-card" data-level="'+n+'">','<button type="button" class="tone-slider-apply tone-level-run" data-action="tone-apply"'+t+' data-i18n-aria-label="tone.apply" aria-label="'+i+'">','<span class="tone-level-icon" aria-hidden="true">'+O(n)+"</span>",'<span class="tone-level-text">','<span class="tone-current" id="tone-current-label" aria-hidden="true">'+r+"</span>",'<span class="tone-level-desc" data-i18n="wm.tone_'+n+'d" aria-hidden="true">'+e.escapeHtml(F(n))+"</span>","</span>",'<span class="tone-level-chevron" aria-hidden="true"></span>',"</button>",'<div class="tone-slider-track-wrap">','<input type="range" class="tone-slider-input" id="tone-slider" min="0" max="4" step="1" value="'+n+'" aria-label="'+o+'" aria-valuetext="'+r+'">','<div class="tone-slider-ticks" aria-hidden="true">'+a+"</div>","</div>",'<div class="tone-slider-ends" aria-hidden="true"><span data-i18n="wm.tone_0">'+e.escapeHtml(R(0))+'</span><span data-i18n="wm.tone_4">'+e.escapeHtml(R(4))+"</span></div>","</div>",ee(),'<span class="tone-slider-i18n" hidden aria-hidden="true"><span data-i18n="wm.tone_0"></span><span data-i18n="wm.tone_1"></span><span data-i18n="wm.tone_2"></span><span data-i18n="wm.tone_3"></span><span data-i18n="wm.tone_4"></span></span>',"</div>"].join("")}function $(e){return e=String(e||"").trim(),h[e]?e:""}function z(e){return String(e||"").trim().slice(0,2400)}function G(e){var t=(e=$(e))?h[e]:null;return t?'<svg class="tone-byot-icon-svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false">'+t.svg+"</svg>":""}function V(e){var t=h[$(e)];return t?H(t.labelKey,t.label):""}function W(){return'<svg class="tone-byot-icon-svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><circle cx="12" cy="12" r="9"/><path d="M5.8 5.8l12.4 12.4"/></svg>'}function J(t){return(t=$(t))?G(t)+"<span>"+e.escapeHtml(V(t))+"</span>":""}function Z(e){if(!e)return null;for(var t=0;t<p.length;t++)if(p[t]&&p[t].id===e)return p[t];return null}function Y(){return'<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false">
3<path d="M5 12h14"/><path d="M13 6l6 6-6 6"/></svg>'}function Q(){return'<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/></svg>'}function X(){return'<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M3 6h18"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/></svg>'}function ee(){for(var t=e.escapeHtml(H("tone.byot.build","Byg din egen tone")),n=e.escapeHtml(H("tone.byot.use","Skriv i denne tone")).replace(/"/g,"""),r=e.escapeHtml(H("tone.byot.edit","Rediger tone")).replace(/"/g,"""),o=e.escapeHtml(H("tone.byot.delete","Slet tone")).replace(/"/g,"""),i=P(),a="",l=0;l<p.length;l++){var s=p[l];if(s&&s.id){var c=e.escapeHtml(String(s.name||"")),d=c.replace(/"/g,"""),u=e.escapeHtml(String(s.id)).replace(/"/g,"""),m=$(s.icon_key),f=e.escapeHtml(m).replace(/"/g,""");a+='<div class="tone-byot-chip" data-byot-id="'+u+'"><button type="button" class="tone-byot-chip-open" data-byot="apply" aria-label="'+n+'" title="'+d+'"'+i+">"+(m?'<span class="tone-byot-chip-icon" data-byot-icon-key="'+f+'" aria-hidden="true">'+G(m)+"</span>":"")+'<span class="tone-byot-chip-name">'+c+'</span><span class="tone-byot-chip-arrow" aria-hidden="true">'+Y()+'</span></button><span class="tone-byot-chip-actions"><button type="button" class="tone-byot-edit" data-byot="edit" aria-label="'+r+'" title="'+r+'">'+Q()+'</button><button type="button" class="tone-byot-delete" data-byot="delete" aria-label="'+o+'" title="'+o+'">'+X()+"</button></span></div>"}}return['<div class="tone-byot">','<div class="tone-byot-divider" aria-hidden="true"></div>','<div class="tone-byot-saved"'+(""!==a?"":" hidden")+">"+a+"</div>",'<button type="button" class="tone-byot-build" data-byot="build">','<span class="tone-byot-build-icon" aria-hidden="true"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M12 5v14"/><path d="M5 12h14"/></svg></span>','<span class="tone-byot-build-label" data-i18n="tone.byot.build">'+t+"</span>","</button>","</div>"].join("")}function te(){var e=document.getElementById(o.msgsId);if(e){var t=e.querySelector(".tone-byot");if(t){var n=document.createElement("div");n.innerHTML=ee();var r=n.firstChild;r&&t.parentNode.replaceChild(r,t),N(e)}}}function ne(){var e=document.getElementById(o.msgsId),t=e?e.querySelector(".tone-byot-build"):null;if(t)try{t.focus()}catch(e){}}function re(){var e="da-DK";try{window.getCurrentUILang&&(e=window.getCurrentUILang()||"da-DK")}catch(e){}return e}function oe(e,t,n){!function(e){try{var t=window._supabase;if(!t||!t.auth||"function"!=typeof t.auth.getSession)return void e(null);t.auth.getSession().then(function(t){var n=t&&t.data&&t.data.session;e(n&&n.access_token?n.access_token:null)}).catch(function(){e(null)})}catch(t){e(null)}}(function(r){r?fetch("/robots/skrivebord/grammar-api.php?action="+e,{method:"POST",headers:{Authorization:"Bearer "+r,"Content-Type":"application/json"},body:JSON.stringify(t||{})}).then(function(e){return e.json().catch(function(){return{error:"parse"}})}).then(function(e){n(e||{error:"empty"})}).catch(function(){n({error:"network"})}):n({error:"auth"})})}function ie(){m||(m=!0,oe("tone-custom-list",{},function(e){p=e&&e.success&&Array.isArray(e.tones)?e.tones.filter(function(e){return e&&e.id}).map(function(e){return{id:String(e.id),name:String(e.name||""),example_text:String(e.example_text||""),icon_key:$(e.icon_key),tone_prompt:z(e.tone_prompt)}}):[],te()}))}function ae(){var e=document.getElementById("tone-byot-modal");if(e){fe(),e._keydown&&document.removeEventListener("keydown",e._keydown,!0);var t=e._returnFocus;e.parentNode&&e.parentNode.removeChild(e);var n=!1;if(t&&"function"==typeof t.focus&&!1!==t.isConnected)try{t.focus(),n=document.activeElement===t}catch(e){}n||ne()}}function ce(e,t){var n=e.querySelector("#tone-byot-error");n&&(n.textContent=t||"",n.hidden=!t)}function de(e){ae();var t=document.activeElement,n=document.createElement("div");n.id="tone-byot-modal",n.className="tone-byot-modal",n.setAttribute("role","dialog"),n.setAttribute("aria-modal","true"),n.setAttribute("aria-labelledby","tone-byot-modal-title"),n._returnFocus=t;var r="tone-byot-dialog"+(e.dialogClass?" "+e.dialogClass:"");n.innerHTML='<div class="tone-byot-backdrop" data-byot-close="1"></div><div class="'+r+'" role="document"><h3 class="tone-byot-modal-title" id="tone-byot-modal-title">'+(e.titleHtml||"")+"</h3>"+(e.subtitleHtml?'<p class="tone-byot-modal-sub">'+e.subtitleHtml+"</p>":"")+'<div class="tone-byot-modal-body">'+(e.bodyHtml||"")+'</div><div class="tone-byot-modal-actions"><button type="button" class="tone-byot-btn tone-byot-btn-cancel" data-byot-close="1">'+(e.cancelLabel||"")+'</button><button type="button" class="tone-byot-btn tone-byot-btn-primary"'+(e.primaryDanger?' data-danger="1"':"")+">"+(e.primaryLabel||"")+"</button></div></div>",document.body.appendChild(n);var o=n.querySelector(".tone-byot-btn-primary"),i=n.querySelector(".tone-byot-btn-cancel");function a(e){if("Escape"===e.key)return e.preventDefault(),void ae();if("Tab"===e.key){var t=n.querySelectorAll('button:not([disabled]), [href], input
3:not([disabled]), textarea:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])');if(t.length){var r=t[0],o=t[t.length-1];e.shiftKey&&document.activeElement===r?(e.preventDefault(),o.focus()):e.shiftKey||document.activeElement!==o||(e.preventDefault(),r.focus())}}}n.addEventListener("click",function(e){e.target.closest("[data-byot-close]")&&(e.preventDefault(),ae())}),o.addEventListener("click",function(t){t.preventDefault(),o.disabled||"true"===o.getAttribute("aria-disabled")||"function"==typeof e.onPrimary&&e.onPrimary(n,o)}),document.addEventListener("keydown",a,!0),n._keydown=a,"function"==typeof e.onReady&&e.onReady(n,o);var l=n.querySelector("[data-byot-autofocus]")||(e.primaryDanger?i:o);if(l)try{l.focus()}catch(e){}return n}function ue(){ye(null)}function pe(e){ye(Z(e))}function me(){try{var e=localStorage.getItem("ss_chat_lang");if(e){var t=JSON.parse(e);if(t&&t.code)return String(t.code).split("-")[0]}}catch(e){}return"da"}function fe(){if(v){try{v.destroy()}catch(e){}v=null}if(y){try{y.destroy()}catch(e){}y=null}}function ge(e,t,n){var r=me();function o(e,t,n){return e?le({button:e,service:"chat",lang:r,idleAriaLabel:e.getAttribute("aria-label")||H("stt.dictate","Diktér"),onTranscript:function(e){b.remove(),function(e,t,n){if(e&&t){var r="number"==typeof e.selectionStart?e.selectionStart:e.value.length,o="number"==typeof e.selectionEnd?e.selectionEnd:e.value.length,i=e.value,a=i.slice(0,r)+t+i.slice(o);n&&a.length>n&&(a=a.slice(0,n)),e.value=a;var l=Math.min(r+t.length,e.value.length);try{e.selectionStart=e.selectionEnd=l}catch(e){}e.dispatchEvent(new Event("input",{bubbles:!0}))}}(t,e+" ",n)},onPartial:function(e){b.renderInField(t,e)},onStateChange:function(e){"idle"!==e&&"error"!==e||b.remove()}}):null}var i=e.querySelector("#tone-byot-name-mic"),a=e.querySelector("#tone-byot-example-mic");v=o(i,t,80),y=o(a,n,1e4),i&&v&&i.addEventListener("click",function(){y&&y.isActive()&&y.stop(),v.toggle()}),a&&y&&a.addEventListener("click",function(){v&&v.isActive()&&v.stop(),y.toggle()})}function he(t,n,r){var o=t.querySelector("#tone-byot-example-upload"),i=t.querySelector("#tone-byot-file");o&&i&&(o.addEventListener("click",function(){f||i.click()}),i.addEventListener("change",function(){var a=i.files&&i.files[0];i.value="",a&&(ce(t,""),o.disabled=!0,o.setAttribute("aria-busy","true"),function(e){if(!e)return Promise.resolve("");var t=(e.name||"").toLowerCase(),n=e.type||"";if("text/plain"===n||/\.txt$/.test(t))return e.text?e.text().catch(function(){return ve(e)}):ve(e);
3if(/\.docx$/.test(t)||"application/vnd.openxmlformats-officedocument.wordprocessingml.document"===n)return function(e){if(!window.mammoth||"function"!=typeof window.mammoth.convertToHtml||!e.arrayBuffer)return Promise.resolve("");return e.arrayBuffer().then(function(e){return window.mammoth.convertToHtml({arrayBuffer:e})}).then(function(e){var t=document.createElement("div");return t.innerHTML=e&&e.value||"",(t.textContent||"").replace(/\n{3,}/g,"\n\n").trim()}).catch(function(){return""})}(e);if("application/pdf"===n||/\.pdf$/.test(t))return function(e){var t=window.pdfjsLib;return t&&"function"==typeof t.getDocument&&e.arrayBuffer?e.arrayBuffer().then(function(e){return t.getDocument({data:new Uint8Array(e)}).promise}).then(function(e){for(var t=[],n=Math.min(e.numPages||0,50),r=Promise.resolve(),o=1;o<=n;o++)(function(n){r=r.then(function(){return e.getPage(n).then(function(e){return e.getTextContent()}).then(function(e){t.push((e&&e.items||[]).map(function(e){return e.str||""}).join(" "))}).catch(function(){})})})(o);return r.then(function(){return t.join("\n\n").replace(/[ \t]{2,}/g," ").trim()})}).catch(function(){return""}):Promise.resolve("")}(e);if(0===n.indexOf("image/")||/\.(png|jpe?g|gif|webp|bmp|heic|heif)$/.test(t))return function(e){return function(e){return new Promise(function(t){try{var n=new FileReader;n.onload=function(){t(String(n.result||""))},n.onerror=function(){t("")},n.readAsDataURL(e)}catch(e){t("")}})}(e).then(function(e){if(!e)return"";var t=window.HGF_ajax_object||{},n=t.ajax_url||"/robots/skrivebord/grammar-api.php?action=hgf_korrektur_OCR",r=new FormData;return r.append("action","hgf_korrektur_OCR"),r.append("imageData",e),t.nonce&&r.append("nonce",t.nonce),fetch(n,{method:"POST",credentials:"same-origin",body:r}).then(function(e){return e.json().catch(function(){return null})}).then(function(e){return e&&e.success&&"string"==typeof e.data?e.data:""}).catch(function(){return""})})}(e);if(0===n.indexOf("audio/")||/\.(mp3|m4a|wav|ogg|webm|aac|flac)$/.test(t))return function(e){var t=me();return fetch("/api/stt-token.php?service=voice&lang="+encodeURIComponent(t)+"&sp="+encodeURIComponent(location.pathname)).then(function(e){return e.ok?e.json():null}).then(function(n){var r=(n&&n.url||"").match(/[?&]session=([^&]+)/),o=r?r[1]:"";if(!o)return"";var i=new FormData;return i.append("audio",e),i.append("session",o),i.append("language",t),fetch("/robots/skrivebord/grammar-api.php?action=audio-transcribe",{method:"POST",body:i}).then(function(e){return e.ok?e.json():null}).then(function(e){return e&&"string"==typeof e.text?e.text:""})}).catch(function(){return""})}(e);return Promise.resolve("")}(a).then(function(i){o.disabled=!1,o.removeAttribute("aria-busy");var l=(i||"").trim();if(l){var s=n.value,c=s.trim()?s.replace(/\s+$/,"")+"\n\n"+l:l;n.value=c.slice(0,1e4),n.dispatchEvent(new Event("input",{bubbles:!0})),"function"==typeof r&&r(),function(t,n){var r=t.querySelector("#tone-byot-upload-confirm");if(!r)return;r.innerHTML='<svg class="tone-byot-upload-confirm-icon" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><circle cx="12" cy="12" r="9"/><path d="M8.5 12.5l2.5 2.5 4.5-5"/></svg><span class="tone-byot-upload-confirm-text">'+e.escapeHtml(H("tone.byot.uploaded","Fil uploadet!"))+'</span><span class="tone-byot-upload-confirm-file">'+e.escapeHtml(function(e){var t=String(e||"").replace(/^.*[\\/]/,"").replace(/[\r\n\t]+/g," ").trim();t.length>60&&(t=t.slice(0,57)+"â¦");return t||"fil"}(n))+"</span>",r.hidden=!1,r.classList.add("is-visible"),clearTimeout(w),w=setTimeout(function(){r.classList.remove("is-visible"),r.hidden=!0,r.innerHTML=""},2200)}(t,a.name)}else ce(t,H("tone.byot.upload_no_text","Vi fandt ingen tekst i filen â prøv en anden fil eller indsæt teksten."))}).catch(function(){o.disabled=!1,o.removeAttribute("aria-busy"),ce(t,H("tone.byot.upload_error","Kunne ikke læse filen â prøv igen."))}))}))}function ve(e){return new Promise(function(t){try{var n=new FileReader;n.onload=function(){t(String(n.result||""))},n.onerror=function(){t("")},n.readAsText(e)}catch(e){t("")}})}
3function ye(t){var n=!(!t||!t.id),r=e.escapeHtml(n?H("tone.byot.edit_title","Rediger tone"):H("tone.byot.create_title","Byg din egen tone")),o=e.escapeHtml(n?H("tone.byot.edit_sub","Tilpas beskrivelsen, sÃ¥ den rammer din tone."):H("tone.byot.create_sub","Giv din tone et navn, og indsæt et eksempel.")),i=e.escapeHtml(H("tone.byot.name_label","Tonenavn")),a=e.escapeHtml(H("tone.byot.icon_label","Ikon")).replace(/"/g,"""),l=e.escapeHtml(H("tone.byot.icon_choose","Vælg ikon")),s=e.escapeHtml(H("tone.byot.icon_optional","valgfrit")),c=e.escapeHtml(H("tone.byot.prompt_label","Stilbeskrivelse")),d=H("tone.byot.prompt_empty","Udfyld stilbeskrivelsen."),u=e.escapeHtml(H("tone.byot.example_label","Eksempeltekst")),m=e.escapeHtml(H("tone.byot.tip","Tip: 3-5 sætninger fungerer bedst.")),h=e.escapeHtml(n?H("tone.byot.save","Gem ændringer"):H("tone.byot.create_cta","Opret tone")),v=(n?"":'<svg fill="currentColor" class="tone-byot-btn-icon" viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false"><path d="M11.7 2.7c.2-.5.9-.5 1.1 0l1.6 4.4c.1.2.2.3.4.4l4.4 1.6c.5.2.5.9 0 1.1l-4.4 1.6c-.2.1-.3.2-.4.4l-1.6 4.4c-.2.5-.9.5-1.1 0l-1.6-4.4c-.1-.2-.2-.3-.4-.4l-4.4-1.6c-.5-.2-.5-.9 0-1.1l4.4-1.6c.2-.1.3-.2.4-.4Z"/><path d="M18.6 14.7c.1-.3.6-.3.7 0l.7 1.9c0 .1.1.2.2.2l1.9.7c.3.1.3.6 0 .7l-1.9.7c-.1 0-.2.1-.2.2l-.7 1.9c-.1.3-.6.3-.7 0l-.7-1.9c0-.1-.1-.2-.2-.2l-1.9-.7c-.3-.1-.3-.6 0-.7l1.9-.7c.1 0 .2-.1.2-.2Z"/></svg>')+'<span class="tone-byot-btn-label">'+h+"</span>",y=e.escapeHtml(H("tone.byot.dictate_name","Diktér tonenavn")).replace(/"/g,"""),w=e.escapeHtml(H("tone.byot.dictate_example","Diktér eksempeltekst")).replace(/"/g,"""),b=e.escapeHtml(H("tone.byot.upload","Upload en fil")).replace(/"/g,"""),k=e.escapeHtml(H("tone.byot.cancel","Annuller")),S=n&&t.name?e.escapeHtml(t.name).replace(/"/g,"""):"",x=n?$(t.icon_key):"",T=n&&t.tone_prompt?e.escapeHtml(z(t.tone_prompt)):"",L=n&&t.example_text?String(t.example_text):"",E=e.escapeHtml(L),C=e.escapeHtml(H("tone.byot.name_ph","F.eks. Min venlige stil")).replace(/"/g,"""),_=e.escapeHtml(H("tone.byot.example_ph","Indsæt et stykke tekst, du selv har skrevetâ¦")).replace(/"/g,"""),A=n?"":'<div class="tone-byot-field"><label class="tone-byot-field-label" for="tone-byot-example">'+u+'</label><div class="tone-byot-textarea-wrap"><textarea class="tone-byot-textarea" id="tone-byot-example" rows="5" maxlength="10000" placeholder="'+_+'">'+E+'</textarea><div class="tone-byot-field-controls"><button type="button" class="tone-byot-mic ss-mic" id="tone-byot-example-mic" aria-pressed="false" aria-label="'+w+'" title="'+w+'"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M12 2a3 3 0 0 0-3 3v6a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"/><path d="M19 10v1a7 7 0 0 1-14 0v-1"/><path d="M12 18v4"/></svg></button><button type="button" class="tone-byot-upload" id="tone-byot-example-upload" aria-label="'+b+'" title="'+b+'"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M12 16V4"/><path d="M7 9l5-5 5 5"/><path d="M5 20h14"/></svg></button></div><input type="file" id="tone-byot-file" class="tone-byot-file-input" accept="image/*,.pdf,.docx,.txt,.mp3,.m4a,.wav,.ogg,.webm" hidden></div><p class="tone-byot-upload-confirm" id="tone-byot-upload-confirm" role="status" aria-live="polite" hidden></p></div>',q=n?"":'<p class="tone-byot-tip">'+m+"</p>";de({titleHtml:r,subtitleHtml:o,bodyHtml:'<div class="tone-byot-field"><label class="tone-byot-field-label" for="tone-byot-name">'+i+'</label><div class="tone-byot-input-wrap"><input type="text" class="tone-byot-input" id="tone-byot-name" maxlength="80" autocomplete="off" placeholder="'+C+'" value="'+S+'" data-byot-autofocus><button type="button" class="tone-byot-mic ss-mic" id="tone-byot-name-mic" aria-pressed="false" aria-label="'+y+'" title="'+y+'"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false">
3<path d="M12 2a3 3 0 0 0-3 3v6a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"/><path d="M19 10v1a7 7 0 0 1-14 0v-1"/><path d="M12 18v4"/></svg></button></div></div><div class="tone-byot-field tone-byot-field--icon"><button type="button" class="tone-byot-icon-disclosure" id="tone-byot-icon-toggle" aria-expanded="false" aria-controls="tone-byot-icon-panel"><svg class="tone-byot-disclosure-chev" viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><polyline points="9 6 15 12 9 18"/></svg><span class="tone-byot-icon-disclosure-label">'+l+'</span><span class="tone-byot-field-note">('+s+')</span><span class="tone-byot-icon-disclosure-current" id="tone-byot-icon-current">'+J(x)+'</span></button><input type="hidden" id="tone-byot-icon" value="'+e.escapeHtml(x).replace(/"/g,""")+'"><div class="tone-byot-icon-panel" id="tone-byot-icon-panel" hidden><div class="tone-byot-icon-grid" role="radiogroup" aria-label="'+a+'">'+function(t){for(var n=$(t),r=[""].concat(g),o="",i=0;i<r.length;i++){var a=r[i],l=a===n,s=a?V(a):H("tone.byot.icon_none","Uden ikon"),c=e.escapeHtml(s).replace(/"/g,""");o+='<button type="button" role="radio" class="tone-byot-icon-tile'+(a?"":" tone-byot-icon-tile--none")+(l?" is-selected":"")+'" data-byot-icon-key="'+a+'" aria-checked="'+(l?"true":"false")+'" tabindex="'+(l?"0":"-1")+'" aria-label="'+c+'" title="'+c+'">'+(a?G(a):W())+"</button>"}return o}(x)+"</div></div></div>"+(n?'<div class="tone-byot-field"><label class="tone-byot-field-label" for="tone-byot-prompt">'+c+'</label><textarea class="tone-byot-prompt" id="tone-byot-prompt" rows="5" maxlength="2400">'+T+"</textarea></div>":"")+A+q+'<p class="tone-byot-error" id="tone-byot-error" role="status" aria-live="polite" hidden></p><span class="sr-only" role="status" aria-live="polite" id="tone-byot-busy-live"></span>',primaryLabel:v,cancelLabel:k,onReady:function(e,t){var r=e.querySelector("#tone-byot-name"),o=e.querySelector("#tone-byot-example"),i=e.querySelector("#tone-byot-prompt");function a(){var e=r.value.trim().length>0&&(n?i&&i.value.trim().length>0:o&&o.value.trim().length>0)&&!f;t.disabled=!e,t.setAttribute("aria-disabled",e?"false":"true")}r.addEventListener("input",a),o&&o.addEventListener("input",a),i&&i.addEventListener("input",a),a(),function(e){var t=e?e.querySelector("#tone-byot-icon"):null,n=e?e.querySelector(".tone-byot-icon-grid"):null;if(t&&n){var r=[].slice.call(n.querySelectorAll('[role="radio"]'));if(r.length){var o=e.querySelector("#tone-byot-icon-toggle"),i=e.querySelector("#tone-byot-icon-panel"),a=e.querySelector("#tone-byot-icon-current");o&&i&&o.addEventListener("click",function(){var e="true"===o.getAttribute("aria-expanded");o.setAttribute("aria-expanded",e?"false":"true"),i.hidden=e});for(var l=0;l<r.length;l++)r[l].addEventListener("click",function(){s(this.getAttribute("data-byot-icon-key"))});n.addEventListener("keydown",function(e){var t="ArrowRight"===e.key||"ArrowDown"===e.key,n="ArrowLeft"===e.key||"ArrowUp"===e.key;if(t||n){e.preventDefault();var o=r.indexOf(document.activeElement);if(-1===o)for(var i=0;i<r.length;i++)if("true"===r[i].getAttribute("aria-checked")){o=i;break}var a=((-1===o?0:o)+(t?1:-1)+r.length)%r.length;s(r[a].getAttribute("data-byot-icon-key"));try{r[a].focus()}catch(e){}}}),s(t.value)}}function s(e){t.value=$(e);for(var n=0;n<r.length;n++){var o=r[n],i=$(o.getAttribute("data-byot-icon-key"))===t.value;o.classList.toggle("is-selected",i),o.setAttribute("aria-checked",i?"true":"false"),o.setAttribute("tabindex",i?"0":"-1")}a&&(a.innerHTML=J(t.value))}}(e),ge(e,r,o),o&&he(e,o,a)},onPrimary:function(r,o){if(!f){var i=(r.querySelector("#tone-byot-name").value||"").trim(),a=r.querySelector("#tone-byot-example"),l=n?L:(a&&a.value||"").trim(),s=r.querySelector("#tone-byot-prompt"),c=z(s?s.value:""),u=r.querySelector("#tone-byot-icon"),m=$(u?u.value:"");if(i&&(n||l))if(!n||c){f=!0,o.disabled=!0,o.setAttribute("aria-busy","true"),o.classList.add("is-busy"),ce(r,"");var g=H("tone.byot.creating","Opretter din toneâ¦"),h=o.querySelector(".tone-byot-btn-label"),v=h?h.textContent:"",y=r.querySelector("#tone-byot-busy-live");n||(h&&(h.textContent=g),y&&(y.textContent=g));var w={name:i,example_text:l,icon_key:m,ui_lang:re()};n&&(w.id=t.id),n&&(w.tone_prompt=c),oe("tone-custom-save",w,function(t){if(f=!1,t&&t.success&&t.tone&&t.tone.id){var a={id:String(t.tone.id),name:String(t.tone.name||i),example_text:String(null!=t.tone.example_text?t.tone.example_text:l),icon_key:$(null!=t.tone.icon_key?t.tone.icon_key:m),tone_prompt:z(t.tone.tone_prompt)};if(n){for(var s=!1,c=0;c<p.length;c++)if(p[c]&&p[c].id===a.id){p[c]=a,s=!0;break}s||p.push(a),ae(),te(),ne()}else p.push(a),te(),function(t,n){if(!t||!n)return;fe();var r=t.querySelector(".tone-byot-dialog");if(!r)return ae(),void ne();var o=function(e){for(var t=String(e||"").replace(/\r/g,"").split("\n"),n="",r="",o=[],i=[],a=0,l=0;l<t.length;l++){var s=t[l].trim();if(s){var c=s.replace(/^[-*â¢]\s+/,""),d=c!==s;!d&&/:$/.test(s)&&s.length<=40?a=a<1?1:2:0===a?n+=(n?" ":"")+s:d&&1===a?o.push(c):d&&2===a?i.push(c):r+=(r?" ":"")+s}}return{lead:n,dos:o.slice(0,4),avoid:i.slice(0,4),tail:r}}
3(n.tone_prompt),i=e.escapeHtml(H("tone.byot.created_title","Din tone er klar")),a=e.escapeHtml(H("tone.byot.created_apply","Anvend pÃ¥ teksten")),l=e.escapeHtml(H("tone.byot.edit","Rediger tone")),s=e.escapeHtml(H("tone.byot.created_done","Færdig")),c=e.escapeHtml(H("tone.byot.created_fulltext","Vis hele stilbeskrivelsen")),d=H("tone.byot.created_announce","Din tone er oprettet"),u=$(n.icon_key),p=u?'<span class="tone-byot-confirm-chip-icon" aria-hidden="true">'+G(u)+"</span>":"",m=e.escapeHtml(String(n.name||"")),f='<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="20 6 9 17 4 12"/></svg>',g=o.dos.slice(0,3).map(we).filter(Boolean);if(!g.length){var h=function(e){var t=String(e||"").trim();if(!t)return"";var n=t.match(/^[^.!?]*[.!?]/),r=(n?n[0]:t).trim();r.length>180&&(r=r.slice(0,177).replace(/\s+\S*$/,"")+"â¦");return r}(o.lead);h&&(g=[we(h)])}for(var v="",y=0;y<g.length;y++)v+='<li><span class="tone-byot-confirm-ic" aria-hidden="true">'+f+"</span><span>"+e.escapeHtml(g[y])+"</span></li>";var w=e.escapeHtml(z(n.tone_prompt)),b='<details class="tone-byot-confirm-foldout"><summary class="tone-byot-confirm-foldout-summary"><svg class="tone-byot-confirm-foldout-chev" viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="6 9 12 15 18 9"/></svg><span>'+c+'</span></summary><div class="tone-byot-confirm-fulltext" tabindex="0" role="group" aria-label="'+c+'">'+w+"</div></details>",k=v?'<ul class="tone-byot-confirm-summary">'+v+"</ul>"+b:'<div class="tone-byot-confirm-fulltext tone-byot-confirm-fulltext--bare" tabindex="0" role="group" aria-label="'+c+'">'+w+"</div>",S=D()?'<div class="tone-byot-modal-actions tone-byot-confirm-actions"><button type="button" class="tone-byot-btn tone-byot-btn-cancel tone-byot-confirm-edit">'+l+'</button><button type="button" class="tone-byot-btn tone-byot-btn-primary tone-byot-confirm-done">'+s+"</button></div>":'<div class="tone-byot-modal-actions tone-byot-confirm-actions"><button type="button" class="tone-byot-btn tone-byot-btn-cancel tone-byot-confirm-edit">'+l+'</button><button type="button" class="tone-byot-btn tone-byot-btn-primary tone-byot-confirm-apply"><span class="tone-byot-btn-icon-wrap" aria-hidden="true"><svg fill="currentColor" class="tone-byot-btn-icon" viewBox="0 0 24 24" width="16" height="16" aria-hidden="true" focusable="false"><path d="M11.7 2.7c.2-.5.9-.5 1.1 0l1.6 4.4c.1.2.2.3.4.4l4.4 1.6c.5.2.5.9 0 1.1l-4.4 1.6c-.2.1-.3.2-.4.4l-1.6 4.4c-.2.5-.9.5-1.1 0l-1.6-4.4c-.1-.2-.2-.3-.4-.4l-4.4-1.6c-.5-.2-.5-.9 0-1.1l4.4-1.6c.2-.1.3-.2.4-.4Z"/><path d="M18.6 14.7c.1-.3.6-.3.7 0l.7 1.9c0 .1.1.2.2.2l1.9.7c.3.1.3.6 0 .7l-1.9.7c-.1 0-.2.1-.2.2l-.7 1.9c-.1.3-.6.3-.7 0l-.7-1.9c0-.1-.1-.2-.2-.2l-1.9-.7c-.3-.1-.3-.6 0-.7l1.9-.7c.1 0 .2-.1.2-.2Z"/></svg></span><span class="tone-byot-btn-label">'+a+'</span></button></div><div class="tone-byot-confirm-donerow"><button type="button" class="tone-byot-confirm-done">'+s+"</button></div>";r.innerHTML='<div class="tone-byot-confirm"><div class="tone-byot-confirm-head"><div class="tone-byot-confirm-badge" aria-hidden="true"><svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg></div><h3 class="tone-byot-modal-title" id="tone-byot-modal-title">'+i+'</h3></div><div class="tone-byot-confirm-identity"><span class="tone-byot-confirm-chip">'+p+'<span class="tone-byot-confirm-chip-name">'+m+'</span></span></div><div class="tone-byot-confirm-card">'+k+"</div>"+S+'<span class="sr-only" role="status" aria-live="polite" id="tone-byot-confirm-live"></span></div>';var x=r.querySelector(".tone-byot-confirm-apply"),T=r.querySelector(".tone-byot-confirm-edit"),L=r.querySelector(".tone-byot-confirm-done"),E=r.querySelector("#tone-byot-confirm-live");T&&T.addEventListener("click",function(){pe(n.id)});L&&L.addEventListener("click",function(){ae(),ne()});x&&x.addEventListener("click",function(){ae(),be(n.id)});E&&setTimeout(function(){E.textContent=d},60);
3var C=x||L||T;if(C)try{C.focus()}catch(e){}}(r,a)}else o.disabled=!1,o.removeAttribute("aria-busy"),o.classList.remove("is-busy"),h&&(h.textContent=v),y&&(y.textContent=""),ce(r,t&&t.error||H("tone.byot.save_error","Kunne ikke gemme tonen â prøv igen"))})}else ce(r,d)}}})}function we(e){var t=String(e||"").trim().replace(/^[\u2022\-\u2013\u2014]\s*/,"");return t?t.charAt(0).toLocaleUpperCase()+t.slice(1):""}function be(t){var n=Z(t);if(n){if(D())N();else if(!f){window._toneSmartTarget="custom:"+n.id;var r=window._toneSmartTarget;window._toneSmartForceWholeEditor=!0;var i=!1;try{i=!0===e.handleChipAction("tone-smart",o)}catch(e){return window._toneSmartTarget=null,void(window._toneSmartForceWholeEditor=!1)}i||window._toneSmartTarget!==r||(window._toneSmartTarget=null,window._toneSmartForceWholeEditor=!1)}}else ue()}function ke(e){return(e&&e.context_note?String(e.context_note).trim():"")||H("tone.result.summary_fallback","Jeg tilpassede tonen i din tekst.")}function Se(t){if(!t||!0!==t.memory_used)return"";var n=[],r=(t.memory_entity_label||"").toString().trim();r&&n.push(e.escapeHtml(r));var o=parseInt(t.memory_fact_count,10);return isFinite(o)&&o>0&&n.push(o+" "+e.escapeHtml(H("tone.result.memory.notes_count","noter"))),!0===t.memory_style_used&&n.push(e.escapeHtml(H("tone.result.memory.your_style","din skrivestil"))),0===n.length?"":'<div class="tone-memory-trust" style="font-size:12px;opacity:.72;margin-top:8px;display:flex;align-items:center;gap:6px;flex-wrap:wrap;justify-content:center"><svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg><span>'+e.escapeHtml(H("tone.result.memory.used","Brugte:"))+" "+n.join(" · ")+"</span></div>"}function xe(){document.body.classList.add("ws-tone-decision")}function Te(){document.body.classList.remove("ws-tone-decision")}function Le(){Te(),window._toneSmartTarget=null,e&&"function"==typeof e.chipInFlight&&e.chipInFlight(!1);var t=document.getElementById(o.msgsId);if(t){t.innerHTML=U(),N(t),j();var n=t.querySelector(".tone-slider-apply")||t.querySelector('[data-action="tone-smart"]')||t.querySelector(".ai-chip");n&&n.focus()}}function Ee(){Fe(),Ie();var e=i;try{e&&!0===e.memory_path&&!_&&(_=!0,function(e){try{var t=window._supabase;if(!t||!t.auth||"function"!=typeof t.auth.getSession)return;var n=e&&e.improved_text?String(e.improved_text):"";if(!n)return;var r=e&&e.memory_entity_label?String(e.memory_entity_label):"",o="da-DK";try{window.getCurrentUILang&&(o=window.getCurrentUILang()||"da-DK")}catch(e){}t.auth.getSession().then(function(e){var t=e&&e.data&&e.data.session;t&&t.access_token&&fetch("/robots/skrivebord/grammar-api.php?action=tone-memory-commit",{method:"POST",headers:{Authorization:"Bearer "+t.access_token,"Content-Type":"application/json"},body:JSON.stringify({text:n,entity:r,ui_lang:o})}).catch(function(){})}).catch(function(){})}catch(e){}}(e))}catch(e){}i=null,a=null,k="",S=null,Le()}function Ce(){if(Fe(),Ie(),null!==a)if(window.quill1&&"function"==typeof window.quill1.setContents&&"object"==typeof a){if(window.quill1.setContents(a),S)try{window.quill1.setSelection(S.index,S.length,"silent")}catch(e){}}else{var e=document.querySelector(".ql-editor");e&&"string"==typeof a&&(e.innerHTML=a)}i=null,a=null,k="",S=null,Le()}function _e(){Fe(),Ie(),Te(),window._toneSmartTarget=T||"auto",e.handleChipAction("tone-smart",o)}function Ae(){Fe(),Ie(),i=null,a=null,k="",S=null,Le()}function qe(t){return e.escapeHtml(String(t||"")).replace(/\n/g,"<br>")}function Me(){if(e&&e.skCompare&&"function"==typeof e.skCompare.open){var t=qe(k||""),n=qe(function(){if(window.quill1&&"function"==typeof window.quill1.getText)return window.quill1.getText().trim();var e=document.querySelector(".ql-editor");return e?(e.textContent||"").trim():""}());e.skCompare.open(t,n,{returnFocusId:"tone-compare-btn"})}else window.console&&console.warn&&console.warn("[tone-tab] shared compare (bridge.skCompare) unavailable")}function Ie(){if(e&&e.skCompare&&"function"==typeof e.skCompare.close)e.skCompare.close();else{var t=document.getElementById("ws-compare-modal");t&&t.parentNode&&t.parentNode.removeChild(t)}}function Be(){try{var e=localStorage.getItem("ss_chat_lang");if(e){var t=JSON.parse(e);if(t&&t.ttsName)return t.ttsName;if(t&&t.code&&window.TTSEngine&&"function"==typeof window.TTSEngine.normalizeLanguage)return window.TTSEngine.normalizeLanguage(t.code,"Danish")}}catch(e){}var n="da-DK";try{window.getCurrentUILang&&(n=window.getCurrentUILang()||"da-DK")}catch(e){}if(window.TTSEngine&&"function"==typeof window.TTSEngine.normalizeLanguage)return window.TTSEngine.normalizeLanguage(n,"Danish");return{da:"Danish","da-DK":"Danish",en:"English","en-US":"English",de:"German","de-DE":"German",fr:"French","fr-FR":"French",es:"Spanish","es-ES":"Spanish",sv:"Swedish","sv-SE":"Swedish"}[n]||"Danish"}function He(){try{return"male"===(localStorage.getItem("ss_tts_voice")||"female")?"Male":"Female"}catch(e){return"Female"}}function Ke(){try{var e=localStorage.getItem("ss_tts_voice_variant")||"";if("mads"===e||"lars"===e||"anders"===e||"sofie"===e||"freja"===e||"ida"===e)return e}catch(e){}return"Male"===He()?"mads":"sofie"}function De(e,t){var n=e?e.closest(".bedre-result-summary"):null,r=n?n.querySelector(".tone-result-live"):null;r&&(r.textContent=t||"")}function Pe(e,t){if(e){e.setAttribute("data-state",t),e.setAttribute("aria-busy","loading"===t?"true":"false");var n=e.querySelector(".bedre-tts-icon-play"),r=e.querySelector(".bedre-tts-icon-pause"),o="playing"===t;n&&(n.style.display=o?"none":""),r&&(r.style.display=o?"":"none");var i="playing"===t||"loading"===t;e.setAttribute("aria-pressed",i?"true":"false");var a=i?H("tone.result.tts_pause","Pause"):H("tone.result.tts_play","Læs resumé op");e.setAttribute("aria-label",a),e.setAttribute("title",a),"playing"===t?De(e,H("tone.result.tts_pause","Pause")):"idle"===t&&De(e,"")}}function Ne(e){var t=e?e.querySelector(".bedre-tts-ring__progress"):null;t&&t.setAttribute("stroke-dashoffset","138.23")}function je(e){if(e){var t=e.getAttribute("data-state")||"idle";if("loading"!==t)if("playing"!==t)if("paused"!==t){var n=i?ke(i):"";if(n){var r=e.closest(".bedre-result-summary");r&&r.classList.add("ws-expanded"),document.dispatchEvent(new Event("skrivebord:tts-stop-all"));var o=++E;Pe(e,"loading"),Promise.resolve(function(e,t,n){if(!window.TTSEngine||"function"!=typeof window.TTSEngine.create)throw new Error("TTSEngine unavailable");var r=window.TTSEngine.create({fetchChunk:Re,gender:He(),onStateChange:function(t){n===E&&("loading"===t&&Pe(e,"loading"),"playing"===t&&Pe(e,"playing"),"paused"===t&&Pe(e,"paused"),"buffering"===t&&Pe(e,"playing"),"complete"===t&&function(e,t){if(t&&L===t&&"function"==typeof t.revokeAll)try{t.revokeAll()}catch(e){}L===t&&(L=null);e&&(Pe(e,"idle"),Ne(e))}(e,r),"error"!==t||C||Fe())},onProgress:function(t){if(n===E){var r=Math.max(1,t.chunkTotal||1),o=t.duration>0?t.currentTime/t.duration:0;!function(e,t){var n=e?e.querySelector(".bedre-tts-ring__progress"):null;if(n){var r=138.23;n.setAttribute("stroke-dashoffset",String(r-r*t))}}(e,(t.chunkIndex+o)/r)}}});L=r,"function"==typeof r.setVolume&&r.setVolume(function(){try{if("number"==typeof window.__SKRIVEBORD_TTS_VOLUME__)return Math.max(0,Math.min(1,window.__SKRIVEBORD_TTS_VOLUME__));var e=localStorage.getItem("skrivebord.tts.volume");if(null!==e&&""!==e){var t=parseFloat(e);
3if(Number.isFinite(t))return t>1&&t<=100&&(t/=100),Math.max(0,Math.min(1,t))}}catch(e){}return.6}());"function"==typeof r.setPlaybackRate&&r.setPlaybackRate(function(){try{if("function"==typeof window.getPlaybackSpeed){var e=parseFloat(window.getPlaybackSpeed());if(Number.isFinite(e)&&e>0)return e}var t=parseFloat(localStorage.getItem("ss_tts_speed")||"1");if(Number.isFinite(t)&&t>0)return t}catch(e){}return 1}());return r.start(t,{lang:Be(),minWords:18,maxChars:700}),null}(e,n,o)).catch(function(){o===E&&Fe()})}}else L&&"function"==typeof L.resume&&L.resume();else L&&"function"==typeof L.pause?L.pause():Pe(e,"paused");else Fe()}}function Re(e,t,n,r){return window.TTSEngine&&"function"==typeof window.TTSEngine.fetchAudio?window.TTSEngine.fetchAudio({text:e,lang:t||Be(),gender:n||He(),voice:Ke(),quality:"premium",endpoint:window.HGF_ajax_object&&window.HGF_ajax_object.ajax_url||window.ajaxurl||"/robots/skrivebord/grammar-api.php",action:"hgf_important_secure_bots_text_to_speech",signal:r||null,maxLength:1e3}).then(function(e){return{audioUrl:e}}):Promise.reject(new Error("TTSEngine unavailable"))}
3function Fe(){if(!C){if(C=!0,E++,L){try{L.stop()}catch(e){}L=null}var e=document.getElementById("tone-summary-play");e&&(Pe(e,"idle"),Ne(e)),C=!1}}function Oe(t){t.innerHTML=['<div class="ai-card ai-card--sidebar" id="tone-card">','<div class="ai-card-header">','<button class="ai-new-chat-btn" id="tone-new-chat" data-i18n-title="tone.back" title="'+SKT("tone.back")+'" data-i18n-aria-label="tone.back_to_analysis" aria-label="'+SKT("tone.back_to_analysis")+'">','<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M15 18l-6-6 6-6"/><path d="M9 12h10"/></svg>','<span class="ai-new-chat-label" data-i18n="tone.back">'+SKT("tone.back")+"</span>","</button>","</div>",'<div class="ai-card-messages" id="tone-card-messages">',U(),"</div>",'<div class="ai-card-input-row">','<div class="ai-card-input-wrap">','<textarea id="tone-card-input" class="ai-card-input" data-i18n-placeholder="ai.placeholder.default" placeholder="'+SKT("ai.placeholder.default")+'" data-i18n-aria-label="ai.placeholder.default" aria-label="'+SKT("ai.placeholder.default")+'" autocomplete="off" rows="1"></textarea>
3','<button class="ai-card-mic ss-mic" id="tone-card-mic" data-i18n-title="stt.dictate" title="'+SKT("stt.dictate")+'" data-i18n-aria-label="stt.dictateAi" aria-label="'+SKT("stt.dictateAi")+'">','<svg viewBox="0 0 24 24"><path d="M12 23V20M12 20C9.87827 20 7.84344 19.1571 6.34315 17.6569C4.84285 16.1566 4 14.1217 4 12M12 20C14.1217 20 16.1566 19.1571 17.6569 17.6569C19.1571 16.1566 20 14.1217 20 12M12 17C9.25 17 7 14.828 7 12.172V5.828C7 3.172 9.25 1 12 1C14.75 1 17 3.172 17 5.828V12.172C17 14.828 14.75 17 12 17Z"/></svg>',"</button>",'<button class="ai-card-send" id="tone-card-send" data-i18n-title="action.send" title="'+SKT("action.send")+'" data-i18n-aria-label="action.send" aria-label="'+SKT("action.send")+'">','<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><line x1="12" y1="20" x2="12" y2="5"></line><polyline points="6 11 12 5 18 11"></polyline></svg>',"</button>","</div>","</div>","</div>"].join(""),function(t){if(!t)return;t.querySelector("#tone-card-send").addEventListener("click",function(){var n=t.querySelector("#tone-card-input");if(n&&n.value.trim())try{e.handleAiSend(n.value.trim(),null,0,o),n.value="","TEXTAREA"===n.tagName&&(n.style.height="auto",n.style.overflowY="hidden");var r=t.querySelector("#tone-card-send");r&&(r.disabled=!0,r.style.opacity="0.3")}catch(n){console.error("Tone send error:",n);var i=document.getElementById("tone-card-messages");i&&!i.querySelector(".ai-chips")&&(Te(),i.innerHTML=U());var a=t.querySelector("#tone-card-send");a&&(a.disabled=!1,a.style.opacity=""),e.chipInFlight(!1)}});var r=t.querySelector("#tone-new-chat");r&&r.addEventListener("click",function(){B(),Te(),e.aiHistory([]),e.clearChatStorage(),e.chipInFlight(!1),e.cancelAiPanelConversation&&e.cancelAiPanelConversation(o),e.correctionMode()&&e.clearCorrections();var t=document.getElementById("tone-card-messages");t&&(t.style.opacity="0",setTimeout(function(){n&&n.detected?Ue(n,o):(n=null,t.innerHTML=U()),t.style.opacity="1"},150)),r.classList.remove("visible"),e.syncAiConversationChrome&&e.syncAiConversationChrome();var i=document.getElementById("tone-card-input");i&&(i.value="",i.style.height="auto",i.style.overflowY="hidden",i.focus())});var i=t.querySelector("#tone-card-input");i&&"TEXTAREA"===i.tagName&&i.addEventListener("input",function(){this.style.height="auto";var e=120,t=Math.min(this.scrollHeight,e);this.style.height=t+"px",this.style.overflowY=this.scrollHeight>e?"auto":"hidden"});var a=t.querySelector("#tone-card-send");function l(){if(a&&i){var e=i.value.trim().length>0;a.disabled=!e,a.style.opacity=e?"":"0.3"}}l(),i.addEventListener("input",l),i.addEventListener("keydown",function(t){if("Enter"===t.key&&!t.shiftKey&&this.value.trim())return t.preventDefault(),e.handleAiSend(this.value.trim(),null,0,o),this.value="",this.style.height="auto",this.style.overflowY="hidden",void l();var n=this;setTimeout(function(){n.style.height="auto";var e=120,t=Math.min(n.scrollHeight,e);n.style.height=t+"px",n.style.overflowY=n.scrollHeight>e?"auto":"hidden"},0)});var s=t.querySelector("#tone-card-mic");s&&s.addEventListener("click",function(){e.toggleStt({buttonId:"tone-card-mic",inputId:"tone-card-input"})});t.addEventListener("click",function(t){var n=t.target.closest(".ai-chip")||t.target.closest(".ai-action-item");if(n){if(n.disabled||"true"===n.getAttribute("aria-disabled"))return t.preventDefault(),void t.stopPropagation();var r=n.dataset.action;if(r){if("true"===n.dataset.processing)return;e.handleChipAction(r,o)}}}),t.addEventListener("click",function(t){var n=t.target.closest(".tone-slider-apply");n&&(t.preventDefault(),n.disabled||"true"===n.getAttribute("aria-disabled")||n.classList.contains("tone-slider-apply")&&(D()?N():(window._toneSmartTarget=c[u]||"neutral",e.handleChipAction("tone-smart",o))))}),t.addEventListener("click",function(t){var n=t.target.closest("[data-byot]");if(n&&(t.preventDefault(),!n.disabled&&"true"!==n.getAttribute("aria-disabled"))){var r=n.getAttribute("data-byot"),o=n.closest(".tone-byot-chip"),i=o?o.getAttribute("data-byot-id"):"";"build"===r?ue():"apply"===r?be(i):"edit"===r?pe(i):"delete"===r&&function(t){var n=Z(t);
3if(n){var r=e.escapeHtml(H("tone.byot.delete_title","Slet tone")),o=H("tone.byot.delete_confirm",'Er du sikker pÃ¥, at du vil slette "{name}"? Det kan ikke fortrydes.').split("{name}");de({titleHtml:r,subtitleHtml:e.escapeHtml(o[0])+e.escapeHtml(n.name)+e.escapeHtml(o.length>1?o[1]:""),bodyHtml:'<p class="tone-byot-error" id="tone-byot-error" role="status" aria-live="polite" hidden></p>',primaryLabel:e.escapeHtml(H("tone.byot.delete_cta","Slet")),cancelLabel:e.escapeHtml(H("tone.byot.cancel","Annuller")),primaryDanger:!0,dialogClass:"tone-byot-dialog--delete",onPrimary:function(e,t){f||(f=!0,t.disabled=!0,t.setAttribute("aria-busy","true"),ce(e,""),oe("tone-custom-delete",{id:n.id},function(r){f=!1,r&&r.success?(p=p.filter(function(e){return e&&e.id!==n.id}),ae(),te(),ne()):(t.disabled=!1,t.removeAttribute("aria-busy"),ce(e,r&&r.error||H("tone.byot.delete_error","Kunne ikke slette â prøv igen")))}))}})}}(i)}}),t.addEventListener("input",function(e){var t=e.target.closest("#tone-slider");t&&function(e){var t=Math.max(0,Math.min(4,parseInt(e,10)||0));u=t;try{localStorage.setItem(d,String(t))}catch(e){}var n=R(t),r=document.getElementById(o.msgsId);if(r){var i=r.querySelector("#tone-current-label");i&&(i.textContent=n);var a=r.querySelector("#tone-slider");a&&(a.setAttribute("aria-valuetext",n),String(a.value)!==String(t)&&(a.value=t));var l=r.querySelector(".tone-slider-card");l&&l.setAttribute("data-level",String(t));var s=r.querySelector(".tone-level-icon");s&&(s.innerHTML=O(t));var c=r.querySelector(".tone-level-desc");c&&(c.setAttribute("data-i18n","wm.tone_"+t+"d"),c.textContent=F(t))}}(t.value)})}(t.querySelector("#tone-card"))}function Ue(t,r){B(),Te();var i=document.getElementById(r.msgsId);if(i){var a=t.detected||{},s=Math.max(1,Math.min(10,t.consistency||5)),c=t.observations||[],d=(t.recommended_action||"none").toLowerCase(),u=M(a,d),p=t.highlights||[],m=t.paragraphs||[];n={detected:a,primary:a.primary||"neutral",label:u,observations:c,highlights:p,consistency:s,paragraphs:m,recommended_action:d};var f='<div class="ai-completion-icon">'+("none"===d?'<svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>':'<svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path class="tone-bar tone-bar-1" d="M2 10v4"/><path class="tone-bar tone-bar-2" d="M6 6v12"/><path class="tone-bar tone-bar-3" d="M10 3v18"/><path class="tone-bar tone-bar-4" d="M14 8v8"/><path class="tone-bar tone-bar-5" d="M18 5v14"/><path class="tone-bar tone-bar-6" d="M22 10v4"/></svg>')+"</div>",g='<div class="ai-empty-headline">'+e.escapeHtml(u)+"</div>";if("none"===d){for(var h=s>=8?"#7ed856":s>=5?"#e6a23c":"#e07a5f",v=188.5-188.5*s/10,y='<div class="tone-ring-wrap tone-reveal tone-reveal-1" role="img" aria-label="'+e.escapeHtml(u)+" "+s+'/10"><div class="tone-ring"><svg viewBox="0 0 72 72"><circle class="tone-ring-bg" cx="36" cy="36" r="30"/><circle class="tone-ring-fill" cx="36" cy="36" r="30" stroke="'+h+'" style="--ring-target:'+v+'"/></svg><div class="tone-ring-center"><span class="tone-ring-num" data-target="'+s+'" style="color:'+h+'">0</span><span class="tone-ring-max">/10</span></div></div></div>',w='<div class="ai-divider"><span>'+SKT("tone.ask_direction")+'</span></div><div class="ai-actions-list">',b=["professional","confident","diplomatic"],k=0;k<b.length;k++){var S=l[b[k]];w+='<button class="ai-action-item" data-action="'+S.action+'">'+S.svg+'<span class="ai-action-label">'+SKT(S.sktKey)+"</span></button>"}w+="</div>",i.innerHTML='<div class="ai-empty-state ai-completion-state tone-completion-state">'+f+g+y+w+K()+"</div>",setTimeout(function(){var e=i.querySelector(".tone-ring-fill");e&&e.classList.add("tone-ring-fill--animated");var t,n,r,o,a,l=i.querySelector(".tone-ring-num");l&&(t=l,n=0,r=s,o=900,a=null,window.matchMedia("(prefers-reduced-motion: reduce)").matches?t.textContent=r:requestAnimationFrame(function e(i){a||(a=i);var l=Math.min((i-a)/o,1),s=1-Math.pow(1-l,3);t.textContent=Math.round(n+(r-n)*s),l<1&&requestAnimationFrame(e)}))},80)}else{for(var x=l[d]||l.diplomatic,T="",L=0;L<c.length&&L<2;L++)if(c[L].text){var E=c[L].text.replace(/\\"/g,'"'),C=e.escapeHtml(E).replace(/"(.+?)"/g,'<strong>"$1"</strong>');T+='<div class="tone-diagnosis-text tone-reveal tone-reveal-'+L+'">'+(C=(C=C.replace(/\u201c(.+?)\u201d/g,"<strong>â$1â</strong>")).replace(/"(.+?)"/g,"<strong>"$1"</strong>"))+"</div>"}var _='<div class="tone-diagnosis">'+T+(p.length>2?'<div class="tone-diagnosis-more tone-reveal tone-reveal-2"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><circle cx="4" cy="12" r="1.5"/><circle cx="12" cy="12" r="1.5"/><circle cx="20" cy="12" r="1.5"/></svg> '+SKT("tone.more_places")+"</div>":"")+'<button class="tone-diagnosis-action tone-reveal tone-reveal-3" data-action="'+x.action+'">â '+SKT(x.sktKey)+"</button></div>";i.innerHTML='<div class="ai-empty-state ai-completion-state tone-completion-state">'+f+g+_+K()+"</div>"}for(var A=i.querySelectorAll("[data-action]"),q=0;q<A.length;q++)A[q].addEventListener("click",function(){B();var t=this.getAttribute("data-action");if(n&&n.highlights&&n.highlights.length>0){var r=t.replace("tone-","");window._toneRewriteDiagnosis=n,window._toneRewriteTarget=r,e.handleChipAction("tone-rewrite",o)}else e.handleChipAction(t,o)});var H=i.querySelector(".tone-reset-x");H&&H.addEventListener("click",function(t){t.stopPropagation(),n=null,window._toneRewriteDiagnosis=null,window._toneRewriteTarget=null,B(),Te(),e.aiHistory([]),e.clearChatStorage(),e.chipInFlight(!1);var r=document.getElementById("tone-new-chat");r&&r.classList.remove("visible"),i.innerHTML=U(),N(i),j();var o=i.querySelector(".tone-slider-apply")||i.querySelector('[data-action="tone-analyse"]')||i.querySelector(".ai-action-item")||document.getElementById("tone-card-input")||document.getElementById("option-tone");o&&o.focus()}),p.length>0&&setTimeout(function(){!function(e){B();var t=document.querySelector("#inputText .ql-editor");if(t&&e&&e.length)for(var n=0;n<e.length;n++)e[n]&&e[n].length>=3&&I(t,e[n])}(p)},80)}}function $e(){var n=document.getElementById("tone-panel"),r=document.querySelector(".correction-sidebar")||document.querySelector(".sidebar-control
3s");if(window.innerWidth<=767)return n&&(n.style.display="none"),Te(),void(t=!1);n||((n=document.createElement("div")).id="tone-panel",n.className="ai-panel-inner",n.style.display="flex",r?r.appendChild(n):document.body.appendChild(n)),n.parentElement&&"skrivebord-mobile-sheet-body"===n.parentElement.id&&r&&r.appendChild(n),function(){if(window.innerWidth<=767){var n=document.getElementById("tone-panel");return n&&(n.style.display="none"),Te(),void(t=!1)}document.querySelectorAll(".hk-dropdown-option").forEach(function(e){e.classList.remove("active")});var r=document.getElementById("option-tone");r&&r.classList.add("active"),e.hideCorrectionPopup(),(e.correctionMode()||e.hasCorrectionMap())&&e.saveCorrections(),e.hideMarks("ai"),e.loadCorrections("tone"),e.showMarks("tone"),[".improv-inner",".correction-inner",".style-inner",".voice-section","#chat-view","#ai-panel"].forEach(function(e){var t=document.querySelector(e);t&&(t.style.display="none")});var o=document.getElementById("tone-panel");o&&(o.style.display="flex"),o&&o.querySelector(".tone-smart-state")?xe():Te();var i=document.getElementById("chat-reset-link");i&&(i.style.display="none"),e.aiIsOpen(!1),t=!0}(),n.querySelector("#tone-card")||(Oe(n),t=!0),j(),N(n),ie()}function ze(){A&&clearTimeout(A),A=setTimeout(function(){A=null;var e=window.SKT&&window.SKT.lang?window.SKT.lang():null;if(!e||e!==q){q=e;var t=document.querySelector("#tone-card-messages .ai-welcome");if(t){if(document.getElementById("tone-byot-modal"))return;t.outerHTML=U(),j(),N()}}},0)}}(),function(){var e=window._wf;if(e){var t=!1,n=null,r=!1,o="auto",i="",a="",l=null,s=null,c="",d=null,u=null,p=null,m=0,f=!1,g={msgsI
3d:"bedre-card-messages",sendId:"bedre-card-send",buildChips:ye,clearChatLanding:function(e){if(!e)return;e.querySelectorAll("#bedre-card-inner, .bedre-result-wrap").forEach(function(e){e&&e.parentNode&&e.parentNode.removeChild(e)})}},h=["app.skrivsikkert.dk","staging.skrivsikkert.dk","staging2.skrivsikkert.dk","localhost","127.0.0.1","skrivsikkert.dk","www.skrivsikkert.dk","developapplication.se","www.developapplication.se"],v={version:5,hash:"",analyse:null,ideas:null,rewrites:{},applied:null,appliedIds:{},status:{},active:null,gen:0},y=!1,w=null,b=null,k=1e5,S=null,x={closing:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><polyline points="20 6 9 17 4 12"></polyline></svg>',other:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M9 18h6"></path><path d="M10 22h4"></path><path d="M12 2a7 7 0 0 0-4 12.7V17h8v-2.3A7 7 0 0 0 12 2z"></path></svg>'},T={P:["class"],DIV:["class"],BR:[],STRONG:[],B:[],EM:[],I:[],U:[],S:[],H1:["class"],H2:["class"],H3:["class"],H4:["class"],H5:["class"],H6:["class"],UL:["data-checked"],OL:["data-checked"],LI:["data-list","class"],BLOCKQUOTE:["class"],A:["href"],CODE:[],PRE:[],TABLE:[],THEAD:[],TBODY:[],TR:[],TD:["colspan","rowspan"],TH:["colspan","rowspan"]},L=/^ql-(indent-\d+|align-(center|right|justify)|direction-rtl)$/,E={SCRIPT:1,STYLE:1,IFRAME:1,OBJECT:1,EMBED:1,FORM:1,INPUT:1},C=null,_=null,A='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M9 18h6"></path><path d="M10 22h4"></path><path d="M12 2a7 7 0 0 0-4 12.7V17h8v-2.3A7 7 0 0 0 12 2z"></path></svg>',q='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><polyline points="9 6 15 12 9 18"></polyline></svg>',M={precise:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><circle cx="6" cy="6" r="3"></circle><circle cx="6" cy="18" r="3"></circle><line x1="20" y1="4" x2="8.12" y2="15.88"></line><line x1="14.47" y1="14.48" x2="20" y2="20"></line><line x1="8.12" y1="8.12" x2="12" y2="12"></line></svg>',clarity:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="M12 3l1.9 5.1L19 10l-5.1 1.9L12 17l-1.9-5.1L5 10l5.1-1.9z"></path><path d="M19 14l.8 2.2L22 17l-2.2.8L19 20l-.8-2.2L16 17l2.2-.8z"></path></svg>',flow:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><line x1="4" y1="7" x2="20" y2="7"></line><line x1="4" y1="12" x2="16" y2="12"></line><line x1="4" y1="17" x2="18" y2="17"></line></svg>'},I=null,B={P:1,H1:1,H2:1,H3:1,H4:1,H5:1,H6:1,LI:1,BLOCKQUOTE:1,DIV:1},H={STRONG:"bold",B:"bold",EM:"italic",I:"italic",U:"underline",S:"strike",STRIKE:"strike",CODE:"code"},K=["bedre.loading.step1","bedre.loading.step2","bedre.loading.step3","bedre.loading.step4"];document.addEventListener("skrivebord:tts-stop-all",function(){st()});var D=!1,P=null,N=null;window.addEventListener("ss:lang-changed",gt),window.addEventListener("ss:lang-ui-ready",gt),function(){try{var t=e.resetChatForDocumentChange;if("function"==typeof t&&!t._biqWrapped){var n=function(){try{ee("welcome")}catch(e){}return t.apply(this,arguments)};n._biqWrapped=!0,e.resetChatForDocumentChange=n}}catch(e){}document.addEventListener("skrivebord:editor-cleared",function(){ee("welcome")});try{var r=document.getElementById("sk-doc-browser");if(r&&"function"==typeof MutationObserver){var o="none"!==r.style.display;new MutationObserver(function(){var e="none"!==r.style.display;e&&!o&&ee("overlays"),o=e}).observe(r,{attributes:!0,attributeFilter:["style"]})}}catch(e){}}(),e.skCompare={open:Ze,close:Xe},e.skResultCard={build:Me,wire:Ie},e.registerBedre({PANEL:g,init:function(){var e=document.getElementById("option-bedre");e&&(e.addEventListener("click",function(){var e=document.getElementById("bedre-panel");e&&(e.style.display="flex"),setTimeout(function(){ft()},0)}),document.querySelectorAll(".hk-dropdown-option").forEach(function(e){"option-bedre"!==e.id&&e.addEventListener("click",function(){qe(),st(),document.body.classList.remove("ws-bedre-decision"),ee("overlays"),Xe();var e=document.getElementById("bedre-panel");e&&(e.style.display="none"),t=!1})}))},ensureReady:ft,cancelActiveImprovement:Se,isOpen:function(e){return void 0!==e&&(t=e),t}}),e.registerActions({"bedre-improve":{type:"inline",category:"enhancement"}})}else console.error("[bedre-tab] bridge (window._wf) not found");function j(){if(window.quill1&&"function"==typeof window.quill1.getText)return window.quill1.getText().trim();var e=document.querySelector(".ql-editor");return e?(e.textContent||"").trim():""}function R(){return 0===j().length}function F(){return j().length>5e4}function O(){return window.quill1||null}function U(){var e=O();if(!e)return{text:"",html:""};var t=function(){var e=O();if(!e)return null;var t=e.getSelection();return t&&t.length>0?t:null}();
3if(t){var n=e.getText(t.index,t.length).trim(),r="";try{r=e.getSemanticHTML(t.index,t.length)}catch(e){r=n}return{text:n,html:r,selection:t}}var o=e.getLength()-1,i=e.getText(0,o).trim(),a="";try{a=e.getSemanticHTML(0,o)}catch(e){a=i}return{text:i,html:a,selection:null}}function $(){try{if("function"==typeof window.__getCurrentUILang){var e=window.__getCurrentUILang();if(e)return String(e).split("-")[0].toLowerCase()}}catch(e){}try{var t=localStorage.getItem("sb_ui_lang");if(t)return String(t).split("-")[0].toLowerCase()}catch(e){}var n=document.documentElement.getAttribute("lang");return n?String(n).split("-")[0].toLowerCase():"da"}function z(){var e={"Content-Type":"application/json"};function t(t){return t&&(e.Authorization="Bearer "+t),e}try{if(window.SSGrammarAuth&&"function"==typeof window.SSGrammarAuth.getAuthToken)return Promise.resolve(window.SSGrammarAuth.getAuthToken()).then(t).catch(function(){return e});if(window.SSAuth&&"function"==typeof window.SSAuth.token)return Promise.resolve(window.SSAuth.token()).then(t).catch(function(){return e});if(window._supabase&&window._supabase.auth&&"function"==typeof window._supabase.auth.getSession)return window._supabase.auth.getSession().then(function(e){var n=e&&e.data&&e.data.session;return t(n&&n.access_token?n.access_token:"")}).catch(function(){return e})}catch(e){}return Promise.resolve(e)}function G(){var t=v.ideas||[],n=1===t.length?SKT("biq.header_one"):String(SKT("biq.header")).replace("{count}",t.length),r=['<div id="bedre-card-inner" class="bedre-card-inner biq-list">'];if(r.push('<div id="biq-live" class="biq-visually-hidden" aria-live="polite"></div>'),t.length){r.push('<div class="biq-header">'+e.escapeHtml(n)+"</div>"),r.push('<div class="biq-subline" data-i18n="biq.click_hint">'+SKT("biq.click_hint")+"</div>");for(var o=0;o<t.length;o++)r.push(V(t[o]))}else r.push('<div class="biq-empty">','<div class="biq-empty__icon" aria-hidden="true">'+x.closing+"</div>",'<div class="biq-empty__title" data-i18n="biq.empty_title">'+SKT("biq.empty_title")+"</div>",'<div class="biq-empty__sub" data-i18n="biq.empty_sub">'+SKT("biq.empty_sub")+"</div>","</div>");return r.push("</div>"),r.join("")}function V(t){var n=Q(t.id),r=v.active===t.id,o=v.working===t.id,i="applied"===n||"done"===n?x.closing:x.other,a="";"applied"!==n&&"done"!==n||(a=" biq-card--applied"),r&&(a+=" biq-card--active"),o&&(a+=" biq-card--working");var l="";"applied"===n?l='<span class="biq-card__status" data-i18n="biq.undo">'+SKT("biq.undo")+"</span>":"done"===n&&(l='<span class="biq-card__status" data-i18n="biq.applied">'+SKT("biq.applied")+"</span>");var s="applied"===n||"done"===n?"biq.aria_applied_card":"biq.aria_pending_card",c=e.escapeHtml(String(t.titel)+". "+SKT(s)),d=t.beskrivelse?'<span class="biq-card__sub">'+e.escapeHtml(String(t.beskrivelse))+"</span>":"";return'<button type="button" class="biq-card'+a+'" data-idea-id="'+e.escapeHtml(t.id)+'" aria-label="'+c+'"'+(o?' aria-busy="true"':"")+'><span class="biq-card__icon" aria-hidden="true">'+i+'</span><span class="biq-card__text"><span class="biq-card__title">'+e.escapeHtml(String(t.titel))+"</span>"+d+"</span>"+l+"</button>"}function W(){var e=O();if(!e||!e.root)return"";for(var t=e.root.cloneNode(!0),n=t.querySelectorAll(".ql-cursor, .ql-clipboard, .ql-tooltip, .ql-ui"),r=0;r<n.length;r++)n[r].parentNode.removeChild(n[r]);return t.innerHTML}function J(e){var t=O();if(!t)return!1;var n=Math.max(0,t.getLength()-1);if(n>0&&t.deleteText(0,n,"user"),t.clipboard&&t.clipboard.dangerouslyPasteHTML)t.clipboard.dangerouslyPasteHTML(0,e,"user");else{var r=document.createElement("div");r.innerHTML=e,t.insertText(0,r.textContent||"","user")}return t.setSelection(Math.max(0,t.getLength()-1),0,"silent"),!0}function Z(e){var t=String(e||"");t=t.replace(/<(p|div|h[1-6]|li|blockquote|ul|ol|tr)\b[^>]*>/gi,"\n");var n=document.createElement("div");return n.innerHTML=t,(t=(t=(t=(t=(t=n.textContent||"").replace(/[\u200B-\u200D\uFEFF]/g,"")).replace(/[^\S\n]+/g," ")).replace(/ ?\n ?/g,"\n")).replace(/\n{3,}/g,"\n\n")).trim()}function Y(){var e=v.ideas||[];if(v.status={},e.length){var t=oe(),n=v.applied,r=!!n&&t===n.afterHash;n&&!r&&v.hash&&t===v.hash&&(v.applied=null,v.appliedIds={},n=null);for(var o=0;o<e.length;o++){var i=e[o].id;n&&r&&n.id===i?v.status[i]="applied":v.status[i]=v.appliedIds[i]?"done":"pending"}}}function Q(e){return v.status&&v.status[e]||"pending"}function X(e){var t=document.getElementById("biq-live");if(t){t.textContent="";var n=SKT(e);setTimeout(function(){t.textContent=n},30)}}function ee(t){if(v.gen=(v.gen||0)+1,S&&(clearTimeout(S),S=null),_){try{_.abort()}catch(e){}_=null}if(v.working=null,w){try{w.abort()}catch(e){}w=null}b&&(clearTimeout(b),b=null),y&&(y=!1,e.setEditorRobotLoading(!1));try{window.SSGhostPreview&&window.SSGhostPreview.isOpen&&window.SSGhostPreview.isOpen()&&window.SSGhostPreview.close()}catch(e){}re(!1);try{Xe()}catch(e){}if(v.active=null,"welcome"===t){v={version:2,hash:"",norm:"",ideas:null,applied:{},status:{},active:null,gen:v.gen};var n=document.getElementById("bedre-card-messages");return n&&n.querySelector("#bedre-card-inner")&&(n.innerHTML=ye(),ut(n)),te(),void function(){var e=document.getElementById("biq-run");if(e)try{e.focus()}catch(e){}}()}te()}function te(){var e=document.getElementById("biq-done");e&&e.removeAttribute("data-done")}function ne(e){var t=document.getElementById("bedre-card-messages");t&&v.ideas&&(t.innerHTML=G()),te(),e&&function(e){var t=document.querySelector('.biq-card[data-idea-id="'+e+'"]');if(t)try{t.focus()}catch(e){}}(e)}function re(e){var t=O();if(t){try{t.enable(!e)}catch(e){}try{(t.container.closest(".grammar-page")||document).querySelectorAll(".ql-toolbar, .skv2-action-controls").forEach(function(t){if(e){if(t.hasAttribute("inert"))return void(t.dataset.biqPriorInert="1");t.setAttribute("inert",""),t.dataset.biqInertOwner="1"}else{if(t.dataset.biqPriorInert)return void delete t.dataset.biqPriorInert;t.dataset.biqInertOwner&&(delete t.dataset.biqInertOwner,t.removeAttribute("inert"))}})}catch(e){}}}function oe(){return function(e){function t(e,t){return e<<t|e>>>32-t}for(var n=[],r=0;r<e.length;r++){var o=e.codePointAt(r);o>65535&&r++,o<128?n.push(o):o<2048?n.push(192|o>>6,128|63&o):o<65536?n.push(224|o>>12,128|o>>6&63,128|63&o):n.push(240|o>>18,128|o>>12&63,128|o>>6&63,128|63&o)}var i=8*n.length;for(n.push(128);n.length%64!=56;)n.push(0);for(var a=56;a>=0;a-=8)n.push((a>=32?Math.floor(i/4294967296):i)>>>a%32&255);for(var l=1732584193,s=4023233417,c=2562383102,d=271733878,u=3285377520,p=new Array(80),m=0;m<n.length;m+=64){for(var f=0;f<16;
3f++)p[f]=n[m+4*f]<<24|n[m+4*f+1]<<16|n[m+4*f+2]<<8|n[m+4*f+3];for(f=16;f<80;f++)p[f]=t(p[f-3]^p[f-8]^p[f-14]^p[f-16],1);var g=l,h=s,v=c,y=d,w=u;for(f=0;f<80;f++){var b,k;f<20?(b=h&v|~h&y,k=1518500249):f<40?(b=h^v^y,k=1859775393):f<60?(b=h&v|h&y|v&y,k=2400959708):(b=h^v^y,k=3395469782);var S=t(g,5)+b+w+k+p[f]|0;w=y,y=v,v=t(h,30),h=g,g=S}l=l+g|0,s=s+h|0,c=c+v|0,d=d+y|0,u=u+w|0}function x(e){return("00000000"+(e>>>0).toString(16)).slice(-8)}return x(l)+x(s)+x(c)+x(d)+x(u)}(Z(W()))}function ie(e){for(var t=[],n=String(e||"").trim().split(/\s+/),r=0;r<n.length;r++)n[r]&&L.test(n[r])&&t.push(n[r]);return t.join(" ")}function ae(e){for(var t=Array.prototype.slice.call(e.childNodes),n=0;n<t.length;n++){var r=t[n];if(3!==r.nodeType)if(1===r.nodeType){var o=r.tagName;if(T[o]){for(var i=T[o],a=Array.prototype.slice.call(r.attributes),l=0;l<a.length;l++){var s=a[l].name.toLowerCase();if(-1!==i.indexOf(s))if("href"!==s||/^\s*(https?:|mailto:|tel:|#|\/)/i.test(a[l].value||"")){if("class"===s){var c=ie(a[l].value);c?r.setAttribute("class",c):r.removeAttribute(a[l].name)}}else r.removeAttribute(a[l].name);else r.removeAttribute(a[l].name)}ae(r)}else{if(E[o]){e.removeChild(r);continue}for(ae(r);r.firstChild;)e.insertBefore(r.firstChild,r);e.removeChild(r)}}else e.removeChild(r)}}function le(e){for(var t=Array.prototype.slice.call(e.querySelectorAll("ol, ul")),n=0;n<t.length;n++){var r=t[n];if(r.parentNode){var o="OL"===r.tagName?"ordered":"bullet",i=r.getAttribute("data-checked");"true"===i?o="checked":"false"===i&&(o="unchecked");for(var a=[],l=Array.prototype.slice.call(r.childNodes),s=0;s<l.length;s++){var c=l[s];if(1===c.nodeType&&"LI"===c.tagName){var d=c.getAttribute("data-list");-1===["ordered","bullet","checked","unchecked"].indexOf(d)&&(d=o),c.removeAttribute("data-list"),a.length&&a[a.length-1].kind===d||a.push({kind:d,items:[]}),a[a.length-1].items.push(c)}}if(a.length){for(var u=0;u<a.length;u++){var p=document.createElement("ordered"===a[u].kind?"ol":"ul");"checked"===a[u].kind?p.setAttribute("data-checked","true"):"unchecked"===a[u].kind&&p.setAttribute("data-checked","false");for(var m=0;m<a[u].items.length;m++)p.appendChild(a[u].items[m]);r.parentNode.insertBefore(p,r)}r.parentNode.removeChild(r)}}}}function se(e){var t=document.createElement("div");return t.innerHTML=String(e||""),ae(t),le(t),t.innerHTML.trim()}function ce(t){var n=String(t||"");if(/<(p|div|h[1-6]|ul|ol|li|blockquote|strong|b|em|i|u|s|a|br|table)\b/i.test(String(n||""))){var r=se(n);if(r&&""!==r.replace(/<[^>]*>/g,"").trim())return r}return function(t){for(var n=e.escapeHtml,r=String(t||"").replace(/\r\n/g,"\n").trim().split(/\n{2,}/),o="",i=0;i<r.length;i++){var a=r[i].split("\n");if(a.length>0&&a.every(function(e){return/^\s*-\s+/.test(e)||""===e.trim()})){o+="<ul>";for(var l=0;l<a.length;l++){var s=a[l].replace(/^\s*-\s+/,"").trim();s&&(o+="<li>"+n(s)+"</li>")}o+="</ul>"}else o+="<p>"+a.map(function(e){return n(e)}).join("<br>")+"</p>"}return o||"<p></p>"}(n)}function de(e,t){var n=O();if(n){var r=n.root.innerHTML;J(ce(t))&&(v.applied={id:e.id,snapshotHtml:r,afterHash:oe()},v.appliedIds[e.id]=!0,Y(),ne(e.id),X("biq.aria_applied"))}}function ue(e){var t=O(),n=v.applied;t&&n&&n.id===e.id&&(Y(),"applied"===Q(e.id)?J(n.snapshotHtml)&&(delete v.appliedIds[n.id],v.applied=null,Y(),ne(e.id),X("biq.aria_undone")):ne(e.id))}function pe(e){var t=window.SkrivebordApp;if(t&&"function"==typeof t.countWords)return t.countWords(e);var n=String(e||"").trim();return n?n.split(/\s+/).length:0}function me(e){return pe(Z(e))}function fe(e){var t=window.SkrivebordApp;if(t&&"function"==typeof t.setWordCountOverride)try{t.setWordCountOverride(e)}catch(e){}}function ge(){C&&document.removeEventListener("click",C,!0),C=null}function he(e,t){var n=O();if(n){var r,o,i=(r=W(),(o=document.createElement("div")).innerHTML=String(r||""),le(o),o.innerHTML),a=ce(t),l={before:pe(n.getText()),after:me(a)},s=window.SSGhostPreview;if(s&&"function"==typeof s.open&&n.container){var c=!1;try{c=s.open({host:n.container,originalHtml:i,proposedHtml:a,t:SKT,onOpenChange:function(t){var n;re(t),fe(t?l.after:null),t?(n=l,ge(),C=function(e){var t=e.target,r=t&&t.closest?t.closest("[data-ghost-mode]"):null;r&&fe("before"===r.getAttribute("data-ghost-mode")?n.before:n.after)},document.addEventListener("click",C,!0)):ge(),t||v.active!==e.id||(v.active=null,ne(e.id))},onModeChange:function(e){fe("before"===e?l.before:l.after)},onApply:function(){de(e,t)}})}catch(e){c=!1}if(c){v.active=e.id;try{var d=getComputedStyle(n.root);n.container.style.setProperty("--ss-ghost-pad",d.padding);var u=n.root.querySelector("p, li, h1, h2, h3")||n.root,p=getComputedStyle(u);
3n.container.style.setProperty("--biq-ghost-fs",p.fontSize),n.container.style.setProperty("--biq-ghost-lh",p.lineHeight)}catch(e){}return void ne(e.id)}}Ze(i,a,{footerAction:{label:SKT("ea.ghost_apply"),onClick:function(){de(e,t)}}})}}function ve(){if(!y&&!r){var t=O();if(t){var n=W(),o=Math.max(0,t.getLength()-1),i=t.getText(0,o).trim();if(i)if(F())ut();else{ee("overlays"),y=!0;var a=v.gen;v={version:2,hash:"",norm:"",ideas:null,applied:{},status:{},active:null,gen:a},e.setEditorRobotLoading(!0);var l=document.getElementById("bedre-card-messages");l&&function(e){e.innerHTML='<div class="ai-empty-state ai-completion-state" role="status" aria-live="polite" aria-busy="true"><div class="ss-chip-wait"><div class="ss-chip-wait-row"><div class="ai-loading-icon" aria-hidden="true">'+A+'</div><span class="ss-chip-wait-text"><span class="ai-empty-headline" data-i18n="biq.loading1">'+SKT("biq.loading1")+'</span><span class="calm-loading-sub" data-i18n="biq.loading2">'+SKT("biq.loading2")+'</span></span></div><div class="ss-chip-wait-track" aria-hidden="true"><span class="ss-chip-wait-shimmer"></span></div></div><button type="button" class="ai-empty-btn ai-cancel-btn" id="biq-cancel-btn" tabindex="-1" aria-label="'+(SKT("ai.cancel_aria")||"")+'">'+SKT("ai.cancel_request")+"</button></div>"}(l),te();var s=new AbortController;w=s,b=setTimeout(function(){w===s&&(ee("welcome"),Be(SKT("bedre.error")))},k),z().then(function(e){return fetch("/api/grammar-bot.php?action=bedre-ideas",{method:"POST",headers:e,body:JSON.stringify({text:i,html:n,language:$()}),signal:s.signal})}).then(function(e){if((429===e.status||413===e.status)&&window.SSWordLimit){var t=413===e.status&&window.__SS_PUBLIC_MODE?{silent:!0}:void 0;return window.SSWordLimit.handleResponse(e,t).then(function(e){if(e)throw window.SSWordLimit.createError(e);throw new Error("Server error")})}if(!e.ok)throw new Error("Server error");return e.json()}).then(function(t){if(w===s&&v.gen===a)if(y=!1,w=null,b&&(clearTimeout(b),b=null),e.setEditorRobotLoading(!1),!t.error&&t&&1==(0|t.v5)&&"[object Array]"===Object.prototype.toString.call(t.retninger)){v={version:5,hash:String(t.text_hash||""),analyse:t.analyse||null,ideas:t.retninger,rewrites:{},applied:null,appliedIds:{},status:{},active:null,gen:a},Y();var n=document.getElementById("bedre-card-messages");n&&(n.innerHTML=G()),te(),X(v.ideas.length?"biq.aria_results":"biq.aria_no_results"),v.ideas.length||(S&&clearTimeout(S),S=setTimeout(function(){S=null,document.querySelector("#bedre-card-messages .biq-empty")&&ct()},3500))}else Be(SKT("bedre.error"))}).catch(function(t){var n=w===s&&v.gen===a;if(n&&(y=!1,w=null,b&&(clearTimeout(b),b=null),e.setEditorRobotLoading(!1)),"AbortError"!==t.name&&n)t.wordLimitExceeded||"word_limit_exceeded"===t.message?ct():Be(SKT("bedre.error"));else{var r=document.getElementById("bedre-card-messages");n&&r&&r.querySelector(".ss-chip-wait")&&(r.innerHTML=ye(),te())}})}}}}function ye(){return t=("undefined"!=typeof location&&location.hostname||"").toLowerCase(),-1!==h.indexOf(t)?v.ideas?G():function(){var t=F(),n=R()||t?' disabled aria-disabled="true"':' aria-disabled="false"',r=t?'<div class="biq-subline biq-limit-note" role="status">'+e.escapeHtml(String(SKT("biq.too_long")).replace("{count}",String(j().length)))+"</div>":"";return['<div id="bedre-card-inner" class="bedre-card-inner">','<button type="button" class="biq-chip" id="biq-run" data-bedre-requires-text="true"'+n+">",'<span class="biq-chip__icon" aria-hidden="true">'+A+"</span>",'<span class="biq-chip__text">','<span class="biq-chip__title" data-i18n="biq.title">'+SKT("biq.title")+"</span>",'<span class="biq-chip__sub" data-i18n="biq.sub">'+SKT("biq.sub")+"</span>","</span>",'<span class="biq-chip__chevron" aria-hidden="true">'+q+"</span>","</button>",r,"</div>"].join("")}():['<div id="bedre-card-inner" class="bedre-card-inner">','<button type="button" class="bedre-card__run" id="bedre-run" data-bedre-requires-text="true"'+(R()?' disabled aria-disabled="true"':' aria-disabled="false"')+">",'<span class="bedre-card__run-icon" aria-hidden="true">'+A+"</span>",'<span class="bedre-card__run-text">','<span class="bedre-card__run-title" data-i18n="bedre.improve_all">'+SKT("bedre.improve_all")+"</span>",'<span class="bedre-card__run-sub" data-i18n="bedre.improve_all_sub">'+SKT("bedre.improve_all_sub")+"</span>","</span>",'<span class="bedre-card__run-chevron" aria-hidden="true">'+q+"</span>","</button>",'<div class="bedre-card__divider" role="separator" aria-orientation="horizontal"><span data-i18n="bedre.or_focus">'+SKT("bedre.or_focus")+"</span></div>",'<div class="bedre-card__choices" role="radiogroup" aria-label="Forbedringsfokus">',we("precise","bedre.focus_precise","bedre.focus_precise_desc"),we("clarity","bedre.focus_clarity","bedre.focus_clarity_desc"),we("flow","bedre.focus_flow","bedre.focus_flow_desc"),"</div>","</div>"].join("");var t}function we(e,t,r){return'<button type="button" class="bedre-choice" role="radio" aria-checked="'+(n===e)+'" data-focus="'+e+'"><span class="bedre-choice__icon" aria-hidden="true">'+(M[e]||"")+'</span><span class="bedre-choice__text"><span class="bedre-choice__title" data-i18n="'+t+'">'+SKT(t)+'</span><span class="bedre-choice__hint" data-i18n="'+r+'">'+SKT(r)+"</span></span></button>"}function be(t){t.innerHTML=['<div class="ai-card ai-card--sidebar" id="bedre-card">','<div class="ai-card-header">','<button class="ai-new-chat-btn" id="bedre-new-chat" type="button" data-i18n-title="chip.back_to_options" title="'+SKT("chip.back_to_options")+'" data-i18n-aria-label="chip.back_to_options" aria-label="'+SKT("chip.back_to_options")+'">','<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false">
3<path d="M15 18l-6-6 6-6"/><path d="M9 12h10"/></svg>','<span class="ai-new-chat-label" data-i18n="tone.back">'+SKT("tone.back")+"</span>","</button>","</div>",'<div id="bedre-card-messages" class="ai-card-messages">',ye(),"</div>",'<div class="ai-card-input-row" id="bedre-input-row">','<div class="calm-review-footer-host biq-review-footer" id="biq-footer">','<button type="button" class="calm-footer-accept-all" id="biq-done" data-i18n="biq.done">'+SKT("biq.done")+"</button>","</div>",'<div class="ai-card-input-wrap">','<textarea id="bedre-card-input" class="ai-card-input" data-i18n-placeholder="ai.placeholder.default" placeholder="'+SKT("ai.placeholder.default")+'" data-i18n-aria-label="ai.placeholder.default" aria-label="'+SKT("ai.placeholder.default")+'" autocomplete="off" rows="1"></textarea>','<button type="button" class="ai-card-mic ss-mic" id="bedre-card-mic" data-i18n-title="stt.dictate" title="'+SKT("stt.dictate")+'" data-i18n-aria-label="stt.dictateAi" aria-label="'+SKT("stt.dictateAi")+'">','<svg viewBox="0 0 24 24"><path d="M12 23V20M12 20C9.87827 20 7.84344 19.1571 6.34315 17.6569C4.84285 16.1566 4 14.1217 4 12M12 20C14.1217 20 16.1566 19.1571 17.6569 17.6569C19.1571 16.1566 20 14.1217 20 12M12 17C9.25 17 7 14.828 7 12.172V5.828C7 3.172 9.25 1 12 1C14.75 1 17 3.172 17 5.828V12.172C17 14.828 14.75 17 12 17Z"/></svg>',"</button>",'<button type="button" class="ai-card-send" id="bedre-card-send" data-i18n-title="action.send" title="'+SKT("action.send")+'" data-i18n-aria-label="action.send" aria-label="'+SKT("action.send")+'">','<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><line x1="12" y1="20" x2="12" y2="5"></line><polyline points="6 11 12 5 18 11"></polyline></svg>',"</button>","</div>","</div>","</div>"].join(""),function(t){if(!t)return;t.addEventListener("click",function(e){var o=e.target.closest("#biq-run");if(o){if(o.disabled||"true"===o.getAttribute("aria-disabled"))return;ve()}else{if(e.target.closest("#biq-cancel-btn"))Se();else if(e.target.closest("#biq-done"))ee("welcome");else{var i=e.target.closest(".biq-card");if(i){for(var a=i.getAttribute("data-idea-id"),l=null,s=0;s<(v.ideas||[]).length;s++)if(v.ideas[s].id===a){l=v.ideas[s];break}if(!l)return;return Y(),"applied"===Q(a)?void ue(l):void function(e){var t=O();if(t&&!r&&!y&&!v.working)if(Y(),"applied"!==Q(e.id)){var n=e.id+"@"+oe(),o=v.rewrites[n];if(o)he(e,o);else{v.working=e.id,ne(e.id);var i=v.gen,a=new AbortController;_=a;var l=setTimeout(function(){if(_===a){try{a.abort()}catch(e){}_=null,v.gen===i&&(v.working=null,ne(e.id),Be(SKT("bedre.error")))}},k);z().then(function(n){var r=Math.max(0,t.getLength()-1);return fetch("/api/grammar-bot.php?action=bedre-apply",{method:"POST",headers:n,body:JSON.stringify({text:t.getText(0,r),html:W(),language:$(),analyse:v.analyse||{},retning:{titel:e.titel,beskrivelse:e.beskrivelse,hvorfor:e.hvorfor,brief:e.brief}}),signal:a.signal})}).then(function(e){if((429===e.status||413===e.status)&&window.SSWordLimit)return window.SSWordLimit.handleResponse(e).then(function(e){if(e)throw window.SSWordLimit.createError(e);throw new Error("Server error")});if(!e.ok)throw new Error("Server error");return e.json()}).then(function(t){if(_===a&&v.gen===i){if(_=null,clearTimeout(l),v.working=null,!t||1!=(0|t.v5)||!t.rewrite)return ne(e.id),void Be(SKT("bedre.error"));v.rewrites[n]=String(t.rewrite_html||t.rewrite),ne(e.id),he(e,v.rewrites[n])}}).catch(function(t){_===a&&v.gen===i&&(_=null,clearTimeout(l),v.working=null,ne(e.id),t&&"AbortError"===t.name||(!t||!t.wordLimitExceeded&&"word_limit_exceeded"!==t.message?Be(SKT("bedre.error")):ct()))})}}else ue(e)}(l)}var c=e.target.closest("#bedre-run");if(c){if(c.disabled||"true"===c.getAttribute("aria-disabled"))return;ke(n||"auto","")}else{var d=e.target.closest(".bedre-choice");if(d){var u=d.getAttribute("data-focus");return n=n===u?null:u,t.querySelectorAll(".bedre-choice").forEach(function(e){e.setAttribute("aria-checked",e.getAttribute("data-focus")===n?"true":"false")}),void(n&&!R()&&ke(n,""))}}}}}),t.querySelector("#bedre-card-send").addEventListener("click",function(){var e=t.querySelector("#bedre-card-input");e&&e.value.trim()&&(dt(e.value.trim()),e.value="","TEXTAREA"===e.tagName&&(e.style.height="auto",e.style.overflowY="hidden"))});var o=t.querySelector("#bedre-card-input");o&&"TEXTAREA"===o.tagName&&o.addEventListener("input",function(){this.style.height="auto";var e=120,t=Math.min(this.scrollHeight,e);this.style.height=t+"px",this.style.overflowY=this.scrollHeight>e?"auto":"hidden"});var i=t.querySelector("#bedre-card-send");function a(){if(i&&o){var e=o.value.trim().length>0;i.disabled=!e,i.style.opacity=e?"":"0.3"}}a(),o.addEventListener("input",a),o.addEventListener("keydown",function(e){if("Enter"===e.key&&!e.shiftKey&&this.value.trim())return e.preventDefault(),dt(this.value.trim()),this.value="",this.style.height="auto",this.style.overflowY="hidden",void a();var t=this;setTimeout(function(){t.style.height="auto";var e=120,n=Math.min(t.scrollHeight,e);t.style.height=n+"px",t.style.overflowY=t.scrollHeight>e?"auto":"hidden"},0)});var l=t.querySelector("#bedre-card-mic");l&&l.addEventListener("click",function(){e.toggleStt({buttonId:"bedre-card-mic",inputId:"bedre-card-input"})});var s=t.querySelector("#bedre-new-chat");s&&s.addEventListener("click",function(){ct()})}(t.querySelector("#bedre-card")),te()}function ke(t,n){if(!r){var p=U();if(p.text){st(),o=t||"auto",i=n||"",s=null,c="";var m=O();if(m){try{a=m.getSemanticHTML(0,m.getLength())}catch(e){a=""}l=p.selection?{index:p.selection.index,length:p.selection.length}:null}r=!0,e.setEditorRobotLoading(!0),qe();var f=document.getElementById("bedre-card-messages");
3f&&(f.innerHTML='<div class="ai-loading" role="status" aria-live="polite" aria-atomic="true"><div class="ai-loading-icon" aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"><path class="bulb-base" d="M9 18h6"></path><path class="bulb-base" d="M10 22h4"></path><path class="bulb-glass" d="M12 2a7 7 0 0 0-4 12.7V17h8v-2.3A7 7 0 0 0 12 2z"></path></svg></div><div class="ai-loading-text"><div class="ai-loading-title" data-i18n="bedre.loading.title">'+SKT("bedre.loading.title")+'</div><div class="ai-loading-subtitle" data-i18n="bedre.loading.step1">'+SKT("bedre.loading.step1")+"</div></div></div>",function(){qe();var e=0;d=setInterval(function(){var t=document.querySelector("#bedre-card-messages .ai-loading-subtitle");t?(t.classList.add("is-swapping"),u=setTimeout(function(){e=(e+1)%K.length;var n=K[e];t.textContent=SKT(n),t.setAttribute("data-i18n",n),t.classList.remove("is-swapping"),u=null},350)):qe()},2400)}());var g={text:p.text,html:p.html,language:$(),focus:t||"auto",instruction:n||""};p.selection&&(g.selection={index:p.selection.index,length:p.selection.length});var h=new AbortController;I=h,z().then(function(e){return fetch("/api/grammar-bot.php?action=bedre-improve",{method:"POST",headers:e,body:JSON.stringify(g),signal:h.signal})}).then(function(e){if((429===e.status||413===e.status)&&window.SSWordLimit){var t=413===e.status&&window.__SS_PUBLIC_MODE?{silent:!0}:void 0;return window.SSWordLimit.handleResponse(e,t).then(function(e){if(e)throw window.SSWordLimit.createError(e);throw new Error("Server error")})}if(!e.ok)throw new Error("Server error");return e.json()}).then(function(t){if(I===h){if(r=!1,I=null,e.setEditorRobotLoading(!1),"word_limit_exceeded"===t.error)return qe(),window.SSWordLimit?window.SSWordLimit.show({data:t}):window._showWordLimitModal&&window._showWordLimitModal(t.used,t.limit||15e3,t.reset_date||null),void ct();if(t.error)Be(SKT("bedre.error"));else{var n=t.improved_text||t.data&&t.data.improved_text||"";if(n){var o=function(e){if("undefined"==typeof document)return String(e||"").replace(/<[^>]*>/g,"");var t=document.createElement("div");return t.innerHTML=String(e||""),t.textContent||t.innerText||""}(n);e.hasForeignScript(o,p.text)?Be(SKT("bedre.error_foreign_script")):(s=t.summary||null,function(e,t){var n=O();if(!n)return;if(t)n.deleteText(t.index,t.length,"user"),n.clipboard.dangerouslyPasteHTML(t.index,e,"user");else{var r=n.getLength();n.deleteText(0,r,"user"),n.clipboard.dangerouslyPasteHTML(0,e,"user")}}(n,p.selection),function(){qe();var t=document.getElementById("bedre-card-messages");if(!t)return;var n=document.getElementById("bedre-card");n&&n.classList.add("bedre-state-result");var r=document.getElementById("bedre-new-chat");r&&r.classList.remove("visible");var o=function(e){if(e&&e.explanation)return String(e.explanation).trim();var t=e&&e.problem?e.problem:SKT("bedre.result.summary.fallback_problem"),n=e&&e.change?e.change:SKT("bedre.result.summary.fallback_change");return t+" "+n}(s);c=o||"",document.body.classList.add("ws-bedre-decision"),t.innerHTML='<div class="bedre-result-wrap">'+Me({escapeHtml:e.escapeHtml,iconSvg:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',titleAttrs:' data-i18n="bedre.result.title"',titleText:SKT("bedre.result.title"),undoAttrs:' id="bedre-undo" data-i18n="bedre.result.undo"',undoText:SKT("bedre.result.undo"),acceptAttrs:' id="bedre-done" data-i18n="bedre.result.keep"',acceptText:SKT("bedre.result.keep"),showCompare:!!a,compareAttrs:' id="ws-compare-btn"',compareText:" Sammenlign",hasSummary:!!o,summaryText:o,summaryPlayAttrs:' id="bedre-summary-play"',ttsPlayLabel:SKT("bedre.result.tts_play"),summaryLabelHtml:'<span class="ws-summary-label">Hør resumé</span>',dividerAttrs:' data-i18n="bedre.result.adjust"',dividerText:SKT("bedre.result.adjust"),rerunAttrs:' id="bedre-rerun"',rerunTitleAttrs:' data-i18n="bedre.result.rerun.title"',rerunTitleText:SKT("bedre.result.rerun.title"),rerunHintAttrs:' data-i18n="bedre.result.rerun.hint"',rerunHintText:SKT("bedre.result.rerun.hint"),changeAttrs:' id="bedre-change-focus"',changeTitleAttrs:' data-i18n="bedre.result.change_focus.title"',changeTitleText:SKT("bedre.result.change_focus.title"),changeHintAttrs:' data-i18n="bedre.result.change_focus.hint"',changeHintText:SKT("bedre.result.change_focus.hint")})+"</div>",i=t,Ie(i,{undo:"bedre-undo",accept:"bedre-done",compareBtn:"ws-compare-btn",rerun:"bedre-rerun",changeFocus:"bedre-change-focus",summaryPlay:"bedre-summary-play"},{onUndo:Ke,onKeep:De,onCompare:Je,onRerun:Pe,onChangeFocus:Ne,onToggleTts:at}),mt(),setTimeout(function(){var e=document.getElementById("bedre-panel");document.body.classList.contains("ws-bedre-decision")&&et(e)&&mt()}
3,0);var i}())}else Be(SKT("bedre.no_result"))}}}).catch(function(t){var n=I===h;n&&(r=!1,I=null,e.setEditorRobotLoading(!1),qe()),"AbortError"!==t.name&&n&&(t.wordLimitExceeded||"word_limit_exceeded"===t.message?ct():Be(SKT("bedre.error")))})}}}function Se(){if(I){try{I.abort()}catch(e){}I=null}ee("overlays"),r=!1,qe(),e.setEditorRobotLoading(!1);var t=document.getElementById("bedre-card-messages");t&&t.querySelector(".ai-loading, .ss-chip-wait")&&(t.innerHTML=ye(),te(),ut(t))}function xe(e,t){return!(!e||!t)&&(!/[\s\n]$/.test(e)&&!/^[\s\n]/.test(t)&&(!/^[,.;:!?%)]/.test(t)&&(!/[\[(]$/.test(e)&&(!/\d\.$/.test(e)||!/^\d/.test(t)))))}function Te(e){if(3===e.nodeType)return e.nodeValue||"";if(1!==e.nodeType)return"";if("BR"===e.tagName)return"\n";for(var t="",n=e.childNodes,r=0;r<n.length;r++){var o=Te(n[r]);o&&("BR"!==n[r].tagName&&xe(t,o)&&(t+=" "),t+=o)}return t}function Le(e,t){if(t=t||{},3===e.nodeType){var n=e.nodeValue||"";return n?[{text:n,fmt:t}]:[]}if(1!==e.nodeType)return[];if("BR"===e.tagName)return[{text:"\n",fmt:{}}];var r={};for(var o in t)t.hasOwnProperty(o)&&(r[o]=t[o]);var i=H[e.tagName];if(i&&(r[i]=!0),"A"===e.tagName){var a=Fe(e.getAttribute("href"));a&&(r.link=a)}for(var l=[],s="",c=e.childNodes,d=0;d<c.length;d++){var u=Le(c[d],r);if(u.length){for(var p="",m=0;m<u.length;m++)p+=u[m].text;if(p){"BR"!==c[d].tagName&&xe(s,p)&&(l.push({text:" ",fmt:u[0].fmt}),s+=" ");for(var f=0;f<u.length;f++)l.push(u[f]);s+=p}}}return l}function Ee(e,t){for(var n=["bold","italic","underline","strike","code","link"],r=0;r<n.length;r++)if((e[n[r]]||!1)!==(t[n[r]]||!1))return!1;return!0}function Ce(e){if(!e||!e.length)return[];for(var t=[],n=0;n<e.length;n++){var r=e[n].text.replace(/[^\S\n]+/g," ");r&&t.push({text:r,fmt:e[n].fmt})}for(var o=[],i=0;i<t.length;i++)o.length>0&&Ee(o[o.length-1].fmt,t[i].fmt)?o[o.length-1]={text:o[o.length-1].text+t[i].text,fmt:o[o.length-1].fmt}:o.push({text:t[i].text,fmt:t[i].fmt});if(o.length>0&&(o[0]={text:o[0].text.replace(/^\s+/,""),fmt:o[0].fmt},o[0].text||o.shift()),o.length>0){var a=o.length-1;o[a]={text:o[a].text.replace(/\s+$/,""),fmt:o[a].fmt},o[a].text||o.pop()}return o.filter(function(e){return e.text.length>0})}function _e(e){for(var t="",n=0;n<e.length;n++)t+=e[n].text;return t}function Ae(e){var t=String(e||"");if(!t.trim())return[];if("undefined"==typeof document)return t.replace(/<br\s*\/?>/gi,"\n").replace(/<\/?(p|h[1-6]|li|blockquote|div|ul|ol)[^>]*>/gi,"\n").replace(/<[^>]*>/g," ").replace(/ {2,}/g," ").split(/\n+/).filter(function(e){return e.trim().length>0}).map(function(e){return{tag:"p",text:e.trim()}});var n=document.createElement("div");n.innerHTML=t;var r=[],o=0;function i(e){var t=e.replace(/[^\S\n]+/g," ").trim();t&&r.push({tag:"p",text:t})}if(function e(t,n){for(var a=t.childNodes,l="",s=0;s<a.length;s++){var c=a[s];if(3===c.nodeType){var d=c.textContent||"";xe(l,d)&&(l+=" "),l+=d}else if(1===c.nodeType){var u=c.tagName;if("BR"===u)i(l),l="";else if(B[u]){i(l),l="";var p=Le(c,{}),m=_e(p).replace(/[^\S\n]+/g," ").trim();if(m){var f={tag:u.toLowerCase(),text:m,runs:Ce(p),listType:n||null};"ol"===n&&(o++,f.listIndex=o),r.push(f)}}else if("UL"===u||"OL"===u)i(l),l="","OL"===u&&(o=0),e(c,u.toLowerCase());else{var g=Te(c);xe(l,g)&&(l+=" "),l+=g}}}i(l)}(n,null),0===r.length){var a=Te(n).replace(/[^\S\n]+/g," ").trim();a&&r.push({tag:"p",text:a})}return r}function qe(){d&&(clearInterval(d),d=null),u&&(clearTimeout(u),u=null);var e=document.querySelector("#bedre-card-messages .ai-loading-subtitle");e&&e.classList.remove("is-swapping")}function Me(e){var t=(e=e||{}).escapeHtml||function(e){return e},n=e.showCompare?'<button type="button" class="ws-compare-btn"'+(e.compareAttrs||"")+'><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="12" y1="3" x2="12" y2="21"/></svg>'+(e.compareText||"")+"</button>":"",r="";if(e.hasSummary){var o=e.summarySvgAriaHidden?' aria-hidden="true"':"",i=e.summaryPlayAriaPressed?' aria-pressed="false"':"";r='<div class="bedre-result-summary"><button type="button" class="bedre-result-summary__play"'+(e.summaryPlayAttrs||"")+' data-state="idle"'+i+' aria-label="'+(e.ttsPlayLabel||"")+'" title="'+(e.ttsPlayLabel||"")+'"><svg class="bedre-tts-ring" viewBox="0 0 48 48"'+o+'><circle cx="24" cy="24" r="22" fill="none" stroke-width="2.5" opacity="0.15"/><circle class="bedre-tts-ring__progress" cx="24" cy="24" r="22" fill="none" stroke-width="2.5" stroke-dasharray="138.23" stroke-dashoffset="138.23" transform="rotate(-90 24 24)"/></svg>
3<svg class="bedre-tts-icon-play" viewBox="0 0 24 24" fill="currentColor"'+o+'><polygon points="6,3 20,12 6,21"/></svg><svg class="bedre-tts-icon-pause" viewBox="0 0 24 24" fill="currentColor"'+o+' style="display:none"><rect x="5" y="3" width="4" height="18"/><rect x="15" y="3" width="4" height="18"/></svg></button>'+(e.summaryLabelHtml||"")+'<span class="bedre-result-summary__text">'+t(e.summaryText||"")+"</span>"+(e.summaryLiveRegionHtml||"")+"</div>"}return'<div class="bedre-result-head"><div class="bedre-result-icon">'+(e.iconSvg||"")+'</div><h3 class="bedre-result-title"'+(e.titleAttrs||"")+">"+(e.titleText||"")+"</h3></div>"+(e.extraHeadRow||"")+'<div class="bedre-result-decisions"><button type="button" class="bedre-result-undo"'+(e.undoAttrs||"")+'><svg class="ws-btn-icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2 6h8a4 4 0 0 1 0 8H7"/><polyline points="5 3 2 6 5 9"/></svg>'+(e.undoText||"")+'</button><button type="button" class="bedre-result-accept"'+(e.acceptAttrs||"")+'><svg class="ws-btn-icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="3 8.5 6.5 11.5 13 4.5"/></svg>'+(e.acceptText||"")+"</button></div>"+n+r+'<div class="bedre-result-divider" role="separator"><span'+(e.dividerAttrs||"")+">"+(e.dividerText||"")+'</span></div><button type="button" class="bedre-result-adjust-card"'+(e.rerunAttrs||"")+'><span class="bedre-result-adjust-card__title"'+(e.rerunTitleAttrs||"")+">"+(e.rerunTitleText||"")+'</span><span class="bedre-result-adjust-card__hint"'+(e.rerunHintAttrs||"")+">"+(e.rerunHintText||"")+'</span></button><button type="button" class="bedre-result-adjust-card"'+(e.changeAttrs||"")+'><span class="bedre-result-adjust-card__title"'+(e.changeTitleAttrs||"")+">"+(e.changeTitleText||"")+'</span><span class="bedre-result-adjust-card__hint"'+(e.changeHintAttrs||"")+">"+(e.changeHintText||"")+"</span></button>"}function Ie(e,t,n){if(e&&(n=n||{},i((t=t||{}).undo,n.onUndo),i(t.accept,n.onKeep),i(t.compareBtn,n.onCompare),i(t.rerun,n.onRerun),i(t.changeFocus,n.onChangeFocus),t.summaryPlay&&"function"==typeof n.onToggleTts)){var r=e.querySelector("#"+t.summaryPlay);r&&r.addEventListener("click",function(){n.onToggleTts(r)});var o=e.querySelector(".ws-summary-label");o&&o.addEventListener("click",function(){var r=e.querySelector("#"+t.summaryPlay);r&&n.onToggleTts(r)})}function i(t,n){if(t&&"function"==typeof n){var r=e.querySelector("#"+t);r&&r.addEventListener("click",n)}}}function Be(t){qe(),document.body.classList.remove("ws-bedre-decision"),Xe();var n=document.getElementById("bedre-card-messages");if(n){n.innerHTML='<div class="bedre-result-wrap"><div class="bedre-result-title">'+e.escapeHtml(t)+'</div><button type="button" class="bedre-card__run bedre-card__reset" id="bedre-reset">'+SKT("bedre.reset")+"</button></div>";var r=n.querySelector("#bedre-reset");r&&r.addEventListener("click",ct)}}function He(){st(),document.body.classList.remove("ws-bedre-decision"),Xe();var e=document.getElementById("bedre-card");e&&e.classList.remove("bedre-state-result")}function Ke(){He();var e=O();if(a&&e){var t=e.getLength();if(e.deleteText(0,t,"silent"),e.clipboard.dangerouslyPasteHTML(0,a,"silent"),l)try{e.setSelection(l.index,l.length,"silent")}catch(e){}}else e&&void 0!==e.history&&"function"==typeof e.history.undo&&e.history.undo();a="",s=null,c="",l=null,ct()}function De(){He(),a="",s=null,c="",l=null,ct()}function Pe(){He(),ct(),ke(o,i)}function Ne(){He(),n=null,ct()}function je(e){return String(e||"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function Re(e){return String(e||"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Fe(e){var t=String(e||"").trim();if(!t)return"";var n=t.replace(/[\u0000-\u001F\u007F\s]+/g,"").toLowerCase();return/^[a-z][a-z0-9+.-]*:/.test(n)&&!/^(https?:|mailto:|tel:)/.test(t.toLowerCase())||0===t.indexOf("//")||/[\u0000-\u001F\u007F<>"']/.test(t)?"":t}function Oe(e,t){if(!e||!e.length)return{};for(var n=0,r=0;r<e.length;r++){if(t<n+e[r].text.length)return e[r].fmt;n+=e[r].text.length}return e[e.length-1].fmt}function Ue(e,t){if(!function(e){if(!e)return!1;for(var t in e)if(e.hasOwnProperty(t)&&e[t])return!0;return!1}(t))return e;var n=e;if(t.code&&(n="<code>"+n+"</code>"),t.strike&&(n="<s>"+n+"</s>"),t.underline&&(n="<u>"+n+"</u>"),t.italic&&(n="<em>"+n+"</em>"),t.bold&&(n="<strong>"+n+"</strong>"),t.link){var r=Fe(t.link);r&&(n='<a href="'+Re(r)+'" target="_blank" rel="noopener noreferrer">'+n+"</a>")}return n}function $e(e,t){if(!e||!e.length)return je(t||"");for(var n="",r=0;r<e.length;r++)n+=Ue(je(e[r].text),e[r].fmt);return n}
3function ze(e){for(var t,n=[],r=/(\S+|[^\S\n]+|\n)/g;null!==(t=r.exec(e));)n.push(t[0]);return n}function Ge(e,t,n,r,o){if(!e&&!t)return{html:"",count:0};if(e===t)return{html:$e(o,t),count:0};var i=ze(e),a=ze(t),l=i.length,s=a.length;if(l*s>5e5)return{html:$e(o,t),count:0};var c,d,u=[];for(c=0;c<=l;c++)for(u[c]=new Array(s+1),d=0;d<=s;d++)0===c||0===d?u[c][d]=0:i[c-1]===a[d-1]?u[c][d]=u[c-1][d-1]+1:u[c][d]=Math.max(u[c-1][d],u[c][d-1]);for(var p=[],m=l,f=s;m>0||f>0;)m>0&&f>0&&i[m-1]===a[f-1]?(p.unshift({t:"eq",v:i[m-1]}),m--,f--):f>0&&(0===m||u[m][f-1]>=u[m-1][f])?(p.unshift({t:"ins",v:a[f-1]}),f--):(p.unshift({t:"del",v:i[m-1]}),m--);for(var g=[],h=!1,v=0;v<p.length;v++){var y=p[v];"eq"===y.t||/^\s+$/.test(y.v)||(h=!0);var w=g.length?g[g.length-1]:null;w&&w.t===y.t&&"eq"!==y.t?w.v+=y.v:g.push({t:y.t,v:y.v})}p=g;for(var b="",k=(Number(n)||0)-1,S=0,x=!1,T=0,L=0,E=0;E<p.length;E++){var C=p[E];if("eq"===C.t){x=!1;var _=je(C.v);o&&!/^\s+$/.test(C.v)&&(_=Ue(_,Oe(o,L))),b+=_,T+=C.v.length,L+=C.v.length}else{if(h&&/^\s+$/.test(C.v)){"ins"===C.t&&(b+=je(C.v)),"del"===C.t?T+=C.v.length:L+=C.v.length;continue}x||(k++,S++,x=!0);var A="del"===C.t?"del":"ins",q=je(C.v);if(!/^\s+$/.test(C.v)){var M="del"===C.t?r:o,I="del"===C.t?T:L;M&&(q=Ue(q,Oe(M,I)))}b+="<"+A+' class="ws-change" data-change="'+k+'">'+q+"</"+A+">","del"===C.t?T+=C.v.length:L+=C.v.length}}return{html:b,count:S}}function Ve(e,t){var n=e&&e.tag||"p",r="ws-diff-block",o="p",i="";if(/^h[1-6]$/.test(n))o="div",r+=" ws-diff-heading ws-diff-"+n,i=' role="heading" aria-level="'+n.charAt(1)+'"';else if("li"===n){o="div",r+=" "+("ol"===e.listType?"ws-diff-li ws-diff-li--ol":"ws-diff-li"),"ol"===e.listType&&"number"==typeof e.listIndex&&(i=' data-list-index="'+e.listIndex+'"')}else"blockquote"===n&&(o="blockquote",r+=" ws-diff-blockquote");return"<"+o+' class="'+r+'"'+i+">"+t+"</"+o+">"}function We(e,t){if(!e.length&&!t.length)return{html:"",count:0};var n=e.length,r=t.length;if(0===n){for(var o="",i=0,a=0;a<r;a++)o+=Ve(t[a],'<ins class="ws-change" data-change="'+i+'">'+$e(t[a].runs,t[a].text)+"</ins>"),i++;return{html:o,count:i}}if(0===r){for(var l="",s=0,c=0;c<n;c++)l+=Ve(e[c],'<del class="ws-change" data-change="'+s+'">'+$e(e[c].runs,e[c].text)+"</del>"),s++;return{html:l,count:s}}var d=n*r<=1e4;function u(e){var t,n=String(null==e?"":e).toLowerCase().split(/\s+/),r=Object.create(null),o=0;for(t=0;t<n.length;t++)n[t]&&(r[n[t]]=(r[n[t]]||0)+1,o++);return{c:r,len:o}}var p,m=null,f=null;if(d){for(m=new Array(n),f=new Array(r),p=0;p<n;p++)m[p]=u(e[p].text);for(p=0;p<r;p++)f[p]=u(t[p].text)}function g(e,t){if(!d)return 1;var n=m[e],r=f[t];if(!n.len&&!r.len)return.001;if(!n.len||!r.len)return 1;var o,i=n.len<=r.len?n.c:r.c,a=n.len<=r.len?r.c:n.c,l=0;for(o in i)a[o]&&(l+=i[o]<a[o]?i[o]:a[o]);return Math.max(.001,1-2*l/(n.len+r.len))}var h,v,y=[],w=[];for(h=0;h<=n;h++)y[h]=new Array(r+1),w[h]=new Array(r+1);for(y[0][0]=0,w[0][0]="stop",v=1;v<=r;v++)y[0][v]=v,w[0][v]="ins";for(h=1;h<=n;h++)y[h][0]=h,w[h][0]="del";for(h=1;h<=n;h++)for(v=1;v<=r;v++){var b=e[h-1].text===t[v-1].text,k=b?0:g(h-1,v-1),S=y[h-1][v-1]+k,x=y[h-1][v]+1,T=y[h][v-1]+1,L=S,E=b?"eq":"mod";x<L&&(L=x,E="del"),T<L&&(L=T,E="ins"),y[h][v]=L,w[h][v]=E}for(var C=[],_=n,A=r;_>0||A>0;){var q=_>0&&A>0?w[_][A]:_>0?"del":"ins";"eq"===q?(C.unshift({t:"eq",before:e[_-1],after:t[A-1]}),_--,A--):"mod"===q?(C.unshift({t:"mod",before:e[_-1],after:t[A-1]}),_--,A--):"del"===q?(C.unshift({t:"del",before:e[_-1]}),_--):(C.unshift({t:"ins",after:t[A-1]}),A--)}for(var M="",I=0,B=0;B<C.length;B++){if("eq"===(E=C[B]).t)M+=Ve(E.after,$e(E.after.runs,E.after.text));else if("del"===E.t)M+=Ve(E.before,'<del class="ws-change" data-change="'+I+'">'+$e(E.before.runs,E.before.text)+"</del>"),I++;else if("ins"===E.t)M+=Ve(E.after,'<ins class="ws-change" data-change="'+I+'">'+$e(E.after.runs,E.after.text)+"</ins>"),I++;else if("mod"===E.t){var H=Ge(E.before.text,E.after.text,I,E.before.runs,E.after.runs);M+=Ve(E.after,H.html),I+=H.count}}return{html:M,count:I}}function Je(){var e=O(),t="";if(e)try{t=e.getSemanticHTML(0,e.getLength())}catch(e){t=""}Qe(We(Ae(a||""),Ae(t)),{returnFocusId:"ws-compare-btn"})}function Ze(e,t,n){Qe(We(Ae(e||""),Ae(t||"")),n||{})}function Ye(e,t){try{if("function"==typeof SKT){var n=SKT(e);if(n&&n!==e)return n}}catch(e){}return t}function Qe(e,t){Xe();var n=(t=t||{}).returnFocusId||"ws-compare-btn",r=e.count,o=1===r?Ye("compare.changes_one","{n} ændring"):Ye("compare.changes_other","{n} ændringer"),i=String(o).split("{n}").join("<strong>"+r+"</strong>"),a=0===r?" disabled":"",l=t.footerAction&&t.footerAction.label?t.footerAction:null,s=l?'<div class="ws-compare-footer"><button type="button" class="ws-compare-apply">'+je(l.label)+"</button></div>":"",c=document.createElement("div");c.id="ws-compare-modal",c.setAttribute("role","dialog"),c.setAttribute("aria-modal","true"),c.setAttribute("aria-labelledby","ws-compare-title"),c.setAttribute("data-return-focus",n),c.innerHTML='<div class="ws-compare-backdrop"></div><div class="ws-compare-dialog"><div class="ws-compare-header"><div><h3 id="ws-compare-title" data-i18n="compare.title">'+je(Ye("compare.title","Sammenlign"))+'</h3><div class="ws-compare-subtitle">'+i+'</div></div><button type="button" class="ws-compare-close" data-i18n-aria-label="compare.close" aria-label="'+Re(Ye("compare.close","Luk"))+'">×</button></div><div class="ws-compare-toolbar"><div class="ws-compare-legend"><span class="ws-compare-legend__del" data-i18n="compare.removed">'+je(Ye("compare.removed","Fjernet"))+'</span><span class="ws-compare-legend__ins" data-i18n="compare.added">'+je(Ye("compare.added","Tilføjet"))+'</span></div><div class="ws-compare-nav"><button type="button" class="ws-compare-prev" data-i18n-aria-label="compare.prev" aria-label="'+Re(Ye("compare.prev","Forrige ændring"))+'"'+a+'><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="10 12 6 8 10 4"/></svg></button><span class="ws-compare-count">â / '+r+'</span><button type="button" class="ws-compare-next" data-i18n-aria-label="compare.next" aria-label="'+Re(Ye("compare.next","Næste ændring"))+'"'+a+'><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="6 4 10 8 6 12"/></svg></button></div></div><div class="ws-compare-body"><div class="ws-diff">'+e.html+"</div></div>"+s+"</div>",document.body.appendChild(c);var d=c.querySelector(".ws-compare-dialog"),u=c.querySelector(".ws-compare-close");u.focus();var p=c.querySelector(".ws-compare-apply");p&&l&&"function"==typeof l.onClick&&p.addEventListener("click",function(){Xe();try{l.onClick()}catch(e){}});var m=-1;function f(e){if(0!==r){for(var t=c.querySelectorAll(".ws-change--active"),n=0;n<t.length;n++)t[n].classList.remove("ws-change--active");m="next"===e?m<r-1?m+1:0:m>0?m-1:r-1;for(var o=c.querySelectorAll('[data-change="'+m+'"]'),i=0;i<o.length;i++)o[i].classList.add("ws-change--active");o[0]&&o[0].scrollIntoView({behavior:"smooth",block:"center"});var a=c.querySelector(".ws-compare-count");a&&(a.textContent=m+1+" / "+r)}}var g=c.querySelector(".ws-compare-prev"),h=c.querySelector(".ws-compare-next");g&&g.addEventListener("click",function(){f("prev")}),h&&h.addEventListener("click",function(){f("next")}),r>0&&f("next"),u.addEventListener("click",Xe),c.querySelector(".ws-compare-backdrop").addEventListener("click",Xe),c.addEventListener("keydown",function(e){if("Escape"===e.key)return e.preventDefault(),void Xe();if("ArrowDown"===e.key||"j"===e.key||"n"===e.key)return e.preventDefault(),void f("next");if("ArrowUp"===e.key||"k"===e.key||"p"===e.key)return e.preventDefault(),void f("prev");if("Tab"===e.key){var t=d.querySelectorAll('button:not(:disabled), [href], input, select, textarea, [tabindex]:not
3([tabindex="-1"])');if(!t.length)return;var n=t[0],r=t[t.length-1];e.shiftKey?document.activeElement===n&&(e.preventDefault(),r.focus()):document.activeElement===r&&(e.preventDefault(),n.focus())}})}function Xe(){var e=document.getElementById("ws-compare-modal");if(e){var t=e.getAttribute("data-return-focus")||"ws-compare-btn";e.parentNode&&e.parentNode.removeChild(e);var n=document.getElementById(t);n&&n.focus()}}function et(e){return!(!e||!e.querySelector(".bedre-result-decisions"))}function tt(){var e="da-DK";try{window.getCurrentUILang&&(e=window.getCurrentUILang()||"da-DK")}catch(e){}if(window.TTSEngine&&"function"==typeof window.TTSEngine.normalizeLanguage)return window.TTSEngine.normalizeLanguage(e,"Danish");return{da:"Danish","da-DK":"Danish",en:"English","en-US":"English",de:"German","de-DE":"German",fr:"French","fr-FR":"French",es:"Spanish","es-ES":"Spanish",sv:"Swedish","sv-SE":"Swedish"}[e]||"Danish"}function nt(){try{return"male"===(localStorage.getItem("ss_tts_voice")||"female")?"Male":"Female"}catch(e){return"Female"}}function rt(){try{var e=localStorage.getItem("ss_tts_voice_variant")||"";if("mads"===e||"lars"===e||"anders"===e||"sofie"===e||"freja"===e||"ida"===e)return e}catch(e){}return"Male"===nt()?"mads":"sofie"}function ot(e,t){if(e){e.setAttribute("data-state",t),e.setAttribute("aria-busy","loading"===t?"true":"false");var n=e.querySelector(".bedre-tts-icon-play"),r=e.querySelector(".bedre-tts-icon-pause");"playing"===t?(n&&(n.style.display="none"),r&&(r.style.display="")):"loading"===t?(n&&(n.style.display="none"),r&&(r.style.display="none")):(n&&(n.style.display=""),r&&(r.style.display="none")),"loading"===t?(e.setAttribute("aria-label",SKT("bedre.result.tts_stop")),e.setAttribute("title",SKT("bedre.result.tts_stop"))):"playing"===t?(e.setAttribute("aria-label",SKT("bedre.result.tts_pause")),e.setAttribute("title",SKT("bedre.result.tts_pause"))):(e.setAttribute("aria-label",SKT("bedre.result.tts_play")),e.setAttribute("title",SKT("bedre.result.tts_play")))}}function it(e){var t=e?e.querySelector(".bedre-tts-ring__progress"):null;t&&t.setAttribute("stroke-dashoffset","138.23")}function at(e){if(e){var t=e.getAttribute("data-state")||"idle";if("loading"!==t)if("playing"!==t)if("paused"!==t){var n=c||SKT("bedre.result.summary."+(o||"auto"));if(n){var r=e.closest(".bedre-result-summary");r&&r.classList.add("ws-expanded"),document.dispatchEvent(new Event("skrivebord:tts-stop-all"));var i=++m;ot(e,"loading"),Promise.resolve(function(e,t,n){if(!window.TTSEngine||"function"!=typeof window.TTSEngine.create)throw new Error("TTSEngine unavailable");var r=window.TTSEngine.create({fetchChunk:lt,gender:nt(),onStateChange:function(t){n===m&&("loading"===t&&ot(e,"loading"),"playing"===t&&ot(e,"playing"),"paused"===t&&ot(e,"paused"),"buffering"===t&&ot(e,"playing"),"complete"===t&&function(e,t){if(t&&p===t&&"function"==typeof t.revokeAll)try{t.revokeAll()}catch(e){}p===t&&(p=null);e&&(ot(e,"idle"),it(e))}(e,r),"error"!==t||f||st())},onProgress:function(t){if(n===m){var r=Math.max(1,t.chunkTotal||1),o=t.duration>0?t.currentTime/t.duration:0;!function(e,t){var n=e?e.querySelector(".bedre-tts-ring__progress"):null;if(n){var r=138.23;n.setAttribute("stroke-dashoffset",String(r-r*t))}}(e,(t.chunkIndex+o)/r)}},onTelemetry:function(e){"function"==typeof ss_track&&ss_track("bedre_summary_tts_"+e.event,{chunks:e.totalChunks,retries:e.retries,underruns:e.underruns,avg_latency_ms:e.avgLatencyMs,elapsed_ms:e.elapsedMs,surface:"skrivebord_bedre_summary"})}});p=r,"function"==typeof r.setVolume&&r.setVolume(function(){try{if("number"==typeof window.__SKRIVEBORD_TTS_VOLUME__)return Math.max(0,Math.min(1,window.__SKRIVEBORD_TTS_VOLUME__));var e=localStorage.getItem("skrivebord.tts.volume");if(null!==e&&""!==e){var t=parseFloat(e);if(Number.isFinite(t))return t>1&&t<=100&&(t/=100),Math.max(0,Math.min(1,t))}}catch(e){}return.6}());"function"==typeof r.setPlaybackRate&&r.setPlaybackRate(function(){try{if("function"==typeof window.getPlaybackSpeed){var e=parseFloat(window.getPlaybackSpeed());if(Number.isFinite(e)&&e>0)return e}var t=parseFloat(localStorage.getItem("ss_tts_speed")||"1");if(Number.isFinite(t)&&t>0)return t}catch(e){}return 1}());return r.start(t,{lang:tt(),minWords:18,maxChars:700}),null}(e,n,i)).catch(function(){i===m&&st()})}}else p&&"function"==typeof p.resume&&p.resume();else p&&"function"==typeof p.pause?p.pause():ot(e,"paused");else st()}}function lt(e,t,n,r){return window.TTSEngine&&"function"==typeof window.TTSEngine.fetchAudio?window.TTSEngine.fetchAudio({text:e,lang:t||tt(),gender:n||nt(),voice:rt(),quality:"premium",endpoint:window.HGF_ajax_object&&window.HGF_ajax_object.ajax_url||window.ajaxurl||"/robots/skrivebord/grammar-api.php",action:"hgf_important_secure_bots_text_to_speech",signal:r||null,maxLength:1e3}).then(function(e){return{audioUrl:e}}):Promise.reject(new Error("TTSEngine unavailable"))}function st(){if(!f){if(f=!0,m++,p){try{p.stop()}catch(e){}p=null}var e=document.getElementById("bedre-summary-play");e&&(ot(e,"idle"),it(e)),f=!1}}function ct(){qe(),st(),document.body.classList.remove("ws-bedre-decision"),Xe(),e.aiHistory([]),e.clearChatStorage(),e.chipInFlight(!1),e.cancelAiPanelConversation&&e.cancelAiPanelConversation(g);var t=document.getElementById("bedre-card");t&&t.classList.remove("bedre-state-result");var r=document.getElementById("bedre-new-chat");r&&r.classList.remove("visible"),n=null,ee("welcome");var o=document.getElementById("bedre-card-messages");o&&(o.innerHTML=ye(),ut(o));var i=document.getElementById("bedre-card-input");i&&(i.value="",i.style.height="auto",i.style.overflowY="hidden"),e.syncAiConversationChrome&&e.syncAiConversationChrome()}function dt(t){var n=String(t||"").trim();if(!n)return!1;qe(),st(),document.body.classList.remove("ws-bedre-decision"),Xe();var r=document.getElementById("bedre-card");r&&r.classList.remove("bedre-state-result");var o=document.getElementById("bedre-new-chat");o&&o.classList.add("visible"),e.syncAiConversationChrome&&e.syncAiConversationChrome();try{return e.handleAiSend(n,null,0,g),!0}catch(t){return console.error("Bedre chat send error:",t),e.chipInFlight(!1),o&&o.classList.remove("visible"),!1}}function ut(e){var t=e||document,n=F(),r=R()||n;t.querySelectorAll('[data-bedre-requires-text="true"]').forEach(function(e){e.disabled=r,e.setAttribute("aria-disabled",r?"true":"false")});var o=document.getElementById("bedre-card-inner");if(o&&!o.classList.contains("biq-list")){var i=o.querySelector(".biq-limit-note");if(n){var a=String(SKT("biq.too_long")).replace("{count}",String(j().length));i||((i=document.createElement("div")).className="biq-subline biq-limit-note",i.setAttribute("role","status"),o.appendChild(i)),i.textContent!==a&&(i.textContent=a)}else i&&i.remove()}}
3function pt(){if(!D){if(window.quill1&&"function"==typeof window.quill1.on)return window.quill1.on("text-change",function(){ut()}),void(D=!0);var e=document.querySelector(".ql-editor");e&&(e.addEventListener("input",function(){ut()}),D=!0)}}function mt(){document.querySelectorAll(".hk-dropdown-option").forEach(function(e){e.classList.remove("active")});var n=document.getElementById("option-bedre");n&&n.classList.add("active"),e.hideCorrectionPopup(),(e.correctionMode()||e.hasCorrectionMap())&&e.saveCorrections(),e.hideMarks("ai"),e.hideMarks("tone");[".improv-inner",".correction-inner",".style-inner",".voice-section","#chat-view","#ai-panel","#tone-panel"].forEach(function(e){var t=document.querySelector(e);t&&(t.style.display="none")});var r=document.getElementById("bedre-panel");r&&(r.style.display="flex"),et(r)&&document.body.classList.add("ws-bedre-decision");var o=document.getElementById("chat-reset-link");o&&(o.style.display="none"),e.aiIsOpen(!1),t=!0}function ft(){var e=document.getElementById("bedre-panel");if(!e){(e=document.createElement("div")).id="bedre-panel",e.className="ai-panel-inner",e.style.display="flex";var n=document.querySelector(".correction-sidebar")||document.querySelector(".sidebar-controls");n?n.appendChild(e):document.body.appendChild(e)}mt(),e.querySelector("#bedre-card")||(be(e),t=!0),pt(),ut(e)}function gt(){P&&clearTimeout(P),P=setTimeout(function(){P=null;var e=window.SKT&&window.SKT.lang?window.SKT.lang():null;if(!e||e!==N){N=e;var t=document.querySelector("#bedre-card-messages #bedre-card-inner");t&&(t.outerHTML=ye(),pt(),ut(),te())}},0)}}();var sh=window.SkrivebordApp=window.SkrivebordApp||{};document.addEventListener("DOMContentLoaded",function(){var e=new URLSearchParams(window.location.search),t=e.get("tool"),n={chat:"/chat"};if(t&&n[t])window.location.href=n[t];else{var r=e.get("doc");sh.waitForQuill().then(function(t){if(t){var n=t.keyboard.bindings[" "]?" ":32,o=t.keyboard.bindings[n];o&&(t.keyboard.bindings[n]=o.filter(function(e){return!(e.prefix&&e.handler&&e.format&&("list"in e.format||"code-block"in e.format))}));var i="chat"===e.get("from"),a=!1;if(i)try{var l=localStorage.getItem("ss-workshop-transfer");if(l){var s=JSON.parse(l);s.html&&s.ts&&Date.now()-s.ts<6e4&&(t.setText("","silent"),t.clipboard.dangerouslyPasteHTML(0,s.html,"silent"),a=!0),localStorage.removeItem("ss-workshop-transfer")}}catch(e){console.warn("Workshop transfer failed:",e)}sh.initToolbar(t);var c=!!document.getElementById("sk-doc-browser");a||c&&!r&&!i||sh.initDocumentPersistence(r,t)}else console.warn("Editor init failed")})}});const ch="skrivsikkert_recent_docs",dh=120,uh=["Skole","Arbejde","Personlig","Projekt","Andet"],ph="https://www.googleapis.com/auth/drive.file",mh="gdocs_status_v2";let fh=[],gh=12,hh="",vh=null,yh=!1,wh=!1,bh="newest",kh="all",Sh=null,xh=new Set,Th=-1,Lh=null,Eh=null,Ch=null,_h=null,Ah=-1,qh=null,Mh=null,Ih=null,Bh=null,Hh=null,Kh=null,Dh=null,Ph=null,Nh=null,jh=!1,Rh=!1,Fh=!1,Oh=0,Uh={},$h=null,zh=null,Gh=null,Vh=null,Wh=null,Jh=null,Zh=null,Yh=null,Qh=null,Xh=null,ev=null,tv=null;function nv(e){if(!e)return"";if("undefined"==typeof document)return String(e).replace(/<style[\s\S]*?<\/style>/gi," ").replace(/<script[\s\S]*?<\/script>/gi," ").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim();var t=document.createElement("div");return t.innerHTML=(e||"").replace(/<\/(?:p|div|h[1-6]|li|blockquote|pre|tr|td)>|<br\s*\/?>/gi,"$& "),(t.textContent||t.innerText||"").replace(/\s+/g," ").trim()}function rv(e){var t=null==e?"":String(e);if("undefined"==typeof document)return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");var n=document.createElement("div");return n.textContent=t,n.innerHTML}function ov(e){var t=nv(e&&e.content?e.content:""),n="function"==typeof SKT?SKT("toolbar.untitled"):"Unavngivet dokument",r=(e&&e.title?e.title:"").trim()||n,o=Array.isArray(e&&e.tags)?e.tags.filter(Boolean):[];return{id:e?e.id:"",title:r,preview:t.substring(0,dh),_plainForSnippet:t.substring(0,500),aiSummary:e&&e.ai_summary?e.ai_summary:null,contentHash:e&&e.content_hash?e.content_hash:null,wordCount:e&&e.word_count?e.word_count:0,createdAt:e?e.created_at:null,updatedAt:e?e.updated_at:null,isPinned:e&&!0===e.is_pinned,tags:o,isPdf:!(!e||"pdf"!==e.doc_type||!e.storage_path),storagePath:e&&e.storage_path?e.storage_path:null,pageCount:e&&e.page_count?e.page_count:0,_searchText:(r+" "+t.substring(0,500)+" "+o.join(" ")).toLowerCase()}}function iv(e){var t={};
3return(e||[]).forEach(function(e){(Array.isArray(e.tags)?e.tags:[]).forEach(function(e){var n=String(e||"").trim();n&&(t[n]=!0)})}),Object.keys(t).sort(function(e,t){return e.localeCompare(t,"da",{sensitivity:"base"})})}function av(e,t,n){var r=n||{},o=(t||"").trim().toLowerCase(),i=(e||[]).slice();return o&&(i=i.filter(function(e){return-1!==(e._searchText||"").indexOf(o)})),r.hideStaleEmpty&&(i=i.filter(function(e){return!function(e,t){return!!e&&!e.isPinned&&!(e.wordCount>0)&&!String(e.preview||e._plainForSnippet||"").trim()&&(t||new Date)-new Date(e.updatedAt||e.createdAt||0)>=36e5}(e,r.nowDate)})),"pinned"===r.activeFilter&&(i=i.filter(function(e){return e.isPinned})),r.activeTag&&(i=i.filter(function(e){return Array.isArray(e.tags)&&-1!==e.tags.indexOf(r.activeTag)})),"name-asc"===r.currentSort?i.sort(function(e,t){return(e.title||"").localeCompare(t.title||"","da",{sensitivity:"base"})}):"name-desc"===r.currentSort&&i.sort(function(e,t){return(t.title||"").localeCompare(e.title||"","da",{sensitivity:"base"})}),i}function lv(e,t){if(!e)return"";var n=new Date(e),r=new Date-n,o=Math.floor(r/6e4),i=Math.floor(r/36e5),a=Math.floor(r/864e5);return o<1?SKT("doc.relNow"):o<60?SKT("doc.relMinAgo",{n:o}):i<24?SKT("doc.relHoursAgo",{n:i}):a<7?SKT("doc.relDaysAgo",{n:a}):n.toLocaleDateString("da-DK",{day:"numeric",month:"short"})}function sv(e){return"/skrivebord/?doc="+encodeURIComponent(e)}function cv(){return window.SkrivebordApp||window.app||{}}function dv(){return(window.SkrivebordApp||{})._apiClient}function uv(){return $h=document.getElementById("sk-doc-browser"),zh=document.getElementById("sk-doc-list"),Gh=document.getElementById("sk-doc-empty"),Vh=document.getElementById("sk-doc-search"),Wh=document.getElementById("sk-doc-filters"),Jh=document.getElementById("sk-doc-load-more"),Zh=document.getElementById("sk-doc-new-btn"),Yh=document.getElementById("sk-doc-gdocs-btn"),Qh=document.getElementById("sk-doc-selection-bar"),Xh=document.querySelector(".robot-container"),ev=document.querySelector(".bb-skrivebord"),tv=function(){var e=document.getElementById("sk-edit-toolbar");e&&e.parentElement!==document.body&&document.body.appendChild(e);return e}(),!(!$h||!zh)}let pv=null;function mv(e){pv=e,ev&&(ev.classList.toggle("sk-doc-browser-mode","browser"===e),ev.classList.toggle("sk-doc-editor-mode","editor"===e))}function fv(){try{var e=localStorage.getItem("sb-skrivsikkert-auth");if(!e)return null;var t=JSON.parse(e);return t&&t.currentSession&&(t=t.currentSession),t&&t.user&&t.user.id?t.user:null}catch(e){return null}}var gv=null;async function hv(){try{if(window.currentUser&&window.currentUser.id)return window.currentUser;if(window._session&&window._session.user&&window._session.user.id)return window._session.user;var e=fv();if(e)return e;if(await(t=5e3,window.currentUser&&window.currentUser.id||fv()?Promise.resolve(!0):window.SSGrammarAuth&&"function"==typeof window.SSGrammarAuth.waitForAuthReady?window.SSGrammarAuth.waitForAuthReady(t):new Promise(function(e){var n=!1,r=setTimeout(function(){n||(n=!0,window.removeEventListener("auth-ready",o),e(!(!window.currentUser||!window.currentUser.id)||!!fv()))},t);function o(){n||(n=!0,clearTimeout(r),window.removeEventListener("auth-ready",o),e(!0))}window.addEventListener("auth-ready",o,{once:!0})})),window.currentUser&&window.currentUser.id)return window.currentUser;if(e=fv())return e;if(window._supabase&&window._supabase.auth&&"function"==typeof window._supabase.auth.getUser)return gv||(gv=window._supabase.auth.getUser().then(function(e){return e&&e.data&&e.data.user?e.data.user:null}).catch(function(){return null}).finally(function(){setTimeout(function(){gv=null},1e3)})),await gv}catch(e){console.warn("[sk-doc-browser] user lookup failed:",e)}var t;return null}async function vv(){var e=await hv();return e&&e.id?e.id:null}async function yv(){var e=function(){try{var e=localStorage.getItem("sb-skrivsikkert-auth");if(!e)return null;var t=JSON.parse(e);return t&&t.currentSession&&(t=t.currentSession),t&&t.access_token?t:null}catch(e){return null}}();if(e&&e.access_token)return e.access_token;if(window.SSGrammarAuth&&"function"==typeof window.SSGrammarAuth.getAuthToken)return await window.SSGrammarAuth.getAuthToken();if(window.SSGrammarAuth&&"function"==typeof window.SSGrammarAuth.getAuthTokenSync){var t=window.SSGrammarAuth.getAuthTokenSync();if(t)return t}return null}async function wv(){if(!yh){if(yh=!0,function(){for(var e="",t=0;t<6;t++)e+='<div class="sk-doc-skeleton" aria-hidden="true"><div class="sk-doc-skeleton-title"></div><div class="sk-doc-skeleton-text"></div><div class="sk-doc-skeleton-meta"></div></div>';zh.innerHTML=e}(),!await async function(e){for(var t=e,n=Date.now();!window._supabase&&Date.now()-n<t;)await new Promise(function(e){setTimeout(e,200)});return!!window._supabase}(8e3))return Lv(SKT("doc.loadError")),void(yh=!1);var e,t=await hv();if(!t||!t.id)return Lv(SKT("doc.authError")),void(yh=!1);try{var n="id, title, content, word_count, created_at, updated_at, deleted_at, is_pinned, tags",r=n+", doc_type, storage_path, page_count",o=function(e){return dv().list(t.id,e)},i=await o(r);if(i.error&&(i=await o(n)),i.error)throw i.error;e=i.data||[],fh=(e||[]).map(ov)}catch(e){console.error("[sk-doc-browser] load error:",e),Lv(SKT("doc.fetchError"))}yh=!1,kv()}}function bv(){return av(fh,hh,{activeFilter:kh,activeTag:Sh,currentSort:bh,hideStaleEmpty:!hh&&"all"===kh&&!Sh})}function kv(){var e=bv();if(function(){if(!Wh)return;var e=iv(fh);
3Sh&&-1===e.indexOf(Sh)&&(e=[Sh].concat(e));var t='<div class="sk-doc-filter-pills" role="group" aria-label="'+rv(SKT("doc.filterDocs"))+'">';t+=Tv(SKT("doc.filterAll"),"all","all"===kh&&!Sh),t+=Tv(SKT("doc.filterFavorites"),"pinned","pinned"===kh),e.forEach(function(e){t+=Tv(e,"tag:"+e,Sh===e)}),t+="</div>",Wh.innerHTML=t}(),0===e.length)return zh.innerHTML="",Gh&&(Gh.style.display="",Gh.querySelector(".sk-doc-empty-text").textContent=fh.length?SKT("doc.searchEmpty"):SKT("doc.emptyTitle"),Gh.querySelector(".sk-doc-empty-hint").textContent=fh.length?SKT("doc.searchEmptyHint"):SKT("doc.emptyHint")),Jh&&(Jh.style.display="none"),void Hv();Gh&&(Gh.style.display="none");var t,n="";if(hh||"all"!==kh||Sh){var r=e.slice(0,gh);n+='<div class="sk-doc-group-header">'+rv((t=e.length,hh?SKT("doc.searchResults",{count:t}):"pinned"===kh?SKT("doc.favorites",{count:t}):Sh?Sh+" ("+t+")":SKT("doc.texts",{count:t})))+"</div>",r.forEach(function(e){n+=xv(e)}),Jh&&(Jh.style.display=r.length<e.length?"":"none")}else{var o=e.filter(function(e){return e.isPinned}),i=e.filter(function(e){return!e.isPinned}),a=0;o.length>0&&(n+='<div class="sk-doc-group-header">'+rv(SKT("doc.pinnedGroup",{count:o.length}))+"</div>",o.forEach(function(e){n+=xv(e)})),function(e){var t=new Date,n=new Date(t.getFullYear(),t.getMonth(),t.getDate()),r=new Date(n);r.setDate(n.getDate()-1);var o=new Date(n),i=n.getDay()||7;o.setDate(n.getDate()-i+1);var a=new Date(t.getFullYear(),t.getMonth(),1),l={today:{label:SKT("doc.groupToday"),docs:[]},yesterday:{label:SKT("doc.groupYesterday"),docs:[]},week:{label:SKT("doc.groupThisWeek"),docs:[]},month:{label:SKT("doc.groupThisMonth"),docs:[]},older:{label:SKT("doc.groupOlder"),docs:[]}};return(e||[]).forEach(function(e){var t=new Date(e.updatedAt||e.updated_at||e.createdAt||e.created_at||0);t>=n?l.today.docs.push(e):t>=r?l.yesterday.docs.push(e):t>=o?l.week.docs.push(e):t>=a?l.month.docs.push(e):l.older.docs.push(e)}),Object.keys(l).map(function(e){return l[e]}).filter(function(e){return e.docs.length>0})}(i).forEach(function(e){a>=gh||(n+='<div class="sk-doc-group-header">'+rv(e.label)+" ("+e.docs.length+")</div>",e.docs.forEach(function(e){a>=gh||(n+=xv(e),a++)}))}),Jh&&(Jh.style.display=a<i.length?"":"none")}zh.innerHTML=n}function Sv(e){if(hh){var t=function(e,t){if(!t||!e)return"";var n=t.toLowerCase(),r=e,o=r.toLowerCase().indexOf(n);if(-1===o)return r.substring(0,dh);var i=Math.max(0,o-40),a=Math.min(r.length,o+t.length+40),l="";return i>0&&(l+="â¦"),l+=r.substring(i,a),a<r.length&&(l+="â¦"),l}(e._plainForSnippet||e.preview,hh);if(t)return function(e,t){if(!t||!e)return rv(e||"");var n=rv(e),r=rv(t),o=new RegExp("("+r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+")","gi");return n.replace(o,'<mark class="sk-doc-match">$1</mark>')}(t,hh)}var n=e.aiSummary||e.preview,r=!e.aiSummary&&e.preview.length>=dh?"...":"";return rv(n)+r}function xv(e){var t=lv(e.updatedAt);e.preview.length;var n=xh.has(e.id);return'<article class="'+("sk-doc-card"+(e.isPinned?" sk-doc-card--pinned":"")+(e.isPdf?" sk-doc-card--pdf":"")+(n?" sk-doc-card--selected":""))+'" data-doc-id="'+rv(e.id)+'" role="listitem" tabindex="0" aria-label="'+rv(SKT("doc.openPrefix",{title:e.title}))+'"><button type="button" class="sk-doc-card-checkbox" data-sk-doc-action="select" role="checkbox" aria-checked="'+(n?"true":"false")+'" aria-label="'+rv(SKT("doc.selectPrefix",{title:e.title}))+'"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.5" aria-hidden="true"><polyline points="20 6 9 17 4 12"></polyline></svg></button><div class="sk-doc-card-top"><span class="sk-doc-card-title">'+(e.isPdf?'<span class="sk-doc-card-badge">PDF</span>':"")+rv(e.title)+'</span><button type="button" class="sk-doc-card-pin-btn" data-sk-doc-action="pin" aria-label="'+rv(e.isPinned?SKT("doc.removePinTitle"):SKT("doc.addPinTitle"))+'" aria-pressed="'+(e.isPinned?"true":"false")+'" title="'+rv(e.isPinned?SKT("doc.removePinTitle"):SKT("doc.addPinTitle"))+'"><svg class="sk-doc-card-pin" viewBox="0 0 24 24" width="16" height="16" fill="'+(e.isPinned?"currentColor":"none")+'" stroke="currentColor" stroke-width="1.7" stroke-linejoin="round" aria-hidden="true"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87L18.18 21 12 17.27 5.82 21 7 14.14 2 9.27l6.91-1.01L12 2z"></path></svg></button></div><p class="sk-doc-card-summary'+(hh?" sk-doc-card-summary--search":"")+'">'+Sv(e)+"</p>"+function(e){var t=Array.isArray(e.tags)?e.tags:[];if(!t.length)return"";var n=t.slice(0,3),r='<div class="sk-doc-tag-pills" aria-label="'+rv(SKT("doc.tagPillAria"))+'">';
3n.forEach(function(e){r+='<span class="sk-doc-tag-pill">'+rv(e)+"</span>"}),t.length>3&&(r+='<span class="sk-doc-tag-pill sk-doc-tag-pill--more">+'+rv(String(t.length-3))+"</span>");return r+="</div>"}(e)+'<div class="sk-doc-card-meta"><span>'+rv(t)+"</span><span>"+(e.isPdf&&e.pageCount?rv(String(e.pageCount))+" "+rv(SKT("doc.pagesUnit")):rv(String(e.wordCount))+" "+rv(SKT("doc.wordsUnit")))+"</span></div></article>"}function Tv(e,t,n){return'<button type="button" class="sk-doc-filter-pill'+(n?" sk-doc-filter-pill--active":"")+'" aria-pressed="'+(n?"true":"false")+'" data-filter="'+rv(t)+'">'+rv(e)+"</button>"}function Lv(e){zh.innerHTML='<div class="sk-doc-error">'+rv(e)+"</div>",Gh&&(Gh.style.display="none"),Jh&&(Jh.style.display="none")}function Ev(e,t){"undefined"!=typeof window&&"function"==typeof window.showToast?window.showToast(e,t||"info"):console.log("[sk-doc-browser]",t||"info",e)}function Cv(e){return fh.find(function(t){return t.id===e})||null}async function _v(e){var t=Cv(e);if(t){var n=t.isPinned;t.isPinned=!n,kv();try{var r=await vv();if(!r)throw new Error("missing-user");var o=await dv().update(e,r,{is_pinned:t.isPinned,updated_at:(new Date).toISOString()});if(o.error)throw o.error}catch(e){t.isPinned=n,kv(),console.error("[sk-doc-browser] pin failed:",e),Ev(SKT("doc.toastPinFail"),"error")}}}function Av(e,t){Mv();var n=Cv(e);if(n&&t){var r=Array.isArray(n.tags)?n.tags.slice():[],o=uh.concat(iv(fh).filter(function(e){return-1===uh.indexOf(e)})),i=document.createElement("div");i.className="sk-doc-tag-editor",i.setAttribute("role","dialog"),i.setAttribute("data-doc-id",e),i.setAttribute("aria-label",SKT("doc.tagEditorAria")),i.innerHTML='<div class="sk-doc-tag-editor-header"><span>'+rv(SKT("doc.tagEditorTitle"))+'</span><button type="button" class="sk-doc-tag-editor-close" aria-label="'+rv(SKT("doc.tagEditorClose"))+'">x</button></div><div class="sk-doc-tag-editor-list"></div><div class="sk-doc-tag-editor-input-wrap"><input type="text" class="sk-doc-tag-editor-input" placeholder="'+rv(SKT("doc.tagEditorPlaceholder"))+'" maxlength="30" aria-label="'+rv(SKT("doc.tagEditorAddTag"))+'"></div>';var a=i.querySelector(".sk-doc-tag-editor-list"),l=i.querySelector(".sk-doc-tag-editor-input");l.addEventListener("keydown",function(e){if("Enter"===e.key){e.preventDefault();var t=qv(l.value);if(!t||-1!==r.indexOf(t)||r.length>=10)return;r.push(t),-1===o.indexOf(t)&&o.push(t),l.value="",c(),s()}else"Escape"===e.key&&Mv()}),i.querySelector(".sk-doc-tag-editor-close").addEventListener("click",Mv),document.body.appendChild(i),qh=i,function(e,t){var n=t.getBoundingClientRect();e.style.position="fixed",e.style.left="0px",e.style.top="0px";var r=e.getBoundingClientRect(),o=8,i=n.left,a=n.bottom+6;i+r.width+o>window.innerWidth&&(i=n.right-r.width);i<o&&(i=o);a+r.height+o>window.innerHeight&&(a=n.top-r.height-6);a<o&&(a=o);e.style.left=Math.round(i)+"px",e.style.top=Math.round(a)+"px"}(i,t),c(),Mh=function(e){!qh||qh.contains(e.target)||t.contains(e.target)||Mv()},setTimeout(function(){document.addEventListener("click",Mh,!0)},0)}function s(){n.tags=r.slice(),kv(),function(e,t){Uh[e]&&clearTimeout(Uh[e]);Uh[e]=setTimeout(function(){(async function(e,t){var n=Cv(e);if(!n)return;var r=Array.isArray(n.tags)?n.tags.slice():[];n.tags=t.length?t.slice():[];try{var o=await vv();if(!o)throw new Error("missing-user");var i=await dv().update(e,o,{tags:t.length?t:null,updated_at:(new Date).toISOString()});if(i.error)throw i.error}catch(e){n.tags=r,kv(),console.error("[sk-doc-browser] tag save failed:",e),Ev(SKT("doc.toastTagFail"),"error")}})(e,t).finally(function(){delete Uh[e]})},400)}(e,r.slice())}function c(){a.textContent="",o.forEach(function(e){var t=-1!==r.indexOf(e),n=document.createElement("button");n.type="button",n.className="sk-doc-tag-option"+(t?" sk-doc-tag-option--active":""),n.textContent=e,n.setAttribute("aria-pressed",t?"true":"false"),n.addEventListener("click",function(n){n.stopPropagation(),t?r=r.filter(function(t){return t!==e}):r.length<10&&r.push(e),c(),s()}),a.appendChild(n)})}}function qv(e){var t=String(e||"").replace(/[<>"'&\x00-\x1f]/g,"").trim();return t?(t=t.substring(0,30)).charAt(0).toUpperCase()+t.slice(1):""}function Mv(){qh&&(qh.remove(),qh=null),Mh&&(document.removeEventListener("click",Mh,!0),Mh=null)}function Iv(e,t){var n=bv(),r=n.findIndex(function(t){return t.id===e});if(t&&t.shiftKey&&Th>=0&&r>=0)for(var o=Math.min(Th,r),i=Math.max(Th,r),a=o;a<=i;a++)xh.add(n[a].id);else xh.has(e)?xh.delete(e):xh.add(e);Th=r,Hv()}function Bv(){xh.clear(),Th=-1,Hv()}function Hv(){if(zh&&zh.classList.toggle("sk-doc-list--selecting",xh.size>0),Qh){Qh.style.display=xh.size?"":"none";var e=Qh.querySelector(".sk-doc-sel-count");e&&(e.textContent=SKT("doc.selectedCount",{count:xh.size}))}zh&&zh.querySelectorAll(".sk-doc-card").forEach(function(e){var t=e.getAttribute("data-doc-id"),n=xh.has(t);e.classList.toggle("sk-doc-card--selected",n);var r=e.querySelector(".sk-doc-card-checkbox");r&&r.setAttribute("aria-checked",n?"true":"false")})}async function Kv(){if(xh.size){var e=Array.from(xh),t=e.length,n=1===t?"":"er";if(await window.ssConfirm({title:SKT("doc.bulkDeleteTitle",{count:t,pl:n}),message:SKT("doc.bulkDeleteMsg",{count:t,pl:n}),okLabel:SKT("doc.bulkDeleteOk",{pl:n}),cancelLabel:SKT("doc.cancelLabel"),danger:!0}))try{var r=await vv();if(!r)throw new Error("missing-user");for(var o=(new Date).toISOString(),i=0;i<e.length;i++){var a=await dv().update(e[i],r,{deleted_at:o});if(a.error)throw a.error}fh=fh.filter(function(t){return-1===e.indexOf(t.id)}),Bv(),kv(),Ev(SKT("doc.textsDeleted"),"success")}catch(e){console.error("[sk-doc-browser] bulk delete failed:",e),Ev(SKT("doc.deleteError"),"error")}}}async function Dv(){for(var e=Array.from(xh),t=0;t<e.length;t++)await Gv(e[t])}function Pv(e,t,n){Nv();var r=n.getAttribute("data-doc-id"),o=Cv(r);
3if(o){var i=document.createElement("div");i.className="sk-doc-ctx-menu",i.setAttribute("role","menu"),i.setAttribute("aria-label",SKT("doc.actions"));var a='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>',l='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 01-2 2H5a2 2 0 01-2-2V8a2 2 0 012-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>',s='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>',c='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 11 12 14 22 4"/><path d="M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11"/></svg>',d='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87L18.18 21 12 17.27 5.82 21 7 14.14 2 9.27l6.91-1.01L12 2z"/></svg>',u='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M20.59 13.41l-7.17 7.17a2 2 0 01-2.83 0L2 12V2h10l8.59 8.59a2 2 0 010 2.82z"/><line x1="7" y1="7" x2="7.01" y2="7"/></svg>',p='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>',m='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/></svg>',f='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>',g='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/></svg>',h='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2"/></svg>',v=o.isPdf?function(){window.open("/chat/?open_pdf="+encodeURIComponent(r),"_blank")}:function(){window.open(sv(r),"_blank")},y=[{label:SKT("doc.open"),icon:a,action:function(){cy(r)}},{label:SKT("doc.openNewTab"),icon:l,action:v},{label:SKT("doc.preview"),icon:s,action:function(){jv(r)}},{label:xh.has(r)?SKT("doc.deselect"):SKT("doc.markSelect"),icon:c,action:function(){Iv(r)}},{divider:!0},{label:o.isPinned?SKT("doc.removeFav"):SKT("doc.addFav"),icon:d,action:function(){_v(r)}},{label:SKT("doc.tags"),icon:u,action:function(){Av(r,n)}},{label:SKT("doc.rename"),icon:p,action:function(){Uv(r)}}];o.isPdf||y.push({divider:!0},{label:SKT("doc.duplicate"),icon:m,action:function(){!async function(e){var t=Cv(e);if(!t)return;try{var n=await vv();if(!n)throw new Error("missing-user");var r=await dv().getColumn(e,n,"content");if(r.error)throw r.error;var o=(new Date).toISOString(),i=await dv().insert({user_id:n,title:(t.title||SKT("toolbar.untitled"))+" "+SKT("toolbar.copySuffix"),content:r.data&&r.data.content?r.data.content:"",word_count:t.wordCount||0,is_draft:!1,is_pinned:!1,tags:Array.isArray(t.tags)&&t.tags.length?t.tags:null,created_at:o,updated_at:o},{select:"id, title, content, word_count, created_at, updated_at, deleted_at, is_pinned, tags",single:!0});if(i.error)throw i.error;fh.unshift(ov(i.data)),kv(),Ev(SKT("doc.textDuplicated"),"success")}catch(e){console.error("[sk-doc-browser] duplicate failed:",e),Ev(SKT("doc.duplicateError"),"error")}}(r)}},{label:SKT("doc.download"),icon:f,action:function(){Gv(r)}},{label:SKT("doc.pushGDocs"),icon:g,action:function(){!async function(e){var t=Cv(e);if(!t)return;try{var n=await vv();if(!n)throw new Error("missing-user");var r=await dv().getColumn(e,n,"content");
3if(r.error)throw r.error;var o=r.data&&r.data.content?r.data.content:"";if(!nv(o))return void Ev(SKT("doc.toastDownloadEmpty"),"warning");var i=await Jv();if(i||(i=await Yv()),!i)return;Ev(SKT("doc.toastGdocsPushing"),"info");var a=await Wv("push",{title:t.title||"SkrivSikkert dokument",html:Vv(o)});a&&a.ok&&a.url?(Ev(SKT("doc.toastGdocsPushOk"),"success"),window.open(a.url,"_blank")):Ev(a&&a.error?a.error:SKT("doc.toastGdocsPushFail"),"error")}catch(e){console.error("[sk-doc-browser] gdocs push failed:",e),Ev(SKT("doc.toastGdocsError"),"error")}}(r)}}),y.push({divider:!0},{label:SKT("doc.deleteDoc"),icon:h,danger:!0,action:function(){$v(r,o.title)}}),y.forEach(function(e){if(e.divider){var t=document.createElement("div");return t.className="sk-doc-ctx-divider",t.setAttribute("role","separator"),void i.appendChild(t)}var n=document.createElement("button");n.type="button",n.className="sk-doc-ctx-item"+(e.danger?" sk-doc-ctx-item--danger":""),n.setAttribute("role","menuitem"),e.icon?n.innerHTML=e.icon+"<span>"+rv(e.label)+"</span>":n.textContent=e.label,n.addEventListener("click",function(){Nv(),e.action()}),i.appendChild(n)}),document.body.appendChild(i),Lh=i,function(e,t,n){e.style.position="fixed",e.style.left="0px",e.style.top="0px";var r=e.getBoundingClientRect(),o=8,i=t,a=n;i+r.width+o>window.innerWidth&&(i=t-r.width);a+r.height+o>window.innerHeight&&(a=n-r.height);i<o&&(i=o);a<o&&(a=o);e.style.left=Math.round(i)+"px",e.style.top=Math.round(a)+"px"}(i,e,t);var w=i.querySelector(".sk-doc-ctx-item");w&&w.focus()}}function Nv(){Lh&&(Lh.remove(),Lh=null)}function jv(e){Ov();var t=Cv(e);if(t){var n=!!t.isPdf,r=document.createElement("div");r.className="sk-doc-preview-modal",r.setAttribute("role","dialog"),r.setAttribute("aria-modal","true"),r.setAttribute("aria-label",SKT("doc.previewDialogAria")),r.innerHTML='<div class="sk-doc-preview-panel'+(n?" sk-doc-preview-panel--pdf":"")+'"><div class="sk-doc-preview-header"><div><p class="sk-doc-preview-kicker">'+rv(n?SKT("doc.pdfKicker"):SKT("doc.previewKicker"))+'</p><h2 class="sk-doc-preview-title">'+rv(t.title||SKT("toolbar.untitled"))+'</h2></div><button type="button" class="sk-doc-preview-close" aria-label="'+rv(SKT("doc.closePreview"))+'">×</button></div>'+(n?'<div class="sk-doc-preview-pdfbody"><p class="sk-doc-preview-pdfstatus">'+rv(SKT("doc.pdfOpening"))+'</p><div class="sk-doc-preview-pages" aria-live="polite"></div></div>':'<p class="sk-doc-preview-text">'+rv(t.preview||SKT("doc.noText"))+"</p>")+'<div class="sk-doc-preview-meta"><span>'+rv(lv(t.updatedAt))+"</span><span>"+(n?rv(String(t.pageCount||0))+" "+rv(SKT("doc.pagesUnit")):rv(String(t.wordCount||0))+" "+rv(SKT("doc.wordsUnit")))+'</span></div><div class="sk-doc-preview-actions">'+(n?'<button type="button" class="sk-doc-preview-write">'+rv(SKT("doc.openInWrite"))+'</button><button type="button" class="sk-doc-preview-chat">'+rv(SKT("doc.openInChat"))+"</button>":'<button type="button" class="sk-doc-preview-open">'+rv(SKT("doc.openText"))+"</button>")+'<button type="button" class="sk-doc-preview-cancel">'+rv(SKT("doc.closeBtn"))+"</button></div></div>",document.body.appendChild(r),Eh=r;var o=r.querySelector(".sk-doc-preview-close"),i=r.querySelector(".sk-doc-preview-cancel"),a=r.querySelector(".sk-doc-preview-open"),l=r.querySelector(".sk-doc-preview-chat"),s=r.querySelector(".sk-doc-preview-write");o&&o.addEventListener("click",Ov),i&&i.addEventListener("click",Ov),a&&a.addEventListener("click",function(){Ov(),cy(e)}),l&&l.addEventListener("click",function(){oy(e)}),s&&s.addEventListener("click",function(){!function(e){sy("open-pdf-text:"+e,function(){return async function(e){var t=Cv(e);if(!t)return;var n="";try{var r=await vv();if(!r)throw new Error("missing-user");var o=await dv().getColumn(e,r,"content");if(o.error)throw o.error;n=nv(o.data&&o.data.content?o.data.content:"").trim()}catch(e){return console.error("[sk-doc-browser] pdf text fetch failed:",e),void Ev(SKT("doc.pdfTextFailed"),"error")}if(!n)return void Ev(SKT("doc.pdfNoTextToOpen"),"warning");Ov(),"function"==typeof window.stopAllSkrivebordTTS&&window.stopAllSkrivebordTTS();if(!(await iy(cv())).proceed)return{stayed:!0};history.pushState({scratch:!0},"","/skrivebord/"),mv("editor"),$h.style.display="none",Xh&&(Xh.style.display="");ry();var i=await ny(),a=document.querySelector(".skv2-doc-title")||document.getElementById("doc-title"),l=cv();l&&"function"==typeof l.resetToScratch?await l.resetToScratch(i):i&&(i.setContents([]),a&&(a.value=""));if(!i)return;var s=!1;if("function"==typeof window.displayResponse)try{"function"==typeof window.setEditorRobotLoading&&window.setEditorRobotLoading(!0,SKT("fileUpload.formattingText")),await Ne({text:n,aiFormat:!0,asHtml:!1,preserveLanguage:!0},{deps:{displayResponse:window.displayResponse,getLanguageFullName:It,HGF_ajax_object:window.HGF_ajax_object},t:function(e){return"function"==typeof SKT?SKT(e):e}}),s=i.getLength()>1}catch(e){console.error("[sk-doc-browser] pdf format failed:",e)}finally{"function"==typeof window.setEditorRobotLoading&&window.setEditorRobotLoading(!1)}s||i.setText(n,"user");i.setSelection(0,0),a&&(a.value=t.title||SKT("toolbar.untitled"),a.dispatchEvent(new Event("input",{bubbles:!0})));i.focus()}(e)})}(e)}),r.addEventListener("click",function(e){e.target===r&&Ov()});var c=o||a||l;c&&c.focus(),n&&async function(e,t){var n=e.querySelector(".sk-doc-preview-pdfstatus"),r=e.querySelector(".sk-doc-preview-pages");function o(e,t){n&&n.isConnected&&(n.textContent=e,n.classList.toggle("is-error",!!t),n.style.display=e?"":"none")}
3try{if(!t.storagePath)return void o(SKT("doc.pdfOpenFailed"),!0);var i=await async function(){var e=dv();if(e&&e.storageDownloadPdf)return e;try{await Promise.resolve().then(function(){return Ps})}catch(e){}return dv()}();if(!i||"function"!=typeof i.storageDownloadPdf)return void o(SKT("doc.pdfOpenFailed"),!0);var a=await i.storageDownloadPdf(t.storagePath);if(!a.ok||!a.data)return void o(SKT("doc.pdfOpenFailed"),!0);var l=new Uint8Array(await a.data.arrayBuffer()),s=await function(){if(Rv)return Rv;var e="";try{e=new URL(import.meta.url).searchParams.get("v")||""}catch(e){}var t=e?"?v="+encodeURIComponent(e):"";return Rv=import("/chat/lib/pdfjs/pdf.min.mjs"+t).then(function(e){if(!e.GlobalWorkerOptions.workerPort)try{e.GlobalWorkerOptions.workerPort=new Worker("/chat/lib/pdfjs/pdf.worker.min.mjs"+t,{type:"module"})}catch(e){}return e.GlobalWorkerOptions.workerSrc="/chat/lib/pdfjs/pdf.worker.min.mjs"+t,e}).catch(function(e){throw Rv=null,e})}(),c=await s.getDocument({data:l}).promise;if(!e.isConnected){try{c.destroy()}catch(h){}return}o("");var d=c.numPages,u={};async function g(t){if(!u[t]&&e.isConnected){u[t]=!0;var n=r.querySelector('[data-sk-pdf-page="'+t+'"]');if(n)try{var o=await c.getPage(t),i=o.getViewport({scale:1}),a=Math.min(r.clientWidth||640,900)/i.width,l=o.getViewport({scale:a*(window.devicePixelRatio||1)}),s=document.createElement("canvas");s.width=Math.floor(l.width),s.height=Math.floor(l.height),s.style.width="100%";var d=s.getContext("2d",{alpha:!1});if(d.fillStyle="#ffffff",d.fillRect(0,0,s.width,s.height),await o.render({canvasContext:d,viewport:l}).promise,!e.isConnected)return;n.innerHTML="",n.appendChild(s)}catch(e){u[t]=!1}}}for(var p=new IntersectionObserver(function(e){e.forEach(function(e){e.isIntersecting&&g(Number(e.target.getAttribute("data-sk-pdf-page")))})},{root:r,rootMargin:"400px"}),m=1;m<=d;m++){var f=document.createElement("div");f.className="sk-doc-preview-page",f.setAttribute("data-sk-pdf-page",String(m)),f.setAttribute("aria-label",m+" / "+d),r.appendChild(f),p.observe(f)}g(1),d>=2&&g(2),Fv=function(){try{p.disconnect()}catch(e){}try{c.cleanup(),c.destroy()}catch(e){}}}catch(v){o(SKT("doc.pdfOpenFailed"),!0)}}(r,t)}}"undefined"==typeof window||window.__ssDocSavedWired||(window.__ssDocSavedWired=!0,window.addEventListener("ss-doc-saved",function(){wv()}));var Rv=null,Fv=null;function Ov(){if(Eh&&(Eh.remove(),Eh=null),Fv){var e=Fv;Fv=null;try{e()}catch(e){}}}function Uv(e){_h&&function(){var e=zh&&zh.querySelector('.sk-doc-card[data-renaming="true"]');if(e){var t=e.querySelector(".sk-doc-rename-input"),n=e.querySelector(".sk-doc-card-title");t&&t.remove(),n&&(n.style.display=""),e.removeAttribute("data-renaming")}_h=null}();var t=Cv(e);if(t){var n,r=zh&&zh.querySelector('.sk-doc-card[data-doc-id="'+(n=e,("undefined"!=typeof CSS&&"function"==typeof CSS.escape?CSS.escape(String(n)):String(n).replace(/["\\]/g,"\\$&"))+'"]'));if(r){var o=r.querySelector(".sk-doc-card-title");if(o){_h=e,r.setAttribute("data-renaming","true");var i=document.createElement("input");i.type="text",i.className="sk-doc-rename-input",i.value=t.title||"",i.setAttribute("aria-label",SKT("doc.renameAria")),o.style.display="none",o.insertAdjacentElement("afterend",i),i.focus(),i.select();var a=!1;i.addEventListener("keydown",function(e){"Enter"===e.key?(e.preventDefault(),s()):"Escape"===e.key&&(e.preventDefault(),l())}),i.addEventListener("blur",s,{once:!0})}}}function l(){a||(a=!0,_h=null,r.removeAttribute("data-renaming"),i.parentNode&&i.remove(),o.style.display="")}function s(){if(!a){var n=i.value.trim().substring(0,200);l(),n&&n!==t.title&&async function(e,t){var n=Cv(e);if(!n)return;var r=n.title;n.title=t,n._searchText=(t+" "+(n._searchText||"")).toLowerCase(),kv();try{var o=await vv();if(!o)throw new Error("missing-user");var i=await dv().update(e,o,{title:t,updated_at:(new Date).toISOString()});if(i.error)throw i.error;Ev(SKT("doc.toastRenameSuc"),"success")}catch(e){n.title=r,kv(),console.error("[sk-doc-browser] rename failed:",e),Ev(SKT("doc.toastRenameFail"),"error")}}(e,n)}}}async function $v(e,t){var n=t||SKT("toolbar.untitled");await window.ssConfirm({title:SKT("doc.deleteConfirmTitle"),message:SKT("doc.deleteConfirmMsg",{title:n}),okLabel:SKT("doc.deleteConfirmOk"),cancelLabel:SKT("doc.cancelLabel"),danger:!0})&&async function(e){try{var t=await vv();if(!t)throw new Error("missing-user");var n=await dv().update(e,t,{deleted_at:(new Date).toISOString()});if(n.error)throw n.error;var r=fh.find(function(t){return t.id===e});if(r&&r.isPdf&&r.storagePath)try{await dv().storageRemovePdf(r.storagePath)}catch(e){}fh=fh.filter(function(t){return t.id!==e}),xh.delete(e),kv(),Ev(SKT("doc.toastDeleteSuc"),"success")}catch(e){console.error("[sk-doc-browser] delete failed:",e),Ev(SKT("doc.toastDeleteFail"),"error")}}(e)}function zv(e){return new Promise(function(t,n){var r=document.querySelector('script[src="'+e+'"]');if(r)return"true"===r.getAttribute("data-sk-loaded")?void t():(r.addEventListener("load",t,{once:!0}),void r.addEventListener("error",n,{once:!0}));var o=document.createElement("script");o.src=e,o.onload=function(){o.setAttribute("data-sk-loaded","true"),t()},o.onerror=n,document.head.appendChild(o)})}async function Gv(e){var t,n=Cv(e);if(n)try{var r=await vv();if(!r)throw new Error("missing-user");var o=await dv().getColumn(e,r,"content");
3if(o.error)throw o.error;var i=o.data&&o.data.content?o.data.content:"";if(!nv(i))return void Ev(SKT("doc.toastDownloadEmpty"),"warning");await async function(){return Kh||((window.htmlDocx||window.htmlDocxJS||"undefined"!=typeof htmlDocx)&&"function"==typeof window.saveAs?(Kh=Promise.resolve(),Kh):(Kh=Promise.all([zv("/assets/lib/html-docx.min.js"),zv("/assets/lib/FileSaver.min.js")]).then(function(){return!0}),Kh))}();var a=window.htmlDocx||("undefined"!=typeof htmlDocx?htmlDocx:null),l='<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>'+Vv(i)+"</body></html>";a&&"function"==typeof a.asBlob&&"function"==typeof window.saveAs&&window.saveAs(a.asBlob(l),(t=n.title,(String(t||"dokument").replace(/[\\/:*?"<>|]/g,"").trim().substring(0,100)||"dokument")+".docx"))}catch(e){console.error("[sk-doc-browser] download failed:",e),Ev(SKT("doc.toastDownloadFail"),"error")}}function Vv(e){return String(e||"").replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"")}async function Wv(e,t){var n=await yv();if(!n)throw new Error("missing-auth-token");var r={method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json",Authorization:"Bearer "+n}};t&&(r.body=JSON.stringify(t));var o=await fetch("/api/gdocs.php?action="+encodeURIComponent(e),r);if(!o.ok)throw new Error("gdocs-http-"+o.status);return o.json()}async function Jv(){try{var e=JSON.parse(localStorage.getItem(mh)||"null");if(e&&Date.now()-e.ts<3e5)return jh=!!e.connected,jh}catch(e){}try{var t=await Wv("status");return Rh=!(!t||!t.has_calendar_scope),jh=!(!t||!t.connected),localStorage.setItem(mh,JSON.stringify({connected:jh,ts:Date.now()})),jh}catch(e){return jh=!1,!1}}async function Zv(){await async function(){window.gapi||(Ph||(Ph=zv("https://apis.google.com/js/api.js")),await Ph)}(),window.google&&window.google.picker||(Nh||(Nh=new Promise(function(e,t){window.gapi&&"function"==typeof window.gapi.load?window.gapi.load("picker",{callback:e,onerror:function(){t(new Error("picker-load-failed"))}}):t(new Error("gapi-missing"))})),await Nh)}async function Yv(){return await async function(){window.google&&window.google.accounts&&window.google.accounts.oauth2||(Dh||(Dh=zv("https://accounts.google.com/gsi/client")),await Dh)}(),new Promise(function(e){if(!window.google||!window.google.accounts||!window.google.accounts.oauth2)return Ev(SKT("doc.toastGdocsLoginFail"),"error"),void e(!1);window.google.accounts.oauth2.initCodeClient({client_id:"844299901051-5qr9lrbcphsiodgm7dbvdhsv66s4b8qs.apps.googleusercontent.com",scope:Rh?ph+" https://www.googleapis.com/auth/calendar":ph,include_granted_scopes:!1,ux_mode:"popup",redirect_uri:"postmessage",callback:async function(t){if(!t||t.error||!t.code)return Ev(SKT("doc.toastGdocsConnFail"),"error"),void e(!1);try{var n=await Wv("connect",{code:t.code,redirect_uri:"postmessage"});jh=!(!n||!n.ok),localStorage.setItem(mh,JSON.stringify({connected:jh,ts:Date.now()})),Ev(jh?SKT("doc.toastGdocsConnOk"):SKT("doc.toastGdocsConnError"),jh?"success":"error"),e(jh)}catch(t){console.error("[sk-doc-browser] gdocs connect failed:",t),Ev(SKT("doc.toastGdocsConnErrGeneric"),"error"),e(!1)}}}).requestCode()})}async function Qv(){if(!Fh){Fh=!0;try{var e=await Jv();if(e||(e=await Yv()),!e)return;var t=await async function(){try{return await Wv("token")}catch(e){if(jh=!1,localStorage.setItem(mh,JSON.stringify({connected:!1,ts:Date.now()})),!await Yv())throw e;return await Wv("token")}}();if(!t||!t.access_token||!t.api_key)throw jh=!1,localStorage.setItem(mh,JSON.stringify({connected:!1,ts:Date.now()})),new Error("missing-gdocs-picker-token");await Zv(),function(e,t){Oh=window.scrollY||0,document.documentElement.style.overflow="hidden",document.body.style.overflow="hidden",document.body.style.position="fixed",document.body.style.top="-"+Oh+"px",document.body.style.width="100%";var n=new window.google.picker.DocsView(window.google.picker.ViewId.DOCUMENTS);n.setMimeTypes("application/vnd.google-apps.document"),n.setMode(window.google.picker.DocsViewMode.LIST),(new window.google.picker.PickerBuilder).addView(n).setOAuthToken(e).setDeveloperKey(t).setAppId("844299901051").setOrigin(window.location.protocol+"//"+window.location.host).setTitle(SKT("doc.gdocsPicker")).setLocale("da").setCallback(ey).build().setVisible(!0)}(t.access_token,t.api_key)}catch(e){console.error("[sk-doc-browser] gdocs import failed:",e),Ev(SKT("doc.toastGdocsImportFail"),"error"),Fh=!1,ty()}}}async function Xv(e){e&&(await wv(),cy(e))}async function ey(e){if("picked"!==e.action&&"cancel"!==e.action||(ty(),Fh=!1),"picked"===e.action){var t=e.docs&&e.docs[0];if(t&&t.id)try{Ev(SKT("doc.toastGdocsImporting",{name:t.name||"dokument"}),"info");var n=await Wv("pull",{file_id:t.id});if(n&&n.ok&&n.doc_id)return Ev(SKT("doc.toastGdocsImported"),"success"),void await Xv(n.doc_id);if(n&&n.html){var r=await vv();if(!r)throw new Error("missing-user");var o=await dv().insert({user_id:r,title:t.name||"Fra Google Docs",content:n.html,word_count:(nv(n.html).match(/\S+/g)||[]).length,is_draft:!1},{select:"id",single:!0});if(o.error)throw o.error;return void await Xv(o.data.id)}Ev(SKT("doc.toastGdocsImportDeepFail"),"error")}catch(e){console.error("[sk-doc-browser] gdocs pull failed:",e),Ev(SKT("doc.toastGdocsImportError"),"error")}}}function ty(){document.documentElement.style.overflow="",document.body.style.overflow="",document.body.style.position="",document.body.style.top="",document.body.style.width="",Oh&&window.scrollTo(0,Oh)}async function ny(){var e=cv();return window.quill1?window.quill1:e&&"function"==typeof e.waitForQuill?e.waitForQuill():null}function ry(){document.body.classList.add("skrivebord-editing")}function oy(e){window.location.href="/chat/?open_pdf="+encodeURIComponent(e)}async function iy(e,t){if(!(e=e||cv())||"function"!=typeof e.flushCurrentDoc)return{proceed:!0,reason:"no-persistence"};var n;try{n=await e.flushCurrentDoc()}catch(e){n={ok:!1,saved:!1,reason:"exception"}}if(n&&n.ok)return{proceed:!0,reason:n.reason||"flushed",flush:n};if("function"==typeof e.verifyCurrentDocRecovered&&e.verifyCurrentDocRecovered()){try{"function"==typeof window.showToast&&window.showToast("Ikke gemt online endnu â kladden er sikret lokalt","info")}catch(e){}return{proceed:!0,reason:"local-recovery-proven",flush:n}}if(t&&t.forceProceed){try{"function"==typeof window.showToast&&window.showToast("Kunne ikke gemme â dine ændringer er ikke sikret","error")}catch(e){}return{proceed:!0,reason:"forced-unproven",flush:n}}try{"function"==typeof window.showToast&&window.showToast("Kunne ikke gemme â bliv pÃ¥ dokumentet og prøv igen","error")}catch(e){}return{proceed:!1,reason:"unproven",flush:n}}(window.SkrivebordApp=window.SkrivebordApp||{}
3).openPdfExternal=oy,window.SkrivebordApp.requestNav=function(e,t){var n=function(){return"number"==typeof t&&(cv()._ctxGen||0)!==t};return"scratch"===e?sy("request:scratch",function(){if(!n())return py()}):"browser"===e?sy("request:browser",function(){n()||uy(!0)}):void 0};var ay=!1,ly=null;async function sy(e,t){if(ay)return ly={label:e,run:t},{queued:!0};ay=!0;try{var n=await t();for(n&&n.stayed&&(ly=null);ly;){var r=ly;ly=null;var o=await r.run();o&&o.stayed&&(ly=null)}}finally{ay=!1,function(){try{var e,t=cv();e="browser"===pv?"tag"===kh&&Sh?"/skrivebord/?tag="+encodeURIComponent(Sh):"/skrivebord/":t&&t.currentDocId?sv(t.currentDocId):"/skrivebord/",window.location.pathname+window.location.search!==e&&history.replaceState(history.state,"",e)}catch(e){}}()}return{queued:!1}}function cy(e){if(e){var t=(fh||[]).find(function(t){return t.id===e});if(!t||!t.isPdf)return sy("open:"+e,function(){return async function(e){"function"==typeof window.stopAllSkrivebordTTS&&window.stopAllSkrivebordTTS();return(await iy(cv())).proceed?(function(e){try{var t=JSON.parse(localStorage.getItem(ch)||"[]");t=t.filter(function(t){return t.id!==e});var n=fh.find(function(t){return t.id===e});n&&t.unshift({id:e,title:n.title,ts:Date.now()}),t.length>5&&(t=t.slice(0,5)),localStorage.setItem(ch,JSON.stringify(t))}catch(e){}}(e),history.pushState({doc:e},"",sv(e)),dy(e,{leaveGuarded:!0})):{stayed:!0}}(e)});jv(e)}}async function dy(e,t){var n=cv();if((!t||!t.leaveGuarded)&&!(await iy(n)).proceed)return{stayed:!0};mv("editor"),$h.style.display="none",Xh&&(Xh.style.display=""),ry(),window._wf&&"function"==typeof window._wf.resetChatForDocumentChange&&window._wf.resetChatForDocumentChange(e);var r=await ny();e&&n&&"function"==typeof n.initDocumentPersistence&&r?n.initDocumentPersistence(e,r):e&&(window.location.href=sv(e))}function uy(e){var t;"function"==typeof window.stopAllSkrivebordTTS&&window.stopAllSkrivebordTTS(),iy(cv(),{forceProceed:!0}),mv("browser"),document.body.classList.remove("skrivebord-editing"),(t=document.getElementById("skrivebord-mobile-sheet"))&&t.classList.contains("open")&&("function"!=typeof window.closeMobileAiSheet?(t.classList.remove("open","closing"),document.body.classList.remove("skrivebord-mobile-sheet-is-open")):window.closeMobileAiSheet()),Xh&&(Xh.style.display="none"),$h.style.display="",(e||0===fh.length)&&wv()}async function py(e){var t=cv();if(!(await iy(t)).proceed)return{stayed:!0};mv("editor"),$h.style.display="none",Xh&&(Xh.style.display=""),ry();var n=await ny();t&&"function"==typeof t.initDocumentPersistence&&n&&t.initDocumentPersistence(null,n),n&&n.focus()}function my(){return sy("new-document",fy)}async function fy(){if("function"==typeof window.stopAllSkrivebordTTS&&window.stopAllSkrivebordTTS(),!(await iy(cv())).proceed)return{stayed:!0};history.pushState({scratch:!0},"","/skrivebord/"),mv("editor"),$h.style.display="none",Xh&&(Xh.style.display=""),ry();var e=await ny(),t=document.querySelector(".skv2-doc-title")||document.getElementById("doc-title"),n=cv();n&&"function"==typeof n.resetToScratch?await n.resetToScratch(e):e&&(e.setContents([]),t&&(t.value="")),e&&e.focus(),document.dispatchEvent(new CustomEvent("skrivebord:editor-cleared"))}function gy(){if(!Ch){var e=document.createElement("div");e.className="sk-doc-qs-overlay",e.innerHTML='<div class="sk-doc-qs-panel" role="dialog" aria-label="'+rv(SKT("doc.qsDialogAria"))+'"><div class="sk-doc-qs-input-wrap"><svg class="sk-doc-qs-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="18" height="18" aria-hidden="true"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg><input type="text" class="sk-doc-qs-input" placeholder="'+rv(SKT("doc.qsInputPlaceholder"))+'" autocomplete="off" spellcheck="false" aria-label="'+rv(SKT("doc.qsInputAria"))+'"><kbd class="sk-doc-qs-kbd">ESC</kbd></div><div class="sk-doc-qs-results" role="listbox" aria-label="'+rv(SKT("doc.qsResultsAria"))+'"></div><div class="sk-doc-qs-footer"><span><kbd>ââ</kbd> '+rv(SKT("doc.qsNavigate"))+"</span><span><kbd>Enter</kbd> "+rv(SKT("doc.qsOpen"))+"</span><span><kbd>Esc</kbd> "+rv(SKT("doc.qsClose"))+"</span></div></div>",document.body.appendChild(e),Ch=e;var t=e.querySelector(".sk-doc-qs-input"),n=e.querySelector(".sk-doc-qs-results"),r=0;o(),t.focus(),fh.length||yh||wv().then(function(){o()}),t.addEventListener("input",function(){r=0,o()}),t.addEventListener("keydown",function(e){var t=Array.from(n.querySelectorAll(".sk-doc-qs-item"));if("ArrowDown"===e.key)e.preventDefault(),hy(t,r=Math.min(r+1,Math.max(0,t.length-1)));else if("ArrowUp"===e.key)e.preventDefault(),hy(t,r=Math.max(r-1,0));else if("Enter"===e.key){if(e.preventDefault(),t[r]){var o=t[r].getAttribute("data-doc-id");vy(),cy(o)}}else"Escape"===e.key&&(e.preventDefault(),vy())}),e.addEventListener("click",function(t){t.target===e&&vy()})}function o(){!function(e,t,n){var r=t?av(fh,t).slice(0,12):fh.slice(0,8);if(!r.length)return void(e.innerHTML='<div class="sk-doc-qs-empty">'+rv(SKT("doc.qsEmpty"))+"</div>");e.innerHTML=r.map(function(e,t){var r=lv(e.updatedAt);
3return e.wordCount&&(r+=" · "+e.wordCount+" "+SKT("doc.wordsUnit")),'<button type="button" class="sk-doc-qs-item'+(t===n?" sk-doc-qs-item--focused":"")+'" role="option" aria-selected="'+(t===n?"true":"false")+'" data-doc-id="'+rv(e.id)+'"><span class="sk-doc-qs-item-main">'+(e.isPinned?'<svg class="sk-doc-qs-pin" viewBox="0 0 24 24" width="12" height="12" fill="currentColor" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87L18.18 21 12 17.27 5.82 21 7 14.14 2 9.27l6.91-1.01L12 2z"></path></svg>':"")+'<span class="sk-doc-qs-title">'+rv(e.title)+'</span></span><span class="sk-doc-qs-meta">'+rv(r)+"</span></button>"}).join(""),e.querySelectorAll(".sk-doc-qs-item").forEach(function(e){e.addEventListener("click",function(){vy(),cy(e.getAttribute("data-doc-id"))})})}(n,t.value.trim(),r)}}function hy(e,t){e.forEach(function(e,n){e.classList.toggle("sk-doc-qs-item--focused",n===t),e.setAttribute("aria-selected",n===t?"true":"false")}),e[t]&&e[t].scrollIntoView({block:"nearest"})}function vy(){Ch&&(Ch.remove(),Ch=null)}function yy(){clearTimeout(vh),vh=setTimeout(function(){hh=Vh.value.trim(),gh=12,kv()},300)}function wy(e){if("string"==typeof e.key){if((e.ctrlKey||e.metaKey)&&"k"===e.key.toLowerCase())return e.preventDefault(),void(Ch?vy():gy());if(!Ch&&$h&&"none"!==$h.style.display){var t=e.target;if(!t||"INPUT"!==t.tagName&&"TEXTAREA"!==t.tagName&&!t.isContentEditable){if("/"===e.key)return e.preventDefault(),void(Vh&&(Vh.focus(),Vh.select()));if("ArrowDown"===e.key||"j"===e.key.toLowerCase())return e.preventDefault(),void ky(1);if("ArrowUp"===e.key||"k"===e.key.toLowerCase())return e.preventDefault(),void ky(-1);if("Enter"===e.key&&Ah>=0){e.preventDefault();var n=by();n[Ah]&&cy(n[Ah].getAttribute("data-doc-id"))}else{if("Escape"===e.key)return xh.size&&Bv(),Ah=-1,void Sy();if("d"!==e.key.toLowerCase()||e.ctrlKey||e.metaKey||e.altKey||!(Ah>=0))"n"!==e.key.toLowerCase()||e.ctrlKey||e.metaKey||e.altKey||(e.preventDefault(),my());else{e.preventDefault();var r=by();if(r[Ah]){var o=r[Ah].getAttribute("data-doc-id"),i=Cv(o);$v(o,i?i.title:"")}}}}}}}function by(){return zh?Array.from(zh.querySelectorAll(".sk-doc-card")):[]}function ky(e){var t=by();t.length&&(Ah+=e,Ah<0&&(Ah=0),Ah>=t.length&&(Ah=t.length-1),Sy(),t[Ah].scrollIntoView({block:"nearest",behavior:"smooth"}))}function Sy(){by().forEach(function(e,t){e.classList.toggle("sk-doc-card--focused",t===Ah)})}function xy(){if(!wh){if(wh=!0,Vh&&Vh.addEventListener("input",yy),Jh&&Jh.addEventListener("click",function(){gh+=12,kv()}),Zh&&Zh.addEventListener("click",my),Yh&&Yh.addEventListener("click",Qv),Wh&&Wh.addEventListener("click",function(e){var t=e.target.closest(".sk-doc-filter-pill");t&&function(e){if("all"===e)kh="all",Sh=null;else if("pinned"===e)kh="pinned"===kh?"all":"pinned",Sh=null;else if(e&&0===e.indexOf("tag:")){var t=e.substring(4);Sh===t?(Sh=null,kh="all"):(Sh=t,kh="tag")}gh=12,kv()}(t.getAttribute("data-filter"))}),Qh){var e=Qh.querySelector('[data-action="cancel"]'),t=Qh.querySelector('[data-action="delete"]'),n=Qh.querySelector('[data-action="export"]');e&&e.addEventListener("click",Bv),t&&t.addEventListener("click",Kv),n&&n.addEventListener("click",Dv)}window.addEventListener("ss:lang-ui-ready",function(){if(kv(),Hv(),Ch){var e=Ch.querySelector(".sk-doc-qs-input"),t=e?e.value:"";if(vy(),gy(),t&&Ch){var n=Ch.querySelector(".sk-doc-qs-input");n&&(n.value=t,n.dispatchEvent(new Event("input")))}}if(qh){var r=qh.getAttribute("data-doc-id"),o=qh.querySelector(".sk-doc-tag-editor-input"),i=o?o.value:"",a=null;if((zh?Array.from(zh.querySelectorAll(".sk-doc-card")):[]).some(function(e){return e.getAttribute("data-doc-id")===r&&(a=e,!0)}),Mv(),r&&a){Av(r,a);var l=qh?qh.querySelector(".sk-doc-tag-editor-input"):null;l&&(l.value=i)}}if(Eh){var s=Eh.querySelector(".sk-doc-preview-panel");if(s){Eh.setAttribute("aria-label",SKT("doc.previewDialogAria"));var c=s.querySelector(".sk-doc-preview-kicker");c&&(c.textContent=SKT("doc.previewKicker"));var d=s.querySelector(".sk-doc-preview-close");d&&d.setAttribute("aria-label",SKT("doc.closePreview"));var u=s.querySelector(".sk-doc-preview-open");u&&(u.textContent=SKT("doc.openText"));var p=s.querySelector(".sk-doc-preview-cancel");p&&(p.textContent=SKT("doc.closeBtn"));var m=s.querySelectorAll(".sk-doc-preview-meta span");if(m.length>=2){var f=m[1].textContent.match(/\d+/);f&&(m[1].textContent=f[0]+" "+SKT("doc.wordsUnit"))}}}}),zh.addEventListener("click",function(e){var t=e.target.closest(".sk-doc-card");if(t){var n=t.getAttribute("data-doc-id"),r=e.target.closest("[data-sk-doc-action]");if(r){e.preventDefault(),e.stopPropagation();var o=r.getAttribute("data-sk-doc-action");"select"===o?Iv(n,e):"pin"===o&&_v(n)}else if("true"!==t.getAttribute("data-renaming")){if(!(xh.size>0||e.shiftKey))return e.target.closest(".sk-doc-card-title")?(clearTimeout(Hh),void(Hh=setTimeout(function(){Hh=null,cy(n)}
3,260))):void cy(n);Iv(n,e)}}}),zh.addEventListener("keydown",function(e){var t=e.target.closest(".sk-doc-card");t&&"true"!==t.getAttribute("data-renaming")&&("Enter"===e.key?(e.preventDefault(),cy(t.getAttribute("data-doc-id"))):" "===e.key&&(e.preventDefault(),Iv(t.getAttribute("data-doc-id"),e)))}),zh.addEventListener("dblclick",function(e){var t=e.target.closest(".sk-doc-card-title");if(t){var n=t.closest(".sk-doc-card");n&&(e.preventDefault(),e.stopPropagation(),clearTimeout(Hh),Hh=null,Uv(n.getAttribute("data-doc-id")))}}),$h.addEventListener("contextmenu",function(e){var t=e.target.closest(".sk-doc-card");t&&(e.preventDefault(),Pv(e.clientX,e.clientY,t))}),$h.addEventListener("touchstart",function(e){var t=e.target.closest(".sk-doc-card");if(t){var n=e.touches[0];Bh={x:n.clientX,y:n.clientY,card:t},clearTimeout(Ih),Ih=setTimeout(function(){navigator.vibrate&&navigator.vibrate(30),Pv(Bh.x,Bh.y,Bh.card)},500)}},{passive:!0}),$h.addEventListener("touchmove",function(e){if(Ih&&Bh){var t=e.touches[0],n=t.clientX-Bh.x,r=t.clientY-Bh.y;Math.sqrt(n*n+r*r)>10&&(clearTimeout(Ih),Ih=null)}},{passive:!0}),$h.addEventListener("touchend",function(){clearTimeout(Ih),Ih=null},{passive:!0}),document.addEventListener("click",function(e){Lh&&!Lh.contains(e.target)&&Nv()},!0),document.addEventListener("keydown",function(e){"Escape"===e.key&&(Nv(),Ov(),Mv())}),document.addEventListener("keydown",wy),window.addEventListener("popstate",function(e){var t=new URLSearchParams(window.location.search),n=t.get("doc"),r=qv(t.get("tag")),o=!!(r||e.state&&e.state.browser);sy("popstate",function(){return n?dy(n):o?(r&&(Sh=r,kh="tag"),void uy(!1)):py()})}),(tv?tv.querySelector("#sk-tb-back"):document.getElementById("sk-tb-back"))?.addEventListener("click",function(){sy("back-to-browser",function(){history.pushState({browser:!0},"","/skrivebord/"),uy(!1)})});var r=document.getElementById("skv2DocBack");r&&r.addEventListener("click",function(e){e.preventDefault(),sy("back-to-browser",function(){history.pushState({browser:!0},"","/skrivebord/"),uy(!1)})})}}var Ty=!1;function Ly(){if(!Ty&&uv()){Ty=!0,xy();var e=function(e){var t=new URLSearchParams(e||""),n=t.get("doc");if(n)return{mode:"editor",docId:n,source:"url"};var r=qv(t.get("tag"));return r?{mode:"browser",tag:r}:{mode:"editor"}}(window.location.search);sy("boot",function(){return"editor"===e.mode&&e.docId?dy(e.docId):"browser"===e.mode?(e.tag&&(Sh=e.tag,kh="tag"),void uy(!0)):py()})}}"undefined"!=typeof window&&"undefined"!=typeof document&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",Ly):Ly());
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.