makethisbetter 1.5.2 → 1.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,11 @@
1
- "use strict";var yt=Object.create;var H=Object.defineProperty;var xt=Object.getOwnPropertyDescriptor;var wt=Object.getOwnPropertyNames;var kt=Object.getPrototypeOf,vt=Object.prototype.hasOwnProperty;var St=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of wt(t))!vt.call(i,s)&&s!==e&&H(i,s,{get:()=>t[s],enumerable:!(r=xt(t,s))||r.enumerable});return i};var Et=(i,t,e)=>(e=i!=null?yt(kt(i)):{},St(t||!i||!i.__esModule?H(e,"default",{value:i,enumerable:!0}):e,i));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ct='*,*:before,*:after{box-sizing:border-box;margin:0;padding:0}:host{all:initial;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;font-size:14px;line-height:1.5;color:#191a1c;-webkit-font-smoothing:antialiased}:host([data-mtb-theme="dark"]) .mtb-popup,:host([data-mtb-theme="dark"]) .mtb-success{background:#151719;border-color:#ffffff1f;color:#f9fafb}:host([data-mtb-theme="dark"]) .mtb-popup-header{border-bottom-color:#ffffff1a}:host([data-mtb-theme="dark"]) .mtb-popup-title,:host([data-mtb-theme="dark"]) .mtb-success-title{color:#f9fafb}:host([data-mtb-theme="dark"]) .mtb-quick-option,:host([data-mtb-theme="dark"]) .mtb-textarea{background:#1f2327;border-color:#ffffff1f;color:#f9fafb}:host([data-mtb-theme="dark"]) .mtb-popup-close,:host([data-mtb-theme="dark"]) .mtb-success-msg,:host([data-mtb-theme="dark"]) .mtb-close-link{color:#ffffffad}@media (prefers-color-scheme: dark){:host([data-mtb-theme="auto"]) .mtb-popup,:host([data-mtb-theme="auto"]) .mtb-success{background:#151719;border-color:#ffffff1f;color:#f9fafb}:host([data-mtb-theme="auto"]) .mtb-popup-header{border-bottom-color:#ffffff1a}:host([data-mtb-theme="auto"]) .mtb-popup-title,:host([data-mtb-theme="auto"]) .mtb-success-title{color:#f9fafb}:host([data-mtb-theme="auto"]) .mtb-quick-option,:host([data-mtb-theme="auto"]) .mtb-textarea{background:#1f2327;border-color:#ffffff1f;color:#f9fafb}:host([data-mtb-theme="auto"]) .mtb-popup-close,:host([data-mtb-theme="auto"]) .mtb-success-msg,:host([data-mtb-theme="auto"]) .mtb-close-link{color:#ffffffad}}.mtb-tab{position:fixed;top:50%;right:0;transform:translateY(-50%);z-index:2147483646;display:flex;align-items:center;justify-content:center;width:32px;padding:14px 0;background:#059669;color:#fff;border-radius:8px 0 0 8px;cursor:pointer;box-shadow:-2px 0 14px #05966959;transition:background .15s,box-shadow .15s,width .15s;writing-mode:vertical-lr;text-orientation:mixed;font-size:12px;font-weight:600;letter-spacing:.04em;user-select:none;border:none;outline:none}.mtb-tab.left{right:auto;left:0;border-radius:0 8px 8px 0;box-shadow:2px 0 14px #05966959}.mtb-tab:hover{background:#047857;box-shadow:-3px 0 20px #05966980}.mtb-tab.active{background:#065f46}.mtb-toolbar{position:fixed;top:18px;left:50%;transform:translate(-50%);z-index:2147483647;display:flex;align-items:center;gap:11px;height:46px;padding:0 7px;border-radius:13px;background:linear-gradient(120deg,#10b981,#059669);box-shadow:0 10px 26px #0f172a38;animation:mtbBarIn .2s ease;white-space:nowrap}@keyframes mtbBarIn{0%{transform:translate(-50%,12px);opacity:0}to{transform:translate(-50%);opacity:1}}.mtb-toolbar-modes{display:flex;align-items:center;gap:3px;background:#ffffff29;border-radius:9px;padding:3px}.mtb-toolbar-mode-btn{display:inline-flex;align-items:center;gap:6px;height:30px;padding:0 12px;border-radius:7px;border:none;cursor:pointer;font-family:inherit;font-size:12px;font-weight:550;white-space:nowrap;background:transparent;color:#fffffff2;transition:all .12s}.mtb-toolbar-mode-btn.active{background:#fff;color:#047857}.mtb-toolbar-hint{font-size:12px;color:#fffffff2;white-space:nowrap}.mtb-toolbar-sep{width:1px;height:20px;background:#ffffff38}.mtb-exit-btn{display:inline-flex;align-items:center;gap:5px;height:30px;padding:0 12px;border-radius:8px;font-size:11.5px;font-weight:500;color:#fff;cursor:pointer;background:#ffffff29;border:none;font-family:inherit;transition:background .12s}.mtb-exit-btn:hover{background:#ffffff47}.mtb-overlay{position:fixed;inset:0;z-index:2147483640;cursor:crosshair}.mtb-dim{position:fixed;inset:0;z-index:2147483639;background:#00000014}.mtb-highlight{position:fixed;z-index:2147483641;pointer-events:none;border:2px solid #10b981;border-radius:6px;background:#10b9810f;transition:all .08s ease}.mtb-highlight-tooltip{position:fixed;z-index:2147483642;pointer-events:none;transform:translate(-50%);background:#064e3b;color:#fff;padding:4px 10px;border-radius:6px;font-size:11px;font-weight:500;white-space:nowrap;box-shadow:0 4px 12px #0000002e}.mtb-highlight-tooltip:after{content:"";position:absolute;top:100%;left:50%;transform:translate(-50%);border:4px solid transparent;border-top-color:#064e3b}.mtb-draw-svg{position:fixed;inset:0;z-index:2147483643;pointer-events:none;width:100%;height:100%;overflow:visible}.mtb-pin{position:fixed;z-index:2147483644;pointer-events:none;width:22px;height:22px;border-radius:50% 50% 50% 2px;background:#059669;border:2px solid #fff;display:flex;align-items:center;justify-content:center;font-size:10px;color:#fff;font-weight:700;box-shadow:0 2px 8px #05966973;animation:mtbPinPop .25s cubic-bezier(.34,1.56,.64,1);transform:translate(-50%,-50%)}@keyframes mtbPinPop{0%{transform:translate(-50%,-50%) scale(.4)}to{transform:translate(-50%,-50%) scale(1)}}.mtb-popup{position:fixed;z-index:2147483645;width:320px;background:#fff;border:1px solid rgba(0,0,0,.1);border-radius:14px;box-shadow:0 12px 40px #00000029;overflow:hidden;animation:mtbSlideUp .28s cubic-bezier(.34,1.56,.64,1);font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif}@keyframes mtbSlideUp{0%{transform:translateY(14px) scale(.97);opacity:0}to{transform:translateY(0) scale(1);opacity:1}}.mtb-popup-header{padding:11px 13px 11px 14px;border-bottom:1px solid rgba(0,0,0,.06);display:flex;align-items:center;gap:8px}.mtb-popup-icon{width:20px;height:20px;border-radius:5px;background:#10b9811a;display:flex;align-items:center;justify-content:center;flex-shrink:0}.mtb-popup-title{flex:1;font-size:12.5px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:#191a1c}.mtb-popup-close{background:none;border:none;cursor:pointer;padding:3px;color:#00000061;display:flex;align-items:center;border-radius:4px;transition:color .12s}.mtb-popup-close:hover{color:#000000b3}.mtb-popup-body{padding:13px}.mtb-quick-options{display:flex;flex-direction:column;gap:6px;margin-bottom:12px}.mtb-quick-option{display:flex;align-items:center;gap:10px;width:100%;padding:10px 12px;border:1px solid rgba(0,0,0,.09);border-radius:10px;background:#fafafa;cursor:pointer;font-family:inherit;font-size:13px;color:#191a1c;text-align:left;transition:all .12s}.mtb-quick-option:hover{background:#10b9810f;border-color:#10b9814d}.mtb-quick-option-emoji{font-size:15px;flex-shrink:0;line-height:1}.mtb-textarea-wrap{position:relative}.mtb-textarea{width:100%;height:64px;padding:9px 11px;border:1px solid rgba(0,0,0,.12);border-radius:9px;font-family:inherit;font-size:12.5px;line-height:1.5;color:#191a1c;outline:none;background:#fff;resize:none;transition:border-color .12s,box-shadow .12s}.mtb-textarea:focus{border-color:#10b981;box-shadow:0 0 0 3px #10b9811f}.mtb-textarea::placeholder{color:#00000057}.mtb-popup-error{margin-top:8px;color:#b91c1c;font-size:11.5px}.mtb-popup-error:empty,.mtb-popup-error[hidden]{display:none}.mtb-popup-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:12px}.mtb-cancel-btn,.mtb-submit-btn{min-width:72px;height:30px;border:none;border-radius:7px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0 12px;font-family:inherit;font-size:12px;font-weight:600;transition:background .12s}.mtb-cancel-btn{background:#f3f4f6;color:#000000ad}.mtb-cancel-btn:hover{background:#e5e7eb}.mtb-submit-btn{background:#d1d5db;color:#fff}.mtb-submit-btn.ready{background:#059669}.mtb-submit-btn.ready:hover{background:#047857}.mtb-submit-btn.loading{background:#059669;opacity:.7;cursor:wait}.mtb-submit-btn:disabled{cursor:not-allowed}.mtb-success{position:fixed;z-index:2147483645;width:300px;background:#fff;border:1px solid rgba(0,0,0,.1);border-radius:16px;box-shadow:0 20px 60px #0000001f;padding:26px 22px;text-align:center;animation:mtbSlideUp .35s cubic-bezier(.34,1.56,.64,1);font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif}.mtb-success-icon{width:44px;height:44px;border-radius:50%;background:#05966914;display:flex;align-items:center;justify-content:center;margin:0 auto 12px}.mtb-success-title{font-size:16px;font-weight:700;margin-bottom:6px;color:#191a1c}.mtb-success-msg{font-size:13px;color:#0000008c;margin-bottom:16px;line-height:1.6}.mtb-close-link{background:none;border:none;cursor:pointer;font-size:12px;color:#00000073;font-family:inherit;transition:color .12s}.mtb-close-link:hover{color:#000000b3}.mtb-email-capture{margin-bottom:14px;text-align:left}.mtb-email-prompt{font-size:12px;color:#0000008c;line-height:1.5;margin-bottom:8px}.mtb-email-row{display:flex;gap:6px}.mtb-email-input{flex:1;min-width:0;font-size:12.5px;font-family:inherit;padding:7px 10px;border:1px solid rgba(0,0,0,.14);border-radius:8px;outline:none}.mtb-email-input:focus{border-color:#059669}.mtb-email-input.mtb-email-invalid{border-color:#dc2626}.mtb-email-submit{font-size:12px;font-weight:600;font-family:inherit;color:#fff;background:#059669;border:none;border-radius:8px;padding:7px 12px;cursor:pointer;white-space:nowrap}.mtb-email-submit:disabled{opacity:.6;cursor:default}.mtb-email-error{font-size:11.5px;color:#dc2626;margin-top:6px}.mtb-email-saved{font-size:12px;color:#059669;line-height:1.5}.mtb-my-feedback{display:block;margin:8px auto 0;background:none;border:none;cursor:pointer;font-size:11.5px;font-family:inherit;color:#0006;text-decoration:underline;text-underline-offset:2px;transition:color .12s}.mtb-my-feedback:hover{color:#059669}.mtb-pet{position:fixed;bottom:20px;right:20px;z-index:2147483646;cursor:pointer;width:52px;height:52px;display:flex;align-items:center;justify-content:center;border-radius:50%;background:transparent;animation:mtbPetBounce 3s ease-in-out infinite;transition:transform .2s;user-select:none;outline:none;filter:drop-shadow(0 4px 12px rgba(5,150,105,.35))}.mtb-pet:hover{transform:scale(1.12);animation-play-state:paused}.mtb-pet:hover .mtb-pet-bubble{opacity:1;transform:translate(-50%) translateY(0);pointer-events:auto}.mtb-pet.active{animation:none;opacity:.6}.mtb-pet-svg{display:block}@keyframes mtbPetBounce{0%,to{transform:translateY(0)}50%{transform:translateY(-6px)}}.mtb-pet-bubble{position:absolute;bottom:100%;left:50%;transform:translate(-50%) translateY(4px);margin-bottom:8px;background:#064e3b;color:#fff;padding:6px 12px;border-radius:8px;font-size:12px;font-weight:500;white-space:nowrap;box-shadow:0 4px 14px #0000002e;opacity:0;pointer-events:none;transition:opacity .2s,transform .2s}.mtb-pet-bubble.visible{opacity:1;transform:translate(-50%) translateY(0);pointer-events:auto}.mtb-pet-bubble.hidden{opacity:0;pointer-events:none}.mtb-pet-bubble:after{content:"";position:absolute;top:100%;left:50%;transform:translate(-50%);border:5px solid transparent;border-top-color:#064e3b}.mtb-frustration-prompt{position:fixed;bottom:20px;right:20px;z-index:2147483645;display:flex;align-items:center;gap:10px;padding:12px 16px;background:#fff;border:1px solid rgba(0,0,0,.1);border-radius:12px;box-shadow:0 8px 30px #0000001f;animation:mtbSlideUp .35s cubic-bezier(.34,1.56,.64,1);font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif}:host([data-mtb-theme="dark"]) .mtb-frustration-prompt{background:#151719;border-color:#ffffff1f;color:#f9fafb}@media (prefers-color-scheme: dark){:host([data-mtb-theme="auto"]) .mtb-frustration-prompt{background:#151719;border-color:#ffffff1f;color:#f9fafb}}.mtb-frustration-icon{width:32px;height:32px;border-radius:50%;background:#eab3081a;display:flex;align-items:center;justify-content:center;flex-shrink:0;font-size:16px;line-height:1}.mtb-frustration-text{font-size:13px;font-weight:500;color:inherit;line-height:1.4}.mtb-frustration-actions{display:flex;gap:6px;flex-shrink:0}.mtb-frustration-tell{height:28px;padding:0 12px;border:none;border-radius:7px;background:#059669;color:#fff;cursor:pointer;font-family:inherit;font-size:12px;font-weight:600;transition:background .12s}.mtb-frustration-tell:hover{background:#047857}.mtb-frustration-dismiss{height:28px;padding:0 8px;border:none;border-radius:7px;background:transparent;color:#0006;cursor:pointer;font-family:inherit;font-size:12px;transition:color .12s}.mtb-frustration-dismiss:hover{color:#000000b3}:host([data-mtb-theme="dark"]) .mtb-frustration-dismiss{color:#fff6}:host([data-mtb-theme="dark"]) .mtb-frustration-dismiss:hover{color:#ffffffb3}@media (prefers-color-scheme: dark){:host([data-mtb-theme="auto"]) .mtb-frustration-dismiss{color:#fff6}:host([data-mtb-theme="auto"]) .mtb-frustration-dismiss:hover{color:#ffffffb3}}.mtb-record-bar{position:fixed;bottom:24px;left:50%;transform:translate(-50%);z-index:2147483647;display:flex;align-items:center;gap:12px;height:42px;padding:0 8px 0 14px;border-radius:12px;background:#0f172aeb;box-shadow:0 8px 24px #00000040;animation:mtbBarIn .2s ease}.mtb-record-dot{width:8px;height:8px;border-radius:50%;background:#ef4444;animation:mtbRecordPulse 1.2s ease-in-out infinite;flex-shrink:0}@keyframes mtbRecordPulse{0%,to{opacity:1}50%{opacity:.3}}.mtb-record-timer{font-family:JetBrains Mono,SF Mono,Fira Code,Cascadia Code,monospace;font-size:13px;font-weight:500;color:#fff;font-variant-numeric:tabular-nums;letter-spacing:.02em;min-width:38px}.mtb-record-stop{height:28px;padding:0 14px;border:none;border-radius:7px;background:#059669;color:#fff;cursor:pointer;font-family:inherit;font-size:12px;font-weight:600;transition:background .12s}.mtb-record-stop:hover{background:#047857}.mtb-click-ripple{position:fixed;z-index:2147483644;width:24px;height:24px;border-radius:50%;border:2px solid #10b981;background:#10b98133;pointer-events:none;transform:translate(-50%,-50%) scale(.5);animation:mtbClickRipple .3s ease-out forwards}@keyframes mtbClickRipple{0%{transform:translate(-50%,-50%) scale(.5);opacity:1}to{transform:translate(-50%,-50%) scale(2);opacity:0}}.mtb-dot{display:inline-block;width:4px;height:4px;border-radius:50%;background:#fff;animation:mtbDot 1.2s infinite}.mtb-dot:nth-child(2){animation-delay:.2s}.mtb-dot:nth-child(3){animation-delay:.4s}@keyframes mtbDot{0%,80%,to{opacity:.3;transform:translateY(0)}40%{opacity:1;transform:translateY(-3px)}}.mtb-clarify{position:fixed;z-index:2147483645;width:346px;background:#fff;border:1px solid rgba(0,0,0,.1);border-radius:14px;box-shadow:0 12px 40px #00000029;display:flex;flex-direction:column;animation:mtbSlideUp .28s cubic-bezier(.34,1.56,.64,1);font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;overflow:hidden}.mtb-clarify-header{padding:11px 13px 11px 14px;display:flex;align-items:center;gap:9px;border-bottom:1px solid rgba(0,0,0,.06)}.mtb-clarify-icon{width:24px;height:24px;border-radius:7px;background:linear-gradient(140deg,#10b981,#059669);box-shadow:0 1px 3px #05966966;display:flex;align-items:center;justify-content:center;flex-shrink:0}.mtb-clarify-titles{flex:1;min-width:0}.mtb-clarify-title{font-size:12.5px;font-weight:650;line-height:1.2;color:#191a1c}.mtb-clarify-subtitle{font-size:10px;color:#0000006b}.mtb-clarify-close{background:none;border:none;cursor:pointer;padding:3px;color:#00000061;display:flex;transition:color .12s}.mtb-clarify-close:hover{color:#000000b3}.mtb-clarify-messages{flex:1;max-height:250px;overflow-y:auto;padding:13px 13px 5px;display:flex;flex-direction:column;gap:9px}.mtb-clarify-bubble{max-width:82%;padding:9px 12px;font-size:12.5px;line-height:1.5;white-space:pre-wrap;word-break:break-word}.mtb-clarify-ai{align-self:flex-start;background:#fff;color:#191a1c;border:1px solid rgba(0,0,0,.09);border-radius:13px 13px 13px 4px}.mtb-clarify-user{align-self:flex-end;background:#059669;color:#fff;border:1px solid #059669;border-radius:13px 13px 4px}.mtb-clarify-thinking{display:flex;align-items:center;gap:4px;padding:11px 14px}.mtb-clarify-thinking .mtb-dot{width:6px;height:6px;background:#059669b3}.mtb-clarify-footer{padding:3px 13px 13px;display:flex;flex-direction:column}.mtb-clarify-input{width:100%;height:52px;padding:9px 11px;border:1px solid rgba(0,0,0,.12);border-radius:9px;font-family:inherit;font-size:13px;line-height:1.5;color:#191a1c;outline:none;background:#fafafa;resize:none;box-sizing:border-box;transition:border-color .12s,box-shadow .12s,background .12s}.mtb-clarify-input:focus{border-color:#10b981;box-shadow:0 0 0 3px #10b9811f;background:#fff}.mtb-clarify-input::placeholder{color:#00000057}.mtb-clarify-actions{display:flex;gap:8px;margin-top:9px}.mtb-clarify-skip{flex:0 0 auto;height:34px;padding:0 14px;border:1px solid rgba(0,0,0,.12);border-radius:9px;background:#fff;cursor:pointer;font-family:inherit;font-size:12.5px;font-weight:550;color:#0000008c;transition:background .12s}.mtb-clarify-skip:hover{background:#0000000a}.mtb-clarify-send{flex:1;height:34px;display:inline-flex;align-items:center;justify-content:center;gap:6px;border:none;border-radius:9px;background:#059669;color:#fff;cursor:pointer;font-family:inherit;font-size:12.5px;font-weight:600;transition:background .12s}.mtb-clarify-send:not(:disabled):hover{background:#047857}.mtb-clarify-send:disabled{background:#00000026;cursor:not-allowed}:host([data-mtb-theme="dark"]) .mtb-clarify{background:#151719;border-color:#ffffff1f;color:#f9fafb}:host([data-mtb-theme="dark"]) .mtb-clarify-header{border-bottom-color:#ffffff1a}:host([data-mtb-theme="dark"]) .mtb-clarify-title{color:#f9fafb}:host([data-mtb-theme="dark"]) .mtb-clarify-subtitle{color:#ffffff73}:host([data-mtb-theme="dark"]) .mtb-clarify-close{color:#ffffff73}:host([data-mtb-theme="dark"]) .mtb-clarify-close:hover{color:#ffffffbf}:host([data-mtb-theme="dark"]) .mtb-clarify-skip{background:#1f2327;border-color:#ffffff24;color:#ffffffb3}:host([data-mtb-theme="dark"]) .mtb-clarify-skip:hover{background:#ffffff0f}:host([data-mtb-theme="dark"]) .mtb-clarify-ai{background:#1f2327;border-color:#ffffff1f;color:#f9fafb}:host([data-mtb-theme="dark"]) .mtb-clarify-input{background:#1f2327;border-color:#ffffff1f;color:#f9fafb}@media (prefers-color-scheme: dark){:host([data-mtb-theme="auto"]) .mtb-clarify{background:#151719;border-color:#ffffff1f;color:#f9fafb}:host([data-mtb-theme="auto"]) .mtb-clarify-header{border-bottom-color:#ffffff1a}:host([data-mtb-theme="auto"]) .mtb-clarify-title{color:#f9fafb}:host([data-mtb-theme="auto"]) .mtb-clarify-subtitle{color:#ffffff73}:host([data-mtb-theme="auto"]) .mtb-clarify-close{color:#ffffff73}:host([data-mtb-theme="auto"]) .mtb-clarify-close:hover{color:#ffffffbf}:host([data-mtb-theme="auto"]) .mtb-clarify-skip{background:#1f2327;border-color:#ffffff24;color:#ffffffb3}:host([data-mtb-theme="auto"]) .mtb-clarify-skip:hover{background:#ffffff0f}:host([data-mtb-theme="auto"]) .mtb-clarify-ai{background:#1f2327;border-color:#ffffff1f;color:#f9fafb}:host([data-mtb-theme="auto"]) .mtb-clarify-input{background:#1f2327;border-color:#ffffff1f;color:#f9fafb}}';class _t{constructor(t="auto"){this.host=document.createElement("div"),this.host.id="mtb-widget-host",this.host.style.cssText="position:fixed;top:0;left:0;width:0;height:0;overflow:visible;z-index:2147483646;",this.host.setAttribute("data-mtb-theme",t),document.body.appendChild(this.host),this.root=this.host.attachShadow({mode:"open"});const e=document.createElement("style");e.textContent=Ct,this.root.appendChild(e)}el(t,e){const r=document.createElement(t);return e&&(r.className=e),r}append(...t){for(const e of t)this.root.appendChild(e)}remove(...t){for(const e of t)e.parentNode===this.root&&this.root.removeChild(e)}destroy(){this.host.remove()}}class Tt{constructor(t,e,r,s,n){this.onClick=s,this.el=t.el("button","mtb-tab"),r==="left"&&this.el.classList.add("left");const o=n??e.tab;this.el.textContent=o,this.el.setAttribute("aria-label",o),this.el.addEventListener("click",s),t.append(this.el)}setActive(t){this.el.classList.toggle("active",t)}destroy(){this.el.removeEventListener("click",this.onClick),this.el.remove()}}const Mt=8e3;class Lt{constructor(t,e,r){this.el=t.el("div","mtb-frustration-prompt"),this.el.innerHTML=`
1
+ "use strict";var yt=Object.create;var H=Object.defineProperty;var xt=Object.getOwnPropertyDescriptor;var wt=Object.getOwnPropertyNames;var kt=Object.getPrototypeOf,vt=Object.prototype.hasOwnProperty;var St=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of wt(t))!vt.call(i,s)&&s!==e&&H(i,s,{get:()=>t[s],enumerable:!(r=xt(t,s))||r.enumerable});return i};var Et=(i,t,e)=>(e=i!=null?yt(kt(i)):{},St(t||!i||!i.__esModule?H(e,"default",{value:i,enumerable:!0}):e,i));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ct='*,*:before,*:after{box-sizing:border-box;margin:0;padding:0}:host{all:initial;font-family:Inter,-apple-system,BlinkMacSystemFont,sans-serif;font-size:14px;line-height:1.5;color:#191a1c;-webkit-font-smoothing:antialiased}:host([data-mtb-theme="dark"]) .mtb-popup,:host([data-mtb-theme="dark"]) .mtb-success{background:#151719;border-color:#ffffff1f;color:#f9fafb}:host([data-mtb-theme="dark"]) .mtb-popup-header{border-bottom-color:#ffffff1a}:host([data-mtb-theme="dark"]) .mtb-popup-title,:host([data-mtb-theme="dark"]) .mtb-success-title{color:#f9fafb}:host([data-mtb-theme="dark"]) .mtb-quick-option,:host([data-mtb-theme="dark"]) .mtb-textarea{background:#1f2327;border-color:#ffffff1f;color:#f9fafb}:host([data-mtb-theme="dark"]) .mtb-popup-close,:host([data-mtb-theme="dark"]) .mtb-success-msg,:host([data-mtb-theme="dark"]) .mtb-close-link{color:#ffffffad}@media (prefers-color-scheme: dark){:host([data-mtb-theme="auto"]) .mtb-popup,:host([data-mtb-theme="auto"]) .mtb-success{background:#151719;border-color:#ffffff1f;color:#f9fafb}:host([data-mtb-theme="auto"]) .mtb-popup-header{border-bottom-color:#ffffff1a}:host([data-mtb-theme="auto"]) .mtb-popup-title,:host([data-mtb-theme="auto"]) .mtb-success-title{color:#f9fafb}:host([data-mtb-theme="auto"]) .mtb-quick-option,:host([data-mtb-theme="auto"]) .mtb-textarea{background:#1f2327;border-color:#ffffff1f;color:#f9fafb}:host([data-mtb-theme="auto"]) .mtb-popup-close,:host([data-mtb-theme="auto"]) .mtb-success-msg,:host([data-mtb-theme="auto"]) .mtb-close-link{color:#ffffffad}}.mtb-tab{position:fixed;top:50%;right:0;transform:translateY(-50%);z-index:2147483646;display:flex;align-items:center;justify-content:center;width:32px;padding:14px 0;background:#059669;color:#fff;border-radius:8px 0 0 8px;cursor:pointer;box-shadow:-2px 0 14px #05966959;transition:background .15s,box-shadow .15s,width .15s;writing-mode:vertical-lr;text-orientation:mixed;font-size:12px;font-weight:600;letter-spacing:.04em;user-select:none;border:none;outline:none}.mtb-tab.left{right:auto;left:0;border-radius:0 8px 8px 0;box-shadow:2px 0 14px #05966959}.mtb-tab:hover{background:#047857;box-shadow:-3px 0 20px #05966973}.mtb-tab.active{background:#065f46}.mtb-toolbar{position:fixed;top:18px;left:50%;transform:translate(-50%);z-index:2147483647;display:flex;align-items:center;gap:11px;height:46px;padding:0 7px;border-radius:13px;background:linear-gradient(120deg,#10b981,#059669);box-shadow:0 10px 26px #0f172a38;animation:mtbBarIn .2s ease;white-space:nowrap}@keyframes mtbBarIn{0%{transform:translate(-50%,12px);opacity:0}to{transform:translate(-50%);opacity:1}}.mtb-toolbar-modes{display:flex;align-items:center;gap:3px;background:#ffffff29;border-radius:9px;padding:3px}.mtb-toolbar-mode-btn{display:inline-flex;align-items:center;gap:6px;height:30px;padding:0 12px;border-radius:7px;border:none;cursor:pointer;font-family:inherit;font-size:12px;font-weight:550;white-space:nowrap;background:transparent;color:#fffffff2;transition:all .12s}.mtb-toolbar-mode-btn.active{background:#fff;color:#047857}.mtb-toolbar-hint{font-size:12px;color:#fffffff2;white-space:nowrap}.mtb-toolbar-sep{width:1px;height:20px;background:#ffffff38}.mtb-exit-btn{display:inline-flex;align-items:center;gap:5px;height:30px;padding:0 12px;border-radius:8px;font-size:11.5px;font-weight:500;color:#fff;cursor:pointer;background:#ffffff29;border:none;font-family:inherit;transition:background .12s}.mtb-exit-btn:hover{background:#ffffff47}.mtb-overlay{position:fixed;inset:0;z-index:2147483640;cursor:crosshair}.mtb-dim{position:fixed;inset:0;z-index:2147483639;background:#00000014}.mtb-highlight{position:fixed;z-index:2147483641;pointer-events:none;border:2px solid #10b981;border-radius:6px;background:#10b9810f;transition:all .08s ease}.mtb-highlight-tooltip{position:fixed;z-index:2147483642;pointer-events:none;transform:translate(-50%);background:#064e3b;color:#fff;padding:4px 10px;border-radius:6px;font-size:11px;font-weight:500;white-space:nowrap;box-shadow:0 4px 12px #0000002e}.mtb-highlight-tooltip:after{content:"";position:absolute;top:100%;left:50%;transform:translate(-50%);border:4px solid transparent;border-top-color:#064e3b}.mtb-draw-svg{position:fixed;inset:0;z-index:2147483643;pointer-events:none;width:100%;height:100%;overflow:visible}.mtb-pin{position:fixed;z-index:2147483644;pointer-events:none;width:22px;height:22px;border-radius:50% 50% 50% 2px;background:#059669;border:2px solid #fff;display:flex;align-items:center;justify-content:center;font-size:10px;color:#fff;font-weight:700;box-shadow:0 2px 8px #05966973;animation:mtbPinPop .25s cubic-bezier(.34,1.56,.64,1);transform:translate(-50%,-50%)}@keyframes mtbPinPop{0%{transform:translate(-50%,-50%) scale(.4)}to{transform:translate(-50%,-50%) scale(1)}}.mtb-popup{position:fixed;z-index:2147483645;width:320px;background:#fff;border:1px solid rgba(0,0,0,.1);border-radius:16px;box-shadow:0 24px 64px #0000003d;overflow:hidden;animation:mtbSlideUp .28s cubic-bezier(.34,1.56,.64,1);font-family:Inter,-apple-system,BlinkMacSystemFont,sans-serif}@keyframes mtbSlideUp{0%{transform:translateY(14px) scale(.97);opacity:0}to{transform:translateY(0) scale(1);opacity:1}}.mtb-popup-header{padding:11px 13px 11px 14px;border-bottom:1px solid rgba(0,0,0,.06);display:flex;align-items:center;gap:8px}.mtb-popup-icon{width:20px;height:20px;border-radius:5px;background:#10b9811a;display:flex;align-items:center;justify-content:center;flex-shrink:0}.mtb-popup-title{flex:1;font-size:12.5px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:#191a1c}.mtb-popup-close{background:none;border:none;cursor:pointer;padding:3px;color:#00000061;display:flex;align-items:center;border-radius:4px;transition:color .12s}.mtb-popup-close:hover{color:#000000b3}.mtb-popup-body{padding:13px}.mtb-quick-options{display:flex;flex-direction:column;gap:6px;margin-bottom:12px}.mtb-quick-option{display:flex;align-items:center;gap:10px;width:100%;padding:10px 12px;border:1px solid rgba(0,0,0,.09);border-radius:10px;background:#fafafa;cursor:pointer;font-family:inherit;font-size:13px;color:#191a1c;text-align:left;transition:all .12s}.mtb-quick-option:hover{background:#10b9810f;border-color:#10b9814d}.mtb-quick-option-emoji{font-size:15px;flex-shrink:0;line-height:1}.mtb-textarea-wrap{position:relative}.mtb-textarea{width:100%;height:64px;padding:9px 11px;border:1px solid rgba(0,0,0,.12);border-radius:10px;font-family:inherit;font-size:12.5px;line-height:1.5;color:#191a1c;outline:none;background:#fff;resize:none;transition:border-color .12s,box-shadow .12s}.mtb-textarea:focus{border-color:#10b981;box-shadow:0 0 0 3px #10b98126}.mtb-textarea::placeholder{color:#00000057}.mtb-popup-error{margin-top:8px;color:#dc2626;font-size:11.5px}.mtb-popup-error:empty,.mtb-popup-error[hidden]{display:none}.mtb-popup-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:12px}.mtb-cancel-btn,.mtb-submit-btn{min-width:72px;height:32px;border:none;border-radius:8px;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0 12px;font-family:inherit;font-size:12.5px;font-weight:600;transition:background .12s}.mtb-cancel-btn{background:#f3f4f6;color:#000000ad}.mtb-cancel-btn:hover{background:#e5e7eb}.mtb-submit-btn{background:#d1d5db;color:#fff}.mtb-submit-btn.ready{background:#059669}.mtb-submit-btn.ready:hover{background:#047857}.mtb-submit-btn.loading{background:#059669;opacity:.7;cursor:wait}.mtb-submit-btn:disabled{cursor:not-allowed}.mtb-success{position:fixed;z-index:2147483645;width:332px;background:#fff;border:1px solid rgba(0,0,0,.1);border-radius:16px;box-shadow:0 24px 64px #0000003d;padding:24px 22px;text-align:center;animation:mtbSlideUp .35s cubic-bezier(.34,1.56,.64,1);font-family:Inter,-apple-system,BlinkMacSystemFont,sans-serif}.mtb-success-icon{width:46px;height:46px;border-radius:50%;background:#05966917;display:flex;align-items:center;justify-content:center;margin:0 auto 12px}.mtb-success-title{font-size:16px;font-weight:700;margin-bottom:5px;letter-spacing:-.01em;color:#191a1c}.mtb-success-msg{font-size:13px;color:#0000008c;margin-bottom:16px;line-height:1.6}.mtb-view-feedback-link{display:inline-flex;align-items:center;gap:5px;color:#047857;text-decoration:none;font-size:13px;font-weight:500;font-family:JetBrains Mono,monospace;background:none;border:none;cursor:pointer;transition:text-decoration .12s}.mtb-view-feedback-link:hover{text-decoration:underline}.mtb-close-link{margin-top:13px;background:none;border:none;cursor:pointer;font-size:12px;color:#0006;font-family:inherit;transition:color .12s}.mtb-close-link:hover{color:#000000b3}.mtb-email-capture{margin-bottom:14px;text-align:left}.mtb-email-prompt{font-size:12px;color:#0000008c;line-height:1.5;margin-bottom:8px}.mtb-email-row{display:flex;gap:6px}.mtb-email-input{flex:1;min-width:0;font-size:12.5px;font-family:inherit;padding:7px 10px;border:1px solid rgba(0,0,0,.14);border-radius:8px;outline:none}.mtb-email-input:focus{border-color:#059669}.mtb-email-input.mtb-email-invalid{border-color:#dc2626}.mtb-email-submit{font-size:12px;font-weight:600;font-family:inherit;color:#fff;background:#059669;border:none;border-radius:8px;padding:7px 12px;cursor:pointer;white-space:nowrap}.mtb-email-submit:disabled{opacity:.6;cursor:default}.mtb-email-error{font-size:11.5px;color:#dc2626;margin-top:6px}.mtb-email-saved{font-size:12px;color:#059669;line-height:1.5}.mtb-my-feedback{display:block;margin:8px auto 0;background:none;border:none;cursor:pointer;font-size:11.5px;font-family:inherit;color:#0006;text-decoration:underline;text-underline-offset:2px;transition:color .12s}.mtb-my-feedback:hover{color:#059669}.mtb-pet{position:fixed;bottom:20px;right:20px;z-index:2147483646;cursor:pointer;width:52px;height:52px;display:flex;align-items:center;justify-content:center;border-radius:50%;background:transparent;animation:mtbPetBounce 3s ease-in-out infinite;transition:transform .2s;user-select:none;outline:none;filter:drop-shadow(0 4px 12px rgba(5,150,105,.35))}.mtb-pet:hover{transform:scale(1.12);animation-play-state:paused}.mtb-pet:hover .mtb-pet-bubble{opacity:1;transform:translate(-50%) translateY(0);pointer-events:auto}.mtb-pet.active{animation:none;opacity:.6}.mtb-pet-svg{display:block}@keyframes mtbPetBounce{0%,to{transform:translateY(0)}50%{transform:translateY(-6px)}}.mtb-pet-bubble{position:absolute;bottom:100%;left:50%;transform:translate(-50%) translateY(4px);margin-bottom:8px;background:#064e3b;color:#fff;padding:6px 12px;border-radius:8px;font-size:12px;font-weight:500;white-space:nowrap;box-shadow:0 4px 14px #0000002e;opacity:0;pointer-events:none;transition:opacity .2s,transform .2s}.mtb-pet-bubble.visible{opacity:1;transform:translate(-50%) translateY(0);pointer-events:auto}.mtb-pet-bubble.hidden{opacity:0;pointer-events:none}.mtb-pet-bubble:after{content:"";position:absolute;top:100%;left:50%;transform:translate(-50%);border:5px solid transparent;border-top-color:#064e3b}.mtb-frustration-prompt{position:fixed;bottom:20px;right:20px;z-index:2147483645;display:flex;align-items:center;gap:10px;padding:12px 16px;background:#fff;border:1px solid rgba(0,0,0,.1);border-radius:12px;box-shadow:0 8px 30px #0000001f;animation:mtbSlideUp .35s cubic-bezier(.34,1.56,.64,1);font-family:Inter,-apple-system,BlinkMacSystemFont,sans-serif}:host([data-mtb-theme="dark"]) .mtb-frustration-prompt{background:#151719;border-color:#ffffff1f;color:#f9fafb}@media (prefers-color-scheme: dark){:host([data-mtb-theme="auto"]) .mtb-frustration-prompt{background:#151719;border-color:#ffffff1f;color:#f9fafb}}.mtb-frustration-icon{width:32px;height:32px;border-radius:50%;background:#eab3081a;display:flex;align-items:center;justify-content:center;flex-shrink:0;font-size:16px;line-height:1}.mtb-frustration-text{font-size:13px;font-weight:500;color:inherit;line-height:1.4}.mtb-frustration-actions{display:flex;gap:6px;flex-shrink:0}.mtb-frustration-tell{height:28px;padding:0 12px;border:none;border-radius:7px;background:#059669;color:#fff;cursor:pointer;font-family:inherit;font-size:12px;font-weight:600;transition:background .12s}.mtb-frustration-tell:hover{background:#047857}.mtb-frustration-dismiss{height:28px;padding:0 8px;border:none;border-radius:7px;background:transparent;color:#0006;cursor:pointer;font-family:inherit;font-size:12px;transition:color .12s}.mtb-frustration-dismiss:hover{color:#000000b3}:host([data-mtb-theme="dark"]) .mtb-frustration-dismiss{color:#fff6}:host([data-mtb-theme="dark"]) .mtb-frustration-dismiss:hover{color:#ffffffb3}@media (prefers-color-scheme: dark){:host([data-mtb-theme="auto"]) .mtb-frustration-dismiss{color:#fff6}:host([data-mtb-theme="auto"]) .mtb-frustration-dismiss:hover{color:#ffffffb3}}.mtb-record-bar{position:fixed;bottom:24px;left:50%;transform:translate(-50%);z-index:2147483647;display:flex;align-items:center;gap:12px;height:42px;padding:0 8px 0 14px;border-radius:12px;background:#0f172aeb;box-shadow:0 8px 24px #00000040;animation:mtbBarIn .2s ease}.mtb-record-dot{width:8px;height:8px;border-radius:50%;background:#ef4444;animation:mtbRecordPulse 1.2s ease-in-out infinite;flex-shrink:0}@keyframes mtbRecordPulse{0%,to{opacity:1}50%{opacity:.3}}.mtb-record-timer{font-family:JetBrains Mono,SF Mono,Fira Code,Cascadia Code,monospace;font-size:13px;font-weight:500;color:#fff;font-variant-numeric:tabular-nums;letter-spacing:.02em;min-width:38px}.mtb-record-stop{height:28px;padding:0 14px;border:none;border-radius:7px;background:#059669;color:#fff;cursor:pointer;font-family:inherit;font-size:12px;font-weight:600;transition:background .12s}.mtb-record-stop:hover{background:#047857}.mtb-click-ripple{position:fixed;z-index:2147483644;width:24px;height:24px;border-radius:50%;border:2px solid #10b981;background:#10b98133;pointer-events:none;transform:translate(-50%,-50%) scale(.5);animation:mtbClickRipple .3s ease-out forwards}@keyframes mtbClickRipple{0%{transform:translate(-50%,-50%) scale(.5);opacity:1}to{transform:translate(-50%,-50%) scale(2);opacity:0}}.mtb-dot{display:inline-block;width:4px;height:4px;border-radius:50%;background:#fff;animation:mtbDot 1.2s infinite}.mtb-dot:nth-child(2){animation-delay:.2s}.mtb-dot:nth-child(3){animation-delay:.4s}@keyframes mtbDot{0%,80%,to{opacity:.3;transform:translateY(0)}40%{opacity:1;transform:translateY(-3px)}}.mtb-clarify{position:fixed;z-index:2147483645;width:346px;background:#fff;border:1px solid rgba(0,0,0,.1);border-radius:16px;box-shadow:0 24px 64px #0000003d;display:flex;flex-direction:column;animation:mtbSlideUp .28s cubic-bezier(.34,1.56,.64,1);font-family:Inter,-apple-system,BlinkMacSystemFont,sans-serif;overflow:hidden}.mtb-clarify-header{padding:11px 13px 11px 14px;display:flex;align-items:center;gap:9px;border-bottom:1px solid rgba(0,0,0,.06)}.mtb-clarify-icon{width:24px;height:24px;border-radius:7px;background:linear-gradient(140deg,#10b981,#059669);box-shadow:0 1px 3px #05966966;display:flex;align-items:center;justify-content:center;flex-shrink:0}.mtb-clarify-titles{flex:1;min-width:0}.mtb-clarify-title{font-size:12.5px;font-weight:650;line-height:1.2;color:#191a1c}.mtb-clarify-subtitle{font-size:10px;color:#0000006b}.mtb-clarify-close{background:none;border:none;cursor:pointer;padding:3px;color:#00000061;display:flex;transition:color .12s}.mtb-clarify-close:hover{color:#000000b3}.mtb-clarify-messages{flex:1;max-height:250px;overflow-y:auto;padding:13px 13px 5px;display:flex;flex-direction:column;gap:9px}.mtb-clarify-bubble{max-width:82%;padding:9px 12px;font-size:12.5px;line-height:1.5;white-space:pre-wrap;word-break:break-word}.mtb-clarify-ai{align-self:flex-start;background:#fff;color:#191a1c;border:1px solid rgba(0,0,0,.09);border-radius:13px 13px 13px 4px}.mtb-clarify-user{align-self:flex-end;background:#059669;color:#fff;border:1px solid #059669;border-radius:13px 13px 4px}.mtb-clarify-thinking{display:flex;align-items:center;gap:4px;padding:11px 14px}.mtb-clarify-thinking .mtb-dot{width:6px;height:6px;background:#059669b3}.mtb-clarify-footer{padding:3px 13px 13px;display:flex;flex-direction:column}.mtb-clarify-input{width:100%;height:52px;padding:9px 11px;border:1px solid rgba(0,0,0,.12);border-radius:10px;font-family:inherit;font-size:13px;line-height:1.5;color:#191a1c;outline:none;background:#fafafa;resize:none;box-sizing:border-box;transition:border-color .12s,box-shadow .12s,background .12s}.mtb-clarify-input:focus{border-color:#10b981;box-shadow:0 0 0 3px #10b98126;background:#fff}.mtb-clarify-input::placeholder{color:#00000057}.mtb-clarify-actions{display:flex;gap:8px;margin-top:9px}.mtb-clarify-skip{flex:0 0 auto;height:34px;padding:0 14px;border:1px solid rgba(0,0,0,.12);border-radius:10px;background:#fff;cursor:pointer;font-family:inherit;font-size:12.5px;font-weight:550;color:#0000008c;transition:background .12s}.mtb-clarify-skip:hover{background:#0000000a}.mtb-clarify-send{flex:1;height:34px;display:inline-flex;align-items:center;justify-content:center;gap:6px;border:none;border-radius:10px;background:#059669;color:#fff;cursor:pointer;font-family:inherit;font-size:12.5px;font-weight:600;transition:background .12s}.mtb-clarify-send:not(:disabled):hover{background:#047857}.mtb-clarify-send:disabled{background:#00000026;cursor:not-allowed}:host([data-mtb-theme="dark"]) .mtb-clarify{background:#151719;border-color:#ffffff1f;color:#f9fafb}:host([data-mtb-theme="dark"]) .mtb-clarify-header{border-bottom-color:#ffffff1a}:host([data-mtb-theme="dark"]) .mtb-clarify-title{color:#f9fafb}:host([data-mtb-theme="dark"]) .mtb-clarify-subtitle{color:#ffffff73}:host([data-mtb-theme="dark"]) .mtb-clarify-close{color:#ffffff73}:host([data-mtb-theme="dark"]) .mtb-clarify-close:hover{color:#ffffffbf}:host([data-mtb-theme="dark"]) .mtb-clarify-skip{background:#1f2327;border-color:#ffffff24;color:#ffffffb3}:host([data-mtb-theme="dark"]) .mtb-clarify-skip:hover{background:#ffffff0f}:host([data-mtb-theme="dark"]) .mtb-clarify-ai{background:#1f2327;border-color:#ffffff1f;color:#f9fafb}:host([data-mtb-theme="dark"]) .mtb-clarify-input{background:#1f2327;border-color:#ffffff1f;color:#f9fafb}@media (prefers-color-scheme: dark){:host([data-mtb-theme="auto"]) .mtb-clarify{background:#151719;border-color:#ffffff1f;color:#f9fafb}:host([data-mtb-theme="auto"]) .mtb-clarify-header{border-bottom-color:#ffffff1a}:host([data-mtb-theme="auto"]) .mtb-clarify-title{color:#f9fafb}:host([data-mtb-theme="auto"]) .mtb-clarify-subtitle{color:#ffffff73}:host([data-mtb-theme="auto"]) .mtb-clarify-close{color:#ffffff73}:host([data-mtb-theme="auto"]) .mtb-clarify-close:hover{color:#ffffffbf}:host([data-mtb-theme="auto"]) .mtb-clarify-skip{background:#1f2327;border-color:#ffffff24;color:#ffffffb3}:host([data-mtb-theme="auto"]) .mtb-clarify-skip:hover{background:#ffffff0f}:host([data-mtb-theme="auto"]) .mtb-clarify-ai{background:#1f2327;border-color:#ffffff1f;color:#f9fafb}:host([data-mtb-theme="auto"]) .mtb-clarify-input{background:#1f2327;border-color:#ffffff1f;color:#f9fafb}}';class _t{constructor(t="auto"){this.host=document.createElement("div"),this.host.id="mtb-widget-host",this.host.style.cssText="position:fixed;top:0;left:0;width:0;height:0;overflow:visible;z-index:2147483646;",this.host.setAttribute("data-mtb-theme",t),document.body.appendChild(this.host),this.root=this.host.attachShadow({mode:"open"});const e=document.createElement("style");e.textContent=Ct,this.root.appendChild(e)}el(t,e){const r=document.createElement(t);return e&&(r.className=e),r}append(...t){for(const e of t)this.root.appendChild(e)}remove(...t){for(const e of t)e.parentNode===this.root&&this.root.removeChild(e)}destroy(){this.host.remove()}}class Mt{constructor(t,e,r,s,n){this.onClick=s,this.el=t.el("button","mtb-tab"),r==="left"&&this.el.classList.add("left");const o=n??e.tab;this.el.textContent=o,this.el.setAttribute("aria-label",o),this.el.addEventListener("click",s),t.append(this.el)}setActive(t){this.el.classList.toggle("active",t)}destroy(){this.el.removeEventListener("click",this.onClick),this.el.remove()}}const Tt=8e3;class Lt{constructor(t,e,r){this.el=t.el("div","mtb-frustration-prompt"),this.el.innerHTML=`
2
2
  <div class="mtb-frustration-icon">&#9888;&#65039;</div>
3
3
  <span class="mtb-frustration-text">${e.frustration.prompt}</span>
4
4
  <div class="mtb-frustration-actions">
5
5
  <button class="mtb-frustration-tell">${e.frustration.action}</button>
6
6
  <button class="mtb-frustration-dismiss">${e.frustration.dismiss}</button>
7
7
  </div>
8
- `,this.el.querySelector(".mtb-frustration-tell").addEventListener("click",r.onTell),this.el.querySelector(".mtb-frustration-dismiss").addEventListener("click",r.onDismiss),t.append(this.el),setTimeout(r.onDismiss,Mt)}destroy(){this.el.remove()}}class At{constructor(t,e,r,s){this.currentMode="markup",this.messages=e,this.el=t.el("div","mtb-toolbar"),this.el.innerHTML=this.buildHTML(e),t.append(this.el),this.hintEl=this.el.querySelector(".mtb-toolbar-hint"),this.markupBtn=this.el.querySelector(".mtb-toolbar-mode-markup"),this.recordBtn=this.el.querySelector(".mtb-toolbar-mode-record"),this.markupBtn.addEventListener("click",()=>{this.setMode("markup"),s?.("markup")}),this.recordBtn.addEventListener("click",()=>{this.setMode("record"),s?.("record")}),this.el.querySelector(".mtb-exit-btn").addEventListener("click",r)}buildHTML(t){return`
8
+ `,this.el.querySelector(".mtb-frustration-tell").addEventListener("click",r.onTell),this.el.querySelector(".mtb-frustration-dismiss").addEventListener("click",r.onDismiss),t.append(this.el),setTimeout(r.onDismiss,Tt)}destroy(){this.el.remove()}}class At{constructor(t,e,r,s){this.currentMode="markup",this.messages=e,this.el=t.el("div","mtb-toolbar"),this.el.innerHTML=this.buildHTML(e),t.append(this.el),this.hintEl=this.el.querySelector(".mtb-toolbar-hint"),this.markupBtn=this.el.querySelector(".mtb-toolbar-mode-markup"),this.recordBtn=this.el.querySelector(".mtb-toolbar-mode-record"),this.markupBtn.addEventListener("click",()=>{this.setMode("markup"),s?.("markup")}),this.recordBtn.addEventListener("click",()=>{this.setMode("record"),s?.("record")}),this.el.querySelector(".mtb-exit-btn").addEventListener("click",r)}buildHTML(t){return`
9
9
  <div class="mtb-toolbar-modes">
10
10
  <button class="mtb-toolbar-mode-btn mtb-toolbar-mode-markup active">
11
11
  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><line x1="12" y1="3" x2="12" y2="7"/><line x1="12" y1="17" x2="12" y2="21"/><line x1="3" y1="12" x2="7" y2="12"/><line x1="17" y1="12" x2="21" y2="12"/></svg>${t.toolbar.markup}
@@ -21,7 +21,7 @@
21
21
  <path d="M18 6L6 18M6 6l12 12"/>
22
22
  </svg>${t.toolbar.exit}
23
23
  </button>
24
- `}setMode(t){this.currentMode=t,t==="markup"?(this.markupBtn.classList.add("active"),this.recordBtn.classList.remove("active"),this.hintEl.textContent=this.messages.toolbar.hint):(this.markupBtn.classList.remove("active"),this.recordBtn.classList.add("active"),this.hintEl.textContent=this.messages.toolbar.hintRecord)}getMode(){return this.currentMode}destroy(){this.el.remove()}}class Dt{constructor(t,e){this.onMouseDown=e.onMouseDown,this.onMouseMove=e.onMouseMove,this.onMouseUp=e.onMouseUp,this.onMouseLeave=e.onMouseLeave,this.overlayEl=t.el("div","mtb-overlay"),this.overlayEl.addEventListener("mousedown",this.onMouseDown),this.overlayEl.addEventListener("mousemove",this.onMouseMove),this.overlayEl.addEventListener("mouseup",this.onMouseUp),this.overlayEl.addEventListener("mouseleave",this.onMouseLeave),t.append(this.overlayEl),this.dimEl=t.el("div","mtb-dim"),t.append(this.dimEl)}destroy(){this.overlayEl.removeEventListener("mousedown",this.onMouseDown),this.overlayEl.removeEventListener("mousemove",this.onMouseMove),this.overlayEl.removeEventListener("mouseup",this.onMouseUp),this.overlayEl.removeEventListener("mouseleave",this.onMouseLeave),this.overlayEl.remove(),this.dimEl.remove()}}class Rt{constructor(t){this.highlightEl=t.el("div","mtb-highlight"),this.hide(),t.append(this.highlightEl)}highlight(t){const e=t.getBoundingClientRect();this.highlightEl.style.top=`${e.top-2}px`,this.highlightEl.style.left=`${e.left-2}px`,this.highlightEl.style.width=`${e.width+4}px`,this.highlightEl.style.height=`${e.height+4}px`,this.highlightEl.style.display="block"}hide(){this.highlightEl.style.display="none"}destroy(){this.highlightEl.remove()}}function Pt(i){if(i instanceof HTMLElement){const t=i.getAttribute("aria-label");if(t)return t;const e=i.getAttribute("title");if(e)return e;const r=i.textContent?.trim().slice(0,40);if(r)return r;const s=i.placeholder;if(s)return s;const n=i.alt;if(n)return n;const o=i.getAttribute("data-mark");if(o)return o}return i.tagName.toLowerCase()}function It(i){const t=[];let e=i;for(;e&&e!==document.body&&t.length<5;){let r=e.tagName.toLowerCase();if(e.id){r=`#${e.id}`,t.unshift(r);break}const s=Array.from(e.classList).filter(o=>!o.startsWith("mtb-")).slice(0,2).join(".");s&&(r+=`.${s}`);const n=e.parentElement;if(n){const o=Array.from(n.children).filter(a=>a.tagName===e.tagName);if(o.length>1){const a=o.indexOf(e)+1;r+=`:nth-child(${a})`}}t.unshift(r),e=e.parentElement}return t.join(" > ")}class $t{constructor(t){this.pins=[],this.shadow=t}addPin(t,e,r){const s=this.shadow.el("div","mtb-pin");s.textContent=String(r),s.style.top=`${e}px`,s.style.left=`${t}px`,this.shadow.append(s),this.pins.push(s)}clearAll(){for(const t of this.pins)t.remove();this.pins=[]}destroy(){this.clearAll()}}const it="#059669",v={color:it,width:"3.5",linecap:"round",linejoin:"round",filter:"drop-shadow(0 1px 2px rgba(5,150,105,0.35))"};class Ht{constructor(t,e){this.path=null,this.points=[],this.isDrawing=!1,this.onDrawComplete=e,this.svg=document.createElementNS("http://www.w3.org/2000/svg","svg"),this.svg.setAttribute("class","mtb-draw-svg"),t.append(this.svg)}startDraw(t,e){this.isDrawing=!0,this.points=[[t,e]],this.path=document.createElementNS("http://www.w3.org/2000/svg","path"),this.path.setAttribute("fill","none"),this.path.setAttribute("stroke",v.color),this.path.setAttribute("stroke-width",v.width),this.path.setAttribute("stroke-linecap",v.linecap),this.path.setAttribute("stroke-linejoin",v.linejoin),this.path.setAttribute("style",`filter:${v.filter}`),this.svg.appendChild(this.path)}continueDraw(t,e){!this.isDrawing||!this.path||(this.points.push([t,e]),this.path.setAttribute("d",this.buildPathD()))}endDraw(){if(!this.isDrawing||this.points.length<2){this.isDrawing=!1,this.path&&(this.path.remove(),this.path=null);return}this.isDrawing=!1;const t=this.getCenter(),e=this.buildPathD(),r={type:"draw",x:t[0],y:t[1],drawPath:e};this.onDrawComplete(r)}buildPathD(){if(this.points.length===0)return"";const[t,e]=this.points[0];let r=`M ${t} ${e}`;for(let s=1;s<this.points.length;s++){const[n,o]=this.points[s];r+=` L ${n} ${o}`}return r}getCenter(){const t=this.points.map(n=>n[0]),e=this.points.map(n=>n[1]),r=(Math.min(...t)+Math.max(...t))/2,s=(Math.min(...e)+Math.max(...e))/2;return[r,s]}clearAll(){for(;this.svg.firstChild;)this.svg.removeChild(this.svg.firstChild);this.path=null,this.isDrawing=!1,this.points=[]}cancelCurrentDraw(){this.path?.remove(),this.path=null,this.isDrawing=!1,this.points=[]}isCurrentlyDrawing(){return this.isDrawing}getPointCount(){return this.points.length}destroy(){this.svg.remove()}}const Ot=5;class O{constructor(t,e,r){this.messages=e,this.onReady=r,this.pinCount=0,this.interactionActive=!0,this.pendingHighlightFrame=null,this.lastMoveX=0,this.lastMoveY=0,this.highlighter=new Rt(t),this.pinMarker=new $t(t),this.drawLayer=new Ht(t,s=>{this.onReady(s,this.messages.annotation.drawing)}),this.overlay=new Dt(t,{onMouseDown:s=>this.handleMouseDown(s),onMouseMove:s=>this.handleMouseMove(s),onMouseUp:s=>this.handleMouseUp(s),onMouseLeave:()=>{this.drawLayer.isCurrentlyDrawing()&&this.drawLayer.endDraw(),this.cancelPendingHighlight(),this.highlighter.hide()}})}handleMouseDown(t){t.preventDefault(),this.drawLayer.startDraw(t.clientX,t.clientY)}handleMouseMove(t){if(this.drawLayer.isCurrentlyDrawing()){this.cancelPendingHighlight(),this.drawLayer.continueDraw(t.clientX,t.clientY),this.highlighter.hide();return}this.lastMoveX=t.clientX,this.lastMoveY=t.clientY,this.pendingHighlightFrame===null&&(this.pendingHighlightFrame=requestAnimationFrame(()=>{this.pendingHighlightFrame=null,this.updateHighlight()}))}updateHighlight(){if(!this.interactionActive||this.drawLayer.isCurrentlyDrawing())return;const t=F(this.lastMoveX,this.lastMoveY);t?this.highlighter.highlight(t):this.highlighter.hide()}cancelPendingHighlight(){this.pendingHighlightFrame!==null&&(cancelAnimationFrame(this.pendingHighlightFrame),this.pendingHighlightFrame=null)}handleMouseUp(t){if(!this.drawLayer.isCurrentlyDrawing())return;if(this.drawLayer.getPointCount()>=Ot){this.drawLayer.endDraw();return}this.drawLayer.cancelCurrentDraw();const e=F(t.clientX,t.clientY),r=e?Pt(e):this.messages.annotation.element,s={type:"pin",x:t.clientX,y:t.clientY,targetSelector:e?It(e):void 0,targetText:e?.textContent?.trim().slice(0,200)??"",targetName:r};this.pinMarker.addPin(t.clientX,t.clientY,++this.pinCount),this.drawLayer.clearAll(),this.highlighter.hide(),this.onReady(s,r)}dismissInteraction(){this.interactionActive&&(this.interactionActive=!1,this.cancelPendingHighlight(),this.overlay.destroy(),this.highlighter.destroy())}destroy(){this.dismissInteraction(),this.pinMarker.destroy(),this.drawLayer.destroy()}}function F(i,t){return document.elementsFromPoint(i,t).find(e=>e.id!=="mtb-widget-host")??null}class Ft{constructor(t,e){this.loading=!1,this.onSubmit=e.onSubmit,this.onClose=e.onClose,this.submitLabel=e.messages.popup.submit,this.el=t.el("div","mtb-popup"),this.el.innerHTML=this.buildHTML(e),t.append(this.el),this.textarea=this.el.querySelector(".mtb-textarea"),this.submitBtn=this.el.querySelector(".mtb-submit-btn"),this.positionPopup(e.x,e.y),this.bindEvents(e.messages),e.onMyFeedback&&this.el.querySelector(".mtb-my-feedback").addEventListener("click",e.onMyFeedback),this.textarea.focus()}buildHTML(t){const e=t.messages,r=e.popup.quickOptions.map(s=>`
24
+ `}setMode(t){this.currentMode=t,t==="markup"?(this.markupBtn.classList.add("active"),this.recordBtn.classList.remove("active"),this.hintEl.textContent=this.messages.toolbar.hint):(this.markupBtn.classList.remove("active"),this.recordBtn.classList.add("active"),this.hintEl.textContent=this.messages.toolbar.hintRecord)}getMode(){return this.currentMode}destroy(){this.el.remove()}}class Dt{constructor(t,e){this.onMouseDown=e.onMouseDown,this.onMouseMove=e.onMouseMove,this.onMouseUp=e.onMouseUp,this.onMouseLeave=e.onMouseLeave,this.overlayEl=t.el("div","mtb-overlay"),this.overlayEl.addEventListener("mousedown",this.onMouseDown),this.overlayEl.addEventListener("mousemove",this.onMouseMove),this.overlayEl.addEventListener("mouseup",this.onMouseUp),this.overlayEl.addEventListener("mouseleave",this.onMouseLeave),t.append(this.overlayEl),this.dimEl=t.el("div","mtb-dim"),t.append(this.dimEl)}destroy(){this.overlayEl.removeEventListener("mousedown",this.onMouseDown),this.overlayEl.removeEventListener("mousemove",this.onMouseMove),this.overlayEl.removeEventListener("mouseup",this.onMouseUp),this.overlayEl.removeEventListener("mouseleave",this.onMouseLeave),this.overlayEl.remove(),this.dimEl.remove()}}class Pt{constructor(t){this.highlightEl=t.el("div","mtb-highlight"),this.hide(),t.append(this.highlightEl)}highlight(t){const e=t.getBoundingClientRect();this.highlightEl.style.top=`${e.top-2}px`,this.highlightEl.style.left=`${e.left-2}px`,this.highlightEl.style.width=`${e.width+4}px`,this.highlightEl.style.height=`${e.height+4}px`,this.highlightEl.style.display="block"}hide(){this.highlightEl.style.display="none"}destroy(){this.highlightEl.remove()}}function Rt(i){if(i instanceof HTMLElement){const t=i.getAttribute("aria-label");if(t)return t;const e=i.getAttribute("title");if(e)return e;const r=i.textContent?.trim().slice(0,40);if(r)return r;const s=i.placeholder;if(s)return s;const n=i.alt;if(n)return n;const o=i.getAttribute("data-mark");if(o)return o}return i.tagName.toLowerCase()}function It(i){const t=[];let e=i;for(;e&&e!==document.body&&t.length<5;){let r=e.tagName.toLowerCase();if(e.id){r=`#${e.id}`,t.unshift(r);break}const s=Array.from(e.classList).filter(o=>!o.startsWith("mtb-")).slice(0,2).join(".");s&&(r+=`.${s}`);const n=e.parentElement;if(n){const o=Array.from(n.children).filter(a=>a.tagName===e.tagName);if(o.length>1){const a=o.indexOf(e)+1;r+=`:nth-child(${a})`}}t.unshift(r),e=e.parentElement}return t.join(" > ")}class $t{constructor(t){this.pins=[],this.shadow=t}addPin(t,e,r){const s=this.shadow.el("div","mtb-pin");s.textContent=String(r),s.style.top=`${e}px`,s.style.left=`${t}px`,this.shadow.append(s),this.pins.push(s)}clearAll(){for(const t of this.pins)t.remove();this.pins=[]}destroy(){this.clearAll()}}const it="#059669",v={color:it,width:"3.5",linecap:"round",linejoin:"round",filter:"drop-shadow(0 1px 2px rgba(5,150,105,0.35))"};class Ht{constructor(t,e){this.path=null,this.points=[],this.isDrawing=!1,this.onDrawComplete=e,this.svg=document.createElementNS("http://www.w3.org/2000/svg","svg"),this.svg.setAttribute("class","mtb-draw-svg"),t.append(this.svg)}startDraw(t,e){this.isDrawing=!0,this.points=[[t,e]],this.path=document.createElementNS("http://www.w3.org/2000/svg","path"),this.path.setAttribute("fill","none"),this.path.setAttribute("stroke",v.color),this.path.setAttribute("stroke-width",v.width),this.path.setAttribute("stroke-linecap",v.linecap),this.path.setAttribute("stroke-linejoin",v.linejoin),this.path.setAttribute("style",`filter:${v.filter}`),this.svg.appendChild(this.path)}continueDraw(t,e){!this.isDrawing||!this.path||(this.points.push([t,e]),this.path.setAttribute("d",this.buildPathD()))}endDraw(){if(!this.isDrawing||this.points.length<2){this.isDrawing=!1,this.path&&(this.path.remove(),this.path=null);return}this.isDrawing=!1;const t=this.getCenter(),e=this.buildPathD(),r={type:"draw",x:t[0],y:t[1],drawPath:e};this.onDrawComplete(r)}buildPathD(){if(this.points.length===0)return"";const[t,e]=this.points[0];let r=`M ${t} ${e}`;for(let s=1;s<this.points.length;s++){const[n,o]=this.points[s];r+=` L ${n} ${o}`}return r}getCenter(){const t=this.points.map(n=>n[0]),e=this.points.map(n=>n[1]),r=(Math.min(...t)+Math.max(...t))/2,s=(Math.min(...e)+Math.max(...e))/2;return[r,s]}clearAll(){for(;this.svg.firstChild;)this.svg.removeChild(this.svg.firstChild);this.path=null,this.isDrawing=!1,this.points=[]}cancelCurrentDraw(){this.path?.remove(),this.path=null,this.isDrawing=!1,this.points=[]}isCurrentlyDrawing(){return this.isDrawing}getPointCount(){return this.points.length}destroy(){this.svg.remove()}}const Ot=5;class O{constructor(t,e,r){this.messages=e,this.onReady=r,this.pinCount=0,this.interactionActive=!0,this.pendingHighlightFrame=null,this.lastMoveX=0,this.lastMoveY=0,this.highlighter=new Pt(t),this.pinMarker=new $t(t),this.drawLayer=new Ht(t,s=>{this.onReady(s,this.messages.annotation.drawing)}),this.overlay=new Dt(t,{onMouseDown:s=>this.handleMouseDown(s),onMouseMove:s=>this.handleMouseMove(s),onMouseUp:s=>this.handleMouseUp(s),onMouseLeave:()=>{this.drawLayer.isCurrentlyDrawing()&&this.drawLayer.endDraw(),this.cancelPendingHighlight(),this.highlighter.hide()}})}handleMouseDown(t){t.preventDefault(),this.drawLayer.startDraw(t.clientX,t.clientY)}handleMouseMove(t){if(this.drawLayer.isCurrentlyDrawing()){this.cancelPendingHighlight(),this.drawLayer.continueDraw(t.clientX,t.clientY),this.highlighter.hide();return}this.lastMoveX=t.clientX,this.lastMoveY=t.clientY,this.pendingHighlightFrame===null&&(this.pendingHighlightFrame=requestAnimationFrame(()=>{this.pendingHighlightFrame=null,this.updateHighlight()}))}updateHighlight(){if(!this.interactionActive||this.drawLayer.isCurrentlyDrawing())return;const t=F(this.lastMoveX,this.lastMoveY);t?this.highlighter.highlight(t):this.highlighter.hide()}cancelPendingHighlight(){this.pendingHighlightFrame!==null&&(cancelAnimationFrame(this.pendingHighlightFrame),this.pendingHighlightFrame=null)}handleMouseUp(t){if(!this.drawLayer.isCurrentlyDrawing())return;if(this.drawLayer.getPointCount()>=Ot){this.drawLayer.endDraw();return}this.drawLayer.cancelCurrentDraw();const e=F(t.clientX,t.clientY),r=e?Rt(e):this.messages.annotation.element,s={type:"pin",x:t.clientX,y:t.clientY,targetSelector:e?It(e):void 0,targetText:e?.textContent?.trim().slice(0,200)??"",targetName:r};this.pinMarker.addPin(t.clientX,t.clientY,++this.pinCount),this.drawLayer.clearAll(),this.highlighter.hide(),this.onReady(s,r)}dismissInteraction(){this.interactionActive&&(this.interactionActive=!1,this.cancelPendingHighlight(),this.overlay.destroy(),this.highlighter.destroy())}destroy(){this.dismissInteraction(),this.pinMarker.destroy(),this.drawLayer.destroy()}}function F(i,t){return document.elementsFromPoint(i,t).find(e=>e.id!=="mtb-widget-host")??null}class Ft{constructor(t,e){this.loading=!1,this.onSubmit=e.onSubmit,this.onClose=e.onClose,this.submitLabel=e.messages.popup.submit,this.el=t.el("div","mtb-popup"),this.el.innerHTML=this.buildHTML(e),t.append(this.el),this.textarea=this.el.querySelector(".mtb-textarea"),this.submitBtn=this.el.querySelector(".mtb-submit-btn"),this.positionPopup(e.x,e.y),this.bindEvents(e.messages),e.onMyFeedback&&this.el.querySelector(".mtb-my-feedback").addEventListener("click",e.onMyFeedback),this.textarea.focus()}buildHTML(t){const e=t.messages,r=e.popup.quickOptions.map(s=>`
25
25
  <button class="mtb-quick-option" data-quick="${p(s.label)}">
26
26
  <span class="mtb-quick-option-emoji">${s.emoji}</span>
27
27
  <span>${p(s.label)}</span>
@@ -53,7 +53,7 @@
53
53
  </div>
54
54
  ${t.onMyFeedback?`<button class="mtb-my-feedback" type="button">${p(e.popup.my_feedback)}</button>`:""}
55
55
  </div>
56
- `}positionPopup(t,e){const n=window.innerWidth,o=window.innerHeight,a=12;let l=t+12,c=e+12;l+320>n-a&&(l=t-320-12),l<a&&(l=a),c+260>o-a&&(c=o-260-a),c<a&&(c=a),this.el.style.left=`${l}px`,this.el.style.top=`${c}px`}bindEvents(t){this.el.querySelector(".mtb-popup-close").addEventListener("click",()=>this.onClose()),this.el.querySelector(".mtb-cancel-btn").addEventListener("click",()=>this.onClose()),this.errorEl=this.el.querySelector(".mtb-popup-error"),this.el.querySelectorAll(".mtb-quick-option").forEach(e=>{e.addEventListener("click",()=>{const r=e.dataset.quick??"";this.textarea.value=r,this.updateSubmitState(),this.textarea.focus()})}),this.textarea.addEventListener("input",()=>this.updateSubmitState()),this.textarea.addEventListener("keydown",e=>{e.key==="Enter"&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),this.submit())}),this.submitBtn.addEventListener("click",()=>this.submit())}updateSubmitState(){const t=this.textarea.value.trim().length>0;this.submitBtn.classList.toggle("ready",t&&!this.loading),this.submitBtn.disabled=!t||this.loading,this.errorEl.hidden=!0,this.errorEl.textContent=""}submit(){const t=this.textarea.value.trim();!t||this.loading||this.onSubmit(t)}setLoading(t){this.loading=t,t?(this.submitBtn.classList.add("loading"),this.submitBtn.innerHTML='<span class="mtb-dot"></span><span class="mtb-dot"></span><span class="mtb-dot"></span>',this.textarea.disabled=!0):(this.submitBtn.classList.remove("loading"),this.submitBtn.textContent=this.submitLabel,this.textarea.disabled=!1),this.updateSubmitState()}setError(t){this.errorEl.textContent=t,this.errorEl.hidden=!1}destroy(){this.el.remove()}}function p(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}const jt=2e3,Ut=2e3,Bt=45e3,L=346,A=320;class zt{constructor(t,e){this.pollTimer=null,this.pollDeadline=0,this.doneTimer=null,this.streamingBubble=null,this.sending=!1,this.destroyed=!1,this.feedbackId=e.feedbackId,this.apiClient=e.apiClient,this.onDone=e.onDone,this.el=t.el("div","mtb-clarify"),this.el.innerHTML=this.buildHTML(e.messages),this.positionCard(e.x,e.y),t.append(this.el),this.messagesEl=this.el.querySelector(".mtb-clarify-messages"),this.inputEl=this.el.querySelector(".mtb-clarify-input"),this.sendBtn=this.el.querySelector(".mtb-clarify-send"),this.bindEvents(e.messages),this.startConversation()}positionCard(t,e){const r=window.innerWidth,s=window.innerHeight,n=12;if(t===void 0||e===void 0){this.el.style.left=`${Math.max(n,(r-L)/2)}px`,this.el.style.top=`${Math.max(n,(s-A)/2)}px`;return}let o=t+12,a=e+12;o+L>r-n&&(o=t-L-12),o<n&&(o=n),a+A>s-n&&(a=s-A-n),a<n&&(a=n),this.el.style.left=`${o}px`,this.el.style.top=`${a}px`}buildHTML(t){return`
56
+ `}positionPopup(t,e){const n=window.innerWidth,o=window.innerHeight,a=12;let l=t+12,c=e+12;l+320>n-a&&(l=t-320-12),l<a&&(l=a),c+260>o-a&&(c=o-260-a),c<a&&(c=a),this.el.style.left=`${l}px`,this.el.style.top=`${c}px`}bindEvents(t){this.el.querySelector(".mtb-popup-close").addEventListener("click",()=>this.onClose()),this.el.querySelector(".mtb-cancel-btn").addEventListener("click",()=>this.onClose()),this.errorEl=this.el.querySelector(".mtb-popup-error"),this.el.querySelectorAll(".mtb-quick-option").forEach(e=>{e.addEventListener("click",()=>{const r=e.dataset.quick??"";this.textarea.value=r,this.updateSubmitState(),this.textarea.focus()})}),this.textarea.addEventListener("input",()=>this.updateSubmitState()),this.textarea.addEventListener("keydown",e=>{e.key==="Enter"&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),this.submit())}),this.submitBtn.addEventListener("click",()=>this.submit())}updateSubmitState(){const t=this.textarea.value.trim().length>0;this.submitBtn.classList.toggle("ready",t&&!this.loading),this.submitBtn.disabled=!t||this.loading,this.errorEl.hidden=!0,this.errorEl.textContent=""}submit(){const t=this.textarea.value.trim();!t||this.loading||this.onSubmit(t)}setLoading(t){this.loading=t,t?(this.submitBtn.classList.add("loading"),this.submitBtn.innerHTML='<span class="mtb-dot"></span><span class="mtb-dot"></span><span class="mtb-dot"></span>',this.textarea.disabled=!0):(this.submitBtn.classList.remove("loading"),this.submitBtn.textContent=this.submitLabel,this.textarea.disabled=!1),this.updateSubmitState()}setError(t){this.errorEl.textContent=t,this.errorEl.hidden=!1}destroy(){this.el.remove()}}function p(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}const jt=2e3,Bt=2e3,Ut=45e3,L=346,A=320;class zt{constructor(t,e){this.pollTimer=null,this.pollDeadline=0,this.doneTimer=null,this.streamingBubble=null,this.sending=!1,this.destroyed=!1,this.feedbackId=e.feedbackId,this.apiClient=e.apiClient,this.onDone=e.onDone,this.el=t.el("div","mtb-clarify"),this.el.innerHTML=this.buildHTML(e.messages),this.positionCard(e.x,e.y),t.append(this.el),this.messagesEl=this.el.querySelector(".mtb-clarify-messages"),this.inputEl=this.el.querySelector(".mtb-clarify-input"),this.sendBtn=this.el.querySelector(".mtb-clarify-send"),this.bindEvents(e.messages),this.startConversation()}positionCard(t,e){const r=window.innerWidth,s=window.innerHeight,n=12;if(t===void 0||e===void 0){this.el.style.left=`${Math.max(n,(r-L)/2)}px`,this.el.style.top=`${Math.max(n,(s-A)/2)}px`;return}let o=t+12,a=e+12;o+L>r-n&&(o=t-L-12),o<n&&(o=n),a+A>s-n&&(a=s-A-n),a<n&&(a=n),this.el.style.left=`${o}px`,this.el.style.top=`${a}px`}buildHTML(t){return`
57
57
  <div class="mtb-clarify-header">
58
58
  <span class="mtb-clarify-icon">
59
59
  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round">
@@ -75,7 +75,7 @@
75
75
  <textarea class="mtb-clarify-input" rows="2" placeholder="${b(t.clarify.placeholder)}"></textarea>
76
76
  <div class="mtb-clarify-actions">
77
77
  <button class="mtb-clarify-skip" type="button">${b(t.clarify.skip)}</button>
78
- <button class="mtb-clarify-send" type="button">
78
+ <button class="mtb-clarify-send" type="button" disabled>
79
79
  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
80
80
  <line x1="22" y1="2" x2="11" y2="13"/>
81
81
  <polygon points="22 2 15 22 11 13 2 9 22 2"/>
@@ -84,7 +84,7 @@
84
84
  </button>
85
85
  </div>
86
86
  </div>
87
- `}bindEvents(t){const e=()=>{this.stopPolling(),this.onDone()};this.el.querySelector(".mtb-clarify-skip").addEventListener("click",e),this.el.querySelector(".mtb-clarify-close").addEventListener("click",e),this.inputEl.addEventListener("keydown",r=>{r.isComposing||r.keyCode===229||r.key==="Enter"&&!r.shiftKey&&(r.preventDefault(),this.sendMessage(t))}),this.sendBtn.addEventListener("click",()=>this.sendMessage(t))}async startConversation(){this.showThinking(),await this.runTurn(void 0)}async sendMessage(t){const e=this.inputEl.value.trim();if(!(!e||this.sending)){this.sending=!0,this.inputEl.disabled=!0,this.sendBtn.disabled=!0,this.stopPolling(),this.appendMessage({role:"user",content:e}),this.inputEl.value="",this.showThinking();try{await this.runTurn(e)}finally{this.sending=!1,this.inputEl.disabled=!1,this.sendBtn.disabled=!1,this.inputEl.focus()}}}async runTurn(t){try{const e=await this.apiClient.streamClarification(this.feedbackId,t,r=>this.appendStreamDelta(r));if(this.destroyed)return;this.endStreamingBubble(),this.renderConversation(e.messages,e.done),e.done?this.handleDone():this.startPolling()}catch{if(this.destroyed)return;this.endStreamingBubble(),await this.runTurnViaPolling(t)}}async runTurnViaPolling(t){try{const e=await this.apiClient.startClarification(this.feedbackId,t);if(this.destroyed)return;this.renderConversation(e.messages,e.done),e.done?this.handleDone():this.startPolling()}catch{if(this.destroyed)return;this.onDone()}}appendStreamDelta(t){this.streamingBubble||(this.removeThinking(),this.streamingBubble=document.createElement("div"),this.streamingBubble.className="mtb-clarify-bubble mtb-clarify-ai",this.messagesEl.appendChild(this.streamingBubble)),this.streamingBubble.textContent=(this.streamingBubble.textContent??"")+t,this.messagesEl.scrollTop=this.messagesEl.scrollHeight}endStreamingBubble(){this.streamingBubble=null}startPolling(){this.stopPolling(),this.pollDeadline=Date.now()+Bt,this.pollTimer=setInterval(()=>this.poll(),jt)}stopPolling(){this.pollTimer!==null&&(clearInterval(this.pollTimer),this.pollTimer=null)}async poll(){if(Date.now()>this.pollDeadline){this.stopPolling(),this.handleDone();return}try{const t=await this.apiClient.getClarification(this.feedbackId);if(this.destroyed)return;this.renderConversation(t.messages,t.done),t.done&&(this.stopPolling(),this.handleDone())}catch{if(this.destroyed)return;this.stopPolling()}}handleDone(){this.inputEl.disabled=!0,this.sendBtn.disabled=!0,this.doneTimer=setTimeout(()=>{this.destroyed||this.onDone()},Ut)}renderConversation(t,e){this.renderMessages(t);const r=t[t.length-1];!e&&(!r||r.role==="user")&&this.showThinking()}renderMessages(t){this.messagesEl.innerHTML="";for(const e of t)this.appendMessage(e);this.messagesEl.scrollTop=this.messagesEl.scrollHeight}appendMessage(t){const e=document.createElement("div");e.className=t.role==="user"?"mtb-clarify-bubble mtb-clarify-user":"mtb-clarify-bubble mtb-clarify-ai",e.textContent=t.content,this.messagesEl.appendChild(e),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}showThinking(){if(this.messagesEl.querySelector(".mtb-clarify-thinking"))return;const t=document.createElement("div");t.className="mtb-clarify-bubble mtb-clarify-ai mtb-clarify-thinking",t.innerHTML='<span class="mtb-dot"></span><span class="mtb-dot"></span><span class="mtb-dot"></span>',this.messagesEl.appendChild(t),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}removeThinking(){this.messagesEl.querySelector(".mtb-clarify-thinking")?.remove()}destroy(){this.destroyed=!0,this.stopPolling(),this.doneTimer!==null&&(clearTimeout(this.doneTimer),this.doneTimer=null),this.el.remove()}}function b(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}const qt=5e3,Wt=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;class Nt{constructor(t,e,r,s,n){this.messages=e,this.el=t.el("div","mtb-success"),this.el.style.right="20px",this.el.style.bottom="20px";const o=n?.skipFollowup?e.success.title_no_ai:e.success.title,a=n?.skipFollowup?e.success.message_no_ai:e.success.message,l=s?`<button class="mtb-view-feedback-link">${e.success.view_feedback}</button>`:"",c=n?.emailCapture?`
87
+ `}bindEvents(t){const e=()=>{this.stopPolling(),this.onDone()};this.el.querySelector(".mtb-clarify-skip").addEventListener("click",e),this.el.querySelector(".mtb-clarify-close").addEventListener("click",e),this.inputEl.addEventListener("input",()=>{this.sendBtn.disabled=!this.inputEl.value.trim()}),this.inputEl.addEventListener("keydown",r=>{r.isComposing||r.keyCode===229||r.key==="Enter"&&!r.shiftKey&&(r.preventDefault(),this.sendMessage(t))}),this.sendBtn.addEventListener("click",()=>this.sendMessage(t))}async startConversation(){this.showThinking(),await this.runTurn(void 0)}async sendMessage(t){const e=this.inputEl.value.trim();if(!(!e||this.sending)){this.sending=!0,this.inputEl.disabled=!0,this.sendBtn.disabled=!0,this.stopPolling(),this.appendMessage({role:"user",content:e}),this.inputEl.value="",this.showThinking();try{await this.runTurn(e)}finally{this.sending=!1,this.inputEl.disabled=!1,this.sendBtn.disabled=!this.inputEl.value.trim(),this.inputEl.focus()}}}async runTurn(t){try{const e=await this.apiClient.streamClarification(this.feedbackId,t,r=>this.appendStreamDelta(r));if(this.destroyed)return;this.endStreamingBubble(),this.renderConversation(e.messages,e.done),e.done?this.handleDone():this.startPolling()}catch{if(this.destroyed)return;this.endStreamingBubble(),await this.runTurnViaPolling(t)}}async runTurnViaPolling(t){try{const e=await this.apiClient.startClarification(this.feedbackId,t);if(this.destroyed)return;this.renderConversation(e.messages,e.done),e.done?this.handleDone():this.startPolling()}catch{if(this.destroyed)return;this.onDone()}}appendStreamDelta(t){this.streamingBubble||(this.removeThinking(),this.streamingBubble=document.createElement("div"),this.streamingBubble.className="mtb-clarify-bubble mtb-clarify-ai",this.messagesEl.appendChild(this.streamingBubble)),this.streamingBubble.textContent=(this.streamingBubble.textContent??"")+t,this.messagesEl.scrollTop=this.messagesEl.scrollHeight}endStreamingBubble(){this.streamingBubble=null}startPolling(){this.stopPolling(),this.pollDeadline=Date.now()+Ut,this.pollTimer=setInterval(()=>this.poll(),jt)}stopPolling(){this.pollTimer!==null&&(clearInterval(this.pollTimer),this.pollTimer=null)}async poll(){if(Date.now()>this.pollDeadline){this.stopPolling(),this.handleDone();return}try{const t=await this.apiClient.getClarification(this.feedbackId);if(this.destroyed)return;this.renderConversation(t.messages,t.done),t.done&&(this.stopPolling(),this.handleDone())}catch{if(this.destroyed)return;this.stopPolling()}}handleDone(){this.inputEl.disabled=!0,this.sendBtn.disabled=!0,this.doneTimer=setTimeout(()=>{this.destroyed||this.onDone()},Bt)}renderConversation(t,e){this.renderMessages(t);const r=t[t.length-1];!e&&(!r||r.role==="user")&&this.showThinking()}renderMessages(t){this.messagesEl.innerHTML="";for(const e of t)this.appendMessage(e);this.messagesEl.scrollTop=this.messagesEl.scrollHeight}appendMessage(t){const e=document.createElement("div");e.className=t.role==="user"?"mtb-clarify-bubble mtb-clarify-user":"mtb-clarify-bubble mtb-clarify-ai",e.textContent=t.content,this.messagesEl.appendChild(e),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}showThinking(){if(this.messagesEl.querySelector(".mtb-clarify-thinking"))return;const t=document.createElement("div");t.className="mtb-clarify-bubble mtb-clarify-ai mtb-clarify-thinking",t.innerHTML='<span class="mtb-dot"></span><span class="mtb-dot"></span><span class="mtb-dot"></span>',this.messagesEl.appendChild(t),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}removeThinking(){this.messagesEl.querySelector(".mtb-clarify-thinking")?.remove()}destroy(){this.destroyed=!0,this.stopPolling(),this.doneTimer!==null&&(clearTimeout(this.doneTimer),this.doneTimer=null),this.el.remove()}}function b(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}const qt=5e3,Wt=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;class Nt{constructor(t,e,r,s,n){this.messages=e,this.el=t.el("div","mtb-success"),this.el.style.right="20px",this.el.style.bottom="20px";const o=n?.skipFollowup?e.success.title_no_ai:e.success.title,a=n?.skipFollowup?e.success.message_no_ai:e.success.message,l=s?`<button class="mtb-view-feedback-link">${e.success.view_feedback} <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14M12 5l7 7-7 7"/></svg></button>`:"",c=n?.emailCapture?`
88
88
  <div class="mtb-email-capture">
89
89
  <div class="mtb-email-prompt">${e.success.email_prompt}</div>
90
90
  <div class="mtb-email-row">
@@ -94,7 +94,7 @@
94
94
  <div class="mtb-email-error" hidden>${e.success.email_error}</div>
95
95
  </div>`:"";this.el.innerHTML=`
96
96
  <div class="mtb-success-icon">
97
- <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="${it}" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
97
+ <svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="${it}" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round">
98
98
  <polyline points="20 6 9 17 4 12"/>
99
99
  </svg>
100
100
  </div>
@@ -103,14 +103,14 @@
103
103
  ${c}
104
104
  ${l}
105
105
  <button class="mtb-close-link">${e.success.close}</button>
106
- `,t.append(this.el),this.el.querySelector(".mtb-close-link").addEventListener("click",r),s&&this.el.querySelector(".mtb-view-feedback-link").addEventListener("click",s),n?.emailCapture?this.bindEmailCapture(n.emailCapture.onSubmit):setTimeout(()=>r(),qt)}bindEmailCapture(t){const e=this.el.querySelector(".mtb-email-input"),r=this.el.querySelector(".mtb-email-submit"),s=this.el.querySelector(".mtb-email-error"),n=async()=>{const o=e.value.trim();if(!Wt.test(o)){e.classList.add("mtb-email-invalid");return}e.classList.remove("mtb-email-invalid"),s.hidden=!0,r.disabled=!0,await t(o)?this.el.querySelector(".mtb-email-capture").innerHTML=`<div class="mtb-email-saved">${this.messages.success.email_saved}</div>`:(s.hidden=!1,r.disabled=!1)};r.addEventListener("click",n),e.addEventListener("keydown",o=>{o.key==="Enter"&&n()})}destroy(){this.el.remove()}}function Vt(i,t){if(i.match(/^[a-z]+:\/\//i))return i;if(i.match(/^\/\//))return window.location.protocol+i;if(i.match(/^[a-z]+:/i))return i;const e=document.implementation.createHTMLDocument(),r=e.createElement("base"),s=e.createElement("a");return e.head.appendChild(r),e.body.appendChild(s),t&&(r.href=t),s.href=i,s.href}const Yt=(()=>{let i=0;const t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(i+=1,`u${t()}${i}`)})();function f(i){const t=[];for(let e=0,r=i.length;e<r;e++)t.push(i[e]);return t}let y=null;function rt(i={}){return y||(i.includeStyleProperties?(y=i.includeStyleProperties,y):(y=f(window.getComputedStyle(document.documentElement)),y))}function _(i,t){const r=(i.ownerDocument.defaultView||window).getComputedStyle(i).getPropertyValue(t);return r?parseFloat(r.replace("px","")):0}function Xt(i){const t=_(i,"border-left-width"),e=_(i,"border-right-width");return i.clientWidth+t+e}function Gt(i){const t=_(i,"border-top-width"),e=_(i,"border-bottom-width");return i.clientHeight+t+e}function st(i,t={}){const e=t.width||Xt(i),r=t.height||Gt(i);return{width:e,height:r}}function Kt(){let i,t;try{t=process}catch{}const e=t&&t.env?t.env.devicePixelRatio:null;return e&&(i=parseInt(e,10),Number.isNaN(i)&&(i=1)),i||window.devicePixelRatio||1}const u=16384;function Jt(i){(i.width>u||i.height>u)&&(i.width>u&&i.height>u?i.width>i.height?(i.height*=u/i.width,i.width=u):(i.width*=u/i.height,i.height=u):i.width>u?(i.height*=u/i.width,i.width=u):(i.width*=u/i.height,i.height=u))}function T(i){return new Promise((t,e)=>{const r=new Image;r.onload=()=>{r.decode().then(()=>{requestAnimationFrame(()=>t(r))})},r.onerror=e,r.crossOrigin="anonymous",r.decoding="async",r.src=i})}async function Qt(i){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(i)).then(encodeURIComponent).then(t=>`data:image/svg+xml;charset=utf-8,${t}`)}async function Zt(i,t,e){const r="http://www.w3.org/2000/svg",s=document.createElementNS(r,"svg"),n=document.createElementNS(r,"foreignObject");return s.setAttribute("width",`${t}`),s.setAttribute("height",`${e}`),s.setAttribute("viewBox",`0 0 ${t} ${e}`),n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.setAttribute("x","0"),n.setAttribute("y","0"),n.setAttribute("externalResourcesRequired","true"),s.appendChild(n),n.appendChild(i),Qt(s)}const d=(i,t)=>{if(i instanceof t)return!0;const e=Object.getPrototypeOf(i);return e===null?!1:e.constructor.name===t.name||d(e,t)};function te(i){const t=i.getPropertyValue("content");return`${i.cssText} content: '${t.replace(/'|"/g,"")}';`}function ee(i,t){return rt(t).map(e=>{const r=i.getPropertyValue(e),s=i.getPropertyPriority(e);return`${e}: ${r}${s?" !important":""};`}).join(" ")}function ie(i,t,e,r){const s=`.${i}:${t}`,n=e.cssText?te(e):ee(e,r);return document.createTextNode(`${s}{${n}}`)}function j(i,t,e,r){const s=window.getComputedStyle(i,e),n=s.getPropertyValue("content");if(n===""||n==="none")return;const o=Yt();try{t.className=`${t.className} ${o}`}catch{return}const a=document.createElement("style");a.appendChild(ie(o,e,s,r)),t.appendChild(a)}function re(i,t,e){j(i,t,":before",e),j(i,t,":after",e)}const U="application/font-woff",B="image/jpeg",se={woff:U,woff2:U,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:B,jpeg:B,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function ne(i){const t=/\.([^./]*?)$/g.exec(i);return t?t[1]:""}function I(i){const t=ne(i).toLowerCase();return se[t]||""}function oe(i){return i.split(/,/)[1]}function R(i){return i.search(/^(data:)/)!==-1}function ae(i,t){return`data:${t};base64,${i}`}async function nt(i,t,e){const r=await fetch(i,t);if(r.status===404)throw new Error(`Resource "${r.url}" not found`);const s=await r.blob();return new Promise((n,o)=>{const a=new FileReader;a.onerror=o,a.onloadend=()=>{try{n(e({res:r,result:a.result}))}catch(l){o(l)}},a.readAsDataURL(s)})}const D={};function le(i,t,e){let r=i.replace(/\?.*/,"");return e&&(r=i),/ttf|otf|eot|woff2?/i.test(r)&&(r=r.replace(/.*\//,"")),t?`[${t}]${r}`:r}async function $(i,t,e){const r=le(i,t,e.includeQueryParams);if(D[r]!=null)return D[r];e.cacheBust&&(i+=(/\?/.test(i)?"&":"?")+new Date().getTime());let s;try{const n=await nt(i,e.fetchRequestInit,({res:o,result:a})=>(t||(t=o.headers.get("Content-Type")||""),oe(a)));s=ae(n,t)}catch(n){s=e.imagePlaceholder||"";let o=`Failed to fetch resource: ${i}`;n&&(o=typeof n=="string"?n:n.message),o&&console.warn(o)}return D[r]=s,s}async function ce(i){const t=i.toDataURL();return t==="data:,"?i.cloneNode(!1):T(t)}async function de(i,t){if(i.currentSrc){const n=document.createElement("canvas"),o=n.getContext("2d");n.width=i.clientWidth,n.height=i.clientHeight,o?.drawImage(i,0,0,n.width,n.height);const a=n.toDataURL();return T(a)}const e=i.poster,r=I(e),s=await $(e,r,t);return T(s)}async function he(i,t){var e;try{if(!((e=i?.contentDocument)===null||e===void 0)&&e.body)return await M(i.contentDocument.body,t,!0)}catch{}return i.cloneNode(!1)}async function ue(i,t){return d(i,HTMLCanvasElement)?ce(i):d(i,HTMLVideoElement)?de(i,t):d(i,HTMLIFrameElement)?he(i,t):i.cloneNode(ot(i))}const me=i=>i.tagName!=null&&i.tagName.toUpperCase()==="SLOT",ot=i=>i.tagName!=null&&i.tagName.toUpperCase()==="SVG";async function fe(i,t,e){var r,s;if(ot(t))return t;let n=[];return me(i)&&i.assignedNodes?n=f(i.assignedNodes()):d(i,HTMLIFrameElement)&&(!((r=i.contentDocument)===null||r===void 0)&&r.body)?n=f(i.contentDocument.body.childNodes):n=f(((s=i.shadowRoot)!==null&&s!==void 0?s:i).childNodes),n.length===0||d(i,HTMLVideoElement)||await n.reduce((o,a)=>o.then(()=>M(a,e)).then(l=>{l&&t.appendChild(l)}),Promise.resolve()),t}function pe(i,t,e){const r=t.style;if(!r)return;const s=window.getComputedStyle(i);s.cssText?(r.cssText=s.cssText,r.transformOrigin=s.transformOrigin):rt(e).forEach(n=>{let o=s.getPropertyValue(n);n==="font-size"&&o.endsWith("px")&&(o=`${Math.floor(parseFloat(o.substring(0,o.length-2)))-.1}px`),d(i,HTMLIFrameElement)&&n==="display"&&o==="inline"&&(o="block"),n==="d"&&t.getAttribute("d")&&(o=`path(${t.getAttribute("d")})`),r.setProperty(n,o,s.getPropertyPriority(n))})}function be(i,t){d(i,HTMLTextAreaElement)&&(t.innerHTML=i.value),d(i,HTMLInputElement)&&t.setAttribute("value",i.value)}function ge(i,t){if(d(i,HTMLSelectElement)){const e=t,r=Array.from(e.children).find(s=>i.value===s.getAttribute("value"));r&&r.setAttribute("selected","")}}function ye(i,t,e){return d(t,Element)&&(pe(i,t,e),re(i,t,e),be(i,t),ge(i,t)),t}async function xe(i,t){const e=i.querySelectorAll?i.querySelectorAll("use"):[];if(e.length===0)return i;const r={};for(let n=0;n<e.length;n++){const a=e[n].getAttribute("xlink:href");if(a){const l=i.querySelector(a),c=document.querySelector(a);!l&&c&&!r[a]&&(r[a]=await M(c,t,!0))}}const s=Object.values(r);if(s.length){const n="http://www.w3.org/1999/xhtml",o=document.createElementNS(n,"svg");o.setAttribute("xmlns",n),o.style.position="absolute",o.style.width="0",o.style.height="0",o.style.overflow="hidden",o.style.display="none";const a=document.createElementNS(n,"defs");o.appendChild(a);for(let l=0;l<s.length;l++)a.appendChild(s[l]);i.appendChild(o)}return i}async function M(i,t,e){return!e&&t.filter&&!t.filter(i)?null:Promise.resolve(i).then(r=>ue(r,t)).then(r=>fe(i,r,t)).then(r=>ye(i,r,t)).then(r=>xe(r,t))}const at=/url\((['"]?)([^'"]+?)\1\)/g,we=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,ke=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function ve(i){const t=i.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function Se(i){const t=[];return i.replace(at,(e,r,s)=>(t.push(s),e)),t.filter(e=>!R(e))}async function Ee(i,t,e,r,s){try{const n=e?Vt(t,e):t,o=I(t);let a;return s||(a=await $(n,o,r)),i.replace(ve(t),`$1${a}$3`)}catch{}return i}function Ce(i,{preferredFontFormat:t}){return t?i.replace(ke,e=>{for(;;){const[r,,s]=we.exec(e)||[];if(!s)return"";if(s===t)return`src: ${r};`}}):i}function lt(i){return i.search(at)!==-1}async function ct(i,t,e){if(!lt(i))return i;const r=Ce(i,e);return Se(r).reduce((n,o)=>n.then(a=>Ee(a,o,t,e)),Promise.resolve(r))}async function x(i,t,e){var r;const s=(r=t.style)===null||r===void 0?void 0:r.getPropertyValue(i);if(s){const n=await ct(s,null,e);return t.style.setProperty(i,n,t.style.getPropertyPriority(i)),!0}return!1}async function _e(i,t){await x("background",i,t)||await x("background-image",i,t),await x("mask",i,t)||await x("-webkit-mask",i,t)||await x("mask-image",i,t)||await x("-webkit-mask-image",i,t)}async function Te(i,t){const e=d(i,HTMLImageElement);if(!(e&&!R(i.src))&&!(d(i,SVGImageElement)&&!R(i.href.baseVal)))return;const r=e?i.src:i.href.baseVal,s=await $(r,I(r),t);await new Promise((n,o)=>{i.onload=n,i.onerror=t.onImageErrorHandler?(...l)=>{try{n(t.onImageErrorHandler(...l))}catch(c){o(c)}}:o;const a=i;a.decode&&(a.decode=n),a.loading==="lazy"&&(a.loading="eager"),e?(i.srcset="",i.src=s):i.href.baseVal=s})}async function Me(i,t){const r=f(i.childNodes).map(s=>dt(s,t));await Promise.all(r).then(()=>i)}async function dt(i,t){d(i,Element)&&(await _e(i,t),await Te(i,t),await Me(i,t))}function Le(i,t){const{style:e}=i;t.backgroundColor&&(e.backgroundColor=t.backgroundColor),t.width&&(e.width=`${t.width}px`),t.height&&(e.height=`${t.height}px`);const r=t.style;return r!=null&&Object.keys(r).forEach(s=>{e[s]=r[s]}),i}const z={};async function q(i){let t=z[i];if(t!=null)return t;const r=await(await fetch(i)).text();return t={url:i,cssText:r},z[i]=t,t}async function W(i,t){let e=i.cssText;const r=/url\(["']?([^"')]+)["']?\)/g,n=(e.match(/url\([^)]+\)/g)||[]).map(async o=>{let a=o.replace(r,"$1");return a.startsWith("https://")||(a=new URL(a,i.url).href),nt(a,t.fetchRequestInit,({result:l})=>(e=e.replace(o,`url(${l})`),[o,l]))});return Promise.all(n).then(()=>e)}function N(i){if(i==null)return[];const t=[],e=/(\/\*[\s\S]*?\*\/)/gi;let r=i.replace(e,"");const s=new RegExp("((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})","gi");for(;;){const l=s.exec(r);if(l===null)break;t.push(l[0])}r=r.replace(s,"");const n=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,o="((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})",a=new RegExp(o,"gi");for(;;){let l=n.exec(r);if(l===null){if(l=a.exec(r),l===null)break;n.lastIndex=a.lastIndex}else a.lastIndex=n.lastIndex;t.push(l[0])}return t}async function Ae(i,t){const e=[],r=[];return i.forEach(s=>{if("cssRules"in s)try{f(s.cssRules||[]).forEach((n,o)=>{if(n.type===CSSRule.IMPORT_RULE){let a=o+1;const l=n.href,c=q(l).then(h=>W(h,t)).then(h=>N(h).forEach(m=>{try{s.insertRule(m,m.startsWith("@import")?a+=1:s.cssRules.length)}catch(k){console.error("Error inserting rule from remote css",{rule:m,error:k})}})).catch(h=>{console.error("Error loading remote css",h.toString())});r.push(c)}})}catch(n){const o=i.find(a=>a.href==null)||document.styleSheets[0];s.href!=null&&r.push(q(s.href).then(a=>W(a,t)).then(a=>N(a).forEach(l=>{o.insertRule(l,o.cssRules.length)})).catch(a=>{console.error("Error loading remote stylesheet",a)})),console.error("Error inlining remote css file",n)}}),Promise.all(r).then(()=>(i.forEach(s=>{if("cssRules"in s)try{f(s.cssRules||[]).forEach(n=>{e.push(n)})}catch(n){console.error(`Error while reading CSS rules from ${s.href}`,n)}}),e))}function De(i){return i.filter(t=>t.type===CSSRule.FONT_FACE_RULE).filter(t=>lt(t.style.getPropertyValue("src")))}async function Re(i,t){if(i.ownerDocument==null)throw new Error("Provided element is not within a Document");const e=f(i.ownerDocument.styleSheets),r=await Ae(e,t);return De(r)}function ht(i){return i.trim().replace(/["']/g,"")}function Pe(i){const t=new Set;function e(r){(r.style.fontFamily||getComputedStyle(r).fontFamily).split(",").forEach(n=>{t.add(ht(n))}),Array.from(r.children).forEach(n=>{n instanceof HTMLElement&&e(n)})}return e(i),t}async function Ie(i,t){const e=await Re(i,t),r=Pe(i);return(await Promise.all(e.filter(n=>r.has(ht(n.style.fontFamily))).map(n=>{const o=n.parentStyleSheet?n.parentStyleSheet.href:null;return ct(n.cssText,o,t)}))).join(`
107
- `)}async function $e(i,t){const e=t.fontEmbedCSS!=null?t.fontEmbedCSS:t.skipFonts?null:await Ie(i,t);if(e){const r=document.createElement("style"),s=document.createTextNode(e);r.appendChild(s),i.firstChild?i.insertBefore(r,i.firstChild):i.appendChild(r)}}async function He(i,t={}){const{width:e,height:r}=st(i,t),s=await M(i,t,!0);return await $e(s,t),await dt(s,t),Le(s,t),await Zt(s,e,r)}async function Oe(i,t={}){const{width:e,height:r}=st(i,t),s=await He(i,t),n=await T(s),o=document.createElement("canvas"),a=o.getContext("2d"),l=t.pixelRatio||Kt(),c=t.canvasWidth||e,h=t.canvasHeight||r;return o.width=c*l,o.height=h*l,t.skipAutoScale||Jt(o),o.style.width=`${c}`,o.style.height=`${h}`,t.backgroundColor&&(a.fillStyle=t.backgroundColor,a.fillRect(0,0,o.width,o.height)),a.drawImage(n,0,0,o.width,o.height),o}async function Fe(i,t={}){return(await Oe(i,t)).toDataURL("image/jpeg",t.quality||1)}async function je(i=[]){const t=Ue(i);try{const e=await Fe(document.body,{quality:.85,pixelRatio:1,backgroundColor:"#ffffff",cacheBust:!0,skipAutoScale:!1,filter:r=>!(r instanceof HTMLElement&&r.id==="mtb-widget-host")});return qe(e)}catch{return null}finally{t?.remove()}}function Ue(i){if(i.length===0)return null;const t=document.createElement("div");t.setAttribute("data-mtb-capture-annotations","true"),t.setAttribute("aria-hidden","true"),t.style.cssText="position:fixed;inset:0;pointer-events:none;z-index:2147483645;";for(const[e,r]of i.entries())r.type==="pin"?t.appendChild(Be(r,e+1)):r.type==="draw"&&r.drawPath&&t.appendChild(ze(r.drawPath));return document.body.appendChild(t),t}function Be(i,t){const e=document.createElement("div");return e.textContent=String(t),e.style.cssText=["position:fixed",`left:${i.x}px`,`top:${i.y}px`,"width:22px","height:22px","border-radius:50% 50% 50% 2px","background:#059669","border:2px solid #fff","display:flex","align-items:center","justify-content:center",'font:700 10px -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif',"color:#fff","box-shadow:0 2px 8px rgba(5,150,105,0.45)","transform:translate(-50%,-50%)"].join(";"),e}function ze(i){const t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("width","100%"),t.setAttribute("height","100%"),t.setAttribute("viewBox",`0 0 ${window.innerWidth} ${window.innerHeight}`),t.style.cssText="position:fixed;inset:0;width:100%;height:100%;overflow:visible;";const e=document.createElementNS("http://www.w3.org/2000/svg","path");return e.setAttribute("d",i),e.setAttribute("fill","none"),e.setAttribute("stroke","#059669"),e.setAttribute("stroke-width","3.5"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round"),e.setAttribute("filter","drop-shadow(0 1px 2px rgba(5,150,105,0.35))"),t.appendChild(e),t}function qe(i){const[t,e]=i.split(","),r=t.match(/:(.*?);/)?.[1]??"image/png",s=atob(e),n=new Uint8Array(s.length);for(let o=0;o<s.length;o++)n[o]=s.charCodeAt(o);return new Blob([n],{type:r})}class We{constructor(){this.listeners=new Set,this.originalOnError=null,this.installedOnError=null,this.rejectionHandler=null,this.hooked=!1}subscribe(t){return this.listeners.add(t),this.hook(),()=>{this.listeners.delete(t),this.listeners.size===0&&this.unhook()}}hook(){this.hooked||(this.hooked=!0,this.originalOnError=window.onerror,this.installedOnError=(t,e,r,s,n)=>(this.emit({message:String(t),source:e,line:r,col:s,error:n}),this.originalOnError?this.originalOnError.call(window,t,e,r,s,n):!1),window.onerror=this.installedOnError,this.rejectionHandler=t=>{const e=t.reason instanceof Error?t.reason.message:String(t.reason);this.emit({message:`Unhandled rejection: ${e}`})},window.addEventListener("unhandledrejection",this.rejectionHandler))}unhook(){this.hooked&&(this.hooked=!1,window.onerror===this.installedOnError&&(window.onerror=this.originalOnError),this.installedOnError=null,this.originalOnError=null,this.rejectionHandler&&(window.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null))}emit(t){for(const e of this.listeners)e(t)}}const ut=new We,Ne=20;class Ve{constructor(){this.errors=[],this.unsubscribe=null}start(){this.unsubscribe||(this.unsubscribe=ut.subscribe(t=>this.record(t)))}record(t){const e=t.line!=null?` (${t.line}:${t.col??0})`:"";this.addError(`${t.message}${e}`)}addError(t){this.errors.length>=Ne||this.errors.includes(t)||this.errors.push(t)}getErrors(){return[...this.errors]}stop(){this.unsubscribe?.(),this.unsubscribe=null}}const Ye=3,Xe=1e3,Ge=3,Ke=5e3,Je=500,Qe=500,Ze=300,ti=new Set(["A","BUTTON","INPUT","SELECT","TEXTAREA","LABEL","SUMMARY","DETAILS"]),ei=new Set(["button","link","checkbox","radio","tab","menuitem","option","switch","textbox","combobox","listbox","slider","spinbutton"]),V=["404","500","not found","page not found","server error","internal server error"],E=class E{constructor(t){this.clickHistory=[],this.unsubscribeErrors=null,this.active=!1,this.errorCount=0,this.deadClickCount=0,this.cooldownUntil=0,this.navTimestamps=[],this.boundPopstateHandler=null,this.originalPushState=null,this.originalReplaceState=null,this.installedPushState=null,this.installedReplaceState=null,this.boundSubmitHandler=null,this.boundInvalidHandler=null,this.errorPageUrls=new Set,this.domObserver=null,this.pendingDomChecks=0,this.lastMutationAt=-1,this.onFrustration=t,this.boundClickHandler=e=>this.handleClick(e)}start(){this.active||(this.active=!0,document.addEventListener("click",this.boundClickHandler,!0),this.unsubscribeErrors=ut.subscribe(t=>{this.errorCount++}),this.startNavigationTracking(),this.startFormTracking(),this.checkErrorPage())}stop(){this.active&&(this.active=!1,document.removeEventListener("click",this.boundClickHandler,!0),this.unsubscribeErrors?.(),this.unsubscribeErrors=null,this.clickHistory=[],this.stopNavigationTracking(),this.stopFormTracking(),this.errorPageUrls.clear(),this.disconnectDomObserver())}startNavigationTracking(){this.boundPopstateHandler=()=>this.handleNavigation(),window.addEventListener("popstate",this.boundPopstateHandler),this.originalPushState=history.pushState.bind(history),this.originalReplaceState=history.replaceState.bind(history);const t=this.originalPushState,e=this.originalReplaceState,r=()=>this.handleNavigation();this.installedPushState=function(s,n,o){t(s,n,o),r()},this.installedReplaceState=function(s,n,o){e(s,n,o),r()},history.pushState=this.installedPushState,history.replaceState=this.installedReplaceState}stopNavigationTracking(){this.boundPopstateHandler&&(window.removeEventListener("popstate",this.boundPopstateHandler),this.boundPopstateHandler=null),this.originalPushState&&history.pushState===this.installedPushState&&(history.pushState=this.originalPushState),this.originalReplaceState&&history.replaceState===this.installedReplaceState&&(history.replaceState=this.originalReplaceState),this.originalPushState=null,this.originalReplaceState=null,this.installedPushState=null,this.installedReplaceState=null,this.navTimestamps=[]}startFormTracking(){this.boundSubmitHandler=t=>this.handleFormSubmit(t),this.boundInvalidHandler=t=>this.handleFormInvalid(t),document.addEventListener("submit",this.boundSubmitHandler,!0),document.addEventListener("invalid",this.boundInvalidHandler,!0)}stopFormTracking(){this.boundSubmitHandler&&(document.removeEventListener("submit",this.boundSubmitHandler,!0),this.boundSubmitHandler=null),this.boundInvalidHandler&&(document.removeEventListener("invalid",this.boundInvalidHandler,!0),this.boundInvalidHandler=null)}handleClick(t){const e=t.target;if(!e||this.isWidgetElement(e))return;const r=Date.now();this.clickHistory.push({target:e,time:r});const s=r-Xe;if(this.clickHistory=this.clickHistory.filter(o=>o.time>s),this.clickHistory.filter(o=>o.target===e).length>=Ye){this.clickHistory=[],this.emitHighPriority({signal:"rage_click",target:w(e),timestamp:r});return}this.isInteractive(e)||(this.deadClickCount++,this.deadClickCount>=3&&this.errorCount>0&&(this.deadClickCount=0,this.errorCount=0,this.emitIfReady({signal:"dead_click",target:w(e),timestamp:r}))),this.checkDeadClickDom(e,r)}handleNavigation(){const t=Date.now();this.navTimestamps.push(t);const e=t-Ke;this.navTimestamps=this.navTimestamps.filter(r=>r>e),this.navTimestamps.length>=Ge&&(this.navTimestamps=[],this.emitIfReady({signal:"rapid_navigation",timestamp:t})),setTimeout(()=>{this.active&&this.checkErrorPage()},Ze)}handleFormSubmit(t){const e=t.target;e instanceof HTMLFormElement&&(this.isWidgetElement(e)||setTimeout(()=>{this.active&&e.querySelector('[aria-invalid="true"], .is-invalid')&&this.emitIfReady({signal:"form_failure",target:w(e),timestamp:Date.now()})},Je))}handleFormInvalid(t){const e=t.target;if(!e||this.isWidgetElement(e))return;const r=e.closest("form");this.emitIfReady({signal:"form_failure",target:w(r||e),timestamp:Date.now()})}checkErrorPage(){const t=location.href;if(this.errorPageUrls.has(t))return;const e=document.title.toLowerCase();if(V.some(s=>e.includes(s))){this.errorPageUrls.add(t),this.emitHighPriority({signal:"error_page",detail:document.title,timestamp:Date.now()});return}const r=document.querySelectorAll('h1, h2, [class*="error"], [class*="not-found"], [id*="error"], [id*="not-found"]');for(const s of r){const n=s.textContent??"";if(n.length<200&&V.some(o=>n.toLowerCase().includes(o))){this.errorPageUrls.add(t),this.emitHighPriority({signal:"error_page",detail:n.trim().slice(0,60),timestamp:Date.now()});return}}}checkDeadClickDom(t,e){this.looksInteractive(t)&&(this.pendingDomChecks++,this.ensureDomObserver(),setTimeout(()=>{this.pendingDomChecks--;const r=this.lastMutationAt>=e;this.pendingDomChecks===0&&this.disconnectDomObserver(),!r&&this.active&&this.emitIfReady({signal:"dead_click_dom",target:w(t),timestamp:e})},Qe))}ensureDomObserver(){this.domObserver||(this.domObserver=new MutationObserver(()=>{this.lastMutationAt=Date.now()}),this.domObserver.observe(document.body,{childList:!0,subtree:!0,attributes:!0,characterData:!0}))}disconnectDomObserver(){this.domObserver?.disconnect(),this.domObserver=null}looksInteractive(t){if(window.getComputedStyle(t).cursor==="pointer")return!0;if(t.classList)for(const r of t.classList){const s=r.toLowerCase();if(s.includes("btn")||s.includes("button"))return!0}return!1}isInteractive(t){if(ti.has(t.tagName))return!0;const e=t.getAttribute("role");return!!(e&&ei.has(e)||t.hasAttribute("onclick")||t.hasAttribute("tabindex")||t.contentEditable==="true"||window.getComputedStyle(t).cursor==="pointer"||t.closest('a, button, [role="button"], [role="link"], label'))}isWidgetElement(t){const e=document.getElementById("mtb-widget-host");return e?e===t||e.contains(t):!1}emitIfReady(t){const e=Date.now();e<this.cooldownUntil||(this.cooldownUntil=e+E.COOLDOWN_MS,this.onFrustration(t))}emitHighPriority(t){this.cooldownUntil=Date.now()+E.COOLDOWN_MS,this.onFrustration(t)}};E.COOLDOWN_MS=6e4;let P=E;function w(i){const t=i.tagName.toLowerCase(),e=i.id?`#${i.id}`:"",r=i.className&&typeof i.className=="string"?"."+i.className.trim().split(/\s+/).slice(0,2).join("."):"",s=i.textContent?.trim().slice(0,30)??"";return`<${t}${e}${r}>${s?` "${s}"`:""}`}function ii(){return{page_url:window.location.href,user_agent:navigator.userAgent,browser:ri(),os:si(),screen_width:window.screen.width,screen_height:window.screen.height}}function ri(){const i=navigator.userAgent;return/Edg\//.test(i)?`Edge ${i.match(/Edg\/(\S+)/)?.[1]??""}`:/OPR\//.test(i)?`Opera ${i.match(/OPR\/(\S+)/)?.[1]??""}`:/Chrome\//.test(i)?`Chrome ${i.match(/Chrome\/(\S+)/)?.[1]??""}`:/Safari\//.test(i)&&/Version\//.test(i)?`Safari ${i.match(/Version\/(\S+)/)?.[1]??""}`:/Firefox\//.test(i)?`Firefox ${i.match(/Firefox\/(\S+)/)?.[1]??""}`:"Unknown"}function si(){const i=navigator.userAgent;return/Windows NT 10/.test(i)?"Windows 10/11":/Windows NT/.test(i)?"Windows":/Mac OS X 10_15|macOS 1[56789]/.test(i)||/Mac OS X/.test(i)?"macOS":/Android/.test(i)?`Android ${i.match(/Android (\d+)/)?.[1]??""}`:/iPhone|iPad|iPod/.test(i)?"iOS":/Linux/.test(i)?"Linux":"Unknown"}const ni="https://makethisbetter.dev/api/v1";class oi{constructor(t,e,r=1e3,s,n){this.projectKey=t,this.apiUrl=(e??ni).replace(/\/$/,""),this.retryDelayMs=r,this.userToken=s,this.userTokenFn=n}async resolveUserToken(){return this.userTokenFn?this.userTokenFn():this.userToken}async authHeaders(t){const e={"X-Project-Key":this.projectKey},r=await this.resolveUserToken();return r&&(e["X-User-Token"]=r),t&&(e["Content-Type"]=t),e}async submitFeedback(t,e){const r=new FormData;if(r.append("feedback[description]",t.description),r.append("feedback[page_url]",t.page_url),r.append("feedback[user_agent]",t.user_agent),r.append("feedback[browser]",t.browser),r.append("feedback[os]",t.os),r.append("feedback[screen_width]",String(t.screen_width)),r.append("feedback[screen_height]",String(t.screen_height)),r.append("feedback[console_errors]",JSON.stringify(t.console_errors)),r.append("feedback[annotations]",JSON.stringify(t.annotations)),t.target_element&&r.append("feedback[target_element]",JSON.stringify(t.target_element)),t.user_id&&r.append("feedback[user_id]",t.user_id),t.reporter_external_id&&r.append("feedback[reporter_external_id]",t.reporter_external_id),t.reporter_email&&r.append("feedback[reporter_email]",t.reporter_email),t.user_email&&r.append("feedback[user_email]",t.user_email),t.user_name&&r.append("feedback[user_name]",t.user_name),t.recording_events&&t.recording_events.length>0){const o=JSON.stringify(t.recording_events),a=new Blob([o],{type:"application/json"});r.append("feedback[recording]",a,"recording.json"),r.append("feedback[recording_duration]",String(t.recording_duration??0))}if(e){const o=e.type==="image/jpeg"?"jpg":"png";r.append("feedback[screenshot]",e,`screenshot.${o}`)}const s=await this.authHeaders();return s["X-Idempotency-Key"]=li(),(await this.fetchWithRetry(`${this.apiUrl}/widget/feedbacks`,{method:"POST",headers:s,body:r})).json()}async createIdentityToken(t){const e=await this.authHeaders("application/json");try{return await(await this.fetchWithRetry(`${this.apiUrl}/widget/identity_tokens`,{method:"POST",headers:e,body:JSON.stringify({reporter_external_id:t})})).json()}catch{return null}}async updateReporter(t,e,r){const s=await this.authHeaders("application/json");s["X-Identity-Token"]=r;try{return await this.fetchWithRetry(`${this.apiUrl}/widget/feedbacks/${t}/reporter`,{method:"PATCH",headers:s,body:JSON.stringify({reporter:{email:e}})}),!0}catch{return!1}}async startClarification(t,e){const r={};e&&(r.message=e);const s=await this.authHeaders("application/json");return(await this.fetchWithRetry(`${this.apiUrl}/widget/feedbacks/${t}/clarify`,{method:"POST",headers:s,body:JSON.stringify(r)})).json()}async getClarification(t){const e=await this.authHeaders();return(await this.fetchWithRetry(`${this.apiUrl}/widget/feedbacks/${t}/clarify`,{method:"GET",headers:e})).json()}async streamClarification(t,e,r){const s={};e&&(s.message=e);const n=await this.authHeaders("application/json");n.Accept="text/event-stream";const o=await fetch(`${this.apiUrl}/widget/feedbacks/${t}/clarify`,{method:"POST",headers:n,body:JSON.stringify(s)}),a=o.headers.get("Content-Type")??"";if(!o.ok||!o.body||!a.includes("text/event-stream"))throw new Error("clarify stream unavailable");return ai(o.body,r)}async fetchWithRetry(t,e,r=1){let s;try{s=await fetch(t,e)}catch(n){if(r>0)return await Y(this.retryDelayMs),this.fetchWithRetry(t,e,r-1);throw n}if(s.ok)return s;if(s.status>=500&&r>0)return await Y(this.retryDelayMs),this.fetchWithRetry(t,e,r-1);throw new Error(`HTTP ${s.status}`)}}function Y(i){return i<=0?Promise.resolve():new Promise(t=>setTimeout(t,i))}async function ai(i,t){const e=i.getReader(),r=new TextDecoder;let s="",n={messages:[],done:!0};const o=a=>{const l=a.split(`
106
+ `,t.append(this.el),this.el.querySelector(".mtb-close-link").addEventListener("click",r),s&&this.el.querySelector(".mtb-view-feedback-link").addEventListener("click",s),n?.emailCapture?this.bindEmailCapture(n.emailCapture.onSubmit):setTimeout(()=>r(),qt)}bindEmailCapture(t){const e=this.el.querySelector(".mtb-email-input"),r=this.el.querySelector(".mtb-email-submit"),s=this.el.querySelector(".mtb-email-error"),n=async()=>{const o=e.value.trim();if(!Wt.test(o)){e.classList.add("mtb-email-invalid");return}e.classList.remove("mtb-email-invalid"),s.hidden=!0,r.disabled=!0,await t(o)?this.el.querySelector(".mtb-email-capture").innerHTML=`<div class="mtb-email-saved">${this.messages.success.email_saved}</div>`:(s.hidden=!1,r.disabled=!1)};r.addEventListener("click",n),e.addEventListener("keydown",o=>{o.key==="Enter"&&n()})}destroy(){this.el.remove()}}function Vt(i,t){if(i.match(/^[a-z]+:\/\//i))return i;if(i.match(/^\/\//))return window.location.protocol+i;if(i.match(/^[a-z]+:/i))return i;const e=document.implementation.createHTMLDocument(),r=e.createElement("base"),s=e.createElement("a");return e.head.appendChild(r),e.body.appendChild(s),t&&(r.href=t),s.href=i,s.href}const Yt=(()=>{let i=0;const t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(i+=1,`u${t()}${i}`)})();function f(i){const t=[];for(let e=0,r=i.length;e<r;e++)t.push(i[e]);return t}let y=null;function rt(i={}){return y||(i.includeStyleProperties?(y=i.includeStyleProperties,y):(y=f(window.getComputedStyle(document.documentElement)),y))}function _(i,t){const r=(i.ownerDocument.defaultView||window).getComputedStyle(i).getPropertyValue(t);return r?parseFloat(r.replace("px","")):0}function Xt(i){const t=_(i,"border-left-width"),e=_(i,"border-right-width");return i.clientWidth+t+e}function Gt(i){const t=_(i,"border-top-width"),e=_(i,"border-bottom-width");return i.clientHeight+t+e}function st(i,t={}){const e=t.width||Xt(i),r=t.height||Gt(i);return{width:e,height:r}}function Kt(){let i,t;try{t=process}catch{}const e=t&&t.env?t.env.devicePixelRatio:null;return e&&(i=parseInt(e,10),Number.isNaN(i)&&(i=1)),i||window.devicePixelRatio||1}const u=16384;function Jt(i){(i.width>u||i.height>u)&&(i.width>u&&i.height>u?i.width>i.height?(i.height*=u/i.width,i.width=u):(i.width*=u/i.height,i.height=u):i.width>u?(i.height*=u/i.width,i.width=u):(i.width*=u/i.height,i.height=u))}function M(i){return new Promise((t,e)=>{const r=new Image;r.onload=()=>{r.decode().then(()=>{requestAnimationFrame(()=>t(r))})},r.onerror=e,r.crossOrigin="anonymous",r.decoding="async",r.src=i})}async function Qt(i){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(i)).then(encodeURIComponent).then(t=>`data:image/svg+xml;charset=utf-8,${t}`)}async function Zt(i,t,e){const r="http://www.w3.org/2000/svg",s=document.createElementNS(r,"svg"),n=document.createElementNS(r,"foreignObject");return s.setAttribute("width",`${t}`),s.setAttribute("height",`${e}`),s.setAttribute("viewBox",`0 0 ${t} ${e}`),n.setAttribute("width","100%"),n.setAttribute("height","100%"),n.setAttribute("x","0"),n.setAttribute("y","0"),n.setAttribute("externalResourcesRequired","true"),s.appendChild(n),n.appendChild(i),Qt(s)}const d=(i,t)=>{if(i instanceof t)return!0;const e=Object.getPrototypeOf(i);return e===null?!1:e.constructor.name===t.name||d(e,t)};function te(i){const t=i.getPropertyValue("content");return`${i.cssText} content: '${t.replace(/'|"/g,"")}';`}function ee(i,t){return rt(t).map(e=>{const r=i.getPropertyValue(e),s=i.getPropertyPriority(e);return`${e}: ${r}${s?" !important":""};`}).join(" ")}function ie(i,t,e,r){const s=`.${i}:${t}`,n=e.cssText?te(e):ee(e,r);return document.createTextNode(`${s}{${n}}`)}function j(i,t,e,r){const s=window.getComputedStyle(i,e),n=s.getPropertyValue("content");if(n===""||n==="none")return;const o=Yt();try{t.className=`${t.className} ${o}`}catch{return}const a=document.createElement("style");a.appendChild(ie(o,e,s,r)),t.appendChild(a)}function re(i,t,e){j(i,t,":before",e),j(i,t,":after",e)}const B="application/font-woff",U="image/jpeg",se={woff:B,woff2:B,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:U,jpeg:U,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function ne(i){const t=/\.([^./]*?)$/g.exec(i);return t?t[1]:""}function I(i){const t=ne(i).toLowerCase();return se[t]||""}function oe(i){return i.split(/,/)[1]}function P(i){return i.search(/^(data:)/)!==-1}function ae(i,t){return`data:${t};base64,${i}`}async function nt(i,t,e){const r=await fetch(i,t);if(r.status===404)throw new Error(`Resource "${r.url}" not found`);const s=await r.blob();return new Promise((n,o)=>{const a=new FileReader;a.onerror=o,a.onloadend=()=>{try{n(e({res:r,result:a.result}))}catch(l){o(l)}},a.readAsDataURL(s)})}const D={};function le(i,t,e){let r=i.replace(/\?.*/,"");return e&&(r=i),/ttf|otf|eot|woff2?/i.test(r)&&(r=r.replace(/.*\//,"")),t?`[${t}]${r}`:r}async function $(i,t,e){const r=le(i,t,e.includeQueryParams);if(D[r]!=null)return D[r];e.cacheBust&&(i+=(/\?/.test(i)?"&":"?")+new Date().getTime());let s;try{const n=await nt(i,e.fetchRequestInit,({res:o,result:a})=>(t||(t=o.headers.get("Content-Type")||""),oe(a)));s=ae(n,t)}catch(n){s=e.imagePlaceholder||"";let o=`Failed to fetch resource: ${i}`;n&&(o=typeof n=="string"?n:n.message),o&&console.warn(o)}return D[r]=s,s}async function ce(i){const t=i.toDataURL();return t==="data:,"?i.cloneNode(!1):M(t)}async function de(i,t){if(i.currentSrc){const n=document.createElement("canvas"),o=n.getContext("2d");n.width=i.clientWidth,n.height=i.clientHeight,o?.drawImage(i,0,0,n.width,n.height);const a=n.toDataURL();return M(a)}const e=i.poster,r=I(e),s=await $(e,r,t);return M(s)}async function he(i,t){var e;try{if(!((e=i?.contentDocument)===null||e===void 0)&&e.body)return await T(i.contentDocument.body,t,!0)}catch{}return i.cloneNode(!1)}async function ue(i,t){return d(i,HTMLCanvasElement)?ce(i):d(i,HTMLVideoElement)?de(i,t):d(i,HTMLIFrameElement)?he(i,t):i.cloneNode(ot(i))}const me=i=>i.tagName!=null&&i.tagName.toUpperCase()==="SLOT",ot=i=>i.tagName!=null&&i.tagName.toUpperCase()==="SVG";async function fe(i,t,e){var r,s;if(ot(t))return t;let n=[];return me(i)&&i.assignedNodes?n=f(i.assignedNodes()):d(i,HTMLIFrameElement)&&(!((r=i.contentDocument)===null||r===void 0)&&r.body)?n=f(i.contentDocument.body.childNodes):n=f(((s=i.shadowRoot)!==null&&s!==void 0?s:i).childNodes),n.length===0||d(i,HTMLVideoElement)||await n.reduce((o,a)=>o.then(()=>T(a,e)).then(l=>{l&&t.appendChild(l)}),Promise.resolve()),t}function pe(i,t,e){const r=t.style;if(!r)return;const s=window.getComputedStyle(i);s.cssText?(r.cssText=s.cssText,r.transformOrigin=s.transformOrigin):rt(e).forEach(n=>{let o=s.getPropertyValue(n);n==="font-size"&&o.endsWith("px")&&(o=`${Math.floor(parseFloat(o.substring(0,o.length-2)))-.1}px`),d(i,HTMLIFrameElement)&&n==="display"&&o==="inline"&&(o="block"),n==="d"&&t.getAttribute("d")&&(o=`path(${t.getAttribute("d")})`),r.setProperty(n,o,s.getPropertyPriority(n))})}function be(i,t){d(i,HTMLTextAreaElement)&&(t.innerHTML=i.value),d(i,HTMLInputElement)&&t.setAttribute("value",i.value)}function ge(i,t){if(d(i,HTMLSelectElement)){const e=t,r=Array.from(e.children).find(s=>i.value===s.getAttribute("value"));r&&r.setAttribute("selected","")}}function ye(i,t,e){return d(t,Element)&&(pe(i,t,e),re(i,t,e),be(i,t),ge(i,t)),t}async function xe(i,t){const e=i.querySelectorAll?i.querySelectorAll("use"):[];if(e.length===0)return i;const r={};for(let n=0;n<e.length;n++){const a=e[n].getAttribute("xlink:href");if(a){const l=i.querySelector(a),c=document.querySelector(a);!l&&c&&!r[a]&&(r[a]=await T(c,t,!0))}}const s=Object.values(r);if(s.length){const n="http://www.w3.org/1999/xhtml",o=document.createElementNS(n,"svg");o.setAttribute("xmlns",n),o.style.position="absolute",o.style.width="0",o.style.height="0",o.style.overflow="hidden",o.style.display="none";const a=document.createElementNS(n,"defs");o.appendChild(a);for(let l=0;l<s.length;l++)a.appendChild(s[l]);i.appendChild(o)}return i}async function T(i,t,e){return!e&&t.filter&&!t.filter(i)?null:Promise.resolve(i).then(r=>ue(r,t)).then(r=>fe(i,r,t)).then(r=>ye(i,r,t)).then(r=>xe(r,t))}const at=/url\((['"]?)([^'"]+?)\1\)/g,we=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,ke=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function ve(i){const t=i.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function Se(i){const t=[];return i.replace(at,(e,r,s)=>(t.push(s),e)),t.filter(e=>!P(e))}async function Ee(i,t,e,r,s){try{const n=e?Vt(t,e):t,o=I(t);let a;return s||(a=await $(n,o,r)),i.replace(ve(t),`$1${a}$3`)}catch{}return i}function Ce(i,{preferredFontFormat:t}){return t?i.replace(ke,e=>{for(;;){const[r,,s]=we.exec(e)||[];if(!s)return"";if(s===t)return`src: ${r};`}}):i}function lt(i){return i.search(at)!==-1}async function ct(i,t,e){if(!lt(i))return i;const r=Ce(i,e);return Se(r).reduce((n,o)=>n.then(a=>Ee(a,o,t,e)),Promise.resolve(r))}async function x(i,t,e){var r;const s=(r=t.style)===null||r===void 0?void 0:r.getPropertyValue(i);if(s){const n=await ct(s,null,e);return t.style.setProperty(i,n,t.style.getPropertyPriority(i)),!0}return!1}async function _e(i,t){await x("background",i,t)||await x("background-image",i,t),await x("mask",i,t)||await x("-webkit-mask",i,t)||await x("mask-image",i,t)||await x("-webkit-mask-image",i,t)}async function Me(i,t){const e=d(i,HTMLImageElement);if(!(e&&!P(i.src))&&!(d(i,SVGImageElement)&&!P(i.href.baseVal)))return;const r=e?i.src:i.href.baseVal,s=await $(r,I(r),t);await new Promise((n,o)=>{i.onload=n,i.onerror=t.onImageErrorHandler?(...l)=>{try{n(t.onImageErrorHandler(...l))}catch(c){o(c)}}:o;const a=i;a.decode&&(a.decode=n),a.loading==="lazy"&&(a.loading="eager"),e?(i.srcset="",i.src=s):i.href.baseVal=s})}async function Te(i,t){const r=f(i.childNodes).map(s=>dt(s,t));await Promise.all(r).then(()=>i)}async function dt(i,t){d(i,Element)&&(await _e(i,t),await Me(i,t),await Te(i,t))}function Le(i,t){const{style:e}=i;t.backgroundColor&&(e.backgroundColor=t.backgroundColor),t.width&&(e.width=`${t.width}px`),t.height&&(e.height=`${t.height}px`);const r=t.style;return r!=null&&Object.keys(r).forEach(s=>{e[s]=r[s]}),i}const z={};async function q(i){let t=z[i];if(t!=null)return t;const r=await(await fetch(i)).text();return t={url:i,cssText:r},z[i]=t,t}async function W(i,t){let e=i.cssText;const r=/url\(["']?([^"')]+)["']?\)/g,n=(e.match(/url\([^)]+\)/g)||[]).map(async o=>{let a=o.replace(r,"$1");return a.startsWith("https://")||(a=new URL(a,i.url).href),nt(a,t.fetchRequestInit,({result:l})=>(e=e.replace(o,`url(${l})`),[o,l]))});return Promise.all(n).then(()=>e)}function N(i){if(i==null)return[];const t=[],e=/(\/\*[\s\S]*?\*\/)/gi;let r=i.replace(e,"");const s=new RegExp("((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})","gi");for(;;){const l=s.exec(r);if(l===null)break;t.push(l[0])}r=r.replace(s,"");const n=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,o="((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})",a=new RegExp(o,"gi");for(;;){let l=n.exec(r);if(l===null){if(l=a.exec(r),l===null)break;n.lastIndex=a.lastIndex}else a.lastIndex=n.lastIndex;t.push(l[0])}return t}async function Ae(i,t){const e=[],r=[];return i.forEach(s=>{if("cssRules"in s)try{f(s.cssRules||[]).forEach((n,o)=>{if(n.type===CSSRule.IMPORT_RULE){let a=o+1;const l=n.href,c=q(l).then(h=>W(h,t)).then(h=>N(h).forEach(m=>{try{s.insertRule(m,m.startsWith("@import")?a+=1:s.cssRules.length)}catch(k){console.error("Error inserting rule from remote css",{rule:m,error:k})}})).catch(h=>{console.error("Error loading remote css",h.toString())});r.push(c)}})}catch(n){const o=i.find(a=>a.href==null)||document.styleSheets[0];s.href!=null&&r.push(q(s.href).then(a=>W(a,t)).then(a=>N(a).forEach(l=>{o.insertRule(l,o.cssRules.length)})).catch(a=>{console.error("Error loading remote stylesheet",a)})),console.error("Error inlining remote css file",n)}}),Promise.all(r).then(()=>(i.forEach(s=>{if("cssRules"in s)try{f(s.cssRules||[]).forEach(n=>{e.push(n)})}catch(n){console.error(`Error while reading CSS rules from ${s.href}`,n)}}),e))}function De(i){return i.filter(t=>t.type===CSSRule.FONT_FACE_RULE).filter(t=>lt(t.style.getPropertyValue("src")))}async function Pe(i,t){if(i.ownerDocument==null)throw new Error("Provided element is not within a Document");const e=f(i.ownerDocument.styleSheets),r=await Ae(e,t);return De(r)}function ht(i){return i.trim().replace(/["']/g,"")}function Re(i){const t=new Set;function e(r){(r.style.fontFamily||getComputedStyle(r).fontFamily).split(",").forEach(n=>{t.add(ht(n))}),Array.from(r.children).forEach(n=>{n instanceof HTMLElement&&e(n)})}return e(i),t}async function Ie(i,t){const e=await Pe(i,t),r=Re(i);return(await Promise.all(e.filter(n=>r.has(ht(n.style.fontFamily))).map(n=>{const o=n.parentStyleSheet?n.parentStyleSheet.href:null;return ct(n.cssText,o,t)}))).join(`
107
+ `)}async function $e(i,t){const e=t.fontEmbedCSS!=null?t.fontEmbedCSS:t.skipFonts?null:await Ie(i,t);if(e){const r=document.createElement("style"),s=document.createTextNode(e);r.appendChild(s),i.firstChild?i.insertBefore(r,i.firstChild):i.appendChild(r)}}async function He(i,t={}){const{width:e,height:r}=st(i,t),s=await T(i,t,!0);return await $e(s,t),await dt(s,t),Le(s,t),await Zt(s,e,r)}async function Oe(i,t={}){const{width:e,height:r}=st(i,t),s=await He(i,t),n=await M(s),o=document.createElement("canvas"),a=o.getContext("2d"),l=t.pixelRatio||Kt(),c=t.canvasWidth||e,h=t.canvasHeight||r;return o.width=c*l,o.height=h*l,t.skipAutoScale||Jt(o),o.style.width=`${c}`,o.style.height=`${h}`,t.backgroundColor&&(a.fillStyle=t.backgroundColor,a.fillRect(0,0,o.width,o.height)),a.drawImage(n,0,0,o.width,o.height),o}async function Fe(i,t={}){return(await Oe(i,t)).toDataURL("image/jpeg",t.quality||1)}async function je(i=[]){const t=Be(i);try{const e=await Fe(document.body,{quality:.85,pixelRatio:1,backgroundColor:"#ffffff",cacheBust:!0,skipAutoScale:!1,filter:r=>!(r instanceof HTMLElement&&r.id==="mtb-widget-host")});return qe(e)}catch{return null}finally{t?.remove()}}function Be(i){if(i.length===0)return null;const t=document.createElement("div");t.setAttribute("data-mtb-capture-annotations","true"),t.setAttribute("aria-hidden","true"),t.style.cssText="position:fixed;inset:0;pointer-events:none;z-index:2147483645;";for(const[e,r]of i.entries())r.type==="pin"?t.appendChild(Ue(r,e+1)):r.type==="draw"&&r.drawPath&&t.appendChild(ze(r.drawPath));return document.body.appendChild(t),t}function Ue(i,t){const e=document.createElement("div");return e.textContent=String(t),e.style.cssText=["position:fixed",`left:${i.x}px`,`top:${i.y}px`,"width:22px","height:22px","border-radius:50% 50% 50% 2px","background:#059669","border:2px solid #fff","display:flex","align-items:center","justify-content:center",'font:700 10px -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif',"color:#fff","box-shadow:0 2px 8px rgba(5,150,105,0.45)","transform:translate(-50%,-50%)"].join(";"),e}function ze(i){const t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("width","100%"),t.setAttribute("height","100%"),t.setAttribute("viewBox",`0 0 ${window.innerWidth} ${window.innerHeight}`),t.style.cssText="position:fixed;inset:0;width:100%;height:100%;overflow:visible;";const e=document.createElementNS("http://www.w3.org/2000/svg","path");return e.setAttribute("d",i),e.setAttribute("fill","none"),e.setAttribute("stroke","#059669"),e.setAttribute("stroke-width","3.5"),e.setAttribute("stroke-linecap","round"),e.setAttribute("stroke-linejoin","round"),e.setAttribute("filter","drop-shadow(0 1px 2px rgba(5,150,105,0.35))"),t.appendChild(e),t}function qe(i){const[t,e]=i.split(","),r=t.match(/:(.*?);/)?.[1]??"image/png",s=atob(e),n=new Uint8Array(s.length);for(let o=0;o<s.length;o++)n[o]=s.charCodeAt(o);return new Blob([n],{type:r})}class We{constructor(){this.listeners=new Set,this.originalOnError=null,this.installedOnError=null,this.rejectionHandler=null,this.hooked=!1}subscribe(t){return this.listeners.add(t),this.hook(),()=>{this.listeners.delete(t),this.listeners.size===0&&this.unhook()}}hook(){this.hooked||(this.hooked=!0,this.originalOnError=window.onerror,this.installedOnError=(t,e,r,s,n)=>(this.emit({message:String(t),source:e,line:r,col:s,error:n}),this.originalOnError?this.originalOnError.call(window,t,e,r,s,n):!1),window.onerror=this.installedOnError,this.rejectionHandler=t=>{const e=t.reason instanceof Error?t.reason.message:String(t.reason);this.emit({message:`Unhandled rejection: ${e}`})},window.addEventListener("unhandledrejection",this.rejectionHandler))}unhook(){this.hooked&&(this.hooked=!1,window.onerror===this.installedOnError&&(window.onerror=this.originalOnError),this.installedOnError=null,this.originalOnError=null,this.rejectionHandler&&(window.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null))}emit(t){for(const e of this.listeners)e(t)}}const ut=new We,Ne=20;class Ve{constructor(){this.errors=[],this.unsubscribe=null}start(){this.unsubscribe||(this.unsubscribe=ut.subscribe(t=>this.record(t)))}record(t){const e=t.line!=null?` (${t.line}:${t.col??0})`:"";this.addError(`${t.message}${e}`)}addError(t){this.errors.length>=Ne||this.errors.includes(t)||this.errors.push(t)}getErrors(){return[...this.errors]}stop(){this.unsubscribe?.(),this.unsubscribe=null}}const Ye=3,Xe=1e3,Ge=3,Ke=5e3,Je=500,Qe=500,Ze=300,ti=new Set(["A","BUTTON","INPUT","SELECT","TEXTAREA","LABEL","SUMMARY","DETAILS"]),ei=new Set(["button","link","checkbox","radio","tab","menuitem","option","switch","textbox","combobox","listbox","slider","spinbutton"]),V=["404","500","not found","page not found","server error","internal server error"],E=class E{constructor(t){this.clickHistory=[],this.unsubscribeErrors=null,this.active=!1,this.errorCount=0,this.deadClickCount=0,this.cooldownUntil=0,this.navTimestamps=[],this.boundPopstateHandler=null,this.originalPushState=null,this.originalReplaceState=null,this.installedPushState=null,this.installedReplaceState=null,this.boundSubmitHandler=null,this.boundInvalidHandler=null,this.errorPageUrls=new Set,this.domObserver=null,this.pendingDomChecks=0,this.lastMutationAt=-1,this.onFrustration=t,this.boundClickHandler=e=>this.handleClick(e)}start(){this.active||(this.active=!0,document.addEventListener("click",this.boundClickHandler,!0),this.unsubscribeErrors=ut.subscribe(t=>{this.errorCount++}),this.startNavigationTracking(),this.startFormTracking(),this.checkErrorPage())}stop(){this.active&&(this.active=!1,document.removeEventListener("click",this.boundClickHandler,!0),this.unsubscribeErrors?.(),this.unsubscribeErrors=null,this.clickHistory=[],this.stopNavigationTracking(),this.stopFormTracking(),this.errorPageUrls.clear(),this.disconnectDomObserver())}startNavigationTracking(){this.boundPopstateHandler=()=>this.handleNavigation(),window.addEventListener("popstate",this.boundPopstateHandler),this.originalPushState=history.pushState.bind(history),this.originalReplaceState=history.replaceState.bind(history);const t=this.originalPushState,e=this.originalReplaceState,r=()=>this.handleNavigation();this.installedPushState=function(s,n,o){t(s,n,o),r()},this.installedReplaceState=function(s,n,o){e(s,n,o),r()},history.pushState=this.installedPushState,history.replaceState=this.installedReplaceState}stopNavigationTracking(){this.boundPopstateHandler&&(window.removeEventListener("popstate",this.boundPopstateHandler),this.boundPopstateHandler=null),this.originalPushState&&history.pushState===this.installedPushState&&(history.pushState=this.originalPushState),this.originalReplaceState&&history.replaceState===this.installedReplaceState&&(history.replaceState=this.originalReplaceState),this.originalPushState=null,this.originalReplaceState=null,this.installedPushState=null,this.installedReplaceState=null,this.navTimestamps=[]}startFormTracking(){this.boundSubmitHandler=t=>this.handleFormSubmit(t),this.boundInvalidHandler=t=>this.handleFormInvalid(t),document.addEventListener("submit",this.boundSubmitHandler,!0),document.addEventListener("invalid",this.boundInvalidHandler,!0)}stopFormTracking(){this.boundSubmitHandler&&(document.removeEventListener("submit",this.boundSubmitHandler,!0),this.boundSubmitHandler=null),this.boundInvalidHandler&&(document.removeEventListener("invalid",this.boundInvalidHandler,!0),this.boundInvalidHandler=null)}handleClick(t){const e=t.target;if(!e||this.isWidgetElement(e))return;const r=Date.now();this.clickHistory.push({target:e,time:r});const s=r-Xe;if(this.clickHistory=this.clickHistory.filter(o=>o.time>s),this.clickHistory.filter(o=>o.target===e).length>=Ye){this.clickHistory=[],this.emitHighPriority({signal:"rage_click",target:w(e),timestamp:r});return}this.isInteractive(e)||(this.deadClickCount++,this.deadClickCount>=3&&this.errorCount>0&&(this.deadClickCount=0,this.errorCount=0,this.emitIfReady({signal:"dead_click",target:w(e),timestamp:r}))),this.checkDeadClickDom(e,r)}handleNavigation(){const t=Date.now();this.navTimestamps.push(t);const e=t-Ke;this.navTimestamps=this.navTimestamps.filter(r=>r>e),this.navTimestamps.length>=Ge&&(this.navTimestamps=[],this.emitIfReady({signal:"rapid_navigation",timestamp:t})),setTimeout(()=>{this.active&&this.checkErrorPage()},Ze)}handleFormSubmit(t){const e=t.target;e instanceof HTMLFormElement&&(this.isWidgetElement(e)||setTimeout(()=>{this.active&&e.querySelector('[aria-invalid="true"], .is-invalid')&&this.emitIfReady({signal:"form_failure",target:w(e),timestamp:Date.now()})},Je))}handleFormInvalid(t){const e=t.target;if(!e||this.isWidgetElement(e))return;const r=e.closest("form");this.emitIfReady({signal:"form_failure",target:w(r||e),timestamp:Date.now()})}checkErrorPage(){const t=location.href;if(this.errorPageUrls.has(t))return;const e=document.title.toLowerCase();if(V.some(s=>e.includes(s))){this.errorPageUrls.add(t),this.emitHighPriority({signal:"error_page",detail:document.title,timestamp:Date.now()});return}const r=document.querySelectorAll('h1, h2, [class*="error"], [class*="not-found"], [id*="error"], [id*="not-found"]');for(const s of r){const n=s.textContent??"";if(n.length<200&&V.some(o=>n.toLowerCase().includes(o))){this.errorPageUrls.add(t),this.emitHighPriority({signal:"error_page",detail:n.trim().slice(0,60),timestamp:Date.now()});return}}}checkDeadClickDom(t,e){this.looksInteractive(t)&&(this.pendingDomChecks++,this.ensureDomObserver(),setTimeout(()=>{this.pendingDomChecks--;const r=this.lastMutationAt>=e;this.pendingDomChecks===0&&this.disconnectDomObserver(),!r&&this.active&&this.emitIfReady({signal:"dead_click_dom",target:w(t),timestamp:e})},Qe))}ensureDomObserver(){this.domObserver||(this.domObserver=new MutationObserver(()=>{this.lastMutationAt=Date.now()}),this.domObserver.observe(document.body,{childList:!0,subtree:!0,attributes:!0,characterData:!0}))}disconnectDomObserver(){this.domObserver?.disconnect(),this.domObserver=null}looksInteractive(t){if(window.getComputedStyle(t).cursor==="pointer")return!0;if(t.classList)for(const r of t.classList){const s=r.toLowerCase();if(s.includes("btn")||s.includes("button"))return!0}return!1}isInteractive(t){if(ti.has(t.tagName))return!0;const e=t.getAttribute("role");return!!(e&&ei.has(e)||t.hasAttribute("onclick")||t.hasAttribute("tabindex")||t.contentEditable==="true"||window.getComputedStyle(t).cursor==="pointer"||t.closest('a, button, [role="button"], [role="link"], label'))}isWidgetElement(t){const e=document.getElementById("mtb-widget-host");return e?e===t||e.contains(t):!1}emitIfReady(t){const e=Date.now();e<this.cooldownUntil||(this.cooldownUntil=e+E.COOLDOWN_MS,this.onFrustration(t))}emitHighPriority(t){this.cooldownUntil=Date.now()+E.COOLDOWN_MS,this.onFrustration(t)}};E.COOLDOWN_MS=6e4;let R=E;function w(i){const t=i.tagName.toLowerCase(),e=i.id?`#${i.id}`:"",r=i.className&&typeof i.className=="string"?"."+i.className.trim().split(/\s+/).slice(0,2).join("."):"",s=i.textContent?.trim().slice(0,30)??"";return`<${t}${e}${r}>${s?` "${s}"`:""}`}function ii(){return{page_url:window.location.href,user_agent:navigator.userAgent,browser:ri(),os:si(),screen_width:window.screen.width,screen_height:window.screen.height}}function ri(){const i=navigator.userAgent;return/Edg\//.test(i)?`Edge ${i.match(/Edg\/(\S+)/)?.[1]??""}`:/OPR\//.test(i)?`Opera ${i.match(/OPR\/(\S+)/)?.[1]??""}`:/Chrome\//.test(i)?`Chrome ${i.match(/Chrome\/(\S+)/)?.[1]??""}`:/Safari\//.test(i)&&/Version\//.test(i)?`Safari ${i.match(/Version\/(\S+)/)?.[1]??""}`:/Firefox\//.test(i)?`Firefox ${i.match(/Firefox\/(\S+)/)?.[1]??""}`:"Unknown"}function si(){const i=navigator.userAgent;return/Windows NT 10/.test(i)?"Windows 10/11":/Windows NT/.test(i)?"Windows":/Mac OS X 10_15|macOS 1[56789]/.test(i)||/Mac OS X/.test(i)?"macOS":/Android/.test(i)?`Android ${i.match(/Android (\d+)/)?.[1]??""}`:/iPhone|iPad|iPod/.test(i)?"iOS":/Linux/.test(i)?"Linux":"Unknown"}const ni="https://makethisbetter.dev/api/v1";class oi{constructor(t,e,r=1e3,s,n){this.projectKey=t,this.apiUrl=(e??ni).replace(/\/$/,""),this.retryDelayMs=r,this.userToken=s,this.userTokenFn=n}async resolveUserToken(){return this.userTokenFn?this.userTokenFn():this.userToken}async authHeaders(t){const e={"X-Project-Key":this.projectKey},r=await this.resolveUserToken();return r&&(e["X-User-Token"]=r),t&&(e["Content-Type"]=t),e}async submitFeedback(t,e){const r=new FormData;if(r.append("feedback[description]",t.description),r.append("feedback[page_url]",t.page_url),r.append("feedback[user_agent]",t.user_agent),r.append("feedback[browser]",t.browser),r.append("feedback[os]",t.os),r.append("feedback[screen_width]",String(t.screen_width)),r.append("feedback[screen_height]",String(t.screen_height)),r.append("feedback[console_errors]",JSON.stringify(t.console_errors)),r.append("feedback[annotations]",JSON.stringify(t.annotations)),t.target_element&&r.append("feedback[target_element]",JSON.stringify(t.target_element)),t.user_id&&r.append("feedback[user_id]",t.user_id),t.reporter_external_id&&r.append("feedback[reporter_external_id]",t.reporter_external_id),t.reporter_email&&r.append("feedback[reporter_email]",t.reporter_email),t.user_email&&r.append("feedback[user_email]",t.user_email),t.user_name&&r.append("feedback[user_name]",t.user_name),t.recording_events&&t.recording_events.length>0){const o=JSON.stringify(t.recording_events),a=new Blob([o],{type:"application/json"});r.append("feedback[recording]",a,"recording.json"),r.append("feedback[recording_duration]",String(t.recording_duration??0))}if(e){const o=e.type==="image/jpeg"?"jpg":"png";r.append("feedback[screenshot]",e,`screenshot.${o}`)}const s=await this.authHeaders();return s["X-Idempotency-Key"]=li(),(await this.fetchWithRetry(`${this.apiUrl}/widget/feedbacks`,{method:"POST",headers:s,body:r})).json()}async createIdentityToken(t){const e=await this.authHeaders("application/json");try{return await(await this.fetchWithRetry(`${this.apiUrl}/widget/identity_tokens`,{method:"POST",headers:e,body:JSON.stringify({reporter_external_id:t})})).json()}catch{return null}}async updateReporter(t,e,r){const s=await this.authHeaders("application/json");s["X-Identity-Token"]=r;try{return await this.fetchWithRetry(`${this.apiUrl}/widget/feedbacks/${t}/reporter`,{method:"PATCH",headers:s,body:JSON.stringify({reporter:{email:e}})}),!0}catch{return!1}}async startClarification(t,e){const r={};e&&(r.message=e);const s=await this.authHeaders("application/json");return(await this.fetchWithRetry(`${this.apiUrl}/widget/feedbacks/${t}/clarify`,{method:"POST",headers:s,body:JSON.stringify(r)})).json()}async getClarification(t){const e=await this.authHeaders();return(await this.fetchWithRetry(`${this.apiUrl}/widget/feedbacks/${t}/clarify`,{method:"GET",headers:e})).json()}async streamClarification(t,e,r){const s={};e&&(s.message=e);const n=await this.authHeaders("application/json");n.Accept="text/event-stream";const o=await fetch(`${this.apiUrl}/widget/feedbacks/${t}/clarify`,{method:"POST",headers:n,body:JSON.stringify(s)}),a=o.headers.get("Content-Type")??"";if(!o.ok||!o.body||!a.includes("text/event-stream"))throw new Error("clarify stream unavailable");return ai(o.body,r)}async fetchWithRetry(t,e,r=1){let s;try{s=await fetch(t,e)}catch(n){if(r>0)return await Y(this.retryDelayMs),this.fetchWithRetry(t,e,r-1);throw n}if(s.ok)return s;if(s.status>=500&&r>0)return await Y(this.retryDelayMs),this.fetchWithRetry(t,e,r-1);throw new Error(`HTTP ${s.status}`)}}function Y(i){return i<=0?Promise.resolve():new Promise(t=>setTimeout(t,i))}async function ai(i,t){const e=i.getReader(),r=new TextDecoder;let s="",n={messages:[],done:!0};const o=a=>{const l=a.split(`
108
108
  `).find(k=>k.startsWith("event:")),c=a.split(`
109
109
  `).find(k=>k.startsWith("data:"));if(!c)return;const h=l?.slice(6).trim(),m=JSON.parse(c.slice(5).trim());h==="delta"&&typeof m.text=="string"?t(m.text):h==="done"&&(n={messages:Array.isArray(m.messages)?m.messages:[],done:m.done!==!1})};for(;;){const{done:a,value:l}=await e.read();if(a)break;s+=r.decode(l,{stream:!0});let c;for(;(c=s.indexOf(`
110
110
 
111
- `))!==-1;){const h=s.slice(0,c);s=s.slice(c+2);try{o(h)}catch{}}}return n}function li(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function ci(i,t,e,r,s,n,o,a){return{description:i,...t,console_errors:e,annotations:r?[r]:[],target_element:r?.targetSelector?{selector:r.targetSelector,text:r.targetText??"",name:r.targetName??""}:void 0,user_id:s?.id,user_email:s?.email,user_name:s?.name,reporter_external_id:s?void 0:o,reporter_email:s?void 0:a,recording_events:n?.events,recording_duration:n?.duration}}const X="mtb_anon_id",mt="mtb_reporter_email",ft="mtb_board_url";let G=null,pt=null,bt=null;function K(){try{const i=window.localStorage.getItem(X);if(i?.startsWith("anon_"))return i;const t=Z();return window.localStorage.setItem(X,t),t}catch{return G??(G=Z()),G}}function J(){try{return window.localStorage.getItem(mt)??void 0}catch{return pt??void 0}}function di(i){pt=i;try{window.localStorage.setItem(mt,i)}catch{}}function hi(){try{return window.localStorage.getItem(ft)??void 0}catch{return bt??void 0}}function Q(i){bt=i;try{window.localStorage.setItem(ft,i)}catch{}}function Z(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`anon_${crypto.randomUUID()}`:`anon_${`${Date.now().toString(16)}-${Math.random().toString(16).slice(2,10)}`}`}const ui={tab:"Feedback",toolbar:{markup:"Mark up",record:"Record",hint:"Click any element to annotate · drag to draw",hintRecord:"Recording your screen",exit:"Exit"},popup:{about:"About",placeholder:"Describe the issue or suggestion...",submit:"Submit",cancel:"Cancel",my_feedback:"My feedback",quickOptions:[{emoji:"🐛",label:"Something is broken"},{emoji:"💡",label:"I wish this worked differently"},{emoji:"🤔",label:"I don't understand this"},{emoji:"✨",label:"I have an idea"}]},success:{title:"Thanks!",message:"Your feedback has been received.",title_no_ai:"Sent — thanks!",message_no_ai:"We'll take it from here. You'll hear back when it's resolved.",view_feedback:"View my feedback",close:"Close",email_prompt:"Want updates? Leave your email and we'll let you know when it's resolved.",email_placeholder:"you@example.com",email_submit:"Notify me",email_saved:"You'll get an email when it's resolved.",email_error:"Couldn't save your email. Please try again."},error:{submit:"Failed to submit. Please try again."},pet:{bubble:"Need help?"},frustration:{prompt:"Something not working? Tell us.",action:"Annotate",dismiss:"Dismiss"},annotation:{drawing:"Drawing",element:"element"},record:{stop:"Stop",timer_label:"Recording",max_reached:"Maximum recording time reached"},clarify:{title:"Make This Better AI",subtitle:"Sharpening your feedback",thinking:"Thinking...",placeholder:"Type your answer — or Skip",send:"Send",skip:"Skip"}},mi={tab:"反馈",toolbar:{markup:"标注",record:"录屏",hint:"点击任意元素进行标注 · 拖拽可自由绘制",hintRecord:"正在录制屏幕",exit:"退出"},popup:{about:"关于",placeholder:"描述问题或建议...",submit:"提交",cancel:"取消",my_feedback:"我的反馈",quickOptions:[{emoji:"🐛",label:"这里有问题"},{emoji:"💡",label:"我希望它能更好用"},{emoji:"🤔",label:"我看不懂这里"},{emoji:"✨",label:"我有个想法"}]},success:{title:"感谢!",message:"您的反馈已收到。",title_no_ai:"已发送,感谢!",message_no_ai:"我们会跟进处理,解决后会通知您。",view_feedback:"查看我的反馈",close:"关闭",email_prompt:"想了解进展?留下邮箱,问题解决后我们会通知您。",email_placeholder:"you@example.com",email_submit:"通知我",email_saved:"问题解决后您会收到邮件通知。",email_error:"邮箱保存失败,请重试。"},error:{submit:"提交失败,请重试。"},pet:{bubble:"需要帮助吗?"},frustration:{prompt:"遇到问题了?告诉我们。",action:"标注",dismiss:"关闭"},annotation:{drawing:"绘制",element:"元素"},record:{stop:"停止",timer_label:"录制中",max_reached:"已达到最大录制时长"},clarify:{title:"让它更好 AI",subtitle:"正在完善你的反馈",thinking:"思考中...",placeholder:"输入你的回答 —— 或跳过",send:"发送",skip:"跳过"}},fi={tab:"フィードバック",toolbar:{markup:"マークアップ",record:"録画",hint:"要素をクリックして注釈 · ドラッグで描画",hintRecord:"画面を録画中",exit:"終了"},popup:{about:"概要",placeholder:"問題や提案を入力してください...",submit:"送信",cancel:"キャンセル",my_feedback:"自分のフィードバック",quickOptions:[{emoji:"🐛",label:"不具合があります"},{emoji:"💡",label:"もっと使いやすくしてほしい"},{emoji:"🤔",label:"ここがわかりにくい"},{emoji:"✨",label:"アイデアがあります"}]},success:{title:"ありがとうございます!",message:"フィードバックを受け付けました。",title_no_ai:"送信しました!",message_no_ai:"チームが対応します。解決次第お知らせします。",view_feedback:"フィードバックを確認",close:"閉じる",email_prompt:"進捗を知りたい場合は、メールアドレスをご記入ください。解決次第お知らせします。",email_placeholder:"you@example.com",email_submit:"通知を受け取る",email_saved:"解決次第メールでお知らせします。",email_error:"メールアドレスを保存できませんでした。もう一度お試しください。"},error:{submit:"送信に失敗しました。もう一度お試しください。"},pet:{bubble:"お困りですか?"},frustration:{prompt:"うまくいかないことがありますか?お知らせください。",action:"注釈",dismiss:"閉じる"},annotation:{drawing:"描画",element:"要素"},record:{stop:"停止",timer_label:"録画中",max_reached:"最大録画時間に達しました"},clarify:{title:"Make This Better AI",subtitle:"フィードバックを整えています",thinking:"考え中...",placeholder:"回答を入力 — またはスキップ",send:"送信",skip:"スキップ"}},pi={tab:"피드백",toolbar:{markup:"마크업",record:"녹화",hint:"요소를 클릭하여 주석 · 드래그하여 그리기",hintRecord:"화면을 녹화 중입니다",exit:"나가기"},popup:{about:"정보",placeholder:"문제 또는 제안 사항을 설명해 주세요...",submit:"제출",cancel:"취소",my_feedback:"내 피드백",quickOptions:[{emoji:"🐛",label:"오류가 있어요"},{emoji:"💡",label:"이 기능을 개선해 주세요"},{emoji:"🤔",label:"이 부분을 모르겠어요"},{emoji:"✨",label:"아이디어가 있어요"}]},success:{title:"감사합니다!",message:"피드백이 접수되었습니다.",title_no_ai:"전송 완료!",message_no_ai:"팀에서 처리 후 알려드리겠습니다.",view_feedback:"내 피드백 보기",close:"닫기",email_prompt:"진행 상황이 궁금하신가요? 이메일을 남겨주시면 해결 시 알려드립니다.",email_placeholder:"you@example.com",email_submit:"알림 받기",email_saved:"해결되면 이메일로 알려드립니다.",email_error:"이메일을 저장하지 못했습니다. 다시 시도해 주세요."},error:{submit:"제출에 실패했습니다. 다시 시도해 주세요."},pet:{bubble:"도움이 필요하신가요?"},frustration:{prompt:"문제가 있으신가요? 알려 주세요.",action:"주석",dismiss:"닫기"},annotation:{drawing:"그리기",element:"요소"},record:{stop:"중지",timer_label:"녹화 중",max_reached:"최대 녹화 시간에 도달했습니다"},clarify:{title:"Make This Better AI",subtitle:"피드백을 다듬는 중",thinking:"생각 중...",placeholder:"답변 입력 — 또는 건너뛰기",send:"보내기",skip:"건너뛰기"}},bi={tab:"Comentarios",toolbar:{markup:"Anotar",record:"Grabar",hint:"Haz clic en cualquier elemento para anotar · arrastra para dibujar",hintRecord:"Grabando tu pantalla",exit:"Salir"},popup:{about:"Acerca de",placeholder:"Describe el problema o sugerencia...",submit:"Enviar",cancel:"Cancelar",my_feedback:"Mis comentarios",quickOptions:[{emoji:"🐛",label:"Algo no funciona"},{emoji:"💡",label:"Me gustaría que funcionara diferente"},{emoji:"🤔",label:"No entiendo esto"},{emoji:"✨",label:"Tengo una idea"}]},success:{title:"¡Gracias!",message:"Tu comentario ha sido recibido.",title_no_ai:"¡Enviado!",message_no_ai:"Nos encargamos. Te avisaremos cuando se resuelva.",view_feedback:"Ver mis comentarios",close:"Cerrar",email_prompt:"¿Quieres novedades? Deja tu correo y te avisaremos cuando se resuelva.",email_placeholder:"tu@ejemplo.com",email_submit:"Avisarme",email_saved:"Recibirás un correo cuando se resuelva.",email_error:"No se pudo guardar tu correo. Inténtalo de nuevo."},error:{submit:"Error al enviar. Por favor, inténtalo de nuevo."},pet:{bubble:"¿Necesitas ayuda?"},frustration:{prompt:"¿Algo no funciona? Cuéntanos.",action:"Anotar",dismiss:"Cerrar"},annotation:{drawing:"Dibujo",element:"elemento"},record:{stop:"Detener",timer_label:"Grabando",max_reached:"Se alcanzó el tiempo máximo de grabación"},clarify:{title:"Make This Better AI",subtitle:"Afinando tus comentarios",thinking:"Pensando...",placeholder:"Escribe tu respuesta — o Omitir",send:"Enviar",skip:"Omitir"}},gi={tab:"Avis",toolbar:{markup:"Annoter",record:"Enregistrer",hint:"Cliquez sur un élément pour l'annoter · glissez pour dessiner",hintRecord:"Enregistrement de l'écran en cours",exit:"Quitter"},popup:{about:"À propos",placeholder:"Décrivez le problème ou votre suggestion...",submit:"Envoyer",cancel:"Annuler",my_feedback:"Mes avis",quickOptions:[{emoji:"🐛",label:"Quelque chose ne fonctionne pas"},{emoji:"💡",label:"J'aimerais que cela fonctionne autrement"},{emoji:"🤔",label:"Je ne comprends pas ceci"},{emoji:"✨",label:"J'ai une idée"}]},success:{title:"Merci !",message:"Votre avis a bien été reçu.",title_no_ai:"Envoyé !",message_no_ai:"On s'en occupe. Vous serez informé(e) dès que ce sera résolu.",view_feedback:"Voir mes avis",close:"Fermer",email_prompt:"Envie de suivre l'avancement ? Laissez votre e-mail et nous vous préviendrons une fois résolu.",email_placeholder:"vous@exemple.com",email_submit:"Me prévenir",email_saved:"Vous recevrez un e-mail une fois résolu.",email_error:"Impossible d'enregistrer votre e-mail. Veuillez réessayer."},error:{submit:"Échec de l'envoi. Veuillez réessayer."},pet:{bubble:"Besoin d'aide ?"},frustration:{prompt:"Un problème ? Dites-le-nous.",action:"Annoter",dismiss:"Fermer"},annotation:{drawing:"Dessin",element:"élément"},record:{stop:"Arrêter",timer_label:"Enregistrement",max_reached:"Durée maximale d'enregistrement atteinte"},clarify:{title:"Make This Better AI",subtitle:"Affinement de votre retour",thinking:"Réflexion...",placeholder:"Saisissez votre réponse — ou Ignorer",send:"Envoyer",skip:"Passer"}},yi={tab:"Feedback",toolbar:{markup:"Markieren",record:"Aufnehmen",hint:"Klicken Sie auf ein Element zum Kommentieren · ziehen Sie zum Zeichnen",hintRecord:"Bildschirmaufnahme läuft",exit:"Beenden"},popup:{about:"Info",placeholder:"Beschreiben Sie das Problem oder Ihren Vorschlag...",submit:"Absenden",cancel:"Abbrechen",my_feedback:"Mein Feedback",quickOptions:[{emoji:"🐛",label:"Etwas funktioniert nicht"},{emoji:"💡",label:"Ich wünsche mir das anders"},{emoji:"🤔",label:"Das verstehe ich nicht"},{emoji:"✨",label:"Ich habe eine Idee"}]},success:{title:"Vielen Dank!",message:"Ihr Feedback wurde empfangen.",title_no_ai:"Gesendet!",message_no_ai:"Wir kümmern uns darum. Sie werden benachrichtigt, sobald es gelöst ist.",view_feedback:"Mein Feedback ansehen",close:"Schließen",email_prompt:"Updates gewünscht? Hinterlassen Sie Ihre E-Mail und wir melden uns, sobald es gelöst ist.",email_placeholder:"sie@beispiel.de",email_submit:"Benachrichtigen",email_saved:"Sie erhalten eine E-Mail, sobald es gelöst ist.",email_error:"E-Mail konnte nicht gespeichert werden. Bitte versuchen Sie es erneut."},error:{submit:"Senden fehlgeschlagen. Bitte versuchen Sie es erneut."},pet:{bubble:"Brauchen Sie Hilfe?"},frustration:{prompt:"Etwas funktioniert nicht? Sagen Sie es uns.",action:"Kommentieren",dismiss:"Schließen"},annotation:{drawing:"Zeichnung",element:"Element"},record:{stop:"Stopp",timer_label:"Aufnahme",max_reached:"Maximale Aufnahmezeit erreicht"},clarify:{title:"Make This Better AI",subtitle:"Wir schärfen dein Feedback",thinking:"Einen Moment...",placeholder:"Gib deine Antwort ein — oder Überspringen",send:"Senden",skip:"Überspringen"}},S={en:ui,"zh-CN":mi,ja:fi,ko:pi,es:bi,fr:gi,de:yi};function xi(i){if(S[i])return S[i];const t=i.split("-")[0];return S[t]?S[t]:S.en}const wi=60,ki="https://cdn.jsdelivr.net/npm/@rrweb/record@2.1.0/umd/record.min.js",vi="sha384-MrD66HBNSykaP2N95+6hQCFlF5oH2tvL3TD/zyvHNkP/sAFWZx98DX9MEDy8MdVT";let C=null;function Si(){return C||(C=Ei().catch(()=>Ci()),C)}async function Ei(){return(await import("@rrweb/record")).record}function tt(){const i=globalThis;return i.rrwebRecord?.record??i.rrweb?.record}function Ci(){return new Promise((i,t)=>{const e=tt();if(e){i(e);return}const r=document.createElement("script");r.src=ki,r.integrity=vi,r.crossOrigin="anonymous",r.onload=()=>{const s=tt();s?i(s):t(new Error("rrweb record global not found after script load"))},r.onerror=()=>t(new Error("Failed to load rrweb from CDN")),document.head.appendChild(r)})}class _i{constructor(t,e){this.events=[],this.stopFn=null,this.startedAt=0,this.timer=null,this.clickHandler=null,this.stopped=!1,this.shadow=t,this.onMaxReached=e}async start(){const t=await Si();this.startedAt=Date.now(),this.stopped=!1,this.stopFn=t({emit:e=>{this.stopped||this.events.push(e)}}),this.clickHandler=e=>{this.showClickRipple(e.clientX,e.clientY),t.addCustomEvent?.("mtb-click",{x:e.clientX,y:e.clientY,target:e.target instanceof HTMLElement?e.target.tagName:""})},document.addEventListener("click",this.clickHandler,!0),this.timer=setTimeout(()=>{this.onMaxReached?.()},wi*1e3)}stop(){return this.stopped=!0,this.stopFn?.(),this.stopFn=null,this.cleanupTimer(),this.cleanupClickHandler(),{events:this.events,duration:this.getDuration()}}getDuration(){return this.startedAt===0?0:Math.round((Date.now()-this.startedAt)/1e3)}destroy(){this.stopped=!0,this.stopFn?.(),this.stopFn=null,this.cleanupTimer(),this.cleanupClickHandler(),this.events=[],this.startedAt=0}cleanupTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null)}cleanupClickHandler(){this.clickHandler&&(document.removeEventListener("click",this.clickHandler,!0),this.clickHandler=null)}showClickRipple(t,e){const r=this.shadow.el("div","mtb-click-ripple");r.style.left=`${t}px`,r.style.top=`${e}px`,this.shadow.append(r),r.addEventListener("animationend",()=>r.remove())}}class Ti{constructor(t,e,r,s){this.intervalId=null,this.getDuration=r,this.el=t.el("div","mtb-record-bar"),this.el.innerHTML=`
111
+ `))!==-1;){const h=s.slice(0,c);s=s.slice(c+2);try{o(h)}catch{}}}return n}function li(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function ci(i,t,e,r,s,n,o,a){return{description:i,...t,console_errors:e,annotations:r?[r]:[],target_element:r?.targetSelector?{selector:r.targetSelector,text:r.targetText??"",name:r.targetName??""}:void 0,user_id:s?.id,user_email:s?.email,user_name:s?.name,reporter_external_id:s?void 0:o,reporter_email:s?void 0:a,recording_events:n?.events,recording_duration:n?.duration}}const X="mtb_anon_id",mt="mtb_reporter_email",ft="mtb_board_url";let G=null,pt=null,bt=null;function K(){try{const i=window.localStorage.getItem(X);if(i?.startsWith("anon_"))return i;const t=Z();return window.localStorage.setItem(X,t),t}catch{return G??(G=Z()),G}}function J(){try{return window.localStorage.getItem(mt)??void 0}catch{return pt??void 0}}function di(i){pt=i;try{window.localStorage.setItem(mt,i)}catch{}}function hi(){try{return window.localStorage.getItem(ft)??void 0}catch{return bt??void 0}}function Q(i){bt=i;try{window.localStorage.setItem(ft,i)}catch{}}function Z(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`anon_${crypto.randomUUID()}`:`anon_${`${Date.now().toString(16)}-${Math.random().toString(16).slice(2,10)}`}`}const ui={tab:"Feedback",toolbar:{markup:"Mark up",record:"Record",hint:"Click any element to annotate · drag to draw",hintRecord:"Recording your screen",exit:"Exit"},popup:{about:"About",placeholder:"Describe the issue or suggestion...",submit:"Submit",cancel:"Cancel",my_feedback:"My feedback",quickOptions:[{emoji:"🐛",label:"Something is broken"},{emoji:"💡",label:"I wish this worked differently"},{emoji:"🤔",label:"I don't understand this"},{emoji:"✨",label:"I have an idea"}]},success:{title:"Thanks!",message:"Your feedback has been received.",title_no_ai:"Sent — thanks!",message_no_ai:"We'll take it from here. You'll hear back when it's resolved.",view_feedback:"View my feedback",close:"Close",email_prompt:"Want updates? Leave your email and we'll let you know when it's resolved.",email_placeholder:"you@example.com",email_submit:"Notify me",email_saved:"You'll get an email when it's resolved.",email_error:"Couldn't save your email. Please try again."},error:{submit:"Failed to submit. Please try again."},pet:{bubble:"Need help?"},frustration:{prompt:"Something not working? Tell us.",action:"Annotate",dismiss:"Dismiss"},annotation:{drawing:"Drawing",element:"element"},record:{stop:"Stop",timer_label:"Recording",max_reached:"Maximum recording time reached"},clarify:{title:"Make This Better AI",subtitle:"Sharpening your feedback",thinking:"Thinking...",placeholder:"Type your answer — or Skip",send:"Send",skip:"Skip"}},mi={tab:"反馈",toolbar:{markup:"标注",record:"录屏",hint:"点击任意元素进行标注 · 拖拽可自由绘制",hintRecord:"正在录制屏幕",exit:"退出"},popup:{about:"关于",placeholder:"描述问题或建议...",submit:"提交",cancel:"取消",my_feedback:"我的反馈",quickOptions:[{emoji:"🐛",label:"这里有问题"},{emoji:"💡",label:"我希望它能更好用"},{emoji:"🤔",label:"我看不懂这里"},{emoji:"✨",label:"我有个想法"}]},success:{title:"感谢!",message:"您的反馈已收到。",title_no_ai:"已发送,感谢!",message_no_ai:"我们会跟进处理,解决后会通知您。",view_feedback:"查看我的反馈",close:"关闭",email_prompt:"想了解进展?留下邮箱,问题解决后我们会通知您。",email_placeholder:"you@example.com",email_submit:"通知我",email_saved:"问题解决后您会收到邮件通知。",email_error:"邮箱保存失败,请重试。"},error:{submit:"提交失败,请重试。"},pet:{bubble:"需要帮助吗?"},frustration:{prompt:"遇到问题了?告诉我们。",action:"标注",dismiss:"关闭"},annotation:{drawing:"绘制",element:"元素"},record:{stop:"停止",timer_label:"录制中",max_reached:"已达到最大录制时长"},clarify:{title:"让它更好 AI",subtitle:"正在完善你的反馈",thinking:"思考中...",placeholder:"输入你的回答 —— 或跳过",send:"发送",skip:"跳过"}},fi={tab:"フィードバック",toolbar:{markup:"マークアップ",record:"録画",hint:"要素をクリックして注釈 · ドラッグで描画",hintRecord:"画面を録画中",exit:"終了"},popup:{about:"概要",placeholder:"問題や提案を入力してください...",submit:"送信",cancel:"キャンセル",my_feedback:"自分のフィードバック",quickOptions:[{emoji:"🐛",label:"不具合があります"},{emoji:"💡",label:"もっと使いやすくしてほしい"},{emoji:"🤔",label:"ここがわかりにくい"},{emoji:"✨",label:"アイデアがあります"}]},success:{title:"ありがとうございます!",message:"フィードバックを受け付けました。",title_no_ai:"送信しました!",message_no_ai:"チームが対応します。解決次第お知らせします。",view_feedback:"フィードバックを確認",close:"閉じる",email_prompt:"進捗を知りたい場合は、メールアドレスをご記入ください。解決次第お知らせします。",email_placeholder:"you@example.com",email_submit:"通知を受け取る",email_saved:"解決次第メールでお知らせします。",email_error:"メールアドレスを保存できませんでした。もう一度お試しください。"},error:{submit:"送信に失敗しました。もう一度お試しください。"},pet:{bubble:"お困りですか?"},frustration:{prompt:"うまくいかないことがありますか?お知らせください。",action:"注釈",dismiss:"閉じる"},annotation:{drawing:"描画",element:"要素"},record:{stop:"停止",timer_label:"録画中",max_reached:"最大録画時間に達しました"},clarify:{title:"Make This Better AI",subtitle:"フィードバックを整えています",thinking:"考え中...",placeholder:"回答を入力 — またはスキップ",send:"送信",skip:"スキップ"}},pi={tab:"피드백",toolbar:{markup:"마크업",record:"녹화",hint:"요소를 클릭하여 주석 · 드래그하여 그리기",hintRecord:"화면을 녹화 중입니다",exit:"나가기"},popup:{about:"정보",placeholder:"문제 또는 제안 사항을 설명해 주세요...",submit:"제출",cancel:"취소",my_feedback:"내 피드백",quickOptions:[{emoji:"🐛",label:"오류가 있어요"},{emoji:"💡",label:"이 기능을 개선해 주세요"},{emoji:"🤔",label:"이 부분을 모르겠어요"},{emoji:"✨",label:"아이디어가 있어요"}]},success:{title:"감사합니다!",message:"피드백이 접수되었습니다.",title_no_ai:"전송 완료!",message_no_ai:"팀에서 처리 후 알려드리겠습니다.",view_feedback:"내 피드백 보기",close:"닫기",email_prompt:"진행 상황이 궁금하신가요? 이메일을 남겨주시면 해결 시 알려드립니다.",email_placeholder:"you@example.com",email_submit:"알림 받기",email_saved:"해결되면 이메일로 알려드립니다.",email_error:"이메일을 저장하지 못했습니다. 다시 시도해 주세요."},error:{submit:"제출에 실패했습니다. 다시 시도해 주세요."},pet:{bubble:"도움이 필요하신가요?"},frustration:{prompt:"문제가 있으신가요? 알려 주세요.",action:"주석",dismiss:"닫기"},annotation:{drawing:"그리기",element:"요소"},record:{stop:"중지",timer_label:"녹화 중",max_reached:"최대 녹화 시간에 도달했습니다"},clarify:{title:"Make This Better AI",subtitle:"피드백을 다듬는 중",thinking:"생각 중...",placeholder:"답변 입력 — 또는 건너뛰기",send:"보내기",skip:"건너뛰기"}},bi={tab:"Comentarios",toolbar:{markup:"Anotar",record:"Grabar",hint:"Haz clic en cualquier elemento para anotar · arrastra para dibujar",hintRecord:"Grabando tu pantalla",exit:"Salir"},popup:{about:"Acerca de",placeholder:"Describe el problema o sugerencia...",submit:"Enviar",cancel:"Cancelar",my_feedback:"Mis comentarios",quickOptions:[{emoji:"🐛",label:"Algo no funciona"},{emoji:"💡",label:"Me gustaría que funcionara diferente"},{emoji:"🤔",label:"No entiendo esto"},{emoji:"✨",label:"Tengo una idea"}]},success:{title:"¡Gracias!",message:"Tu comentario ha sido recibido.",title_no_ai:"¡Enviado!",message_no_ai:"Nos encargamos. Te avisaremos cuando se resuelva.",view_feedback:"Ver mis comentarios",close:"Cerrar",email_prompt:"¿Quieres novedades? Deja tu correo y te avisaremos cuando se resuelva.",email_placeholder:"tu@ejemplo.com",email_submit:"Avisarme",email_saved:"Recibirás un correo cuando se resuelva.",email_error:"No se pudo guardar tu correo. Inténtalo de nuevo."},error:{submit:"Error al enviar. Por favor, inténtalo de nuevo."},pet:{bubble:"¿Necesitas ayuda?"},frustration:{prompt:"¿Algo no funciona? Cuéntanos.",action:"Anotar",dismiss:"Cerrar"},annotation:{drawing:"Dibujo",element:"elemento"},record:{stop:"Detener",timer_label:"Grabando",max_reached:"Se alcanzó el tiempo máximo de grabación"},clarify:{title:"Make This Better AI",subtitle:"Afinando tus comentarios",thinking:"Pensando...",placeholder:"Escribe tu respuesta — o Omitir",send:"Enviar",skip:"Omitir"}},gi={tab:"Avis",toolbar:{markup:"Annoter",record:"Enregistrer",hint:"Cliquez sur un élément pour l'annoter · glissez pour dessiner",hintRecord:"Enregistrement de l'écran en cours",exit:"Quitter"},popup:{about:"À propos",placeholder:"Décrivez le problème ou votre suggestion...",submit:"Envoyer",cancel:"Annuler",my_feedback:"Mes avis",quickOptions:[{emoji:"🐛",label:"Quelque chose ne fonctionne pas"},{emoji:"💡",label:"J'aimerais que cela fonctionne autrement"},{emoji:"🤔",label:"Je ne comprends pas ceci"},{emoji:"✨",label:"J'ai une idée"}]},success:{title:"Merci !",message:"Votre avis a bien été reçu.",title_no_ai:"Envoyé !",message_no_ai:"On s'en occupe. Vous serez informé(e) dès que ce sera résolu.",view_feedback:"Voir mes avis",close:"Fermer",email_prompt:"Envie de suivre l'avancement ? Laissez votre e-mail et nous vous préviendrons une fois résolu.",email_placeholder:"vous@exemple.com",email_submit:"Me prévenir",email_saved:"Vous recevrez un e-mail une fois résolu.",email_error:"Impossible d'enregistrer votre e-mail. Veuillez réessayer."},error:{submit:"Échec de l'envoi. Veuillez réessayer."},pet:{bubble:"Besoin d'aide ?"},frustration:{prompt:"Un problème ? Dites-le-nous.",action:"Annoter",dismiss:"Fermer"},annotation:{drawing:"Dessin",element:"élément"},record:{stop:"Arrêter",timer_label:"Enregistrement",max_reached:"Durée maximale d'enregistrement atteinte"},clarify:{title:"Make This Better AI",subtitle:"Affinement de votre retour",thinking:"Réflexion...",placeholder:"Saisissez votre réponse — ou Ignorer",send:"Envoyer",skip:"Passer"}},yi={tab:"Feedback",toolbar:{markup:"Markieren",record:"Aufnehmen",hint:"Klicken Sie auf ein Element zum Kommentieren · ziehen Sie zum Zeichnen",hintRecord:"Bildschirmaufnahme läuft",exit:"Beenden"},popup:{about:"Info",placeholder:"Beschreiben Sie das Problem oder Ihren Vorschlag...",submit:"Absenden",cancel:"Abbrechen",my_feedback:"Mein Feedback",quickOptions:[{emoji:"🐛",label:"Etwas funktioniert nicht"},{emoji:"💡",label:"Ich wünsche mir das anders"},{emoji:"🤔",label:"Das verstehe ich nicht"},{emoji:"✨",label:"Ich habe eine Idee"}]},success:{title:"Vielen Dank!",message:"Ihr Feedback wurde empfangen.",title_no_ai:"Gesendet!",message_no_ai:"Wir kümmern uns darum. Sie werden benachrichtigt, sobald es gelöst ist.",view_feedback:"Mein Feedback ansehen",close:"Schließen",email_prompt:"Updates gewünscht? Hinterlassen Sie Ihre E-Mail und wir melden uns, sobald es gelöst ist.",email_placeholder:"sie@beispiel.de",email_submit:"Benachrichtigen",email_saved:"Sie erhalten eine E-Mail, sobald es gelöst ist.",email_error:"E-Mail konnte nicht gespeichert werden. Bitte versuchen Sie es erneut."},error:{submit:"Senden fehlgeschlagen. Bitte versuchen Sie es erneut."},pet:{bubble:"Brauchen Sie Hilfe?"},frustration:{prompt:"Etwas funktioniert nicht? Sagen Sie es uns.",action:"Kommentieren",dismiss:"Schließen"},annotation:{drawing:"Zeichnung",element:"Element"},record:{stop:"Stopp",timer_label:"Aufnahme",max_reached:"Maximale Aufnahmezeit erreicht"},clarify:{title:"Make This Better AI",subtitle:"Wir schärfen dein Feedback",thinking:"Einen Moment...",placeholder:"Gib deine Antwort ein — oder Überspringen",send:"Senden",skip:"Überspringen"}},S={en:ui,"zh-CN":mi,ja:fi,ko:pi,es:bi,fr:gi,de:yi};function xi(i){if(S[i])return S[i];const t=i.split("-")[0];return S[t]?S[t]:S.en}const wi=60,ki="https://cdn.jsdelivr.net/npm/@rrweb/record@2.1.0/umd/record.min.js",vi="sha384-MrD66HBNSykaP2N95+6hQCFlF5oH2tvL3TD/zyvHNkP/sAFWZx98DX9MEDy8MdVT";let C=null;function Si(){return C||(C=Ei().catch(()=>Ci()),C)}async function Ei(){return(await import("@rrweb/record")).record}function tt(){const i=globalThis;return i.rrwebRecord?.record??i.rrweb?.record}function Ci(){return new Promise((i,t)=>{const e=tt();if(e){i(e);return}const r=document.createElement("script");r.src=ki,r.integrity=vi,r.crossOrigin="anonymous",r.onload=()=>{const s=tt();s?i(s):t(new Error("rrweb record global not found after script load"))},r.onerror=()=>t(new Error("Failed to load rrweb from CDN")),document.head.appendChild(r)})}class _i{constructor(t,e){this.events=[],this.stopFn=null,this.startedAt=0,this.timer=null,this.clickHandler=null,this.stopped=!1,this.shadow=t,this.onMaxReached=e}async start(){const t=await Si();this.startedAt=Date.now(),this.stopped=!1,this.stopFn=t({emit:e=>{this.stopped||this.events.push(e)}}),this.clickHandler=e=>{this.showClickRipple(e.clientX,e.clientY),t.addCustomEvent?.("mtb-click",{x:e.clientX,y:e.clientY,target:e.target instanceof HTMLElement?e.target.tagName:""})},document.addEventListener("click",this.clickHandler,!0),this.timer=setTimeout(()=>{this.onMaxReached?.()},wi*1e3)}stop(){return this.stopped=!0,this.stopFn?.(),this.stopFn=null,this.cleanupTimer(),this.cleanupClickHandler(),{events:this.events,duration:this.getDuration()}}getDuration(){return this.startedAt===0?0:Math.round((Date.now()-this.startedAt)/1e3)}destroy(){this.stopped=!0,this.stopFn?.(),this.stopFn=null,this.cleanupTimer(),this.cleanupClickHandler(),this.events=[],this.startedAt=0}cleanupTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null)}cleanupClickHandler(){this.clickHandler&&(document.removeEventListener("click",this.clickHandler,!0),this.clickHandler=null)}showClickRipple(t,e){const r=this.shadow.el("div","mtb-click-ripple");r.style.left=`${t}px`,r.style.top=`${e}px`,this.shadow.append(r),r.addEventListener("animationend",()=>r.remove())}}class Mi{constructor(t,e,r,s){this.intervalId=null,this.getDuration=r,this.el=t.el("div","mtb-record-bar"),this.el.innerHTML=`
112
112
  <span class="mtb-record-dot"></span>
113
113
  <span class="mtb-record-timer">00:00</span>
114
114
  <button class="mtb-record-stop" type="button">${e.record.stop}</button>
115
- `,t.append(this.el),this.timerEl=this.el.querySelector(".mtb-record-timer"),this.el.querySelector(".mtb-record-stop").addEventListener("click",s),this.intervalId=setInterval(()=>this.updateTimer(),1e3)}updateTimer(){const t=this.getDuration(),e=String(Math.floor(t/60)).padStart(2,"0"),r=String(t%60).padStart(2,"0");this.timerEl.textContent=`${e}:${r}`}destroy(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.el.remove()}}class Mi{constructor(){this.session=null,this.bar=null,this.result=null}async start(t,e,r){this.session=new _i(t,r),this.bar=new Ti(t,e,()=>this.session?.getDuration()??0,r),await this.session.start()}stop(){return this.session?(this.result=this.session.stop(),this.teardownUI(),this.result):null}getRecording(){return this.result}destroy(){this.teardownUI(),this.result=null}teardownUI(){this.session?.destroy(),this.session=null,this.bar?.destroy(),this.bar=null}}class et{constructor(t){this.tab=null,this.toolbar=null,this.session=null,this.popup=null,this.clarify=null,this.success=null,this.frustrationPrompt=null,this.frustrationDetector=null,this.mode="idle",this.currentAnnotation=null,this.lastPopupPos=null,this.recordingManager=null,this.lastHandoff={},this.config=t,this.messages=xi(t.locale??"en"),this.apiClient=new oi(t.projectKey,t.apiUrl,void 0,t.userToken,t.userTokenFn),this.consoleCollector=new Ve,this.consoleCollector.start(),this.buildUI(),t.frustrationDetection!==!1&&(this.frustrationDetector=new P(()=>this.handleFrustration()),this.frustrationDetector.start())}buildUI(){this.shadow=new _t(this.config.theme??"auto"),this.tab=new Tt(this.shadow,this.messages,this.config.position??"right",()=>this.handleTabClick(),this.config.tabText)}handleTabClick(){this.mode==="idle"?(this.dismissFrustrationPrompt(),this.enterAnnotationMode()):this.exitAll()}handleFrustration(){this.mode!=="idle"||this.frustrationPrompt||(this.frustrationPrompt=new Lt(this.shadow,this.messages,{onTell:()=>{this.dismissFrustrationPrompt(),this.enterAnnotationMode()},onDismiss:()=>this.dismissFrustrationPrompt()}))}dismissFrustrationPrompt(){this.frustrationPrompt?.destroy(),this.frustrationPrompt=null}enterAnnotationMode(){this.mode="annotating",this.tab?.setActive(!0),this.toolbar=new At(this.shadow,this.messages,()=>this.exitAll(),t=>this.handleToolbarModeChange(t)),this.session=new O(this.shadow,this.messages,(t,e)=>{this.currentAnnotation=t,this.showPopup(t.x,t.y,e)})}handleToolbarModeChange(t){t==="record"?(this.mode="recording",this.session?.destroy(),this.session=null,this.recordingManager=new Mi,this.recordingManager.start(this.shadow,this.messages,()=>{this.recordingManager&&(this.recordingManager.stop(),this.showPopup(window.innerWidth/2,window.innerHeight/2,this.messages.record.timer_label))}).catch(e=>{console.warn("[MakeThisBetter] Screen recording unavailable, falling back to markup:",e),this.mode==="recording"&&(this.toolbar?.setMode("markup"),this.handleToolbarModeChange("markup"))})):(this.recordingManager?.destroy(),this.recordingManager=null,this.session||(this.session=new O(this.shadow,this.messages,(e,r)=>{this.currentAnnotation=e,this.showPopup(e.x,e.y,r)})),this.mode="annotating")}showPopup(t,e,r){this.mode="popup",this.lastPopupPos={x:t,y:e},this.session?.dismissInteraction(),this.popup=new Ft(this.shadow,{targetName:r,x:t,y:e,messages:this.messages,onSubmit:s=>this.handleSubmit(s),onClose:()=>this.exitAll(),onMyFeedback:this.buildMyFeedbackHandler()})}buildMyFeedbackHandler(){if(!this.config.user&&hi())return async()=>{const t=await this.apiClient.createIdentityToken(K());!t?.identity_token||!t.board_url||(Q(t.board_url),window.open(`${t.board_url}?identity=${encodeURIComponent(t.identity_token)}`,"_blank"))}}async handleSubmit(t){if(!this.popup)return;this.popup.setLoading(!0);const e=this.currentAnnotation,r=this.recordingManager?.getRecording()??void 0,[s,n]=await Promise.all([je(e?[e]:[]),Promise.resolve(ii())]),o=ci(t,n,this.consoleCollector.getErrors(),e,this.config.user,r,this.config.user?void 0:K(),this.config.user?void 0:J());try{const a=await this.apiClient.submitFeedback(o,s);this.lastHandoff={feedbackId:a.id,boardUrl:a.board_url,identityToken:a.identity_token},a.board_url&&Q(a.board_url),this.popup?.destroy(),this.popup=null,this.session?.destroy(),this.session=null,this.toolbar?.destroy(),this.toolbar=null,this.recordingManager?.destroy(),this.recordingManager=null,a.skip_followup===!0||a.ai_clarify_available===!1?this.showSuccess({skipFollowup:!0}):this.showClarify(a.id,this.lastPopupPos)}catch{this.popup?.setLoading(!1),this.popup?.setError(this.messages.error.submit)}}showClarify(t,e){this.mode="clarifying",this.tab?.setActive(!0),this.clarify=new zt(this.shadow,{feedbackId:t,apiClient:this.apiClient,messages:this.messages,x:e?.x,y:e?.y,onDone:()=>{this.clarify?.destroy(),this.clarify=null,this.showSuccess()}})}showSuccess(t){this.mode="idle",this.tab?.setActive(!1),this.success=new Nt(this.shadow,this.messages,()=>{this.success?.destroy(),this.success=null},this.buildViewFeedbackHandler(),{...t,emailCapture:this.buildEmailCapture()})}buildEmailCapture(){const{feedbackId:t,identityToken:e}=this.lastHandoff;if(!(!t||!e)&&!J())return{onSubmit:async r=>{const s=await this.apiClient.updateReporter(t,r,e);return s&&di(r),s}}}buildViewFeedbackHandler(){const{boardUrl:t,identityToken:e}=this.lastHandoff;if(t){if(e)return()=>{window.open(`${t}?identity=${encodeURIComponent(e)}`,"_blank")};if(this.config.userToken||this.config.userTokenFn)return async()=>{const r=await this.apiClient.resolveUserToken();r&&window.open(`${t}?identity=${encodeURIComponent(r)}`,"_blank")}}}exitAll(){this.mode="idle",this.tab?.setActive(!1),this.toolbar?.destroy(),this.toolbar=null,this.session?.destroy(),this.session=null,this.popup?.destroy(),this.popup=null,this.clarify?.destroy(),this.clarify=null,this.currentAnnotation=null,this.recordingManager?.destroy(),this.recordingManager=null}destroy(){this.exitAll(),this.consoleCollector.stop(),this.frustrationDetector?.stop(),this.dismissFrustrationPrompt(),this.clarify?.destroy(),this.success?.destroy(),this.tab?.destroy(),this.recordingManager?.destroy(),this.shadow.destroy()}}let g=null;const gt={init(i){g&&(g.destroy(),g=null),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{g=new et(i)}):g=new et(i)},destroy(){g?.destroy(),g=null}};typeof window<"u"&&(window.MakeThisBetter=gt);exports.MakeThisBetter=gt;
115
+ `,t.append(this.el),this.timerEl=this.el.querySelector(".mtb-record-timer"),this.el.querySelector(".mtb-record-stop").addEventListener("click",s),this.intervalId=setInterval(()=>this.updateTimer(),1e3)}updateTimer(){const t=this.getDuration(),e=String(Math.floor(t/60)).padStart(2,"0"),r=String(t%60).padStart(2,"0");this.timerEl.textContent=`${e}:${r}`}destroy(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.el.remove()}}class Ti{constructor(){this.session=null,this.bar=null,this.result=null}async start(t,e,r){this.session=new _i(t,r),this.bar=new Mi(t,e,()=>this.session?.getDuration()??0,r),await this.session.start()}stop(){return this.session?(this.result=this.session.stop(),this.teardownUI(),this.result):null}getRecording(){return this.result}destroy(){this.teardownUI(),this.result=null}teardownUI(){this.session?.destroy(),this.session=null,this.bar?.destroy(),this.bar=null}}class et{constructor(t){this.tab=null,this.toolbar=null,this.session=null,this.popup=null,this.clarify=null,this.success=null,this.frustrationPrompt=null,this.frustrationDetector=null,this.mode="idle",this.currentAnnotation=null,this.lastPopupPos=null,this.recordingManager=null,this.lastHandoff={},this.config=t,this.messages=xi(t.locale??"en"),this.apiClient=new oi(t.projectKey,t.apiUrl,void 0,t.userToken,t.userTokenFn),this.consoleCollector=new Ve,this.consoleCollector.start(),this.buildUI(),t.frustrationDetection!==!1&&(this.frustrationDetector=new R(()=>this.handleFrustration()),this.frustrationDetector.start())}buildUI(){this.shadow=new _t(this.config.theme??"auto"),this.tab=new Mt(this.shadow,this.messages,this.config.position??"right",()=>this.handleTabClick(),this.config.tabText)}handleTabClick(){this.mode==="idle"?(this.dismissFrustrationPrompt(),this.enterAnnotationMode()):this.exitAll()}handleFrustration(){this.mode!=="idle"||this.frustrationPrompt||(this.frustrationPrompt=new Lt(this.shadow,this.messages,{onTell:()=>{this.dismissFrustrationPrompt(),this.enterAnnotationMode()},onDismiss:()=>this.dismissFrustrationPrompt()}))}dismissFrustrationPrompt(){this.frustrationPrompt?.destroy(),this.frustrationPrompt=null}enterAnnotationMode(){this.mode="annotating",this.tab?.setActive(!0),this.toolbar=new At(this.shadow,this.messages,()=>this.exitAll(),t=>this.handleToolbarModeChange(t)),this.session=new O(this.shadow,this.messages,(t,e)=>{this.currentAnnotation=t,this.showPopup(t.x,t.y,e)})}handleToolbarModeChange(t){t==="record"?(this.mode="recording",this.session?.destroy(),this.session=null,this.recordingManager=new Ti,this.recordingManager.start(this.shadow,this.messages,()=>{this.recordingManager&&(this.recordingManager.stop(),this.showPopup(window.innerWidth/2,window.innerHeight/2,this.messages.record.timer_label))}).catch(e=>{console.warn("[MakeThisBetter] Screen recording unavailable, falling back to markup:",e),this.mode==="recording"&&(this.toolbar?.setMode("markup"),this.handleToolbarModeChange("markup"))})):(this.recordingManager?.destroy(),this.recordingManager=null,this.session||(this.session=new O(this.shadow,this.messages,(e,r)=>{this.currentAnnotation=e,this.showPopup(e.x,e.y,r)})),this.mode="annotating")}showPopup(t,e,r){this.mode="popup",this.lastPopupPos={x:t,y:e},this.session?.dismissInteraction(),this.popup=new Ft(this.shadow,{targetName:r,x:t,y:e,messages:this.messages,onSubmit:s=>this.handleSubmit(s),onClose:()=>this.exitAll(),onMyFeedback:this.buildMyFeedbackHandler()})}buildMyFeedbackHandler(){if(!this.config.user&&hi())return async()=>{const t=await this.apiClient.createIdentityToken(K());!t?.identity_token||!t.board_url||(Q(t.board_url),window.open(`${t.board_url}?identity=${encodeURIComponent(t.identity_token)}`,"_blank"))}}async handleSubmit(t){if(!this.popup)return;this.popup.setLoading(!0),await new Promise(a=>requestAnimationFrame(()=>setTimeout(a,0)));const e=this.currentAnnotation,r=this.recordingManager?.getRecording()??void 0,[s,n]=await Promise.all([je(e?[e]:[]),Promise.resolve(ii())]),o=ci(t,n,this.consoleCollector.getErrors(),e,this.config.user,r,this.config.user?void 0:K(),this.config.user?void 0:J());try{const a=await this.apiClient.submitFeedback(o,s);this.lastHandoff={feedbackId:a.id,boardUrl:a.board_url,identityToken:a.identity_token},a.board_url&&Q(a.board_url),this.popup?.destroy(),this.popup=null,this.session?.destroy(),this.session=null,this.toolbar?.destroy(),this.toolbar=null,this.recordingManager?.destroy(),this.recordingManager=null,a.skip_followup===!0||a.ai_clarify_available===!1?this.showSuccess({skipFollowup:!0}):this.showClarify(a.id,this.lastPopupPos)}catch{this.popup?.setLoading(!1),this.popup?.setError(this.messages.error.submit)}}showClarify(t,e){this.mode="clarifying",this.tab?.setActive(!0),this.clarify=new zt(this.shadow,{feedbackId:t,apiClient:this.apiClient,messages:this.messages,x:e?.x,y:e?.y,onDone:()=>{this.clarify?.destroy(),this.clarify=null,this.showSuccess()}})}showSuccess(t){this.mode="idle",this.tab?.setActive(!1),this.success=new Nt(this.shadow,this.messages,()=>{this.success?.destroy(),this.success=null},this.buildViewFeedbackHandler(),{...t,emailCapture:this.buildEmailCapture()})}buildEmailCapture(){const{feedbackId:t,identityToken:e}=this.lastHandoff;if(!(!t||!e)&&!J())return{onSubmit:async r=>{const s=await this.apiClient.updateReporter(t,r,e);return s&&di(r),s}}}buildViewFeedbackHandler(){const{boardUrl:t,identityToken:e}=this.lastHandoff;if(t){if(e)return()=>{window.open(`${t}?identity=${encodeURIComponent(e)}`,"_blank")};if(this.config.userToken||this.config.userTokenFn)return async()=>{const r=await this.apiClient.resolveUserToken();r&&window.open(`${t}?identity=${encodeURIComponent(r)}`,"_blank")}}}exitAll(){this.mode="idle",this.tab?.setActive(!1),this.toolbar?.destroy(),this.toolbar=null,this.session?.destroy(),this.session=null,this.popup?.destroy(),this.popup=null,this.clarify?.destroy(),this.clarify=null,this.currentAnnotation=null,this.recordingManager?.destroy(),this.recordingManager=null}destroy(){this.exitAll(),this.consoleCollector.stop(),this.frustrationDetector?.stop(),this.dismissFrustrationPrompt(),this.clarify?.destroy(),this.success?.destroy(),this.tab?.destroy(),this.recordingManager?.destroy(),this.shadow.destroy()}}let g=null;const gt={init(i){g&&(g.destroy(),g=null),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{g=new et(i)}):g=new et(i)},destroy(){g?.destroy(),g=null}};typeof window<"u"&&(window.MakeThisBetter=gt);exports.MakeThisBetter=gt;
116
116
  //# sourceMappingURL=makethisbetter.cjs.map