makethisbetter 1.28.0 → 1.28.2

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.
Files changed (47) hide show
  1. package/dist/i18n/de.d.ts +2 -0
  2. package/dist/i18n/de.d.ts.map +1 -1
  3. package/dist/i18n/en.d.ts +2 -0
  4. package/dist/i18n/en.d.ts.map +1 -1
  5. package/dist/i18n/es.d.ts +2 -0
  6. package/dist/i18n/es.d.ts.map +1 -1
  7. package/dist/i18n/fr.d.ts +2 -0
  8. package/dist/i18n/fr.d.ts.map +1 -1
  9. package/dist/i18n/ja.d.ts +2 -0
  10. package/dist/i18n/ja.d.ts.map +1 -1
  11. package/dist/i18n/ko.d.ts +2 -0
  12. package/dist/i18n/ko.d.ts.map +1 -1
  13. package/dist/i18n/zh-CN.d.ts +2 -0
  14. package/dist/i18n/zh-CN.d.ts.map +1 -1
  15. package/dist/makethisbetter.cjs +16 -27
  16. package/dist/makethisbetter.cjs.map +1 -1
  17. package/dist/makethisbetter.esm.js +380 -388
  18. package/dist/makethisbetter.esm.js.map +1 -1
  19. package/dist/makethisbetter.js +24 -35
  20. package/dist/makethisbetter.js.map +1 -1
  21. package/dist/makethisbetter.standalone.js +1206 -1214
  22. package/dist/makethisbetter.standalone.js.map +1 -1
  23. package/dist/popup/chat-popup.d.ts +6 -2
  24. package/dist/popup/chat-popup.d.ts.map +1 -1
  25. package/dist/widget/controller.d.ts.map +1 -1
  26. package/dist/widget/submission-lifecycle.d.ts +3 -5
  27. package/dist/widget/submission-lifecycle.d.ts.map +1 -1
  28. package/dist/widget/tab.d.ts +1 -0
  29. package/dist/widget/tab.d.ts.map +1 -1
  30. package/package.json +1 -1
  31. package/src/i18n/de.ts +2 -0
  32. package/src/i18n/en.ts +2 -0
  33. package/src/i18n/es.ts +2 -0
  34. package/src/i18n/fr.ts +2 -0
  35. package/src/i18n/ja.ts +2 -0
  36. package/src/i18n/ko.ts +2 -0
  37. package/src/i18n/zh-CN.ts +2 -0
  38. package/src/popup/chat-popup.ts +59 -18
  39. package/src/styles/widget.css +76 -64
  40. package/src/widget/controller.ts +12 -14
  41. package/src/widget/submission-lifecycle.ts +6 -22
  42. package/src/widget/tab.ts +6 -0
  43. package/dist/popup/failure.d.ts +0 -12
  44. package/dist/popup/failure.d.ts.map +0 -1
  45. package/dist/screenshot/html-to-image-fallback.test.d.ts +0 -2
  46. package/dist/screenshot/html-to-image-fallback.test.d.ts.map +0 -1
  47. package/src/popup/failure.ts +0 -57
@@ -1,11 +1,11 @@
1
- var MakeThisBetter=function(){"use strict";const Qe=`*,*: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{--mtb-brand-primary: #059669;--mtb-brand-hover: #047857;--mtb-brand-active: #065f46;--mtb-brand-on-primary: #fff;--mtb-brand-rgb: 5, 150, 105;--mtb-brand-on-primary-rgb: 255, 255, 255;--mtb-brand-emphasis: #10b981;--mtb-brand-emphasis-rgb: 16, 185, 129;--mtb-brand-gradient-start: #10b981;--mtb-brand-gradient-end: #059669;--mtb-panel-bg: #fff;--mtb-panel-border: rgba(0, 0, 0, .1);--mtb-panel-divider: rgba(0, 0, 0, .06);--mtb-fg: #191a1c;--mtb-field-bg: #fff;--mtb-field-bg-subtle: #fafafa;--mtb-field-border: rgba(0, 0, 0, .12);--mtb-field-border-soft: rgba(0, 0, 0, .09);--mtb-placeholder-fg: rgba(0, 0, 0, .34);--mtb-action-bg: #fff;--mtb-action-border: rgba(0, 0, 0, .12);--mtb-action-fg: rgba(0, 0, 0, .55);--mtb-action-hover-bg: rgba(0, 0, 0, .04);--mtb-clarify-close-fg: rgba(0, 0, 0, .38);--mtb-clarify-close-hover-fg: rgba(0, 0, 0, .7);--mtb-dismiss-fg: rgba(0, 0, 0, .4);--mtb-dismiss-hover-fg: rgba(0, 0, 0, .7);--mtb-quick-hover-bg: rgba(var(--mtb-brand-emphasis-rgb), .06);--mtb-quick-hover-border: rgba(var(--mtb-brand-emphasis-rgb), .3);--mtb-quick-selected-bg: rgba(var(--mtb-brand-emphasis-rgb), .1);--mtb-quick-selected-border: rgba(var(--mtb-brand-emphasis-rgb), .5);--mtb-field-focus-border: var(--mtb-brand-emphasis);--mtb-chat-card-bg: #FFFFFF;--mtb-chat-card-shadow: 0 24px 64px rgba(0, 0, 0, .18);--mtb-chat-raised-bg: #F9FAFB;--mtb-chat-write-bg: #FFFFFF;--mtb-chat-title-fg: #111827;--mtb-chat-body-fg: #1f2937;--mtb-chat-muted-fg: #6b7280;--mtb-chat-placeholder-fg: #9ca3af;--mtb-chat-pill-fg: #374151;--mtb-chat-pill-shadow: 0 1px 3px rgba(0, 0, 0, .08), 0 0 0 1px rgba(0, 0, 0, .04);--mtb-chat-pill-hover-shadow: 0 3px 10px rgba(0, 0, 0, .12), 0 0 0 1px rgba(0, 0, 0, .05);--mtb-chat-close-hover-bg: #F3F4F6;--mtb-chat-close-hover-fg: #111827;--mtb-chat-composer-shadow: 0 -1px 6px rgba(0, 0, 0, .06);--mtb-chat-skip-fg: #9ca3af;--mtb-chat-skip-hover-fg: #4b5563;--mtb-chat-camera-lens: #fff;--mtb-chat-accent: var(--mtb-brand-primary);--mtb-chat-accent-fg: var(--mtb-brand-on-primary);--mtb-chat-accent-rgb: var(--mtb-brand-rgb);--mtb-chat-accent-fg-rgb: var(--mtb-brand-on-primary-rgb);--mtb-chat-link-fg: var(--mtb-brand-primary);--mtb-chat-send-shadow: 0 2px 8px rgba(var(--mtb-chat-accent-rgb), .35);--mtb-chat-success-icon-shadow: 0 4px 14px rgba(var(--mtb-chat-accent-rgb), .35);--mtb-chat-logo-start: #10b981;--mtb-chat-logo-end: #059669;--mtb-chat-logo-fg: #fff}:host([data-mtb-theme="dark"]){--mtb-panel-bg: #151719;--mtb-panel-border: rgba(255, 255, 255, .12);--mtb-panel-divider: rgba(255, 255, 255, .1);--mtb-fg: #f9fafb;--mtb-field-bg: #1f2327;--mtb-field-bg-subtle: #1f2327;--mtb-field-border: rgba(255, 255, 255, .12);--mtb-field-border-soft: rgba(255, 255, 255, .12);--mtb-placeholder-fg: rgba(255, 255, 255, .4);--mtb-action-bg: #1f2327;--mtb-action-border: rgba(255, 255, 255, .14);--mtb-action-fg: rgba(255, 255, 255, .7);--mtb-action-hover-bg: rgba(255, 255, 255, .06);--mtb-clarify-close-fg: rgba(255, 255, 255, .45);--mtb-clarify-close-hover-fg: rgba(255, 255, 255, .75);--mtb-dismiss-fg: rgba(255, 255, 255, .4);--mtb-dismiss-hover-fg: rgba(255, 255, 255, .7);--mtb-quick-hover-bg: rgba(var(--mtb-brand-emphasis-rgb), .12);--mtb-quick-hover-border: rgba(var(--mtb-brand-emphasis-rgb), .45);--mtb-quick-selected-bg: rgba(var(--mtb-brand-emphasis-rgb), .18);--mtb-quick-selected-border: var(--mtb-brand-primary);--mtb-field-focus-border: var(--mtb-brand-emphasis);--mtb-chat-card-bg: #17191C;--mtb-chat-card-shadow: 0 24px 64px rgba(0, 0, 0, .55);--mtb-chat-raised-bg: #202327;--mtb-chat-write-bg: #23272C;--mtb-chat-title-fg: #E8EAED;--mtb-chat-body-fg: #DCE0E4;--mtb-chat-muted-fg: #B0B6BD;--mtb-chat-placeholder-fg: #A3AAB2;--mtb-chat-pill-fg: #DDE1E5;--mtb-chat-pill-shadow: 0 1px 3px rgba(0, 0, 0, .5), 0 0 0 1px rgba(255, 255, 255, .08);--mtb-chat-pill-hover-shadow: 0 4px 14px rgba(0, 0, 0, .6), 0 0 0 1px rgba(255, 255, 255, .14);--mtb-chat-close-hover-bg: rgba(255, 255, 255, .08);--mtb-chat-close-hover-fg: #FFFFFF;--mtb-chat-composer-shadow: 0 -1px 6px rgba(0, 0, 0, .45);--mtb-chat-skip-fg: #A3AAB2;--mtb-chat-skip-hover-fg: #E8EAED;--mtb-chat-camera-lens: #EAF7EE;--mtb-chat-accent: #4ADE80;--mtb-chat-accent-fg: #0D1210;--mtb-chat-accent-rgb: 74, 222, 128;--mtb-chat-accent-fg-rgb: 13, 18, 16;--mtb-chat-link-fg: #5BD98A;--mtb-chat-send-shadow: 0 1px 3px rgba(0, 0, 0, .5);--mtb-chat-success-icon-shadow: 0 2px 10px rgba(0, 0, 0, .5);--mtb-chat-logo-start: #1E9E4A;--mtb-chat-logo-end: #0B8AA0;--mtb-chat-logo-fg: #EAF7EE}@media (prefers-color-scheme: dark){:host([data-mtb-theme="auto"]){--mtb-panel-bg: #151719;--mtb-panel-border: rgba(255, 255, 255, .12);--mtb-panel-divider: rgba(255, 255, 255, .1);--mtb-fg: #f9fafb;--mtb-field-bg: #1f2327;--mtb-field-bg-subtle: #1f2327;--mtb-field-border: rgba(255, 255, 255, .12);--mtb-field-border-soft: rgba(255, 255, 255, .12);--mtb-placeholder-fg: rgba(255, 255, 255, .4);--mtb-action-bg: #1f2327;--mtb-action-border: rgba(255, 255, 255, .14);--mtb-action-fg: rgba(255, 255, 255, .7);--mtb-action-hover-bg: rgba(255, 255, 255, .06);--mtb-clarify-close-fg: rgba(255, 255, 255, .45);--mtb-clarify-close-hover-fg: rgba(255, 255, 255, .75);--mtb-dismiss-fg: rgba(255, 255, 255, .4);--mtb-dismiss-hover-fg: rgba(255, 255, 255, .7);--mtb-quick-hover-bg: rgba(var(--mtb-brand-emphasis-rgb), .12);--mtb-quick-hover-border: rgba(var(--mtb-brand-emphasis-rgb), .45);--mtb-quick-selected-bg: rgba(var(--mtb-brand-emphasis-rgb), .18);--mtb-quick-selected-border: var(--mtb-brand-primary);--mtb-field-focus-border: var(--mtb-brand-emphasis);--mtb-chat-card-bg: #17191C;--mtb-chat-card-shadow: 0 24px 64px rgba(0, 0, 0, .55);--mtb-chat-raised-bg: #202327;--mtb-chat-write-bg: #23272C;--mtb-chat-title-fg: #E8EAED;--mtb-chat-body-fg: #DCE0E4;--mtb-chat-muted-fg: #B0B6BD;--mtb-chat-placeholder-fg: #A3AAB2;--mtb-chat-pill-fg: #DDE1E5;--mtb-chat-pill-shadow: 0 1px 3px rgba(0, 0, 0, .5), 0 0 0 1px rgba(255, 255, 255, .08);--mtb-chat-pill-hover-shadow: 0 4px 14px rgba(0, 0, 0, .6), 0 0 0 1px rgba(255, 255, 255, .14);--mtb-chat-close-hover-bg: rgba(255, 255, 255, .08);--mtb-chat-close-hover-fg: #FFFFFF;--mtb-chat-composer-shadow: 0 -1px 6px rgba(0, 0, 0, .45);--mtb-chat-skip-fg: #A3AAB2;--mtb-chat-skip-hover-fg: #E8EAED;--mtb-chat-camera-lens: #EAF7EE;--mtb-chat-accent: #4ADE80;--mtb-chat-accent-fg: #0D1210;--mtb-chat-accent-rgb: 74, 222, 128;--mtb-chat-accent-fg-rgb: 13, 18, 16;--mtb-chat-link-fg: #5BD98A;--mtb-chat-send-shadow: 0 1px 3px rgba(0, 0, 0, .5);--mtb-chat-success-icon-shadow: 0 2px 10px rgba(0, 0, 0, .5);--mtb-chat-logo-start: #1E9E4A;--mtb-chat-logo-end: #0B8AA0;--mtb-chat-logo-fg: #EAF7EE}}.mtb-tab{--mtb-tab-icon: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2' stroke-linecap='round'%3E%3Ccircle cx='12' cy='12' r='8'/%3E%3Ccircle cx='12' cy='12' r='2.4' fill='%23000' stroke='none'/%3E%3Cpath d='M12 1.8v3.4M12 18.8v3.4M1.8 12h3.4M18.8 12h3.4'/%3E%3C/svg%3E");--mtb-tab-bg: var(--mtb-brand-primary);--mtb-tab-hover-bg: var(--mtb-brand-hover);--mtb-tab-active-bg: var(--mtb-brand-active);--mtb-tab-shadow-color: var(--mtb-brand-rgb);--mtb-tab-fg: var(--mtb-brand-on-primary);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:var(--mtb-tab-bg);color:var(--mtb-tab-fg);border-radius:8px 0 0 8px;cursor:pointer;box-shadow:-2px 0 14px rgba(var(--mtb-tab-shadow-color),.35);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 rgba(var(--mtb-tab-shadow-color),.35)}.mtb-tab:hover{background:var(--mtb-tab-hover-bg);box-shadow:-3px 0 20px rgba(var(--mtb-tab-shadow-color),.45)}.mtb-tab.active{background:var(--mtb-tab-active-bg)}.mtb-hint-bar{position:fixed;top:18px;left:50%;transform:translate(-50%);z-index:2147483647;display:flex;align-items:center;height:38px;padding:0 16px;border-radius:13px;background:linear-gradient(120deg,var(--mtb-brand-gradient-start),var(--mtb-brand-gradient-end));color:var(--mtb-brand-on-primary);box-shadow:0 10px 26px #0f172a38;animation:mtbHintIn .2s ease;white-space:nowrap;transition:opacity .15s ease;pointer-events:none}.mtb-hint-bar--under-pointer{opacity:.3}.mtb-hint-bar.mtb-hint-bar--dismissed{display:none}@keyframes mtbHintIn{0%{transform:translate(-50%,12px);opacity:0}to{transform:translate(-50%);opacity:1}}.mtb-toolbar{position:fixed;top:50%;right:8px;transform:translateY(-50%);z-index:2147483647;display:flex;flex-direction:column;align-items:center;gap:6px;width:38px;padding:6px 0;max-height:calc(100vh - 24px);border-radius:19px;background:linear-gradient(160deg,var(--mtb-brand-gradient-start),var(--mtb-brand-gradient-end));color:var(--mtb-brand-on-primary);box-shadow:0 8px 22px #0f172a33;animation:mtbEdgeBarIn .2s ease;white-space:nowrap;pointer-events:none}.mtb-toolbar.left{right:auto;left:8px;animation:mtbEdgeBarInLeft .2s ease}@keyframes mtbBarIn{0%{transform:translate(-50%,12px);opacity:0}to{transform:translate(-50%);opacity:1}}@keyframes mtbEdgeBarIn{0%{transform:translate(12px,-50%);opacity:0}to{transform:translateY(-50%);opacity:1}}@keyframes mtbEdgeBarInLeft{0%{transform:translate(-12px,-50%);opacity:0}to{transform:translateY(-50%);opacity:1}}.mtb-toolbar-label{display:none}:host([data-mtb-toolbar]) .mtb-tab{display:none}.mtb-toolbar-modes{display:flex;align-items:center;gap:3px;background:rgba(var(--mtb-brand-on-primary-rgb),.16);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:var(--mtb-brand-on-primary);transition:all .12s}.mtb-toolbar-mode-btn.active{background:#fff;color:var(--mtb-brand-active)}.mtb-toolbar-hint{font-size:12px;color:var(--mtb-brand-on-primary);white-space:nowrap}.mtb-toolbar-sep{width:20px;height:1px;align-self:center;background:rgba(var(--mtb-brand-on-primary-rgb),.22)}.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:var(--mtb-brand-on-primary);cursor:pointer;background:rgba(var(--mtb-brand-on-primary-rgb),.16);border:none;font-family:inherit;transition:background .12s}.mtb-toolbar-modes{flex-direction:column;gap:6px;padding:0;background:none;border-radius:0}.mtb-toolbar-mode-btn,.mtb-exit-btn{pointer-events:auto;display:flex;align-items:center;justify-content:center;gap:0;width:30px;height:30px;padding:0;border-radius:50%;background:none;color:var(--mtb-brand-on-primary)}.mtb-toolbar-mode-btn{opacity:.72}.mtb-exit-btn{opacity:1}.mtb-toolbar-mode-btn:hover,.mtb-exit-btn:hover{background:rgba(var(--mtb-brand-on-primary-rgb),.16);color:var(--mtb-brand-on-primary);opacity:1}.mtb-toolbar-mode-btn.active,.mtb-toolbar-mode-btn.active:hover{background:var(--mtb-brand-on-primary);color:var(--mtb-brand-hover);opacity:1}.mtb-exit-btn{color:var(--mtb-brand-on-primary)}.mtb-toolbar-sep{width:16px;height:1px;margin:1px 0;align-self:center;background:rgba(var(--mtb-brand-on-primary-rgb),.28)}.mtb-exit-btn:hover{background:rgba(var(--mtb-brand-on-primary-rgb),.28)}.mtb-overlay{position:fixed;inset:0;z-index:2147483640;cursor:crosshair;touch-action:none}.mtb-dim{position:fixed;inset:0;z-index:2147483639;background:#00000014}.mtb-highlight{position:fixed;z-index:2147483641;pointer-events:none;border:2px solid var(--mtb-brand-emphasis);border-radius:6px;background:rgba(var(--mtb-brand-emphasis-rgb),.06);transition:all .08s ease}.mtb-highlight-tooltip{position:fixed;z-index:2147483642;pointer-events:none;transform:translate(-50%,-100%);max-width:240px;overflow:hidden;text-overflow:ellipsis;background:var(--mtb-brand-active);color:var(--mtb-brand-on-primary);padding:4px 10px;border-radius:6px;font-size:11px;font-weight:500;white-space:nowrap;box-shadow:0 4px 12px #0000002e;font-family:Inter,-apple-system,BlinkMacSystemFont,sans-serif}.mtb-highlight-tooltip.below{transform:translate(-50%)}.mtb-highlight-tooltip:after{content:"";position:absolute;top:100%;left:50%;transform:translate(-50%);border:4px solid transparent;border-top-color:var(--mtb-brand-active)}.mtb-highlight-tooltip.below:after{top:auto;bottom:100%;border-top-color:transparent;border-bottom-color:var(--mtb-brand-active)}.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:var(--mtb-brand-primary);border:2px solid #fff;display:flex;align-items:center;justify-content:center;font-size:10px;color:var(--mtb-brand-on-primary);font-weight:700;box-shadow:0 0 0 1px #0f172aad,0 2px 8px rgba(var(--mtb-brand-rgb),.45);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)}}@keyframes mtbSlideUp{0%{transform:translateY(14px) scale(.97);opacity:0}to{transform:translateY(0) scale(1);opacity:1}}.mtb-draw-shot input:disabled{appearance:none;-webkit-appearance:none;border:none;border-radius:4px;background-color:var(--mtb-placeholder-fg);background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath fill='none' stroke='%23fff' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round' d='M3.5 8.5l3 3 6-6'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:center;background-size:contain;opacity:1}.mtb-draw-shot input:disabled{background-color:#0000004d}.mtb-btn-loading{pointer-events:none;opacity:.8}.mtb-btn-loading:after{content:"";display:inline-block;width:10px;height:10px;margin-left:6px;border:1.5px solid rgba(255,255,255,.35);border-top-color:#fff;border-radius:50%;animation:mtbSpin .7s linear infinite;vertical-align:middle}.mtb-chat{position:fixed;z-index:2147483645;display:flex;flex-direction:column;width:min(320px,calc(100vw - 56px));max-height:420px;background:var(--mtb-chat-card-bg);border-radius:16px;color:var(--mtb-chat-title-fg);box-shadow:var(--mtb-chat-card-shadow);overflow:hidden;animation:mtbSlideUp .28s cubic-bezier(.34,1.56,.64,1);font-family:Inter,-apple-system,BlinkMacSystemFont,sans-serif}.mtb-chat.mtb-chat-receipt{inset:auto 20px 20px auto;width:min(320px,calc(100vw - 40px));animation:none}.mtb-chat-header{display:flex;align-items:center;gap:7px;padding:11px 12px;background:var(--mtb-chat-raised-bg);flex-shrink:0}.mtb-chat-brand{display:flex;align-items:center;gap:7px;text-decoration:none;opacity:.9;transition:opacity .16s}.mtb-chat-brand:hover{opacity:1}.mtb-chat-brand:hover .mtb-chat-brand-name{text-decoration:underline;text-underline-offset:2px}.mtb-chat-logo{width:20px;height:20px;border-radius:6px;overflow:hidden;flex:none}.mtb-chat-logo svg{width:100%;height:100%;display:block}.mtb-chat-brand-name{font-size:12px;font-weight:600;color:var(--mtb-chat-title-fg)}.mtb-chat-header-row{display:flex;align-items:center;gap:7px;width:100%}.mtb-chat-header-gap{flex:1}.mtb-chat-close{width:28px;height:28px;border-radius:99px;display:flex;align-items:center;justify-content:center;background:none;border:none;padding:0;color:var(--mtb-chat-muted-fg);cursor:pointer;flex:none;transition:background .16s,color .16s}.mtb-chat-close:hover{background:var(--mtb-chat-close-hover-bg);color:var(--mtb-chat-close-hover-fg)}.mtb-chat-messages{flex:1;overflow-y:auto;padding:12px;display:flex;flex-direction:column;gap:8px;min-height:0;background:var(--mtb-chat-card-bg)}.mtb-chat-messages:empty{display:none}.mtb-chat-bubble{font-size:13px;max-width:85%;word-break:break-word}.mtb-chat-bubble-user{align-self:flex-end;background:var(--mtb-chat-accent);color:var(--mtb-chat-accent-fg);line-height:1.45;padding:8px 11px;border-radius:12px 12px 4px}.mtb-chat-bubble-ai{background:var(--mtb-chat-raised-bg);color:var(--mtb-chat-body-fg);line-height:1.5;padding:9px 12px;border-radius:12px 12px 12px 4px}.mtb-chat-ai-row{display:flex;align-items:flex-end;gap:7px}.mtb-chat-avatar{width:22px;height:22px;border-radius:7px;overflow:hidden;flex:none}.mtb-chat-avatar svg{width:100%;height:100%;display:block}.mtb-chat-dots{display:flex;align-items:center;gap:4px;padding:10px 12px;background:var(--mtb-chat-raised-bg);border-radius:12px 12px 12px 4px}.mtb-chat-dots span{width:5px;height:5px;background:var(--mtb-chat-accent);border-radius:99px;animation:mtbChatDot 1.1s infinite}.mtb-chat-dots span:nth-child(2){animation-delay:.15s}.mtb-chat-dots span:nth-child(3){animation-delay:.3s}@keyframes mtbChatDot{0%,60%,to{transform:translateY(0);opacity:.45}30%{transform:translateY(-4px);opacity:1}}.mtb-chat-suggestions{display:flex;flex-wrap:wrap;gap:6px;padding-left:29px}.mtb-chat-sg{background:var(--mtb-chat-write-bg);border:none;border-radius:99px;padding:5px 10px;font-size:11px;font-weight:500;font-family:inherit;color:var(--mtb-chat-pill-fg);cursor:pointer;box-shadow:var(--mtb-chat-pill-shadow);transition:box-shadow .16s,transform .16s}.mtb-chat-sg:hover{box-shadow:var(--mtb-chat-pill-hover-shadow);transform:translateY(-1px)}.mtb-chat-quick-replies{display:flex;flex-wrap:wrap;gap:6px;padding:12px;background:var(--mtb-chat-card-bg)}.mtb-chat-qr{display:flex;align-items:center;gap:5px;background:var(--mtb-chat-write-bg);border:none;border-radius:99px;padding:7px 12px;font-size:12px;font-weight:500;font-family:inherit;color:var(--mtb-chat-pill-fg);cursor:pointer;box-shadow:var(--mtb-chat-pill-shadow);transition:box-shadow .16s,transform .16s}.mtb-chat-qr:hover{box-shadow:var(--mtb-chat-pill-hover-shadow);transform:translateY(-1px)}.mtb-chat-qr:disabled{opacity:.5;pointer-events:none;cursor:default;transform:none!important;box-shadow:var(--mtb-chat-pill-shadow)!important}.mtb-chat-composer{display:flex;flex-direction:column;gap:8px;padding:10px;background:var(--mtb-chat-raised-bg);box-shadow:var(--mtb-chat-composer-shadow);flex-shrink:0}.mtb-chat-composer-disabled{pointer-events:none}.mtb-chat-composer-disabled .mtb-chat-input{opacity:.3}.mtb-chat-input{box-sizing:border-box;width:100%;min-height:64px;max-height:132px;padding:10px 12px;background:var(--mtb-chat-write-bg);border:none;border-radius:10px;font-size:13px;line-height:1.5;font-family:inherit;color:var(--mtb-chat-title-fg);outline:none;resize:none}.mtb-chat-input::placeholder{color:var(--mtb-chat-placeholder-fg)}.mtb-chat-input:disabled{opacity:.5;cursor:default}.mtb-chat-actions{display:flex;align-items:center;gap:10px}.mtb-chat-actions-gap{flex:1}.mtb-chat-screenshot,.mtb-chat-attachment{display:flex;align-items:center;gap:6px;background:none;border:none;padding:0;font-family:inherit;color:var(--mtb-chat-accent);cursor:pointer;transition:opacity .16s}.mtb-chat-screenshot svg,.mtb-chat-attachment svg{display:flex;flex:none}.mtb-chat-icon-lens{fill:var(--mtb-chat-camera-lens)}.mtb-chat-screenshot:hover{opacity:.75}.mtb-chat-attachment{cursor:default}.mtb-chat-capture-label{font-size:11px;color:var(--mtb-chat-muted-fg)}.mtb-chat-screenshot[aria-pressed=false],.mtb-chat-screenshot-off{opacity:.4;color:var(--mtb-chat-muted-fg)}.mtb-chat-screenshot:disabled{opacity:.3;pointer-events:none;cursor:default}.mtb-chat-skip{height:26px;border:none;border-radius:6px;background:none;display:flex;align-items:center;padding:0 4px;font-size:11px;font-weight:500;font-family:inherit;color:var(--mtb-chat-skip-fg);cursor:pointer;flex:none;transition:color .16s}.mtb-chat-skip:hover{color:var(--mtb-chat-skip-hover-fg)}.mtb-chat-send{position:relative;height:34px;padding:0 14px;border:none;border-radius:10px;background:var(--mtb-chat-accent);font-size:12px;font-weight:600;font-family:inherit;color:var(--mtb-chat-accent-fg);display:flex;align-items:center;justify-content:center;flex:none;cursor:pointer;box-shadow:var(--mtb-chat-send-shadow)}.mtb-chat-send:disabled{opacity:.3;box-shadow:none;cursor:default}.mtb-chat-error-row{display:flex;align-items:center;justify-content:center;gap:8px;padding:4px 0}.mtb-chat-error-text{font-size:11px;color:var(--mtb-danger, #ef4444)}.mtb-chat-error-retry{font-size:11px;font-weight:600;font-family:inherit;color:var(--mtb-chat-pill-fg);background:var(--mtb-chat-write-bg);border:none;border-radius:999px;padding:4px 11px;box-shadow:var(--mtb-chat-pill-shadow);cursor:pointer}.mtb-chat-error-retry:hover{box-shadow:var(--mtb-chat-pill-hover-shadow)}.mtb-chat-success{padding:30px 20px 26px;display:flex;flex-direction:column;align-items:center;gap:10px;background:var(--mtb-chat-card-bg);animation:mtbSlideUp .28s cubic-bezier(.34,1.56,.64,1) both}.mtb-chat-success-simple{padding-top:34px;padding-bottom:22px}.mtb-chat-success-icon{width:40px;height:40px;border-radius:99px;background:var(--mtb-chat-accent);color:var(--mtb-chat-accent-fg);display:flex;align-items:center;justify-content:center;box-shadow:var(--mtb-chat-success-icon-shadow)}.mtb-chat-success-title{font-size:15px;font-weight:600;color:var(--mtb-chat-title-fg);margin-top:2px;text-align:center}.mtb-chat-success-link{display:inline-flex;align-items:center;font-size:12px;font-weight:500;color:var(--mtb-chat-link-fg);text-decoration:none;margin-top:4px;cursor:pointer}.mtb-chat-success-link-pending{color:var(--mtb-chat-muted-fg);cursor:default;pointer-events:none}.mtb-chat-email-card{align-self:stretch;margin-top:10px;background:var(--mtb-chat-raised-bg);border-radius:10px;padding:10px;display:flex;flex-direction:column;gap:7px}.mtb-chat-email-row{display:flex;align-items:center;gap:7px}.mtb-chat-email-field{flex:1;background:var(--mtb-chat-write-bg);border-radius:8px;box-sizing:border-box;min-height:40px;display:flex;align-items:center;padding:0 10px;min-width:0}.mtb-chat-email-input{flex:1;min-width:0;background:none;border:none;outline:none;font-size:12px;font-family:inherit;color:var(--mtb-chat-title-fg)}.mtb-chat-email-input::placeholder{color:var(--mtb-chat-placeholder-fg)}.mtb-chat-email-submit{height:30px;padding:0 10px;border:none;border-radius:8px;background:var(--mtb-chat-accent);font-size:11px;font-weight:600;font-family:inherit;color:var(--mtb-chat-accent-fg);display:flex;align-items:center;justify-content:center;flex:none;cursor:pointer}.mtb-chat-email-submit:disabled{opacity:.3;cursor:default}.mtb-chat-email-note{font-size:12px;color:var(--mtb-chat-muted-fg);text-align:center}.mtb-chat-email-error{font-size:11px;color:var(--mtb-danger, #ef4444);text-align:center}.mtb-failure{position:fixed;z-index:2147483645;width:332px;background:var(--mtb-panel-bg);border:1px solid var(--mtb-panel-border);border-radius:16px;color:var(--mtb-fg);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-failure-icon{width:46px;height:46px;border-radius:50%;background:#dc262617;display:flex;align-items:center;justify-content:center;margin:0 auto 12px}.mtb-failure-title{font-size:15px;font-weight:600;margin-bottom:14px;letter-spacing:-.01em;line-height:1.45;color:var(--mtb-fg)}.mtb-failure-title:last-child{margin-bottom:0}.mtb-failure-actions{display:flex;align-items:center;justify-content:center}.mtb-failure-close{position:absolute;top:12px;right:12px;background:none;border:none;cursor:pointer;padding:3px;color:var(--mtb-clarify-close-fg);display:flex;transition:color .12s}.mtb-failure-close:hover{color:var(--mtb-clarify-close-hover-fg)}.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(var(--mtb-brand-rgb),.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:var(--mtb-panel-bg);border:1px solid var(--mtb-panel-border);border-radius:12px;color:var(--mtb-fg);box-shadow:0 8px 30px #0000001f;animation:mtbSlideUp .35s cubic-bezier(.34,1.56,.64,1);font-family:Inter,-apple-system,BlinkMacSystemFont,sans-serif}.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:var(--mtb-brand-primary);color:var(--mtb-brand-on-primary);cursor:pointer;font-family:inherit;font-size:12px;font-weight:600;transition:background .12s}.mtb-frustration-tell:hover{background:var(--mtb-brand-hover)}.mtb-frustration-tell:active{background:var(--mtb-brand-active)}.mtb-frustration-dismiss{height:28px;padding:0 8px;border:none;border-radius:7px;background:transparent;color:var(--mtb-dismiss-fg);cursor:pointer;font-family:inherit;font-size:12px;transition:color .12s}.mtb-frustration-dismiss:hover{color:var(--mtb-dismiss-hover-fg)}.mtb-record-bar{position:fixed;bottom:48px;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:#dc2626;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:var(--mtb-brand-primary);color:var(--mtb-brand-on-primary);cursor:pointer;font-family:inherit;font-size:12px;font-weight:600;transition:background .12s}.mtb-record-stop:hover{background:var(--mtb-brand-hover)}.mtb-record-stop:active{background:var(--mtb-brand-active)}.mtb-click-ripple{position:fixed;z-index:2147483644;width:24px;height:24px;border-radius:50%;border:2px solid var(--mtb-brand-emphasis);background:rgba(var(--mtb-brand-emphasis-rgb),.25);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}}@keyframes mtbDot{0%,80%,to{opacity:.3;transform:translateY(0)}40%{opacity:1;transform:translateY(-3px)}}.mtb-clarify-retry{flex:1;height:30px;display:inline-flex;align-items:center;justify-content:center;gap:5px;border:none;border-radius:8px;background:var(--mtb-brand-primary);color:var(--mtb-brand-on-primary);cursor:pointer;font-family:inherit;font-size:12px;font-weight:600;transition:background .12s}.mtb-clarify-retry:not(:disabled):hover{background:var(--mtb-brand-hover)}.mtb-clarify-retry:not(:disabled):active{background:var(--mtb-brand-active)}.mtb-clarify-retry:disabled{background:#00000026;cursor:not-allowed}@keyframes mtbSpin{to{transform:rotate(360deg)}}.mtb-dim-clickable{z-index:2147483643;pointer-events:auto;cursor:default;background:#0000001f}.mtb-draw-bar{position:fixed;bottom:48px;left:50%;transform:translate(-50%);z-index:2147483647;display:flex;align-items:center;gap:8px;height:46px;padding:0 8px 0 12px;border-radius:13px;background:#fff;border:1px solid rgba(0,0,0,.08);box-shadow:0 10px 30px #0f172a38;animation:mtbBarIn .2s ease;font-family:Inter,-apple-system,BlinkMacSystemFont,sans-serif}.mtb-draw-input{width:220px;height:32px;padding:0 10px;border:1px solid rgba(0,0,0,.12);border-radius:8px;font-family:inherit;font-size:13px;color:#191a1c;outline:none;background:#fafafa;transition:border-color .12s,box-shadow .12s,background .12s}.mtb-draw-input:focus{border-color:var(--mtb-brand-emphasis);box-shadow:0 0 0 3px rgba(var(--mtb-brand-emphasis-rgb),.15);background:#fff}.mtb-draw-input::placeholder{color:#00000057}.mtb-draw-icon-btn{width:30px;height:30px;display:inline-flex;align-items:center;justify-content:center;border:none;border-radius:8px;background:transparent;color:#374151;cursor:pointer;transition:background .12s,color .12s}.mtb-draw-icon-btn:hover:not(:disabled){background:#0000000f}.mtb-draw-icon-btn:disabled{color:#00000038;cursor:default}.mtb-draw-shot{display:inline-flex;align-items:center;gap:6px;font-size:12.5px;color:#0000008c;white-space:nowrap;cursor:default;user-select:none}.mtb-draw-shot input{width:14px;height:14px;margin:0;accent-color:var(--mtb-brand-primary);cursor:default}.mtb-draw-sep{width:1px;height:22px;background:#0000001a}.mtb-draw-cancel{height:32px;padding:0 12px;border:1px solid rgba(0,0,0,.12);border-radius:8px;background:#fff;color:#0000008c;cursor:pointer;font-family:inherit;font-size:12.5px;font-weight:550;transition:background .12s}.mtb-draw-cancel:hover{background:#0000000a}.mtb-draw-submit{height:32px;padding:0 14px;border:none;border-radius:8px;background:var(--mtb-brand-primary);color:var(--mtb-brand-on-primary);cursor:pointer;font-family:inherit;font-size:12.5px;font-weight:600;transition:background .12s}.mtb-draw-submit:hover:not(:disabled){background:var(--mtb-brand-hover)}.mtb-draw-submit:active:not(:disabled){background:var(--mtb-brand-active)}.mtb-draw-submit:disabled{opacity:.6;cursor:default}.mtb-record-preview{margin-bottom:12px}.mtb-record-preview-stage{position:relative;width:100%;height:132px;border-radius:10px;overflow:hidden;background:#0f172a;display:flex;align-items:center;justify-content:center}.mtb-record-preview-stage.playing{align-items:flex-start;justify-content:flex-start}.mtb-record-preview-play{width:44px;height:44px;border-radius:50%;border:none;background:#ffffffeb;color:var(--mtb-brand-primary);display:inline-flex;align-items:center;justify-content:center;cursor:pointer;transition:transform .12s,background .12s}.mtb-record-preview-play:hover:not(:disabled){transform:scale(1.06);background:#fff}.mtb-record-preview-play:disabled{cursor:default;opacity:.6}.mtb-record-preview-badge{position:absolute;right:8px;bottom:8px;padding:2px 7px;border-radius:6px;background:#0009;color:#fff;font-size:11px;font-variant-numeric:tabular-nums;font-family:JetBrains Mono,SF Mono,monospace}.mtb-record-preview-fallback{color:#ffffffd9;font-size:12px}.mtb-record-preview-name{display:block;margin-top:5px;font-size:11px;color:#0000006b}@media (pointer: coarse){.mtb-tab:after{content:"";position:absolute;inset:-6px 0 -6px -12px}.mtb-tab.left:after{inset:-6px -12px -6px 0}.mtb-toolbar{min-height:56px;border-radius:16px}.mtb-toolbar-mode-btn,.mtb-exit-btn{min-height:44px}.mtb-chat-input,.mtb-chat-email-input,.mtb-draw-input{font-size:16px}}@media (max-width: 480px){.mtb-tab{width:36px;height:40px;padding:0;font-size:0;writing-mode:horizontal-tb;border-radius:12px 0 0 12px;right:env(safe-area-inset-right,0px)}.mtb-tab.left{left:env(safe-area-inset-left,0px);border-radius:0 12px 12px 0}.mtb-tab:before{content:"";width:18px;height:18px;background:currentColor;-webkit-mask:var(--mtb-tab-icon) center / contain no-repeat;mask:var(--mtb-tab-icon) center / contain no-repeat}.mtb-toolbar{inset:0 0 auto;width:100%;max-width:none;max-height:none;transform:none;flex-direction:row;align-items:center;border-radius:0;gap:8px;justify-content:center;padding:env(safe-area-inset-top,0px) 8px 0;height:calc(44px + env(safe-area-inset-top,0px));min-height:calc(44px + env(safe-area-inset-top,0px));border-bottom:1px solid rgba(60,60,67,.16);background:#f8f8f8f5;box-shadow:0 1px 3px #00000014;-webkit-backdrop-filter:blur(18px);backdrop-filter:blur(18px);animation:none}.mtb-toolbar-modes{flex-direction:row;gap:0;padding:2px;background:#7676801f;border-radius:8px}.mtb-toolbar-sep{display:none}.mtb-hint-bar{top:calc(44px + env(safe-area-inset-top,0px));right:0;bottom:0;left:0;transform:none;justify-content:center;height:auto;padding:0 24px;border-radius:0;background:#0000001a;box-shadow:none;animation:none;white-space:normal;text-align:center;transition:none}.mtb-hint-bar .mtb-toolbar-hint{max-width:280px;color:#fffffff5;font-size:17px;font-weight:600;line-height:1.4;letter-spacing:0;white-space:normal;text-shadow:0 1px 3px rgba(0,0,0,.45)}.mtb-toolbar-mode-btn,.mtb-exit-btn{position:relative;width:auto;height:32px;min-height:32px;gap:6px;border-radius:6px;padding-right:8px;padding-left:8px;color:#3c3c43d1;transition:none}.mtb-toolbar-mode-btn:hover{background:transparent;color:#3c3c43d1}.mtb-toolbar-mode-btn.active,.mtb-toolbar-mode-btn.active:hover{background:var(--mtb-brand-on-primary);color:var(--mtb-brand-hover);box-shadow:0 1px 3px #0000001f}.mtb-toolbar-mode-btn:after,.mtb-exit-btn:after{content:"";position:absolute;inset:-6px 0}.mtb-exit-btn{width:32px;padding:0;border-radius:50%;background:#7676801f}.mtb-exit-btn:hover{background:#7676801f;color:#3c3c43d1}.mtb-toolbar-label{display:inline}.mtb-exit-btn .mtb-toolbar-label{display:none}.mtb-draw-bar{left:0;right:0;bottom:0;transform:none;height:auto;padding:10px 12px calc(10px + env(safe-area-inset-bottom,0px));border-radius:16px 16px 0 0}.mtb-frustration-prompt{left:0;right:0;bottom:0;flex-direction:column;align-items:stretch;gap:12px;padding:16px 16px calc(16px + env(safe-area-inset-bottom,0px));border-radius:16px 16px 0 0;border-width:1px 0 0;animation:none}.mtb-frustration-actions{display:flex;gap:8px}.mtb-frustration-tell,.mtb-frustration-dismiss{flex:1;min-height:44px}.mtb-chat{position:fixed;left:0!important;right:0;bottom:0;top:auto!important;width:100%;max-width:none;max-height:85vh;border-radius:20px 20px 0 0;box-shadow:0 -18px 60px #0003;animation:none}.mtb-chat-handle{width:36px;height:4px;border-radius:99px;background:#0000001f;margin:0 auto;flex-shrink:0}.mtb-chat-header{flex-direction:column;align-items:center;gap:8px;border-radius:20px 20px 0 0;padding:10px 16px 12px}.mtb-chat-header-row{width:100%;display:flex;align-items:center}.mtb-chat-messages,.mtb-chat-quick-replies{padding:14px 16px 12px}.mtb-chat-qr{padding:8px 13px}.mtb-chat-suggestions{padding-left:45px}.mtb-chat-sg{padding:8px 13px;font-size:12px}.mtb-chat-composer{padding:10px 12px calc(10px + env(safe-area-inset-bottom,12px))}.mtb-chat-success{padding:30px 20px}.mtb-chat-success-simple{padding-top:36px;padding-bottom:calc(44px + env(safe-area-inset-bottom,0px))}.mtb-chat-email-card{margin-top:12px;padding:12px;gap:8px}}:host([data-mtb-theme="dark"]) .mtb-chat-handle{background:#fff3}@media (prefers-color-scheme: dark){:host([data-mtb-theme="auto"]) .mtb-chat-handle{background:#fff3}}@media (max-width: 480px){:host([data-mtb-theme="dark"]) .mtb-chat{box-shadow:0 -18px 60px #0000008c}}@media (max-width: 480px) and (prefers-color-scheme: dark){:host([data-mtb-theme="auto"]) .mtb-chat{box-shadow:0 -18px 60px #0000008c}}.mtb-chat-handle{display:none}@media (max-width: 480px){.mtb-chat-handle{display:block}}`,x="mtb-widget-host";function C(e){const t=document.getElementById(x);return t?t===e||t.contains(e):!1}function G(e,t){return document.elementsFromPoint?.(e,t).find(r=>r.id!==x)??null}function d(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function pt(e){return e.isComposing||e.keyCode===229}const tr=/^(script|style|noscript|template)$/i;function $t(e,t=80){let r="";for(const i of Array.from(e.childNodes)){if(r.length>=t)break;i.nodeType===3?r+=i.nodeValue??"":i instanceof Element&&!tr.test(i.tagName)&&(r+=$t(i,t-r.length))}return r}function ft(e){if(e instanceof HTMLElement){const t=e.getAttribute("aria-label");if(t)return t;const r=e.getAttribute("title");if(r)return r;const i=$t(e).trim().slice(0,40);if(i)return i;const n=e.placeholder;if(n)return n;const s=e.alt;if(s)return s;const o=e.getAttribute("data-mark");if(o)return o}return e.tagName.toLowerCase()}function Ut(e){const t=[];let r=e;for(;r&&r!==document.body&&t.length<5;){let i=r.tagName.toLowerCase();if(r.id){i=`#${r.id}`,t.unshift(i);break}const n=Array.from(r.classList).filter(o=>!o.startsWith("mtb-")).slice(0,2).join(".");n&&(i+=`.${n}`);const s=r.parentElement;if(s){const o=Array.from(s.children).filter(a=>a.tagName===r.tagName);if(o.length>1){const a=o.indexOf(r)+1;i+=`:nth-of-type(${a})`}}t.unshift(i),r=r.parentElement}return t.join(" > ")}const X=class X{constructor(t="auto",r){this.stopHostInteraction=s=>{s.stopPropagation()};const i=document.getElementById(x);if(this.ownsHost=!i,this.host=i??document.createElement("div"),this.root=this.host.shadowRoot??this.host.attachShadow({mode:"open"}),this.root.replaceChildren(),this.originalInlineStyle=this.host.getAttribute("style"),this.originalTheme=this.host.getAttribute("data-mtb-theme"),this.host.id=x,this.host.style.cssText="position:fixed;top:0;left:0;width:0;height:0;overflow:visible;z-index:2147483646;",r){const s=[1,3,5].map(a=>parseInt(r.primary.slice(a,a+2),16)),o=[1,3,5].map(a=>parseInt(r.onPrimary.slice(a,a+2),16));this.host.style.setProperty("--mtb-brand-primary",r.primary.toLowerCase()),this.host.style.setProperty("--mtb-brand-hover",r.hover.toLowerCase()),this.host.style.setProperty("--mtb-brand-active",r.active.toLowerCase()),this.host.style.setProperty("--mtb-brand-on-primary",r.onPrimary.toLowerCase()),this.host.style.setProperty("--mtb-brand-rgb",s.join(", ")),this.host.style.setProperty("--mtb-brand-on-primary-rgb",o.join(", ")),this.host.style.setProperty("--mtb-brand-emphasis",r.primary.toLowerCase()),this.host.style.setProperty("--mtb-brand-emphasis-rgb",s.join(", ")),this.host.style.setProperty("--mtb-brand-gradient-start",r.primary.toLowerCase()),this.host.style.setProperty("--mtb-brand-gradient-end",r.hover.toLowerCase())}this.host.setAttribute("data-mtb-theme",t),this.ownsHost&&document.body.appendChild(this.host);for(const s of X.HOST_INTERACTION_EVENTS)this.root.addEventListener(s,this.stopHostInteraction);const n=document.createElement("style");n.textContent=Qe,this.root.appendChild(n)}el(t,r){const i=document.createElement(t);return r&&(i.className=r),i}append(...t){for(const r of t)this.root.appendChild(r)}remove(...t){for(const r of t)r.parentNode===this.root&&this.root.removeChild(r)}destroy(){for(const t of X.HOST_INTERACTION_EVENTS)this.root.removeEventListener(t,this.stopHostInteraction);if(!this.ownsHost){this.root.replaceChildren(),this.host.removeAttribute("data-mtb-toolbar"),this.originalInlineStyle===null?this.host.removeAttribute("style"):this.host.setAttribute("style",this.originalInlineStyle),this.originalTheme===null?this.host.removeAttribute("data-mtb-theme"):this.host.setAttribute("data-mtb-theme",this.originalTheme);return}this.host.remove()}};X.HOST_INTERACTION_EVENTS=["pointerdown","pointerup","pointercancel","mousedown","mouseup","touchstart","touchend","touchcancel","click"];let gt=X;class er{constructor(t,r,i,n,s){this.active=!1,this.onClick=n,this.customText=s,this.el=t.el("button","mtb-tab"),i==="left"&&this.el.classList.add("left"),this.idleLabel=s??r.tab,this.activeLabel=r.toolbar.exit,this.setLabel(this.idleLabel),this.el.addEventListener("click",n),t.append(this.el)}setLabel(t){this.el.textContent=t,this.el.setAttribute("aria-label",t)}setMessages(t){this.idleLabel=this.customText??t.tab,this.activeLabel=t.toolbar.exit,this.setLabel(this.active?this.activeLabel:this.idleLabel)}setActive(t){this.active=t,this.el.classList.toggle("active",t),this.setLabel(t?this.activeLabel:this.idleLabel)}destroy(){this.el.removeEventListener("click",this.onClick),this.el.remove()}}const rr=8e3;class ir{constructor(t,r,i){this.autoHideTimer=null,this.el=t.el("div","mtb-frustration-prompt"),this.el.innerHTML=`
1
+ var MakeThisBetter=function(){"use strict";const Qe=`*,*: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{--mtb-brand-primary: #059669;--mtb-brand-hover: #047857;--mtb-brand-active: #065f46;--mtb-brand-on-primary: #fff;--mtb-brand-rgb: 5, 150, 105;--mtb-brand-on-primary-rgb: 255, 255, 255;--mtb-brand-emphasis: #10b981;--mtb-brand-emphasis-rgb: 16, 185, 129;--mtb-brand-gradient-start: #10b981;--mtb-brand-gradient-end: #059669;--mtb-panel-bg: #fff;--mtb-panel-border: rgba(0, 0, 0, .1);--mtb-panel-divider: rgba(0, 0, 0, .06);--mtb-fg: #191a1c;--mtb-field-bg: #fff;--mtb-field-bg-subtle: #fafafa;--mtb-field-border: rgba(0, 0, 0, .12);--mtb-field-border-soft: rgba(0, 0, 0, .09);--mtb-placeholder-fg: rgba(0, 0, 0, .34);--mtb-action-bg: #fff;--mtb-action-border: rgba(0, 0, 0, .12);--mtb-action-fg: rgba(0, 0, 0, .55);--mtb-action-hover-bg: rgba(0, 0, 0, .04);--mtb-clarify-close-fg: rgba(0, 0, 0, .38);--mtb-clarify-close-hover-fg: rgba(0, 0, 0, .7);--mtb-dismiss-fg: rgba(0, 0, 0, .4);--mtb-dismiss-hover-fg: rgba(0, 0, 0, .7);--mtb-quick-hover-bg: rgba(var(--mtb-brand-emphasis-rgb), .06);--mtb-quick-hover-border: rgba(var(--mtb-brand-emphasis-rgb), .3);--mtb-quick-selected-bg: rgba(var(--mtb-brand-emphasis-rgb), .1);--mtb-quick-selected-border: rgba(var(--mtb-brand-emphasis-rgb), .5);--mtb-field-focus-border: var(--mtb-brand-emphasis);--mtb-chat-card-bg: #FFFFFF;--mtb-chat-card-shadow: 0 24px 64px rgba(0, 0, 0, .18);--mtb-chat-raised-bg: #F9FAFB;--mtb-chat-write-bg: #FFFFFF;--mtb-chat-title-fg: #111827;--mtb-chat-body-fg: #1f2937;--mtb-chat-muted-fg: #6b7280;--mtb-chat-placeholder-fg: #9ca3af;--mtb-chat-pill-fg: #374151;--mtb-chat-pill-shadow: 0 1px 3px rgba(0, 0, 0, .08), 0 0 0 1px rgba(0, 0, 0, .04);--mtb-chat-pill-hover-shadow: 0 3px 10px rgba(0, 0, 0, .12), 0 0 0 1px rgba(0, 0, 0, .05);--mtb-chat-close-hover-bg: #F3F4F6;--mtb-chat-close-hover-fg: #111827;--mtb-chat-composer-shadow: 0 -1px 6px rgba(0, 0, 0, .06);--mtb-chat-skip-fg: #9ca3af;--mtb-chat-skip-hover-fg: #4b5563;--mtb-chat-camera-lens: #fff;--mtb-chat-accent: var(--mtb-brand-primary);--mtb-chat-accent-hover: var(--mtb-brand-hover);--mtb-chat-accent-fg: var(--mtb-brand-on-primary);--mtb-chat-accent-rgb: var(--mtb-brand-rgb);--mtb-chat-accent-fg-rgb: var(--mtb-brand-on-primary-rgb);--mtb-chat-link-fg: var(--mtb-brand-primary);--mtb-chat-send-shadow: 0 2px 8px rgba(var(--mtb-chat-accent-rgb), .35);--mtb-chat-success-icon-shadow: 0 4px 14px rgba(var(--mtb-chat-accent-rgb), .35);--mtb-chat-danger: #EF4444;--mtb-chat-logo-start: #10b981;--mtb-chat-logo-end: #059669;--mtb-chat-logo-fg: #fff}:host([data-mtb-theme="dark"]){--mtb-panel-bg: #151719;--mtb-panel-border: rgba(255, 255, 255, .12);--mtb-panel-divider: rgba(255, 255, 255, .1);--mtb-fg: #f9fafb;--mtb-field-bg: #1f2327;--mtb-field-bg-subtle: #1f2327;--mtb-field-border: rgba(255, 255, 255, .12);--mtb-field-border-soft: rgba(255, 255, 255, .12);--mtb-placeholder-fg: rgba(255, 255, 255, .4);--mtb-action-bg: #1f2327;--mtb-action-border: rgba(255, 255, 255, .14);--mtb-action-fg: rgba(255, 255, 255, .7);--mtb-action-hover-bg: rgba(255, 255, 255, .06);--mtb-clarify-close-fg: rgba(255, 255, 255, .45);--mtb-clarify-close-hover-fg: rgba(255, 255, 255, .75);--mtb-dismiss-fg: rgba(255, 255, 255, .4);--mtb-dismiss-hover-fg: rgba(255, 255, 255, .7);--mtb-quick-hover-bg: rgba(var(--mtb-brand-emphasis-rgb), .12);--mtb-quick-hover-border: rgba(var(--mtb-brand-emphasis-rgb), .45);--mtb-quick-selected-bg: rgba(var(--mtb-brand-emphasis-rgb), .18);--mtb-quick-selected-border: var(--mtb-brand-primary);--mtb-field-focus-border: var(--mtb-brand-emphasis);--mtb-chat-card-bg: #17191C;--mtb-chat-card-shadow: 0 24px 64px rgba(0, 0, 0, .55);--mtb-chat-raised-bg: #202327;--mtb-chat-write-bg: #23272C;--mtb-chat-title-fg: #E8EAED;--mtb-chat-body-fg: #DCE0E4;--mtb-chat-muted-fg: #B0B6BD;--mtb-chat-placeholder-fg: #A3AAB2;--mtb-chat-pill-fg: #DDE1E5;--mtb-chat-pill-shadow: 0 1px 3px rgba(0, 0, 0, .5), 0 0 0 1px rgba(255, 255, 255, .08);--mtb-chat-pill-hover-shadow: 0 4px 14px rgba(0, 0, 0, .6), 0 0 0 1px rgba(255, 255, 255, .14);--mtb-chat-close-hover-bg: rgba(255, 255, 255, .08);--mtb-chat-close-hover-fg: #FFFFFF;--mtb-chat-composer-shadow: 0 -1px 6px rgba(0, 0, 0, .45);--mtb-chat-skip-fg: #A3AAB2;--mtb-chat-skip-hover-fg: #E8EAED;--mtb-chat-camera-lens: #EAF7EE;--mtb-chat-accent: #4ADE80;--mtb-chat-accent-hover: #34D399;--mtb-chat-accent-fg: #0D1210;--mtb-chat-accent-rgb: 74, 222, 128;--mtb-chat-accent-fg-rgb: 13, 18, 16;--mtb-chat-link-fg: #5BD98A;--mtb-chat-send-shadow: 0 1px 3px rgba(0, 0, 0, .5);--mtb-chat-success-icon-shadow: 0 2px 10px rgba(0, 0, 0, .5);--mtb-chat-danger: #F87171;--mtb-chat-logo-start: #1E9E4A;--mtb-chat-logo-end: #0B8AA0;--mtb-chat-logo-fg: #EAF7EE}@media (prefers-color-scheme: dark){:host([data-mtb-theme="auto"]){--mtb-panel-bg: #151719;--mtb-panel-border: rgba(255, 255, 255, .12);--mtb-panel-divider: rgba(255, 255, 255, .1);--mtb-fg: #f9fafb;--mtb-field-bg: #1f2327;--mtb-field-bg-subtle: #1f2327;--mtb-field-border: rgba(255, 255, 255, .12);--mtb-field-border-soft: rgba(255, 255, 255, .12);--mtb-placeholder-fg: rgba(255, 255, 255, .4);--mtb-action-bg: #1f2327;--mtb-action-border: rgba(255, 255, 255, .14);--mtb-action-fg: rgba(255, 255, 255, .7);--mtb-action-hover-bg: rgba(255, 255, 255, .06);--mtb-clarify-close-fg: rgba(255, 255, 255, .45);--mtb-clarify-close-hover-fg: rgba(255, 255, 255, .75);--mtb-dismiss-fg: rgba(255, 255, 255, .4);--mtb-dismiss-hover-fg: rgba(255, 255, 255, .7);--mtb-quick-hover-bg: rgba(var(--mtb-brand-emphasis-rgb), .12);--mtb-quick-hover-border: rgba(var(--mtb-brand-emphasis-rgb), .45);--mtb-quick-selected-bg: rgba(var(--mtb-brand-emphasis-rgb), .18);--mtb-quick-selected-border: var(--mtb-brand-primary);--mtb-field-focus-border: var(--mtb-brand-emphasis);--mtb-chat-card-bg: #17191C;--mtb-chat-card-shadow: 0 24px 64px rgba(0, 0, 0, .55);--mtb-chat-raised-bg: #202327;--mtb-chat-write-bg: #23272C;--mtb-chat-title-fg: #E8EAED;--mtb-chat-body-fg: #DCE0E4;--mtb-chat-muted-fg: #B0B6BD;--mtb-chat-placeholder-fg: #A3AAB2;--mtb-chat-pill-fg: #DDE1E5;--mtb-chat-pill-shadow: 0 1px 3px rgba(0, 0, 0, .5), 0 0 0 1px rgba(255, 255, 255, .08);--mtb-chat-pill-hover-shadow: 0 4px 14px rgba(0, 0, 0, .6), 0 0 0 1px rgba(255, 255, 255, .14);--mtb-chat-close-hover-bg: rgba(255, 255, 255, .08);--mtb-chat-close-hover-fg: #FFFFFF;--mtb-chat-composer-shadow: 0 -1px 6px rgba(0, 0, 0, .45);--mtb-chat-skip-fg: #A3AAB2;--mtb-chat-skip-hover-fg: #E8EAED;--mtb-chat-camera-lens: #EAF7EE;--mtb-chat-accent: #4ADE80;--mtb-chat-accent-hover: #34D399;--mtb-chat-accent-fg: #0D1210;--mtb-chat-accent-rgb: 74, 222, 128;--mtb-chat-accent-fg-rgb: 13, 18, 16;--mtb-chat-link-fg: #5BD98A;--mtb-chat-send-shadow: 0 1px 3px rgba(0, 0, 0, .5);--mtb-chat-success-icon-shadow: 0 2px 10px rgba(0, 0, 0, .5);--mtb-chat-danger: #F87171;--mtb-chat-logo-start: #1E9E4A;--mtb-chat-logo-end: #0B8AA0;--mtb-chat-logo-fg: #EAF7EE}}.mtb-tab{--mtb-tab-icon: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23000' stroke-width='2' stroke-linecap='round'%3E%3Ccircle cx='12' cy='12' r='8'/%3E%3Ccircle cx='12' cy='12' r='2.4' fill='%23000' stroke='none'/%3E%3Cpath d='M12 1.8v3.4M12 18.8v3.4M1.8 12h3.4M18.8 12h3.4'/%3E%3C/svg%3E");--mtb-tab-bg: var(--mtb-brand-primary);--mtb-tab-hover-bg: var(--mtb-brand-hover);--mtb-tab-active-bg: var(--mtb-brand-active);--mtb-tab-shadow-color: var(--mtb-brand-rgb);--mtb-tab-fg: var(--mtb-brand-on-primary);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:var(--mtb-tab-bg);color:var(--mtb-tab-fg);border-radius:8px 0 0 8px;cursor:pointer;box-shadow:-2px 0 14px rgba(var(--mtb-tab-shadow-color),.35);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 rgba(var(--mtb-tab-shadow-color),.35)}.mtb-tab:hover{background:var(--mtb-tab-hover-bg);box-shadow:-3px 0 20px rgba(var(--mtb-tab-shadow-color),.45)}.mtb-tab.active{background:var(--mtb-tab-active-bg)}.mtb-hint-bar{position:fixed;top:18px;left:50%;transform:translate(-50%);z-index:2147483647;display:flex;align-items:center;height:38px;padding:0 16px;border-radius:13px;background:linear-gradient(120deg,var(--mtb-brand-gradient-start),var(--mtb-brand-gradient-end));color:var(--mtb-brand-on-primary);box-shadow:0 10px 26px #0f172a38;animation:mtbHintIn .2s ease;white-space:nowrap;transition:opacity .15s ease;pointer-events:none}.mtb-hint-bar--under-pointer{opacity:.3}.mtb-hint-bar.mtb-hint-bar--dismissed{display:none}@keyframes mtbHintIn{0%{transform:translate(-50%,12px);opacity:0}to{transform:translate(-50%);opacity:1}}.mtb-toolbar{position:fixed;top:50%;right:8px;transform:translateY(-50%);z-index:2147483647;display:flex;flex-direction:column;align-items:center;gap:6px;width:38px;padding:6px 0;max-height:calc(100vh - 24px);border-radius:19px;background:linear-gradient(160deg,var(--mtb-brand-gradient-start),var(--mtb-brand-gradient-end));color:var(--mtb-brand-on-primary);box-shadow:0 8px 22px #0f172a33;animation:mtbEdgeBarIn .2s ease;white-space:nowrap;pointer-events:none}.mtb-toolbar.left{right:auto;left:8px;animation:mtbEdgeBarInLeft .2s ease}@keyframes mtbBarIn{0%{transform:translate(-50%,12px);opacity:0}to{transform:translate(-50%);opacity:1}}@keyframes mtbEdgeBarIn{0%{transform:translate(12px,-50%);opacity:0}to{transform:translateY(-50%);opacity:1}}@keyframes mtbEdgeBarInLeft{0%{transform:translate(-12px,-50%);opacity:0}to{transform:translateY(-50%);opacity:1}}.mtb-toolbar-label{display:none}:host([data-mtb-toolbar]) .mtb-tab{display:none}.mtb-toolbar-modes{display:flex;align-items:center;gap:3px;background:rgba(var(--mtb-brand-on-primary-rgb),.16);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:var(--mtb-brand-on-primary);transition:all .12s}.mtb-toolbar-mode-btn.active{background:#fff;color:var(--mtb-brand-active)}.mtb-toolbar-hint{font-size:12px;color:var(--mtb-brand-on-primary);white-space:nowrap}.mtb-toolbar-sep{width:20px;height:1px;align-self:center;background:rgba(var(--mtb-brand-on-primary-rgb),.22)}.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:var(--mtb-brand-on-primary);cursor:pointer;background:rgba(var(--mtb-brand-on-primary-rgb),.16);border:none;font-family:inherit;transition:background .12s}.mtb-toolbar-modes{flex-direction:column;gap:6px;padding:0;background:none;border-radius:0}.mtb-toolbar-mode-btn,.mtb-exit-btn{pointer-events:auto;display:flex;align-items:center;justify-content:center;gap:0;width:30px;height:30px;padding:0;border-radius:50%;background:none;color:var(--mtb-brand-on-primary)}.mtb-toolbar-mode-btn{opacity:.72}.mtb-exit-btn{opacity:1}.mtb-toolbar-mode-btn:hover,.mtb-exit-btn:hover{background:rgba(var(--mtb-brand-on-primary-rgb),.16);color:var(--mtb-brand-on-primary);opacity:1}.mtb-toolbar-mode-btn.active,.mtb-toolbar-mode-btn.active:hover{background:var(--mtb-brand-on-primary);color:var(--mtb-brand-hover);opacity:1}.mtb-exit-btn{color:var(--mtb-brand-on-primary)}.mtb-toolbar-sep{width:16px;height:1px;margin:1px 0;align-self:center;background:rgba(var(--mtb-brand-on-primary-rgb),.28)}.mtb-exit-btn:hover{background:rgba(var(--mtb-brand-on-primary-rgb),.28)}.mtb-overlay{position:fixed;inset:0;z-index:2147483640;cursor:crosshair;touch-action:none}.mtb-dim{position:fixed;inset:0;z-index:2147483639;background:#00000014}.mtb-highlight{position:fixed;z-index:2147483641;pointer-events:none;border:2px solid var(--mtb-brand-emphasis);border-radius:6px;background:rgba(var(--mtb-brand-emphasis-rgb),.06);transition:all .08s ease}.mtb-highlight-tooltip{position:fixed;z-index:2147483642;pointer-events:none;transform:translate(-50%,-100%);max-width:240px;overflow:hidden;text-overflow:ellipsis;background:var(--mtb-brand-active);color:var(--mtb-brand-on-primary);padding:4px 10px;border-radius:6px;font-size:11px;font-weight:500;white-space:nowrap;box-shadow:0 4px 12px #0000002e;font-family:Inter,-apple-system,BlinkMacSystemFont,sans-serif}.mtb-highlight-tooltip.below{transform:translate(-50%)}.mtb-highlight-tooltip:after{content:"";position:absolute;top:100%;left:50%;transform:translate(-50%);border:4px solid transparent;border-top-color:var(--mtb-brand-active)}.mtb-highlight-tooltip.below:after{top:auto;bottom:100%;border-top-color:transparent;border-bottom-color:var(--mtb-brand-active)}.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:var(--mtb-brand-primary);border:2px solid #fff;display:flex;align-items:center;justify-content:center;font-size:10px;color:var(--mtb-brand-on-primary);font-weight:700;box-shadow:0 0 0 1px #0f172aad,0 2px 8px rgba(var(--mtb-brand-rgb),.45);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)}}@keyframes mtbSlideUp{0%{transform:translateY(14px) scale(.97);opacity:0}to{transform:translateY(0) scale(1);opacity:1}}.mtb-draw-shot input:disabled{appearance:none;-webkit-appearance:none;border:none;border-radius:4px;background-color:var(--mtb-placeholder-fg);background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath fill='none' stroke='%23fff' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round' d='M3.5 8.5l3 3 6-6'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:center;background-size:contain;opacity:1}.mtb-draw-shot input:disabled{background-color:#0000004d}.mtb-btn-loading{pointer-events:none;opacity:.8}.mtb-btn-loading:after{content:"";display:inline-block;width:10px;height:10px;margin-left:6px;border:1.5px solid rgba(255,255,255,.35);border-top-color:#fff;border-radius:50%;animation:mtbSpin .7s linear infinite;vertical-align:middle}.mtb-chat{position:fixed;z-index:2147483645;display:flex;flex-direction:column;width:min(320px,calc(100vw - 56px));max-height:420px;background:var(--mtb-chat-card-bg);border-radius:16px;color:var(--mtb-chat-title-fg);box-shadow:var(--mtb-chat-card-shadow);overflow:hidden;animation:mtbSlideUp .28s cubic-bezier(.34,1.56,.64,1);font-family:Inter,-apple-system,BlinkMacSystemFont,sans-serif}.mtb-chat.mtb-chat-receipt{inset:auto 20px 20px auto;width:min(320px,calc(100vw - 40px));animation:none}.mtb-chat-header{display:flex;align-items:center;gap:7px;padding:11px 12px;background:var(--mtb-chat-raised-bg);flex-shrink:0}.mtb-chat-brand{display:flex;align-items:center;gap:7px;text-decoration:none;opacity:.9;transition:opacity .16s}.mtb-chat-brand:hover{opacity:1}.mtb-chat-brand:hover .mtb-chat-brand-name{text-decoration:underline;text-underline-offset:2px}.mtb-chat-logo{width:20px;height:20px;border-radius:6px;overflow:hidden;flex:none}.mtb-chat-logo svg{width:100%;height:100%;display:block}.mtb-chat-brand-name{font-size:12px;font-weight:600;color:var(--mtb-chat-title-fg)}.mtb-chat-header-row{display:flex;align-items:center;gap:7px;width:100%}.mtb-chat-header-gap{flex:1}.mtb-chat-close{width:28px;height:28px;border-radius:99px;display:flex;align-items:center;justify-content:center;background:none;border:none;padding:0;color:var(--mtb-chat-muted-fg);cursor:pointer;flex:none;transition:background .16s,color .16s}.mtb-chat-close:hover{background:var(--mtb-chat-close-hover-bg);color:var(--mtb-chat-close-hover-fg)}.mtb-chat-messages{flex:1;overflow-y:auto;padding:12px;display:flex;flex-direction:column;gap:8px;min-height:0;background:var(--mtb-chat-card-bg)}.mtb-chat-messages:empty{display:none}.mtb-chat-bubble{font-size:13px;max-width:85%;word-break:break-word}.mtb-chat-bubble-user{align-self:flex-end;background:var(--mtb-chat-accent);color:var(--mtb-chat-accent-fg);line-height:1.45;padding:8px 11px;border-radius:12px 12px 4px}.mtb-chat-bubble-ai{background:var(--mtb-chat-raised-bg);color:var(--mtb-chat-body-fg);line-height:1.5;padding:9px 12px;border-radius:12px 12px 12px 4px}.mtb-chat-ai-row{display:flex;align-items:flex-end;gap:7px}.mtb-chat-avatar{width:22px;height:22px;border-radius:7px;overflow:hidden;flex:none}.mtb-chat-avatar svg{width:100%;height:100%;display:block}.mtb-chat-dots{display:flex;align-items:center;gap:4px;padding:10px 12px;background:var(--mtb-chat-raised-bg);border-radius:12px 12px 12px 4px}.mtb-chat-dots span{width:5px;height:5px;background:var(--mtb-chat-accent);border-radius:99px;animation:mtbChatDot 1.1s infinite}.mtb-chat-dots span:nth-child(2){animation-delay:.15s}.mtb-chat-dots span:nth-child(3){animation-delay:.3s}@keyframes mtbChatDot{0%,60%,to{transform:translateY(0);opacity:.45}30%{transform:translateY(-4px);opacity:1}}.mtb-chat-suggestions{display:flex;flex-wrap:wrap;gap:6px;padding-left:29px}.mtb-chat-sg{background:var(--mtb-chat-write-bg);border:none;border-radius:99px;padding:5px 10px;font-size:11px;font-weight:500;font-family:inherit;color:var(--mtb-chat-pill-fg);cursor:pointer;box-shadow:var(--mtb-chat-pill-shadow);transition:box-shadow .16s,transform .16s}.mtb-chat-sg:hover{box-shadow:var(--mtb-chat-pill-hover-shadow);transform:translateY(-1px)}.mtb-chat-quick-replies{display:flex;flex-wrap:wrap;gap:6px;padding:12px;background:var(--mtb-chat-card-bg)}.mtb-chat-qr{display:flex;align-items:center;gap:5px;background:var(--mtb-chat-write-bg);border:none;border-radius:99px;padding:7px 12px;font-size:12px;font-weight:500;font-family:inherit;color:var(--mtb-chat-pill-fg);cursor:pointer;box-shadow:var(--mtb-chat-pill-shadow);transition:box-shadow .16s,transform .16s}.mtb-chat-qr:hover{box-shadow:var(--mtb-chat-pill-hover-shadow);transform:translateY(-1px)}.mtb-chat-qr:disabled{opacity:.5;pointer-events:none;cursor:default;transform:none!important;box-shadow:var(--mtb-chat-pill-shadow)!important}.mtb-chat-composer{display:flex;flex-direction:column;gap:8px;padding:10px;background:var(--mtb-chat-raised-bg);box-shadow:var(--mtb-chat-composer-shadow);flex-shrink:0}.mtb-chat-composer-disabled{pointer-events:none}.mtb-chat-composer-disabled .mtb-chat-input{opacity:.3}.mtb-chat-input{box-sizing:border-box;width:100%;min-height:64px;max-height:132px;padding:10px 12px;background:var(--mtb-chat-write-bg);border:none;border-radius:10px;font-size:13px;line-height:1.5;font-family:inherit;color:var(--mtb-chat-title-fg);outline:none;resize:none}.mtb-chat-input::placeholder{color:var(--mtb-chat-placeholder-fg)}.mtb-chat-input:disabled{opacity:.5;cursor:default}.mtb-chat-actions{display:flex;align-items:center;gap:10px}.mtb-chat-actions-gap{flex:1}.mtb-chat-screenshot,.mtb-chat-attachment{display:flex;align-items:center;gap:6px;background:none;border:none;padding:0;font-family:inherit;color:var(--mtb-chat-accent);cursor:pointer;transition:opacity .16s}.mtb-chat-screenshot svg,.mtb-chat-attachment svg{display:flex;flex:none}.mtb-chat-icon-lens{fill:var(--mtb-chat-camera-lens)}.mtb-chat-screenshot:hover{opacity:.75}.mtb-chat-attachment{cursor:default}.mtb-chat-capture-label{font-size:11px;color:var(--mtb-chat-muted-fg)}.mtb-chat-screenshot[aria-pressed=false],.mtb-chat-screenshot-off{opacity:.4;color:var(--mtb-chat-muted-fg)}.mtb-chat-screenshot:disabled{opacity:.3;pointer-events:none;cursor:default}.mtb-chat-skip{height:26px;border:none;border-radius:6px;background:none;display:flex;align-items:center;padding:0 4px;font-size:11px;font-weight:500;font-family:inherit;color:var(--mtb-chat-skip-fg);cursor:pointer;flex:none;transition:color .16s}.mtb-chat-skip:hover{color:var(--mtb-chat-skip-hover-fg)}.mtb-chat-send{position:relative;height:34px;padding:0 14px;border:none;border-radius:10px;background:var(--mtb-chat-accent);font-size:12px;font-weight:600;font-family:inherit;color:var(--mtb-chat-accent-fg);display:flex;align-items:center;justify-content:center;flex:none;cursor:pointer;box-shadow:var(--mtb-chat-send-shadow)}.mtb-chat-send:disabled{opacity:.3;box-shadow:none;cursor:default}.mtb-chat-error-row{display:flex;align-items:center;justify-content:center;gap:8px;padding:4px 0}.mtb-chat-error-text{font-size:11px;color:var(--mtb-danger, #ef4444)}.mtb-chat-error-retry{font-size:11px;font-weight:600;font-family:inherit;color:var(--mtb-chat-pill-fg);background:var(--mtb-chat-write-bg);border:none;border-radius:999px;padding:4px 11px;box-shadow:var(--mtb-chat-pill-shadow);cursor:pointer}.mtb-chat-error-retry:hover{box-shadow:var(--mtb-chat-pill-hover-shadow)}.mtb-chat-success{padding:30px 20px 26px;display:flex;flex-direction:column;align-items:center;gap:10px;background:var(--mtb-chat-card-bg);animation:mtbSlideUp .28s cubic-bezier(.34,1.56,.64,1) both}.mtb-chat-success-simple{padding-top:34px;padding-bottom:22px}.mtb-chat-success-icon{width:40px;height:40px;border-radius:99px;background:var(--mtb-chat-accent);color:var(--mtb-chat-accent-fg);display:flex;align-items:center;justify-content:center;box-shadow:var(--mtb-chat-success-icon-shadow)}.mtb-chat-success-title{font-size:15px;font-weight:600;color:var(--mtb-chat-title-fg);margin-top:2px;text-align:center}.mtb-chat-finalize-failure .mtb-chat-failure-icon{background:#ef44441a;color:var(--mtb-chat-danger, #ef4444);box-shadow:none;font-size:20px;font-weight:700}.mtb-chat-finalize-failure{padding:26px 24px;gap:8px}.mtb-chat-finalize-message{color:var(--mtb-chat-muted-fg);font-size:12px;line-height:1.5;text-align:center}.mtb-chat-finalize-retry{margin-top:12px;width:100%;height:34px;border:none;border-radius:10px;background:var(--mtb-chat-accent);box-shadow:var(--mtb-chat-send-shadow);color:var(--mtb-chat-accent-fg);cursor:pointer;font-family:inherit;font-size:12px;font-weight:600}.mtb-chat-finalize-retry:hover:not(:disabled){background:var(--mtb-chat-accent-hover)}.mtb-chat-finalize-retry:disabled{cursor:wait;opacity:.8}.mtb-chat-finalize-spinner{width:14px;height:14px;display:inline-block;border:2px solid currentColor;border-right-color:transparent;border-radius:50%;animation:mtbSpin .7s linear infinite}.mtb-chat-finalize-close{margin-top:8px;padding:0;border:0;background:transparent;color:var(--mtb-chat-muted-fg);cursor:pointer;font-family:inherit;font-size:12px;font-weight:500}.mtb-chat-finalize-close:hover{color:var(--mtb-chat-title-fg)}.mtb-chat-success-link{display:inline-flex;align-items:center;font-size:12px;font-weight:500;color:var(--mtb-chat-link-fg);text-decoration:none;margin-top:4px;cursor:pointer}.mtb-chat-success-link-pending{color:var(--mtb-chat-muted-fg);cursor:default;pointer-events:none}.mtb-chat-email-card{align-self:stretch;margin-top:10px;background:var(--mtb-chat-raised-bg);border-radius:10px;padding:10px;display:flex;flex-direction:column;gap:7px}.mtb-chat-email-row{display:flex;align-items:center;gap:7px}.mtb-chat-email-field{flex:1;background:var(--mtb-chat-write-bg);border-radius:8px;box-sizing:border-box;min-height:40px;display:flex;align-items:center;padding:0 10px;min-width:0}.mtb-chat-email-input{flex:1;min-width:0;background:none;border:none;outline:none;font-size:12px;font-family:inherit;color:var(--mtb-chat-title-fg)}.mtb-chat-email-input::placeholder{color:var(--mtb-chat-placeholder-fg)}.mtb-chat-email-submit{height:30px;padding:0 10px;border:none;border-radius:8px;background:var(--mtb-chat-accent);font-size:11px;font-weight:600;font-family:inherit;color:var(--mtb-chat-accent-fg);display:flex;align-items:center;justify-content:center;flex:none;cursor:pointer}.mtb-chat-email-submit:disabled{opacity:.3;cursor:default}.mtb-chat-email-note{font-size:12px;color:var(--mtb-chat-muted-fg);text-align:center}.mtb-chat-email-error{font-size:11px;color:var(--mtb-danger, #ef4444);text-align:center}.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(var(--mtb-brand-rgb),.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:var(--mtb-panel-bg);border:1px solid var(--mtb-panel-border);border-radius:12px;color:var(--mtb-fg);box-shadow:0 8px 30px #0000001f;animation:mtbSlideUp .35s cubic-bezier(.34,1.56,.64,1);font-family:Inter,-apple-system,BlinkMacSystemFont,sans-serif}.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:var(--mtb-brand-primary);color:var(--mtb-brand-on-primary);cursor:pointer;font-family:inherit;font-size:12px;font-weight:600;transition:background .12s}.mtb-frustration-tell:hover{background:var(--mtb-brand-hover)}.mtb-frustration-tell:active{background:var(--mtb-brand-active)}.mtb-frustration-dismiss{height:28px;padding:0 8px;border:none;border-radius:7px;background:transparent;color:var(--mtb-dismiss-fg);cursor:pointer;font-family:inherit;font-size:12px;transition:color .12s}.mtb-frustration-dismiss:hover{color:var(--mtb-dismiss-hover-fg)}.mtb-record-bar{position:fixed;bottom:48px;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:#dc2626;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:var(--mtb-brand-primary);color:var(--mtb-brand-on-primary);cursor:pointer;font-family:inherit;font-size:12px;font-weight:600;transition:background .12s}.mtb-record-stop:hover{background:var(--mtb-brand-hover)}.mtb-record-stop:active{background:var(--mtb-brand-active)}.mtb-click-ripple{position:fixed;z-index:2147483644;width:24px;height:24px;border-radius:50%;border:2px solid var(--mtb-brand-emphasis);background:rgba(var(--mtb-brand-emphasis-rgb),.25);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}}@keyframes mtbDot{0%,80%,to{opacity:.3;transform:translateY(0)}40%{opacity:1;transform:translateY(-3px)}}.mtb-clarify-retry{flex:1;height:30px;display:inline-flex;align-items:center;justify-content:center;gap:5px;border:none;border-radius:8px;background:var(--mtb-brand-primary);color:var(--mtb-brand-on-primary);cursor:pointer;font-family:inherit;font-size:12px;font-weight:600;transition:background .12s}.mtb-clarify-retry:not(:disabled):hover{background:var(--mtb-brand-hover)}.mtb-clarify-retry:not(:disabled):active{background:var(--mtb-brand-active)}.mtb-clarify-retry:disabled{background:#00000026;cursor:not-allowed}@keyframes mtbSpin{to{transform:rotate(360deg)}}.mtb-dim-clickable{z-index:2147483643;pointer-events:auto;cursor:default;background:#0000001f}.mtb-draw-bar{position:fixed;bottom:48px;left:50%;transform:translate(-50%);z-index:2147483647;display:flex;align-items:center;gap:8px;height:46px;padding:0 8px 0 12px;border-radius:13px;background:#fff;border:1px solid rgba(0,0,0,.08);box-shadow:0 10px 30px #0f172a38;animation:mtbBarIn .2s ease;font-family:Inter,-apple-system,BlinkMacSystemFont,sans-serif}.mtb-draw-input{width:220px;height:32px;padding:0 10px;border:1px solid rgba(0,0,0,.12);border-radius:8px;font-family:inherit;font-size:13px;color:#191a1c;outline:none;background:#fafafa;transition:border-color .12s,box-shadow .12s,background .12s}.mtb-draw-input:focus{border-color:var(--mtb-brand-emphasis);box-shadow:0 0 0 3px rgba(var(--mtb-brand-emphasis-rgb),.15);background:#fff}.mtb-draw-input::placeholder{color:#00000057}.mtb-draw-icon-btn{width:30px;height:30px;display:inline-flex;align-items:center;justify-content:center;border:none;border-radius:8px;background:transparent;color:#374151;cursor:pointer;transition:background .12s,color .12s}.mtb-draw-icon-btn:hover:not(:disabled){background:#0000000f}.mtb-draw-icon-btn:disabled{color:#00000038;cursor:default}.mtb-draw-shot{display:inline-flex;align-items:center;gap:6px;font-size:12.5px;color:#0000008c;white-space:nowrap;cursor:default;user-select:none}.mtb-draw-shot input{width:14px;height:14px;margin:0;accent-color:var(--mtb-brand-primary);cursor:default}.mtb-draw-sep{width:1px;height:22px;background:#0000001a}.mtb-draw-cancel{height:32px;padding:0 12px;border:1px solid rgba(0,0,0,.12);border-radius:8px;background:#fff;color:#0000008c;cursor:pointer;font-family:inherit;font-size:12.5px;font-weight:550;transition:background .12s}.mtb-draw-cancel:hover{background:#0000000a}.mtb-draw-submit{height:32px;padding:0 14px;border:none;border-radius:8px;background:var(--mtb-brand-primary);color:var(--mtb-brand-on-primary);cursor:pointer;font-family:inherit;font-size:12.5px;font-weight:600;transition:background .12s}.mtb-draw-submit:hover:not(:disabled){background:var(--mtb-brand-hover)}.mtb-draw-submit:active:not(:disabled){background:var(--mtb-brand-active)}.mtb-draw-submit:disabled{opacity:.6;cursor:default}.mtb-record-preview{margin-bottom:12px}.mtb-record-preview-stage{position:relative;width:100%;height:132px;border-radius:10px;overflow:hidden;background:#0f172a;display:flex;align-items:center;justify-content:center}.mtb-record-preview-stage.playing{align-items:flex-start;justify-content:flex-start}.mtb-record-preview-play{width:44px;height:44px;border-radius:50%;border:none;background:#ffffffeb;color:var(--mtb-brand-primary);display:inline-flex;align-items:center;justify-content:center;cursor:pointer;transition:transform .12s,background .12s}.mtb-record-preview-play:hover:not(:disabled){transform:scale(1.06);background:#fff}.mtb-record-preview-play:disabled{cursor:default;opacity:.6}.mtb-record-preview-badge{position:absolute;right:8px;bottom:8px;padding:2px 7px;border-radius:6px;background:#0009;color:#fff;font-size:11px;font-variant-numeric:tabular-nums;font-family:JetBrains Mono,SF Mono,monospace}.mtb-record-preview-fallback{color:#ffffffd9;font-size:12px}.mtb-record-preview-name{display:block;margin-top:5px;font-size:11px;color:#0000006b}@media (pointer: coarse){.mtb-tab:after{content:"";position:absolute;inset:-6px 0 -6px -12px}.mtb-tab.left:after{inset:-6px -12px -6px 0}.mtb-toolbar{min-height:56px;border-radius:16px}.mtb-toolbar-mode-btn,.mtb-exit-btn{min-height:44px}.mtb-chat-input,.mtb-chat-email-input,.mtb-draw-input{font-size:16px}}@media (max-width: 480px){.mtb-tab{width:36px;height:40px;padding:0;font-size:0;writing-mode:horizontal-tb;border-radius:12px 0 0 12px;right:env(safe-area-inset-right,0px)}.mtb-tab.left{left:env(safe-area-inset-left,0px);border-radius:0 12px 12px 0}.mtb-tab:before{content:"";width:18px;height:18px;background:currentColor;-webkit-mask:var(--mtb-tab-icon) center / contain no-repeat;mask:var(--mtb-tab-icon) center / contain no-repeat}.mtb-toolbar{inset:0 0 auto;width:100%;max-width:none;max-height:none;transform:none;flex-direction:row;align-items:center;border-radius:0;gap:8px;justify-content:center;padding:env(safe-area-inset-top,0px) 8px 0;height:calc(44px + env(safe-area-inset-top,0px));min-height:calc(44px + env(safe-area-inset-top,0px));border-bottom:1px solid rgba(60,60,67,.16);background:#f8f8f8f5;box-shadow:0 1px 3px #00000014;-webkit-backdrop-filter:blur(18px);backdrop-filter:blur(18px);animation:none}.mtb-toolbar-modes{flex-direction:row;gap:0;padding:2px;background:#7676801f;border-radius:8px}.mtb-toolbar-sep{display:none}.mtb-hint-bar{top:calc(44px + env(safe-area-inset-top,0px));right:0;bottom:0;left:0;transform:none;justify-content:center;height:auto;padding:0 24px;border-radius:0;background:#0000001a;box-shadow:none;animation:none;white-space:normal;text-align:center;transition:none}.mtb-hint-bar .mtb-toolbar-hint{max-width:280px;color:#fffffff5;font-size:17px;font-weight:600;line-height:1.4;letter-spacing:0;white-space:normal;text-shadow:0 1px 3px rgba(0,0,0,.45)}.mtb-toolbar-mode-btn,.mtb-exit-btn{position:relative;width:auto;height:32px;min-height:32px;gap:6px;border-radius:6px;padding-right:8px;padding-left:8px;color:#3c3c43d1;transition:none}.mtb-toolbar-mode-btn:hover{background:transparent;color:#3c3c43d1}.mtb-toolbar-mode-btn.active,.mtb-toolbar-mode-btn.active:hover{background:var(--mtb-brand-on-primary);color:var(--mtb-brand-hover);box-shadow:0 1px 3px #0000001f}.mtb-toolbar-mode-btn:after,.mtb-exit-btn:after{content:"";position:absolute;inset:-6px 0}.mtb-exit-btn{width:32px;padding:0;border-radius:50%;background:#7676801f}.mtb-exit-btn:hover{background:#7676801f;color:#3c3c43d1}.mtb-toolbar-label{display:inline}.mtb-exit-btn .mtb-toolbar-label{display:none}.mtb-draw-bar{left:0;right:0;bottom:0;transform:none;height:auto;padding:10px 12px calc(10px + env(safe-area-inset-bottom,0px));border-radius:16px 16px 0 0}.mtb-frustration-prompt{left:0;right:0;bottom:0;flex-direction:column;align-items:stretch;gap:12px;padding:16px 16px calc(16px + env(safe-area-inset-bottom,0px));border-radius:16px 16px 0 0;border-width:1px 0 0;animation:none}.mtb-frustration-actions{display:flex;gap:8px}.mtb-frustration-tell,.mtb-frustration-dismiss{flex:1;min-height:44px}.mtb-chat{position:fixed;left:0!important;right:0;bottom:0;top:auto!important;width:100%;max-width:none;max-height:85vh;border-radius:20px 20px 0 0;box-shadow:0 -18px 60px #0003;animation:none}.mtb-chat-handle{width:36px;height:4px;border-radius:99px;background:#0000001f;margin:0 auto;flex-shrink:0}.mtb-chat-header{flex-direction:column;align-items:center;gap:8px;border-radius:20px 20px 0 0;padding:10px 16px 12px}.mtb-chat-header-row{width:100%;display:flex;align-items:center}.mtb-chat-messages,.mtb-chat-quick-replies{padding:14px 16px 12px}.mtb-chat-qr{padding:8px 13px}.mtb-chat-suggestions{padding-left:45px}.mtb-chat-sg{padding:8px 13px;font-size:12px}.mtb-chat-composer{padding:10px 12px calc(10px + env(safe-area-inset-bottom,12px))}.mtb-chat-success{padding:30px 20px}.mtb-chat-success-simple{padding-top:36px;padding-bottom:calc(44px + env(safe-area-inset-bottom,0px))}.mtb-chat-email-card{margin-top:12px;padding:12px;gap:8px}}:host([data-mtb-theme="dark"]) .mtb-chat-handle{background:#fff3}@media (prefers-color-scheme: dark){:host([data-mtb-theme="auto"]) .mtb-chat-handle{background:#fff3}}@media (max-width: 480px){:host([data-mtb-theme="dark"]) .mtb-chat{box-shadow:0 -18px 60px #0000008c}}@media (max-width: 480px) and (prefers-color-scheme: dark){:host([data-mtb-theme="auto"]) .mtb-chat{box-shadow:0 -18px 60px #0000008c}}.mtb-chat-handle{display:none}@media (max-width: 480px){.mtb-chat-handle{display:block}}`,x="mtb-widget-host";function C(e){const t=document.getElementById(x);return t?t===e||t.contains(e):!1}function K(e,t){return document.elementsFromPoint?.(e,t).find(i=>i.id!==x)??null}function d(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}function ft(e){return e.isComposing||e.keyCode===229}const ti=/^(script|style|noscript|template)$/i;function $t(e,t=80){let i="";for(const r of Array.from(e.childNodes)){if(i.length>=t)break;r.nodeType===3?i+=r.nodeValue??"":r instanceof Element&&!ti.test(r.tagName)&&(i+=$t(r,t-i.length))}return i}function gt(e){if(e instanceof HTMLElement){const t=e.getAttribute("aria-label");if(t)return t;const i=e.getAttribute("title");if(i)return i;const r=$t(e).trim().slice(0,40);if(r)return r;const n=e.placeholder;if(n)return n;const s=e.alt;if(s)return s;const a=e.getAttribute("data-mark");if(a)return a}return e.tagName.toLowerCase()}function Ut(e){const t=[];let i=e;for(;i&&i!==document.body&&t.length<5;){let r=i.tagName.toLowerCase();if(i.id){r=`#${i.id}`,t.unshift(r);break}const n=Array.from(i.classList).filter(a=>!a.startsWith("mtb-")).slice(0,2).join(".");n&&(r+=`.${n}`);const s=i.parentElement;if(s){const a=Array.from(s.children).filter(o=>o.tagName===i.tagName);if(a.length>1){const o=a.indexOf(i)+1;r+=`:nth-of-type(${o})`}}t.unshift(r),i=i.parentElement}return t.join(" > ")}const Y=class Y{constructor(t="auto",i){this.stopHostInteraction=s=>{s.stopPropagation()};const r=document.getElementById(x);if(this.ownsHost=!r,this.host=r??document.createElement("div"),this.root=this.host.shadowRoot??this.host.attachShadow({mode:"open"}),this.root.replaceChildren(),this.originalInlineStyle=this.host.getAttribute("style"),this.originalTheme=this.host.getAttribute("data-mtb-theme"),this.host.id=x,this.host.style.cssText="position:fixed;top:0;left:0;width:0;height:0;overflow:visible;z-index:2147483646;",i){const s=[1,3,5].map(o=>parseInt(i.primary.slice(o,o+2),16)),a=[1,3,5].map(o=>parseInt(i.onPrimary.slice(o,o+2),16));this.host.style.setProperty("--mtb-brand-primary",i.primary.toLowerCase()),this.host.style.setProperty("--mtb-brand-hover",i.hover.toLowerCase()),this.host.style.setProperty("--mtb-brand-active",i.active.toLowerCase()),this.host.style.setProperty("--mtb-brand-on-primary",i.onPrimary.toLowerCase()),this.host.style.setProperty("--mtb-brand-rgb",s.join(", ")),this.host.style.setProperty("--mtb-brand-on-primary-rgb",a.join(", ")),this.host.style.setProperty("--mtb-brand-emphasis",i.primary.toLowerCase()),this.host.style.setProperty("--mtb-brand-emphasis-rgb",s.join(", ")),this.host.style.setProperty("--mtb-brand-gradient-start",i.primary.toLowerCase()),this.host.style.setProperty("--mtb-brand-gradient-end",i.hover.toLowerCase())}this.host.setAttribute("data-mtb-theme",t),this.ownsHost&&document.body.appendChild(this.host);for(const s of Y.HOST_INTERACTION_EVENTS)this.root.addEventListener(s,this.stopHostInteraction);const n=document.createElement("style");n.textContent=Qe,this.root.appendChild(n)}el(t,i){const r=document.createElement(t);return i&&(r.className=i),r}append(...t){for(const i of t)this.root.appendChild(i)}remove(...t){for(const i of t)i.parentNode===this.root&&this.root.removeChild(i)}destroy(){for(const t of Y.HOST_INTERACTION_EVENTS)this.root.removeEventListener(t,this.stopHostInteraction);if(!this.ownsHost){this.root.replaceChildren(),this.host.removeAttribute("data-mtb-toolbar"),this.originalInlineStyle===null?this.host.removeAttribute("style"):this.host.setAttribute("style",this.originalInlineStyle),this.originalTheme===null?this.host.removeAttribute("data-mtb-theme"):this.host.setAttribute("data-mtb-theme",this.originalTheme);return}this.host.remove()}};Y.HOST_INTERACTION_EVENTS=["pointerdown","pointerup","pointercancel","mousedown","mouseup","touchstart","touchend","touchcancel","click"];let wt=Y;class ei{constructor(t,i,r,n,s){this.active=!1,this.preserveHostFocus=a=>{a.preventDefault()},this.onClick=n,this.customText=s,this.el=t.el("button","mtb-tab"),r==="left"&&this.el.classList.add("left"),this.idleLabel=s??i.tab,this.activeLabel=i.toolbar.exit,this.setLabel(this.idleLabel),this.el.addEventListener("mousedown",this.preserveHostFocus),this.el.addEventListener("click",n),t.append(this.el)}setLabel(t){this.el.textContent=t,this.el.setAttribute("aria-label",t)}setMessages(t){this.idleLabel=this.customText??t.tab,this.activeLabel=t.toolbar.exit,this.setLabel(this.active?this.activeLabel:this.idleLabel)}setActive(t){this.active=t,this.el.classList.toggle("active",t),this.setLabel(t?this.activeLabel:this.idleLabel)}destroy(){this.el.removeEventListener("mousedown",this.preserveHostFocus),this.el.removeEventListener("click",this.onClick),this.el.remove()}}const ii=8e3;class ri{constructor(t,i,r){this.autoHideTimer=null,this.el=t.el("div","mtb-frustration-prompt"),this.el.innerHTML=`
2
2
  <div class="mtb-frustration-icon">&#9888;&#65039;</div>
3
- <span class="mtb-frustration-text">${d(r.frustration.prompt)}</span>
3
+ <span class="mtb-frustration-text">${d(i.frustration.prompt)}</span>
4
4
  <div class="mtb-frustration-actions">
5
- <button class="mtb-frustration-tell">${d(r.frustration.action)}</button>
6
- <button class="mtb-frustration-dismiss">${d(r.frustration.dismiss)}</button>
5
+ <button class="mtb-frustration-tell">${d(i.frustration.action)}</button>
6
+ <button class="mtb-frustration-dismiss">${d(i.frustration.dismiss)}</button>
7
7
  </div>
8
- `,this.el.querySelector(".mtb-frustration-tell").addEventListener("click",i.onTell),this.el.querySelector(".mtb-frustration-dismiss").addEventListener("click",i.onDismiss),t.append(this.el),this.autoHideTimer=setTimeout(i.onAutoHide,rr)}destroy(){this.autoHideTimer&&(clearTimeout(this.autoHideTimer),this.autoHideTimer=null),this.el.remove()}}const nr=400;class zt{constructor(t,r,i=()=>Date.now()){this.bornAt=Date.now(),this.bornAt=i(),this.onClick=()=>{i()-this.bornAt<nr||r()},this.el=t.el("div","mtb-dim mtb-dim-clickable"),this.el.addEventListener("click",this.onClick),t.append(this.el)}destroy(){this.el.removeEventListener("click",this.onClick),this.el.remove()}}function T(){return window.matchMedia?.("(pointer: coarse)").matches??!1}class sr{constructor(){this.applied=!1,this.previousPadding="",this.previousTransition=""}reserve(t){if(this.applied||t<=0)return;this.applied=!0;const r=document.body.style;this.previousPadding=r.paddingTop,this.previousTransition=r.transition;const i=parseFloat(getComputedStyle(document.body).paddingTop)||0;r.transition="none",r.paddingTop=`${i+t}px`}release(){if(!this.applied)return;this.applied=!1;const t=document.body.style;t.paddingTop=this.previousPadding,t.transition=this.previousTransition}isApplied(){return this.applied}}const jt=["wheel","touchmove"],or=new Set(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","PageUp","PageDown","Home","End"," "]);function ar(e){for(const t of e.composedPath()){if(!(t instanceof Element))continue;const r=getComputedStyle(t);if(/auto|scroll/.test(`${r.overflowY} ${r.overflowX}`)&&(t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth))return!0}return!1}function lr(e,t){const r=e.tagName;return!!(r==="INPUT"||r==="TEXTAREA"||r==="SELECT"||e instanceof HTMLElement&&e.isContentEditable||t===" "&&(r==="BUTTON"||r==="SUMMARY"))}function cr(){const e=r=>{ar(r)||r.cancelable&&r.preventDefault()},t=r=>{if(!(r instanceof KeyboardEvent)||!or.has(r.key))return;const i=r.composedPath()[0];i instanceof Element&&lr(i,r.key)||r.cancelable&&r.preventDefault()};for(const r of jt)window.addEventListener(r,e,{capture:!0,passive:!1});return window.addEventListener("keydown",t,{capture:!0}),{release(){for(const r of jt)window.removeEventListener(r,e,{capture:!0});window.removeEventListener("keydown",t,{capture:!0})}}}const hr=44;class dr{constructor(t,r,i,n,s="right",o=!0){this.currentMode="markup",this.handlePointerMove=a=>{if(a.pointerType!=="mouse")return;const l=this.hintBarEl.getBoundingClientRect(),c=a.clientX>=l.left&&a.clientX<=l.right&&a.clientY>=l.top&&a.clientY<=l.bottom;this.hintBarEl.classList.toggle("mtb-hint-bar--under-pointer",c)},this.touchHintDismissListening=!1,this.dismissTouchHint=()=>{this.hintBarEl.classList.add("mtb-hint-bar--dismissed"),this.stopTouchHintDismissListening()},this.messages=r,this.touch=T(),this.hintBarEl=t.el("div","mtb-hint-bar"),this.hintBarEl.innerHTML=`<span class="mtb-toolbar-hint">${d(this.idleHint())}</span>`,this.touch&&!o&&this.hintBarEl.classList.add("mtb-hint-bar--dismissed"),this.el=t.el("div","mtb-toolbar"),s==="left"&&this.el.classList.add("left"),this.el.innerHTML=this.buildHTML(r),t.append(this.hintBarEl,this.el),this.host=t.host,this.host.setAttribute("data-mtb-toolbar",""),this.hintTextEl=this.hintBarEl.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"),n?.("markup")}),this.recordBtn.addEventListener("click",()=>{this.setMode("record"),n?.("record")}),this.el.querySelector(".mtb-exit-btn").addEventListener("click",i),document.addEventListener("pointermove",this.handlePointerMove),this.touch&&o&&(document.addEventListener("pointerdown",this.dismissTouchHint,!0),this.touchHintDismissListening=!0)}stopTouchHintDismissListening(){this.touchHintDismissListening&&(this.touchHintDismissListening=!1,document.removeEventListener("pointerdown",this.dismissTouchHint,!0))}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),this.autoHideTimer=setTimeout(r.onAutoHide,ii)}destroy(){this.autoHideTimer&&(clearTimeout(this.autoHideTimer),this.autoHideTimer=null),this.el.remove()}}const ni=400;class jt{constructor(t,i,r=()=>Date.now()){this.bornAt=Date.now(),this.bornAt=r(),this.onClick=()=>{r()-this.bornAt<ni||i()},this.el=t.el("div","mtb-dim mtb-dim-clickable"),this.el.addEventListener("click",this.onClick),t.append(this.el)}destroy(){this.el.removeEventListener("click",this.onClick),this.el.remove()}}function T(){return window.matchMedia?.("(pointer: coarse)").matches??!1}class si{constructor(){this.applied=!1,this.previousPadding="",this.previousTransition=""}reserve(t){if(this.applied||t<=0)return;this.applied=!0;const i=document.body.style;this.previousPadding=i.paddingTop,this.previousTransition=i.transition;const r=parseFloat(getComputedStyle(document.body).paddingTop)||0;i.transition="none",i.paddingTop=`${r+t}px`}release(){if(!this.applied)return;this.applied=!1;const t=document.body.style;t.paddingTop=this.previousPadding,t.transition=this.previousTransition}isApplied(){return this.applied}}const qt=["wheel","touchmove"],ai=new Set(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","PageUp","PageDown","Home","End"," "]);function oi(e){for(const t of e.composedPath()){if(!(t instanceof Element))continue;const i=getComputedStyle(t);if(/auto|scroll/.test(`${i.overflowY} ${i.overflowX}`)&&(t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth))return!0}return!1}function li(e,t){const i=e.tagName;return!!(i==="INPUT"||i==="TEXTAREA"||i==="SELECT"||e instanceof HTMLElement&&e.isContentEditable||t===" "&&(i==="BUTTON"||i==="SUMMARY"))}function ci(){const e=i=>{oi(i)||i.cancelable&&i.preventDefault()},t=i=>{if(!(i instanceof KeyboardEvent)||!ai.has(i.key))return;const r=i.composedPath()[0];r instanceof Element&&li(r,i.key)||i.cancelable&&i.preventDefault()};for(const i of qt)window.addEventListener(i,e,{capture:!0,passive:!1});return window.addEventListener("keydown",t,{capture:!0}),{release(){for(const i of qt)window.removeEventListener(i,e,{capture:!0});window.removeEventListener("keydown",t,{capture:!0})}}}const hi=44;class di{constructor(t,i,r,n,s="right",a=!0){this.currentMode="markup",this.handlePointerMove=o=>{if(o.pointerType!=="mouse")return;const l=this.hintBarEl.getBoundingClientRect(),c=o.clientX>=l.left&&o.clientX<=l.right&&o.clientY>=l.top&&o.clientY<=l.bottom;this.hintBarEl.classList.toggle("mtb-hint-bar--under-pointer",c)},this.touchHintDismissListening=!1,this.dismissTouchHint=()=>{this.hintBarEl.classList.add("mtb-hint-bar--dismissed"),this.stopTouchHintDismissListening()},this.messages=i,this.touch=T(),this.hintBarEl=t.el("div","mtb-hint-bar"),this.hintBarEl.innerHTML=`<span class="mtb-toolbar-hint">${d(this.idleHint())}</span>`,this.touch&&!a&&this.hintBarEl.classList.add("mtb-hint-bar--dismissed"),this.el=t.el("div","mtb-toolbar"),s==="left"&&this.el.classList.add("left"),this.el.innerHTML=this.buildHTML(i),t.append(this.hintBarEl,this.el),this.host=t.host,this.host.setAttribute("data-mtb-toolbar",""),this.hintTextEl=this.hintBarEl.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"),n?.("markup")}),this.recordBtn.addEventListener("click",()=>{this.setMode("record"),n?.("record")}),this.el.querySelector(".mtb-exit-btn").addEventListener("click",r),document.addEventListener("pointermove",this.handlePointerMove),this.touch&&a&&(document.addEventListener("pointerdown",this.dismissTouchHint,!0),this.touchHintDismissListening=!0)}stopTouchHintDismissListening(){this.touchHintDismissListening&&(this.touchHintDismissListening=!1,document.removeEventListener("pointerdown",this.dismissTouchHint,!0))}buildHTML(t){return`
9
9
  <div class="mtb-toolbar-modes">
10
10
  <button class="mtb-toolbar-mode-btn mtb-toolbar-mode-markup active" aria-label="${d(t.toolbar.markup)}" title="${d(t.toolbar.markup)}">
11
11
  <svg width="16" height="16" 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><span class="mtb-toolbar-label">${d(t.toolbar.markup)}</span>
@@ -20,7 +20,7 @@ var MakeThisBetter=function(){"use strict";const Qe=`*,*:before,*:after{box-sizi
20
20
  <path d="M18 6L6 18M6 6l12 12"/>
21
21
  </svg><span class="mtb-toolbar-label">${d(t.toolbar.exit)}</span>
22
22
  </button>
23
- `}idleHint(){return this.touch?this.messages.toolbar.hintTouch:this.messages.toolbar.hint}setMode(t){this.currentMode=t,t==="markup"?(this.markupBtn.classList.add("active"),this.recordBtn.classList.remove("active"),this.hintTextEl.textContent=this.idleHint()):(this.markupBtn.classList.remove("active"),this.recordBtn.classList.add("active"),this.hintTextEl.textContent=this.messages.toolbar.hintRecord)}getMode(){return this.currentMode}height(){return this.el.getBoundingClientRect().height||hr}destroy(){document.removeEventListener("pointermove",this.handlePointerMove),this.stopTouchHintDismissListening(),this.host.removeAttribute("data-mtb-toolbar"),this.hintBarEl.remove(),this.el.remove()}}class ur{constructor(t,r){this.handlers=r,this.overlayEl=t.el("div","mtb-overlay"),this.onPointerDown=i=>{const n=i;if(n.isPrimary){try{this.overlayEl.setPointerCapture(n.pointerId)}catch{}this.handlers.onPointerDown(n)}},this.onPointerMove=i=>{const n=i;n.isPrimary&&this.handlers.onPointerMove(n)},this.onPointerUp=i=>{const n=i;n.isPrimary&&(this.releaseCapture(n.pointerId),this.handlers.onPointerUp(n))},this.onPointerCancel=i=>{const n=i;n.isPrimary&&(this.releaseCapture(n.pointerId),this.handlers.onPointerCancel(n))},this.overlayEl.addEventListener("pointerdown",this.onPointerDown),this.overlayEl.addEventListener("pointermove",this.onPointerMove),this.overlayEl.addEventListener("pointerup",this.onPointerUp),this.overlayEl.addEventListener("pointercancel",this.onPointerCancel),t.append(this.overlayEl),this.dimEl=t.el("div","mtb-dim"),t.append(this.dimEl)}releaseCapture(t){try{this.overlayEl.releasePointerCapture(t)}catch{}}destroy(){this.overlayEl.removeEventListener("pointerdown",this.onPointerDown),this.overlayEl.removeEventListener("pointermove",this.onPointerMove),this.overlayEl.removeEventListener("pointerup",this.onPointerUp),this.overlayEl.removeEventListener("pointercancel",this.onPointerCancel),this.overlayEl.remove(),this.dimEl.remove()}}class mr{constructor(t){this.highlightEl=t.el("div","mtb-highlight"),this.tooltipEl=t.el("div","mtb-highlight-tooltip"),this.hide(),t.append(this.highlightEl,this.tooltipEl)}highlight(t){const r=t.getBoundingClientRect();this.highlightEl.style.top=`${r.top-2}px`,this.highlightEl.style.left=`${r.left-2}px`,this.highlightEl.style.width=`${r.width+4}px`,this.highlightEl.style.height=`${r.height+4}px`,this.highlightEl.style.display="block",this.showTooltip(t,r)}showTooltip(t,r){this.tooltipEl.textContent=ft(t);const i=r.top<30;this.tooltipEl.classList.toggle("below",i),this.tooltipEl.style.left=`${r.left+r.width/2}px`,this.tooltipEl.style.top=i?`${r.bottom+8}px`:`${r.top-8}px`,this.tooltipEl.style.display="block"}select(){this.highlightEl.classList.add("selected"),this.tooltipEl.style.display="none"}hide(){this.highlightEl.style.display="none",this.highlightEl.classList.remove("selected"),this.tooltipEl.style.display="none"}destroy(){this.highlightEl.remove(),this.tooltipEl.remove()}}function br(e,t,r){return{left:e.left,top:e.top,scaleX:t/e.width,scaleY:r/e.height}}function J(e,t){return(t-e.left)*e.scaleX}function Z(e,t){return(t-e.top)*e.scaleY}function pr(e,t){return{left:J(e,t.left),top:Z(e,t.top),width:t.width*e.scaleX,height:t.height*e.scaleY}}function fr(){return{left:0,top:0,width:window.innerWidth,height:window.innerHeight}}function gr(e,t){return{x:e.x-t.x,y:e.y-t.y}}function D(e){let t=0,r=0,i=e;for(;i&&i!==document.body;)i instanceof HTMLElement&&(t+=i.scrollLeft,r+=i.scrollTop),i=qt(i);return{x:t,y:r}}function qt(e){if(e.parentElement)return e.parentElement;const t=e.getRootNode();return t instanceof ShadowRoot?t.host:null}function Wt(e){const t=D(e);return{x:t.x+window.scrollX,y:t.y+window.scrollY}}class yr{constructor(t){this.pins=[],this.shadow=t}addPin(t,r){const i=this.shadow.el("div","mtb-pin");i.style.top=`${r}px`,i.style.left=`${t}px`,this.shadow.append(i),this.pins.push(i)}clearAll(){for(const t of this.pins)t.remove();this.pins=[]}destroy(){this.clearAll()}}const Vt="#059669",M={color:"var(--mtb-brand-primary)",width:"3.5",linecap:"round",linejoin:"round",filter:"drop-shadow(0 0 1px rgba(255, 255, 255, 0.95)) drop-shadow(0 1px 2px rgba(15, 23, 42, 0.72))"};class wr{constructor(t){this.currentPath=null,this.currentPoints=[],this.currentAnchor=vr(),this.isDrawing=!1,this.committed=[],this.redoStack=[],this.svg=document.createElementNS("http://www.w3.org/2000/svg","svg"),this.svg.setAttribute("class","mtb-draw-svg"),t.append(this.svg)}startDraw(t,r){this.isDrawing=!0,this.currentPoints=[[t,r]],this.currentAnchor=xr(t,r),this.currentPath=this.createPath(),this.svg.appendChild(this.currentPath)}continueDraw(t,r){!this.isDrawing||!this.currentPath||(this.currentPoints.push([t,r]),this.currentPath.setAttribute("d",yt(this.currentPoints)))}getCurrentSpan(){const[t]=this.currentPoints;if(!t)return 0;let r=0;for(const[i,n]of this.currentPoints)r=Math.max(r,Math.hypot(i-t[0],n-t[1]));return r}commitStroke(){return!this.isDrawing||!this.currentPath?!1:(this.isDrawing=!1,this.committed.push({path:this.currentPath,d:yt(this.currentPoints),points:this.currentPoints,anchor:this.currentAnchor}),this.redoStack=[],this.currentPath=null,this.currentPoints=[],!0)}cancelCurrentDraw(){this.currentPath?.remove(),this.currentPath=null,this.isDrawing=!1,this.currentPoints=[]}undo(){const t=this.committed.pop();return t?(t.path.remove(),this.redoStack.push({d:t.d,points:t.points,anchor:t.anchor}),!0):!1}redo(){const t=this.redoStack.pop();if(!t)return!1;const r=this.createPath();return r.setAttribute("d",t.d),this.svg.appendChild(r),this.committed.push({path:r,d:t.d,points:t.points,anchor:t.anchor}),!0}canUndo(){return this.committed.length>0}canRedo(){return this.redoStack.length>0}hasStrokes(){return this.committed.length>0}getAnnotation(){const[t]=this.committed;if(!t)return null;const r=this.committed.map(s=>kr(s.points,{x:s.anchor.offset.x-t.anchor.offset.x,y:s.anchor.offset.y-t.anchor.offset.y})),[i,n]=Er(r.flat());return{type:"draw",x:i,y:n,drawPath:r.map(yt).join(" "),captureOffsetX:t.anchor.offset.x,captureOffsetY:t.anchor.offset.y}}viewportDrift(){const[t]=this.committed;return t?{x:window.scrollX-t.anchor.pageScroll.x,y:window.scrollY-t.anchor.pageScroll.y}:{x:0,y:0}}clearAll(){for(;this.svg.firstChild;)this.svg.removeChild(this.svg.firstChild);this.currentPath=null,this.isDrawing=!1,this.currentPoints=[],this.committed=[],this.redoStack=[]}isCurrentlyDrawing(){return this.isDrawing}destroy(){this.svg.remove()}createPath(){const t=document.createElementNS("http://www.w3.org/2000/svg","path");return t.setAttribute("fill","none"),t.setAttribute("stroke",M.color),t.setAttribute("stroke-width",M.width),t.setAttribute("stroke-linecap",M.linecap),t.setAttribute("stroke-linejoin",M.linejoin),t.setAttribute("style",`filter:${M.filter}`),t}}function yt(e){if(e.length===0)return"";const[t,r]=e[0];let i=`M ${t} ${r}`;for(let n=1;n<e.length;n++){const[s,o]=e[n];i+=` L ${s} ${o}`}return i}function vr(){return{offset:{x:0,y:0},pageScroll:{x:0,y:0}}}function xr(e,t){const r={x:window.scrollX,y:window.scrollY},i=D(G(e,t));return{offset:{x:i.x+r.x,y:i.y+r.y},pageScroll:r}}function kr(e,t){return t.x===0&&t.y===0?e:e.map(([r,i])=>[r+t.x,i+t.y])}function Er(e){const t=e.map(s=>s[0]),r=e.map(s=>s[1]),i=(Math.min(...t)+Math.max(...t))/2,n=(Math.min(...r)+Math.max(...r))/2;return[i,n]}const Q="rr-block",I="rr-mask",Sr=`.${Q}, .${I}`;function tt(e){return e.closest(Sr)!==null}function wt(e){const t=e.getAttribute("role")?.trim().split(/\s+/)[0];return t&&/^[a-z][a-z0-9-]*$/i.test(t)?t:e.tagName.toLowerCase()}function Yt(e){return e.tagName.toLowerCase()}const Cr=10;function Xt(e){return tt(e)?{name:wt(e),text:"",selector:Yt(e)}:{name:ft(e),text:e.textContent?.trim().slice(0,200)??"",selector:Ut(e)}}class Tr{constructor(t,r,i){this.messages=r,this.handlers=i,this.interactionActive=!0,this.pendingHighlightFrame=null,this.lastMoveX=0,this.lastMoveY=0,this.touch=T(),this.highlighter=new mr(t),this.pinMarker=new yr(t),this.drawLayer=new wr(t),this.overlay=new ur(t,{onPointerDown:n=>this.handlePointerDown(n),onPointerMove:n=>this.handlePointerMove(n),onPointerUp:n=>this.handlePointerUp(n),onPointerCancel:()=>{this.drawLayer.isCurrentlyDrawing()&&this.finishStroke(),this.cancelPendingHighlight(),this.highlighter.hide()}})}handlePointerDown(t){t.preventDefault(),this.drawLayer.startDraw(t.clientX,t.clientY)}handlePointerMove(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()||this.drawSessionActive())return;const t=G(this.lastMoveX,this.lastMoveY);t?this.highlighter.highlight(t):this.highlighter.hide()}cancelPendingHighlight(){this.pendingHighlightFrame!==null&&(cancelAnimationFrame(this.pendingHighlightFrame),this.pendingHighlightFrame=null)}handlePointerUp(t){this.drawLayer.isCurrentlyDrawing()&&this.finishStroke(t)}finishStroke(t){if(this.drawLayer.getCurrentSpan()>=Cr){this.drawLayer.commitStroke(),this.highlighter.hide(),this.handlers.onDrawStroke();return}if(this.drawLayer.cancelCurrentDraw(),this.touch||this.drawLayer.hasStrokes()||!t)return;const r=G(t.clientX,t.clientY),i=r?Xt(r):null,n=i?.name??this.messages.annotation.element,s=r?.getBoundingClientRect(),o=Wt(r),a={type:"pin",x:t.clientX,y:t.clientY,targetSelector:i?.selector,targetText:i?.text??"",targetName:n,targetRect:s?{top:s.top,left:s.left,width:s.width,height:s.height,bottom:s.bottom}:void 0,captureOffsetX:o.x,captureOffsetY:o.y};this.pinMarker.addPin(t.clientX,t.clientY),this.highlighter.select(),this.handlers.onPin(a,n)}undoDraw(){this.drawLayer.undo()}redoDraw(){this.drawLayer.redo()}canUndoDraw(){return this.drawLayer.canUndo()}canRedoDraw(){return this.drawLayer.canRedo()}hasDrawStrokes(){return this.drawLayer.hasStrokes()}drawSessionActive(){return this.drawLayer.hasStrokes()||this.drawLayer.canRedo()}getDrawAnnotation(){const t=this.drawLayer.getAnnotation();if(!t)return null;const r=this.drawLayer.viewportDrift(),i=G(t.x-r.x,t.y-r.y);if(!i)return t;const n=i.getBoundingClientRect(),s=Wt(i),o=s.x-(t.captureOffsetX??0),a=s.y-(t.captureOffsetY??0),l=Xt(i);return{...t,targetSelector:l.selector,targetText:l.text,targetName:l.name,targetRect:{top:n.top+a,left:n.left+o,width:n.width,height:n.height,bottom:n.bottom+a}}}clearDraw(){this.drawLayer.clearAll()}dismissInteraction(){this.interactionActive&&(this.interactionActive=!1,this.cancelPendingHighlight(),this.overlay.destroy())}hideHighlight(){this.highlighter.hide()}destroy(){this.dismissInteraction(),this.highlighter.destroy(),this.pinMarker.destroy(),this.drawLayer.destroy()}}const _r=140;class Ar{constructor(){this.onChange=null,this.timer=null,this.lastReading=null,this.handler=()=>{this.timer!==null&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=null;const t=this.current();if(t===this.lastReading){this.lastReading=null,this.onChange?.(t);return}this.lastReading=t,this.handler()},_r)}}current(){const t=window.visualViewport;if(!t||t.height<=0)return 0;const r=Math.round(window.innerHeight-(t.height+t.offsetTop));return Math.min(Math.max(0,r),window.innerHeight)}observe(t){const r=window.visualViewport;r&&(this.onChange=t,r.addEventListener("resize",this.handler),r.addEventListener("scroll",this.handler))}stop(){const t=window.visualViewport;this.onChange=null,this.lastReading=null,this.timer!==null&&(clearTimeout(this.timer),this.timer=null),t&&(t.removeEventListener("resize",this.handler),t.removeEventListener("scroll",this.handler))}}const Lr=480;function Pr(){return window.innerWidth<=Lr}class Kt{constructor(t){this.el=t,this.inset=new Ar}apply(){return Pr()?(this.el.style.left="",this.el.style.top="",this.el.style.maxHeight="",this.lift(this.inset.current()),this.inset.observe(t=>this.lift(t)),!0):!1}release(){this.inset.stop()}lift(t){const r=Math.max(0,window.innerHeight-this.el.offsetHeight),i=Math.min(t,r);this.el.style.bottom=i>0?`${i}px`:""}}class Rr{constructor(t,r){this.onSubmit=r.onSubmit,this.submitLabel=r.messages.draw.submit,this.messages=r.messages,this.el=t.el("div","mtb-draw-bar"),this.el.innerHTML=this.buildHTML(r.messages),t.append(this.el),this.sheet=new Kt(this.el),this.sheet.apply(),this.input=this.el.querySelector(".mtb-draw-input"),this.undoBtn=this.el.querySelector(".mtb-draw-undo"),this.redoBtn=this.el.querySelector(".mtb-draw-redo"),this.submitBtn=this.el.querySelector(".mtb-draw-submit"),this.undoBtn.addEventListener("click",r.onUndo),this.redoBtn.addEventListener("click",r.onRedo),this.el.querySelector(".mtb-draw-cancel").addEventListener("click",r.onCancel),this.submitBtn.addEventListener("click",()=>this.submit()),r.onActivity&&this.input.addEventListener("input",r.onActivity),this.input.addEventListener("keydown",i=>{pt(i)||i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),this.submit())}),this.input.focus({preventScroll:!0})}buildHTML(t){return`
23
+ `}idleHint(){return this.touch?this.messages.toolbar.hintTouch:this.messages.toolbar.hint}setMode(t){this.currentMode=t,t==="markup"?(this.markupBtn.classList.add("active"),this.recordBtn.classList.remove("active"),this.hintTextEl.textContent=this.idleHint()):(this.markupBtn.classList.remove("active"),this.recordBtn.classList.add("active"),this.hintTextEl.textContent=this.messages.toolbar.hintRecord)}getMode(){return this.currentMode}height(){return this.el.getBoundingClientRect().height||hi}destroy(){document.removeEventListener("pointermove",this.handlePointerMove),this.stopTouchHintDismissListening(),this.host.removeAttribute("data-mtb-toolbar"),this.hintBarEl.remove(),this.el.remove()}}class ui{constructor(t,i){this.handlers=i,this.overlayEl=t.el("div","mtb-overlay"),this.onPointerDown=r=>{const n=r;if(n.isPrimary){try{this.overlayEl.setPointerCapture(n.pointerId)}catch{}this.handlers.onPointerDown(n)}},this.onPointerMove=r=>{const n=r;n.isPrimary&&this.handlers.onPointerMove(n)},this.onPointerUp=r=>{const n=r;n.isPrimary&&(this.releaseCapture(n.pointerId),this.handlers.onPointerUp(n))},this.onPointerCancel=r=>{const n=r;n.isPrimary&&(this.releaseCapture(n.pointerId),this.handlers.onPointerCancel(n))},this.overlayEl.addEventListener("pointerdown",this.onPointerDown),this.overlayEl.addEventListener("pointermove",this.onPointerMove),this.overlayEl.addEventListener("pointerup",this.onPointerUp),this.overlayEl.addEventListener("pointercancel",this.onPointerCancel),t.append(this.overlayEl),this.dimEl=t.el("div","mtb-dim"),t.append(this.dimEl)}releaseCapture(t){try{this.overlayEl.releasePointerCapture(t)}catch{}}destroy(){this.overlayEl.removeEventListener("pointerdown",this.onPointerDown),this.overlayEl.removeEventListener("pointermove",this.onPointerMove),this.overlayEl.removeEventListener("pointerup",this.onPointerUp),this.overlayEl.removeEventListener("pointercancel",this.onPointerCancel),this.overlayEl.remove(),this.dimEl.remove()}}class mi{constructor(t){this.highlightEl=t.el("div","mtb-highlight"),this.tooltipEl=t.el("div","mtb-highlight-tooltip"),this.hide(),t.append(this.highlightEl,this.tooltipEl)}highlight(t){const i=t.getBoundingClientRect();this.highlightEl.style.top=`${i.top-2}px`,this.highlightEl.style.left=`${i.left-2}px`,this.highlightEl.style.width=`${i.width+4}px`,this.highlightEl.style.height=`${i.height+4}px`,this.highlightEl.style.display="block",this.showTooltip(t,i)}showTooltip(t,i){this.tooltipEl.textContent=gt(t);const r=i.top<30;this.tooltipEl.classList.toggle("below",r),this.tooltipEl.style.left=`${i.left+i.width/2}px`,this.tooltipEl.style.top=r?`${i.bottom+8}px`:`${i.top-8}px`,this.tooltipEl.style.display="block"}select(){this.highlightEl.classList.add("selected"),this.tooltipEl.style.display="none"}hide(){this.highlightEl.style.display="none",this.highlightEl.classList.remove("selected"),this.tooltipEl.style.display="none"}destroy(){this.highlightEl.remove(),this.tooltipEl.remove()}}function bi(e,t,i){return{left:e.left,top:e.top,scaleX:t/e.width,scaleY:i/e.height}}function G(e,t){return(t-e.left)*e.scaleX}function J(e,t){return(t-e.top)*e.scaleY}function pi(e,t){return{left:G(e,t.left),top:J(e,t.top),width:t.width*e.scaleX,height:t.height*e.scaleY}}function fi(){return{left:0,top:0,width:window.innerWidth,height:window.innerHeight}}function gi(e,t){return{x:e.x-t.x,y:e.y-t.y}}function D(e){let t=0,i=0,r=e;for(;r&&r!==document.body;)r instanceof HTMLElement&&(t+=r.scrollLeft,i+=r.scrollTop),r=Wt(r);return{x:t,y:i}}function Wt(e){if(e.parentElement)return e.parentElement;const t=e.getRootNode();return t instanceof ShadowRoot?t.host:null}function Vt(e){const t=D(e);return{x:t.x+window.scrollX,y:t.y+window.scrollY}}class wi{constructor(t){this.pins=[],this.shadow=t}addPin(t,i){const r=this.shadow.el("div","mtb-pin");r.style.top=`${i}px`,r.style.left=`${t}px`,this.shadow.append(r),this.pins.push(r)}clearAll(){for(const t of this.pins)t.remove();this.pins=[]}destroy(){this.clearAll()}}const Yt="#059669",M={color:"var(--mtb-brand-primary)",width:"3.5",linecap:"round",linejoin:"round",filter:"drop-shadow(0 0 1px rgba(255, 255, 255, 0.95)) drop-shadow(0 1px 2px rgba(15, 23, 42, 0.72))"};class yi{constructor(t){this.currentPath=null,this.currentPoints=[],this.currentAnchor=vi(),this.isDrawing=!1,this.committed=[],this.redoStack=[],this.svg=document.createElementNS("http://www.w3.org/2000/svg","svg"),this.svg.setAttribute("class","mtb-draw-svg"),t.append(this.svg)}startDraw(t,i){this.isDrawing=!0,this.currentPoints=[[t,i]],this.currentAnchor=xi(t,i),this.currentPath=this.createPath(),this.svg.appendChild(this.currentPath)}continueDraw(t,i){!this.isDrawing||!this.currentPath||(this.currentPoints.push([t,i]),this.currentPath.setAttribute("d",yt(this.currentPoints)))}getCurrentSpan(){const[t]=this.currentPoints;if(!t)return 0;let i=0;for(const[r,n]of this.currentPoints)i=Math.max(i,Math.hypot(r-t[0],n-t[1]));return i}commitStroke(){return!this.isDrawing||!this.currentPath?!1:(this.isDrawing=!1,this.committed.push({path:this.currentPath,d:yt(this.currentPoints),points:this.currentPoints,anchor:this.currentAnchor}),this.redoStack=[],this.currentPath=null,this.currentPoints=[],!0)}cancelCurrentDraw(){this.currentPath?.remove(),this.currentPath=null,this.isDrawing=!1,this.currentPoints=[]}undo(){const t=this.committed.pop();return t?(t.path.remove(),this.redoStack.push({d:t.d,points:t.points,anchor:t.anchor}),!0):!1}redo(){const t=this.redoStack.pop();if(!t)return!1;const i=this.createPath();return i.setAttribute("d",t.d),this.svg.appendChild(i),this.committed.push({path:i,d:t.d,points:t.points,anchor:t.anchor}),!0}canUndo(){return this.committed.length>0}canRedo(){return this.redoStack.length>0}hasStrokes(){return this.committed.length>0}getAnnotation(){const[t]=this.committed;if(!t)return null;const i=this.committed.map(s=>ki(s.points,{x:s.anchor.offset.x-t.anchor.offset.x,y:s.anchor.offset.y-t.anchor.offset.y})),[r,n]=Ei(i.flat());return{type:"draw",x:r,y:n,drawPath:i.map(yt).join(" "),captureOffsetX:t.anchor.offset.x,captureOffsetY:t.anchor.offset.y}}viewportDrift(){const[t]=this.committed;return t?{x:window.scrollX-t.anchor.pageScroll.x,y:window.scrollY-t.anchor.pageScroll.y}:{x:0,y:0}}clearAll(){for(;this.svg.firstChild;)this.svg.removeChild(this.svg.firstChild);this.currentPath=null,this.isDrawing=!1,this.currentPoints=[],this.committed=[],this.redoStack=[]}isCurrentlyDrawing(){return this.isDrawing}destroy(){this.svg.remove()}createPath(){const t=document.createElementNS("http://www.w3.org/2000/svg","path");return t.setAttribute("fill","none"),t.setAttribute("stroke",M.color),t.setAttribute("stroke-width",M.width),t.setAttribute("stroke-linecap",M.linecap),t.setAttribute("stroke-linejoin",M.linejoin),t.setAttribute("style",`filter:${M.filter}`),t}}function yt(e){if(e.length===0)return"";const[t,i]=e[0];let r=`M ${t} ${i}`;for(let n=1;n<e.length;n++){const[s,a]=e[n];r+=` L ${s} ${a}`}return r}function vi(){return{offset:{x:0,y:0},pageScroll:{x:0,y:0}}}function xi(e,t){const i={x:window.scrollX,y:window.scrollY},r=D(K(e,t));return{offset:{x:r.x+i.x,y:r.y+i.y},pageScroll:i}}function ki(e,t){return t.x===0&&t.y===0?e:e.map(([i,r])=>[i+t.x,r+t.y])}function Ei(e){const t=e.map(s=>s[0]),i=e.map(s=>s[1]),r=(Math.min(...t)+Math.max(...t))/2,n=(Math.min(...i)+Math.max(...i))/2;return[r,n]}const Z="rr-block",I="rr-mask",Si=`.${Z}, .${I}`;function Q(e){return e.closest(Si)!==null}function vt(e){const t=e.getAttribute("role")?.trim().split(/\s+/)[0];return t&&/^[a-z][a-z0-9-]*$/i.test(t)?t:e.tagName.toLowerCase()}function Xt(e){return e.tagName.toLowerCase()}const Ci=10;function Kt(e){return Q(e)?{name:vt(e),text:"",selector:Xt(e)}:{name:gt(e),text:e.textContent?.trim().slice(0,200)??"",selector:Ut(e)}}class Ti{constructor(t,i,r){this.messages=i,this.handlers=r,this.interactionActive=!0,this.pendingHighlightFrame=null,this.lastMoveX=0,this.lastMoveY=0,this.touch=T(),this.highlighter=new mi(t),this.pinMarker=new wi(t),this.drawLayer=new yi(t),this.overlay=new ui(t,{onPointerDown:n=>this.handlePointerDown(n),onPointerMove:n=>this.handlePointerMove(n),onPointerUp:n=>this.handlePointerUp(n),onPointerCancel:()=>{this.drawLayer.isCurrentlyDrawing()&&this.finishStroke(),this.cancelPendingHighlight(),this.highlighter.hide()}})}handlePointerDown(t){t.preventDefault(),this.drawLayer.startDraw(t.clientX,t.clientY)}handlePointerMove(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()||this.drawSessionActive())return;const t=K(this.lastMoveX,this.lastMoveY);t?this.highlighter.highlight(t):this.highlighter.hide()}cancelPendingHighlight(){this.pendingHighlightFrame!==null&&(cancelAnimationFrame(this.pendingHighlightFrame),this.pendingHighlightFrame=null)}handlePointerUp(t){this.drawLayer.isCurrentlyDrawing()&&this.finishStroke(t)}finishStroke(t){if(this.drawLayer.getCurrentSpan()>=Ci){this.drawLayer.commitStroke(),this.highlighter.hide(),this.handlers.onDrawStroke();return}if(this.drawLayer.cancelCurrentDraw(),this.touch||this.drawLayer.hasStrokes()||!t)return;const i=K(t.clientX,t.clientY),r=i?Kt(i):null,n=r?.name??this.messages.annotation.element,s=i?.getBoundingClientRect(),a=Vt(i),o={type:"pin",x:t.clientX,y:t.clientY,targetSelector:r?.selector,targetText:r?.text??"",targetName:n,targetRect:s?{top:s.top,left:s.left,width:s.width,height:s.height,bottom:s.bottom}:void 0,captureOffsetX:a.x,captureOffsetY:a.y};this.pinMarker.addPin(t.clientX,t.clientY),this.highlighter.select(),this.handlers.onPin(o,n)}undoDraw(){this.drawLayer.undo()}redoDraw(){this.drawLayer.redo()}canUndoDraw(){return this.drawLayer.canUndo()}canRedoDraw(){return this.drawLayer.canRedo()}hasDrawStrokes(){return this.drawLayer.hasStrokes()}drawSessionActive(){return this.drawLayer.hasStrokes()||this.drawLayer.canRedo()}getDrawAnnotation(){const t=this.drawLayer.getAnnotation();if(!t)return null;const i=this.drawLayer.viewportDrift(),r=K(t.x-i.x,t.y-i.y);if(!r)return t;const n=r.getBoundingClientRect(),s=Vt(r),a=s.x-(t.captureOffsetX??0),o=s.y-(t.captureOffsetY??0),l=Kt(r);return{...t,targetSelector:l.selector,targetText:l.text,targetName:l.name,targetRect:{top:n.top+o,left:n.left+a,width:n.width,height:n.height,bottom:n.bottom+o}}}clearDraw(){this.drawLayer.clearAll()}dismissInteraction(){this.interactionActive&&(this.interactionActive=!1,this.cancelPendingHighlight(),this.overlay.destroy())}hideHighlight(){this.highlighter.hide()}destroy(){this.dismissInteraction(),this.highlighter.destroy(),this.pinMarker.destroy(),this.drawLayer.destroy()}}const _i=140;class Ai{constructor(){this.onChange=null,this.timer=null,this.lastReading=null,this.handler=()=>{this.timer!==null&&clearTimeout(this.timer),this.timer=setTimeout(()=>{this.timer=null;const t=this.current();if(t===this.lastReading){this.lastReading=null,this.onChange?.(t);return}this.lastReading=t,this.handler()},_i)}}current(){const t=window.visualViewport;if(!t||t.height<=0)return 0;const i=Math.round(window.innerHeight-(t.height+t.offsetTop));return Math.min(Math.max(0,i),window.innerHeight)}observe(t){const i=window.visualViewport;i&&(this.onChange=t,i.addEventListener("resize",this.handler),i.addEventListener("scroll",this.handler))}stop(){const t=window.visualViewport;this.onChange=null,this.lastReading=null,this.timer!==null&&(clearTimeout(this.timer),this.timer=null),t&&(t.removeEventListener("resize",this.handler),t.removeEventListener("scroll",this.handler))}}const Li=480;function Pi(){return window.innerWidth<=Li}class Gt{constructor(t){this.el=t,this.inset=new Ai}apply(){return Pi()?(this.el.style.left="",this.el.style.top="",this.el.style.maxHeight="",this.lift(this.inset.current()),this.inset.observe(t=>this.lift(t)),!0):!1}release(){this.inset.stop()}lift(t){const i=Math.max(0,window.innerHeight-this.el.offsetHeight),r=Math.min(t,i);this.el.style.bottom=r>0?`${r}px`:""}}class Ri{constructor(t,i){this.onSubmit=i.onSubmit,this.submitLabel=i.messages.draw.submit,this.messages=i.messages,this.el=t.el("div","mtb-draw-bar"),this.el.innerHTML=this.buildHTML(i.messages),t.append(this.el),this.sheet=new Gt(this.el),this.sheet.apply(),this.input=this.el.querySelector(".mtb-draw-input"),this.undoBtn=this.el.querySelector(".mtb-draw-undo"),this.redoBtn=this.el.querySelector(".mtb-draw-redo"),this.submitBtn=this.el.querySelector(".mtb-draw-submit"),this.undoBtn.addEventListener("click",i.onUndo),this.redoBtn.addEventListener("click",i.onRedo),this.el.querySelector(".mtb-draw-cancel").addEventListener("click",i.onCancel),this.submitBtn.addEventListener("click",()=>this.submit()),i.onActivity&&this.input.addEventListener("input",i.onActivity),this.input.addEventListener("keydown",r=>{ft(r)||r.key==="Enter"&&!r.shiftKey&&(r.preventDefault(),this.submit())}),this.input.focus({preventScroll:!0})}buildHTML(t){return`
24
24
  <input class="mtb-draw-input" type="text" placeholder="${d(t.draw.note_placeholder)}" />
25
25
  <button class="mtb-draw-icon-btn mtb-draw-undo" type="button" title="${d(t.draw.undo)}" aria-label="${d(t.draw.undo)}" disabled>
26
26
  <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 14L4 9l5-5"/><path d="M4 9h11a5 5 0 0 1 0 10h-1"/></svg>
@@ -34,20 +34,20 @@ var MakeThisBetter=function(){"use strict";const Qe=`*,*:before,*:after{box-sizi
34
34
  <span class="mtb-draw-sep"></span>
35
35
  <button class="mtb-draw-cancel" type="button">${d(t.draw.cancel)}</button>
36
36
  <button class="mtb-draw-submit" type="button">${d(t.draw.submit)}</button>
37
- `}setLoading(t){t?(this.submitBtn.disabled=!0,this.submitBtn.classList.add("mtb-btn-loading"),this.submitBtn.textContent=this.messages.popup.sending,this.input.disabled=!0):(this.submitBtn.disabled=!1,this.submitBtn.classList.remove("mtb-btn-loading"),this.submitBtn.textContent=this.submitLabel,this.input.disabled=!1)}setUndoRedo(t,r){this.undoBtn.disabled=!t,this.redoBtn.disabled=!r}submit(){this.onSubmit(this.input.value.trim())}destroy(){this.sheet.release(),this.el.remove()}}const et=12,vt=32;function Dr(e){const t=window.innerWidth,r=window.innerHeight;return{vw:t,vh:r,minLeft:et+(e==="left"?vt:0),maxRight:t-et-(e==="right"?vt:0)}}function Mr(e,t){return Math.min(e,t.vw-2*et-vt)}const Ir=["button:not([disabled])","input:not([disabled])","textarea:not([disabled])","select:not([disabled])","a[href]",'[tabindex]:not([tabindex="-1"])'].join(", ");function Gt(e){const t=document.activeElement instanceof HTMLElement?document.activeElement:null,r=i=>{if(i.key!=="Tab")return;const n=Array.from(e.querySelectorAll(Ir)).filter(c=>!c.hidden);if(n.length===0)return;const s=n[0],o=n[n.length-1],l=e.getRootNode().activeElement??document.activeElement;i.shiftKey?(l===s||!e.contains(l))&&(i.preventDefault(),o.focus({preventScroll:!0})):(l===o||!e.contains(l))&&(i.preventDefault(),s.focus({preventScroll:!0}))};return e.addEventListener("keydown",r),{release(){e.removeEventListener("keydown",r)},restoreFocus(){t?.isConnected&&t.focus({preventScroll:!0})}}}const Fr=320,Jt=5e3,Hr="https://makethisbetter.dev",rt='<svg viewBox="0 0 512 512" fill="none"><defs><linearGradient id="mtb-bg" x1=".3" y1="0" x2=".7" y2="1"><stop offset="0%" stop-color="var(--mtb-chat-logo-start, #10b981)"/><stop offset="100%" stop-color="var(--mtb-chat-logo-end, #059669)"/></linearGradient></defs><rect width="512" height="512" rx="96" fill="url(#mtb-bg)"/><g transform="translate(89,89) scale(13.9)" stroke="var(--mtb-chat-logo-fg, #fff)" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round"><path d="M21 2v6h-6"/><path d="M21 13a9 9 0 1 1-3-7.7L21 8"/><circle cx="12" cy="12" r="2.2" fill="var(--mtb-chat-logo-fg, #fff)" stroke="none"/></g></svg>',Br='<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor"><path d="M8.9 8l3.3-3.3-.9-.9L8 7.1 4.7 3.8l-.9.9L7.1 8l-3.3 3.3.9.9L8 8.9l3.3 3.3.9-.9z"/></svg>',Nr='<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M6.2 2.6h3.6l.9 1.4H14a1 1 0 011 1v7.4a1 1 0 01-1 1H2a1 1 0 01-1-1V5a1 1 0 011-1h3.3l.9-1.4z"/><circle cx="8" cy="9" r="2.5" class="mtb-chat-icon-lens"/></svg>',Or='<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><circle cx="8" cy="8" r="6.6"/><polygon points="6.4,5.2 11,8 6.4,10.8" class="mtb-chat-icon-lens"/></svg>',$r='<svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor"><path d="M8.1 14.6L3.8 10.3l1.5-1.5 2.8 2.8 6.6-6.6 1.5 1.5z"/></svg>';class xt{constructor(t,r){this.state="idle",this.autoCloseTimer=null,this.session=null,this.clarifyAbort=null,this.streamingBubbleEl=null,this.opts=r,this.i18n=r.messages,this.el=t.el("div","mtb-chat"),this.el.setAttribute("role","dialog"),this.el.setAttribute("aria-modal","true"),this.el.setAttribute("aria-label",r.targetName),this.el.innerHTML=this.buildHTML(),t.append(this.el),this.focusTrap=Gt(this.el),this.sheet=new Kt(this.el),this.sheet.apply()||this.positionCard(r.x,r.y,r.targetRect,r.position??"right"),this.messagesEl=this.el.querySelector(".mtb-chat-messages"),this.composerEl=this.el.querySelector(".mtb-chat-composer"),this.actionsEl=this.el.querySelector(".mtb-chat-actions"),this.inputEl=this.el.querySelector(".mtb-chat-input"),this.sendBtn=this.el.querySelector(".mtb-chat-send"),this.quickRepliesEl=this.el.querySelector(".mtb-chat-quick-replies"),this.bindEvents(),this.handleEscape=this.handleEscape.bind(this),window.addEventListener("keydown",this.handleEscape),this.inputEl.focus({preventScroll:!0})}handleEscape(t){if(t.key==="Escape"&&(t.preventDefault(),t.stopPropagation(),this.state!=="sending")){if(this.state==="done"){this.destroy();return}this.opts.onCancel()}}buildHTML(){const t=this.i18n,r=this.opts,i=t.popup.quickOptions.map(s=>`<button class="mtb-chat-qr" type="button" data-quick="${d(s.label)}" data-value="${d(s.value??s.label)}">${d(s.emoji)} ${d(s.label)}</button>`).join(""),n=r.recordingSeconds!=null?`<span class="mtb-chat-attachment" title="${d(t.popup.recording_locked_hint)}">${Or}<span class="mtb-chat-capture-label">${Math.round(r.recordingSeconds)}s</span></span>`:r.onScreenshotToggle?`<button class="mtb-chat-screenshot" type="button" title="${d(t.popup.screenshot_hint)}" aria-pressed="${r.screenshotEnabled!==!1}">${Nr}<span class="mtb-chat-capture-label">${d(t.popup.screenshot_short)}</span></button>`:"";return`
37
+ `}setLoading(t){t?(this.submitBtn.disabled=!0,this.submitBtn.classList.add("mtb-btn-loading"),this.submitBtn.textContent=this.messages.popup.sending,this.input.disabled=!0):(this.submitBtn.disabled=!1,this.submitBtn.classList.remove("mtb-btn-loading"),this.submitBtn.textContent=this.submitLabel,this.input.disabled=!1)}setUndoRedo(t,i){this.undoBtn.disabled=!t,this.redoBtn.disabled=!i}submit(){this.onSubmit(this.input.value.trim())}destroy(){this.sheet.release(),this.el.remove()}}const tt=12,xt=32;function Di(e){const t=window.innerWidth,i=window.innerHeight;return{vw:t,vh:i,minLeft:tt+(e==="left"?xt:0),maxRight:t-tt-(e==="right"?xt:0)}}function Mi(e,t){return Math.min(e,t.vw-2*tt-xt)}const Ii=["button:not([disabled])","input:not([disabled])","textarea:not([disabled])","select:not([disabled])","a[href]",'[tabindex]:not([tabindex="-1"])'].join(", ");function Jt(e){const t=document.activeElement instanceof HTMLElement?document.activeElement:null,i=r=>{if(r.key!=="Tab")return;const n=Array.from(e.querySelectorAll(Ii)).filter(c=>!c.hidden);if(n.length===0)return;const s=n[0],a=n[n.length-1],l=e.getRootNode().activeElement??document.activeElement;r.shiftKey?(l===s||!e.contains(l))&&(r.preventDefault(),a.focus({preventScroll:!0})):(l===a||!e.contains(l))&&(r.preventDefault(),s.focus({preventScroll:!0}))};return e.addEventListener("keydown",i),{release(){e.removeEventListener("keydown",i)},restoreFocus(){t?.isConnected&&t.focus({preventScroll:!0})}}}const Fi=320,Zt=5e3,Hi="https://makethisbetter.dev",et='<svg viewBox="0 0 512 512" fill="none"><defs><linearGradient id="mtb-bg" x1=".3" y1="0" x2=".7" y2="1"><stop offset="0%" stop-color="var(--mtb-chat-logo-start, #10b981)"/><stop offset="100%" stop-color="var(--mtb-chat-logo-end, #059669)"/></linearGradient></defs><rect width="512" height="512" rx="96" fill="url(#mtb-bg)"/><g transform="translate(89,89) scale(13.9)" stroke="var(--mtb-chat-logo-fg, #fff)" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round"><path d="M21 2v6h-6"/><path d="M21 13a9 9 0 1 1-3-7.7L21 8"/><circle cx="12" cy="12" r="2.2" fill="var(--mtb-chat-logo-fg, #fff)" stroke="none"/></g></svg>',Bi='<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor"><path d="M8.9 8l3.3-3.3-.9-.9L8 7.1 4.7 3.8l-.9.9L7.1 8l-3.3 3.3.9.9L8 8.9l3.3 3.3.9-.9z"/></svg>',Ni='<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M6.2 2.6h3.6l.9 1.4H14a1 1 0 011 1v7.4a1 1 0 01-1 1H2a1 1 0 01-1-1V5a1 1 0 011-1h3.3l.9-1.4z"/><circle cx="8" cy="9" r="2.5" class="mtb-chat-icon-lens"/></svg>',Oi='<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><circle cx="8" cy="8" r="6.6"/><polygon points="6.4,5.2 11,8 6.4,10.8" class="mtb-chat-icon-lens"/></svg>',zi='<svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor"><path d="M8.1 14.6L3.8 10.3l1.5-1.5 2.8 2.8 6.6-6.6 1.5 1.5z"/></svg>';class kt{constructor(t,i){this.state="idle",this.autoCloseTimer=null,this.session=null,this.clarifyAbort=null,this.streamingBubbleEl=null,this.opts=i,this.i18n=i.messages,this.el=t.el("div","mtb-chat"),this.el.setAttribute("role","dialog"),this.el.setAttribute("aria-modal","true"),this.el.setAttribute("aria-label",i.targetName),this.el.innerHTML=this.buildHTML(),t.append(this.el),this.focusTrap=Jt(this.el),this.sheet=new Gt(this.el),this.sheet.apply()||this.positionCard(i.x,i.y,i.targetRect,i.position??"right"),this.messagesEl=this.el.querySelector(".mtb-chat-messages"),this.composerEl=this.el.querySelector(".mtb-chat-composer"),this.actionsEl=this.el.querySelector(".mtb-chat-actions"),this.inputEl=this.el.querySelector(".mtb-chat-input"),this.sendBtn=this.el.querySelector(".mtb-chat-send"),this.quickRepliesEl=this.el.querySelector(".mtb-chat-quick-replies"),this.bindEvents(),this.handleEscape=this.handleEscape.bind(this),window.addEventListener("keydown",this.handleEscape),this.inputEl.focus({preventScroll:!0})}handleEscape(t){if(t.key==="Escape"&&(t.preventDefault(),t.stopPropagation(),this.state!=="sending")){if(this.state==="done"){this.destroy();return}this.opts.onCancel()}}buildHTML(){const t=this.i18n,i=this.opts,r=t.popup.quickOptions.map(s=>`<button class="mtb-chat-qr" type="button" data-quick="${d(s.label)}" data-value="${d(s.value??s.label)}">${d(s.emoji)} ${d(s.label)}</button>`).join(""),n=i.recordingSeconds!=null?`<span class="mtb-chat-attachment" title="${d(t.popup.recording_locked_hint)}">${Oi}<span class="mtb-chat-capture-label">${Math.round(i.recordingSeconds)}s</span></span>`:i.onScreenshotToggle?`<button class="mtb-chat-screenshot" type="button" title="${d(t.popup.screenshot_hint)}" aria-pressed="${i.screenshotEnabled!==!1}">${Ni}<span class="mtb-chat-capture-label">${d(t.popup.screenshot_short)}</span></button>`:"";return`
38
38
  <div class="mtb-chat-header">
39
39
  <div class="mtb-chat-handle"></div>
40
40
  <div class="mtb-chat-header-row">
41
- <a class="mtb-chat-brand" href="${Hr}" target="_blank" rel="noopener">
42
- <span class="mtb-chat-logo">${rt}</span>
41
+ <a class="mtb-chat-brand" href="${Hi}" target="_blank" rel="noopener">
42
+ <span class="mtb-chat-logo">${et}</span>
43
43
  <span class="mtb-chat-brand-name">Make This Better</span>
44
44
  </a>
45
45
  <span class="mtb-chat-header-gap"></span>
46
- <button class="mtb-chat-close" type="button" aria-label="${d(t.popup.close)}">${Br}</button>
46
+ <button class="mtb-chat-close" type="button" aria-label="${d(t.popup.close)}">${Bi}</button>
47
47
  </div>
48
48
  </div>
49
49
  <div class="mtb-chat-messages"></div>
50
- <div class="mtb-chat-quick-replies">${i}</div>
50
+ <div class="mtb-chat-quick-replies">${r}</div>
51
51
  <div class="mtb-chat-composer">
52
52
  <textarea class="mtb-chat-input" rows="1" placeholder="${d(t.popup.placeholder)}"></textarea>
53
53
  <div class="mtb-chat-actions">
@@ -56,31 +56,20 @@ var MakeThisBetter=function(){"use strict";const Qe=`*,*:before,*:after{box-sizi
56
56
  <button class="mtb-chat-send" type="button" disabled>${d(t.clarify.send)}</button>
57
57
  </div>
58
58
  </div>
59
- `}bindEvents(){this.el.querySelector(".mtb-chat-close").addEventListener("click",()=>{this.opts.onCancel()}),this.quickRepliesEl.querySelectorAll(".mtb-chat-qr").forEach(r=>{r.addEventListener("click",()=>{const i=r.dataset.value??r.dataset.quick??"";this.inputEl.value=i,this.sendMessage(i)})}),this.inputEl.addEventListener("input",()=>{this.sendBtn.disabled=!this.inputEl.value.trim(),this.opts.onActivity?.()}),this.inputEl.addEventListener("keydown",r=>{if(!pt(r)&&r.key==="Enter"&&!r.shiftKey){r.preventDefault();const i=this.inputEl.value.trim();i?this.sendMessage(i):this.state==="clarifying"&&this.skipAndSend()}}),this.sendBtn.addEventListener("click",()=>{const r=this.inputEl.value.trim();r&&this.sendMessage(r)});const t=this.el.querySelector(".mtb-chat-screenshot");t&&this.opts.onScreenshotToggle&&t.addEventListener("click",()=>{const r=t.getAttribute("aria-pressed")==="true";t.setAttribute("aria-pressed",String(!r)),t.classList.toggle("mtb-chat-screenshot-off",r),this.opts.onScreenshotToggle(!r)})}async sendMessage(t){if(this.state==="sending"||this.state==="answering")return;if(this.state==="clarifying"){this.handleAnswer(t);return}this.state="sending",this.appendUserBubble(t),this.quickRepliesEl.style.display="none",this.hideCapture(),this.showThinking(),this.setComposerDisabled(!0);let r;try{r=await this.opts.onSubmit(t)}catch{r=null}if(!r){this.removeThinking(),this.setComposerDisabled(!1),this.showRetryableError(this.i18n.error.submit,()=>{this.clearError(),this.sendMessage(t)}),this.state="idle";return}if(this.session=r,!r.ai_clarify_available){this.removeThinking(),this.showDone();return}let i=null;const n=[];this.clarifyAbort=new AbortController;try{i=await this.opts.onClarify(r.id,r.token,o=>{n.push(o)},this.clarifyAbort.signal)}catch{this.removeThinking(),this.showDone();return}if(this.removeThinking(),i.done||!i.messages.length){this.showDone();return}if(n.length){this.startStreamingBubble();for(const o of n)this.appendStreamDelta(o),await new Promise(a=>setTimeout(a,15));this.endStreamingBubble()}const s=i.messages.find(o=>o.role==="assistant");!n.length&&s&&this.appendAiBubble(s.content),this.renderSuggestions(i.suggestions),this.state="clarifying",this.setComposerDisabled(!1),this.inputEl.value="",this.inputEl.placeholder=this.i18n.clarify.placeholder,this.sendBtn.textContent=this.i18n.clarify.submit??this.i18n.clarify.send,this.sendBtn.disabled=!0,this.showSkip(),this.inputEl.focus({preventScroll:!0}),this.opts.onConversationOpen?.()}handleAnswer(t){const r=this.session;r&&(this.state="done",this.appendUserBubble(t),this.clearSuggestions(),this.hideSkip(),this.setComposerDisabled(!0),this.renderSuccess(),Promise.resolve(this.opts.onAnswer(r.id,r.token,t)).catch(()=>{}).then(()=>this.finalizeInBackground()))}showDone(){this.state="done",this.hideSkip(),this.setComposerDisabled(!0),this.renderSuccess(),this.finalizeInBackground()}renderSuccess(){const t=this.i18n.success;this.messagesEl.remove(),this.quickRepliesEl.remove(),this.composerEl.remove();const r=document.createElement("div");r.className="mtb-chat-success mtb-chat-success-simple";const i=document.createElement("div");i.className="mtb-chat-success-icon",i.innerHTML=$r,r.appendChild(i);const n=document.createElement("div");n.className="mtb-chat-success-title",n.textContent=this.session?.ai_clarify_available===!1?t.title_no_ai:t.title,r.appendChild(n);const s=document.createElement("a");s.className="mtb-chat-success-link mtb-chat-success-link-pending",s.href="#",s.textContent=t.track_feedback,s.addEventListener("click",o=>o.preventDefault()),r.appendChild(s),this.el.appendChild(r),this.attachHandoff()}attachHandoff(){const t=this.el.querySelector(".mtb-chat-success");if(!t)return;this.i18n.success;const r=this.opts.resolveBoardLink?.(),i=t.querySelector(".mtb-chat-success-link-pending");r&&i&&(i.classList.remove("mtb-chat-success-link-pending"),i.addEventListener("click",s=>{s.preventDefault(),r()}));const n=this.opts.resolveEmailCapture?.();n&&!t.querySelector(".mtb-chat-email-card")?(this.autoCloseTimer&&(clearTimeout(this.autoCloseTimer),this.autoCloseTimer=null),t.classList.remove("mtb-chat-success-simple"),t.appendChild(this.buildEmailCard(n))):!n&&!this.autoCloseTimer&&!t.querySelector(".mtb-chat-email-card")&&(this.autoCloseTimer=setTimeout(()=>this.destroy(),Jt))}finalizeInBackground(){Promise.resolve(this.opts.onFinalize()).then(()=>this.attachHandoff()).catch(()=>{})}buildEmailCard(t){const r=this.i18n.success,i=document.createElement("div");i.className="mtb-chat-email-card";const n=document.createElement("div");n.className="mtb-chat-email-row";const s=document.createElement("div");s.className="mtb-chat-email-field";const o=document.createElement("input");o.className="mtb-chat-email-input",o.type="email",o.placeholder=r.email_cta,s.appendChild(o);const a=document.createElement("button");a.className="mtb-chat-email-submit",a.type="button",a.textContent=r.notify,a.disabled=!0;const l=async()=>{const c=o.value.trim();if(!c)return;if(a.disabled=!0,o.disabled=!0,await t.onSubmit(c)){const m=document.createElement("div");m.className="mtb-chat-email-note",m.textContent=r.email_saved,i.replaceChildren(m),this.autoCloseTimer=setTimeout(()=>this.destroy(),Jt);return}o.disabled=!1,a.disabled=!1;const u=i.querySelector(".mtb-chat-email-error")??document.createElement("div");u.className="mtb-chat-email-error",u.textContent=r.email_error,i.appendChild(u)};return o.addEventListener("input",()=>{a.disabled=!o.value.trim()}),o.addEventListener("keydown",c=>{c.key==="Enter"&&o.value.trim()&&l()}),a.addEventListener("click",()=>void l()),n.appendChild(s),n.appendChild(a),i.appendChild(n),i}appendUserBubble(t){const r=document.createElement("div");r.className="mtb-chat-bubble mtb-chat-bubble-user",r.textContent=t,this.messagesEl.appendChild(r),this.messagesEl.scrollTop=this.messagesEl.scrollHeight,this.inputEl.value="",this.sendBtn.disabled=!0}startStreamingBubble(){const t=document.createElement("div");t.className="mtb-chat-ai-row",t.innerHTML=`<div class="mtb-chat-avatar">${rt}</div><div class="mtb-chat-bubble mtb-chat-bubble-ai"></div>`,this.messagesEl.appendChild(t),this.streamingBubbleEl=t.querySelector(".mtb-chat-bubble-ai")}appendStreamDelta(t){this.streamingBubbleEl&&(this.streamingBubbleEl.textContent=(this.streamingBubbleEl.textContent??"")+t,this.messagesEl.scrollTop=this.messagesEl.scrollHeight)}endStreamingBubble(){this.streamingBubbleEl=null}appendAiBubble(t){const r=document.createElement("div");r.className="mtb-chat-ai-row",r.innerHTML=`<div class="mtb-chat-avatar">${rt}</div><div class="mtb-chat-bubble mtb-chat-bubble-ai"></div>`,r.querySelector(".mtb-chat-bubble-ai").textContent=t,this.messagesEl.appendChild(r),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}renderSuggestions(t){if(this.clearSuggestions(),!t?.length)return;const r=document.createElement("div");r.className="mtb-chat-suggestions";for(const i of t){const n=document.createElement("button");n.className="mtb-chat-sg",n.type="button",n.textContent=i,n.addEventListener("click",()=>{this.inputEl.value=i,this.sendBtn.disabled=!1,this.inputEl.focus({preventScroll:!0})}),r.appendChild(n)}this.messagesEl.appendChild(r),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}clearSuggestions(){this.messagesEl.querySelector(".mtb-chat-suggestions")?.remove()}showThinking(){if(this.messagesEl.querySelector(".mtb-chat-thinking"))return;const t=document.createElement("div");t.className="mtb-chat-ai-row mtb-chat-thinking",t.innerHTML=`<div class="mtb-chat-avatar">${rt}</div><div class="mtb-chat-dots"><span></span><span></span><span></span></div>`,this.messagesEl.appendChild(t),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}removeThinking(){this.messagesEl.querySelector(".mtb-chat-thinking")?.remove()}showRetryableError(t,r){this.clearError();const i=document.createElement("div");i.className="mtb-chat-error-row";const n=document.createElement("span");n.className="mtb-chat-error-text",n.textContent=t;const s=document.createElement("button");s.className="mtb-chat-error-retry",s.type="button",s.textContent=this.i18n.clarify.retry,s.addEventListener("click",r),i.appendChild(n),i.appendChild(s),this.messagesEl.appendChild(i),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}clearError(){this.messagesEl.querySelectorAll(".mtb-chat-error-row").forEach(t=>t.remove())}showSkip(){if(this.actionsEl.querySelector(".mtb-chat-skip"))return;const t=document.createElement("button");t.className="mtb-chat-skip",t.type="button",t.title=this.i18n.clarify.skip,t.textContent=this.i18n.clarify.skip_short,t.addEventListener("click",()=>this.skipAndSend()),this.actionsEl.insertBefore(t,this.sendBtn)}skipAndSend(){this.hideSkip(),this.state="done",this.setComposerDisabled(!0),this.renderSuccess(),this.finalizeInBackground()}hideSkip(){this.actionsEl?.querySelector(".mtb-chat-skip")?.remove()}hideCapture(){this.actionsEl.querySelector(".mtb-chat-screenshot")?.remove(),this.actionsEl.querySelector(".mtb-chat-attachment")?.remove()}setComposerDisabled(t){this.inputEl.disabled=t,this.sendBtn.disabled=t,this.composerEl.classList.toggle("mtb-chat-composer-disabled",t)}positionCard(t,r,i,n){const s=Dr(n),{vw:o,vh:a,minLeft:l,maxRight:c}=s,h=et,u=8,m=Mr(Fr,s),v=(this.el.offsetHeight||280)+80;let y,b;const Ot=i&&i.width<o*.6&&i.height<a*.6;i&&Ot?(y=i.left,b=i.bottom+u,b+v>a-h&&(b=i.top-v-u),b<h&&(b=Math.min(i.bottom+u,a-v-h))):(y=t+12,b=r+12),y+m>c&&(y=c-m),y<l&&(y=l),b<h&&(b=h),b+v>a-h&&(b=a-v-h),b<h&&(b=h),this.el.style.left=`${y}px`,this.el.style.top=`${b}px`,this.el.style.maxHeight=`${a-b-h}px`}submit(t){this.sendMessage(t)}sessionId(){return this.session?.id??null}destroy(){this.clarifyAbort?.abort(),this.autoCloseTimer&&clearTimeout(this.autoCloseTimer),window.removeEventListener("keydown",this.handleEscape),this.sheet.release(),this.focusTrap.release(),this.el.remove(),this.focusTrap.restoreFocus()}}const Ur=5e3,zr='<svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor"><path d="M8.1 14.6L3.8 10.3l1.5-1.5 2.8 2.8 6.6-6.6 1.5 1.5z"/></svg>';class jr{constructor(t,r,i,n){const s=r.success,o=n?.skipFollowup?s.title_no_ai:s.title;this.el=t.el("div","mtb-chat mtb-chat-receipt"),this.el.setAttribute("role","dialog"),this.el.setAttribute("aria-modal","true"),this.el.setAttribute("aria-label",o);const a=document.createElement("div");a.className="mtb-chat-success mtb-chat-success-simple";const l=document.createElement("div");l.className="mtb-chat-success-icon",l.innerHTML=zr,a.appendChild(l);const c=document.createElement("div");if(c.className="mtb-chat-success-title",c.textContent=o,a.appendChild(c),n?.onViewFeedback){const h=document.createElement("a");h.className="mtb-chat-success-link",h.href="#",h.textContent=s.track_feedback,h.addEventListener("click",u=>{u.preventDefault(),n.onViewFeedback()}),a.appendChild(h)}this.el.appendChild(a),t.append(this.el),this.focusTrap=Gt(this.el),this.autoCloseTimer=setTimeout(i,Ur)}destroy(){clearTimeout(this.autoCloseTimer),this.focusTrap.release(),this.el.remove(),this.focusTrap.restoreFocus()}}const g="[Filtered]",qr=/-----BEGIN ((?:[A-Z0-9]+ )*PRIVATE KEY)-----[\s\S]*?-----END \1-----/g,Wr=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g,Vr=[/\bsk-(?:proj-)?[A-Za-z0-9_-]{20,}\b/g,/\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{20,}\b/g,/\bgh[pousr]_[A-Za-z0-9]{30,}\b/g,/\bAKIA[0-9A-Z]{16}\b/g,/\bxox[baprs]-[A-Za-z0-9-]{20,}\b/g],Yr=/\b(?:\d[ -]?){12,18}\d\b/g,Xr=/\bhttps?:\/\/[^\s<>"']+/gi,Kr=new Set(["type","autocomplete","name","id","aria_label","placeholder"]),Gr=new Set(["value","content"]),Jr=new Set(["password","hidden","file"]),Zr=new Set(["current_password","new_password","one_time_code","cc_number","cc_csc","cc_exp","cc_exp_month","cc_exp_year"]),Qr=/(?:^|_)(?:password|passwd|passcode|card_(?:number|no)(?:_[0-9]+)?|credit_card|cc_(?:number|num|csc|cvv|cvc|exp|expiry)|cvv|cvc|csc|security_code|one_time_(?:code|password)|otp(?:_code)?|verification_code|auth(?:entication)?_token|access_token|refresh_token|id_token|token|api_key|client_secret|secret|authorization|cookie|set_cookie|credential|private_key|hidden_value|file_name|filename)(?:$|_(?:value|field|input|confirmation|confirm|header|data|pem)$)/;function _(e){let t=e.replace(qr,g).replace(Wr,g);for(const r of Vr)t=t.replace(r,g);return t=t.replace(Yr,r=>ti(r)?g:r),t.replace(Xr,r=>F(r)||g)}function F(e){try{const t=new URL(e);return`${t.origin}${t.pathname}`}catch{return""}}function it(e,t){if(t&&Zt(t)&&e!=null)return g;if(typeof e=="string")return _(e);if(Array.isArray(e))return e.map(r=>it(r));if(e&&typeof e=="object"){const r=Qt(e);return Object.fromEntries(Object.entries(e).map(([n,s])=>{const o=r&&Gr.has(H(n))&&s!=null?g:it(s,n);return[_(n),o]}))}return e}function Zt(e){return Qr.test(H(e))}function Qt(e){return Object.entries(e).some(([t,r])=>{if(typeof r!="string")return!1;const i=H(t);return Kr.has(i)?i==="type"?Jr.has(H(r)):i==="autocomplete"?r.split(/\s+/).some(n=>Zr.has(H(n))):Zt(r):!1})}function H(e){return e.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}function ti(e){const t=e.replace(/\D/g,"");if(t.length<13||t.length>19)return!1;let r=0,i=!1;for(let n=t.length-1;n>=0;n-=1){let s=Number(t[n]);i&&(s*=2,s>9&&(s-=9)),r+=s,i=!i}return r%10===0}function te(e){return Qt({type:e.getAttribute("type"),autocomplete:e.getAttribute("autocomplete"),name:e.getAttribute("name"),id:e.id,"aria-label":e.getAttribute("aria-label"),placeholder:e.getAttribute("placeholder")})}function nt(e,t){return e&&(te(t)?g:_(e))}const ei=512;function ee(){return new WeakMap}function re(e,t){let r=e.parentElement;for(;r&&r!==document.body&&r!==document.documentElement;){const i=ie(r,t);if(i==="sensitive")return!0;if(i==="contains-sensitive-child"||i==="too-large")return!1;r=r.parentElement}return!1}function ie(e,t){const r=t.get(e);if(r)return r;const i=e.textContent??"";let n="none";return i.length>ei?n="too-large":_(i)!==i&&(n=Array.from(e.children).some(o=>{const a=ie(o,t);return a==="sensitive"||a==="contains-sensitive-child"})?"contains-sensitive-child":"sensitive"),t.set(e,n),n}function ri(e){return new Promise(t=>{const r=new Image;r.onload=()=>t(r),r.onerror=()=>t(null),r.src=e})}function ne(e){const t=[];let r=null;const i=e.match(/[ML]\s*[-\d.]+\s+[-\d.]+/g)??[];for(const n of i){const[s,o]=n.slice(1).trim().split(/\s+/).map(Number);Number.isNaN(s)||Number.isNaN(o)||(n[0]==="M"?(r=[[s,o]],t.push(r)):r&&r.push([s,o]))}return t}function ii(e,t,r){return ne(e).map(i=>i.map(([n,s],o)=>`${o===0?"M":"L"} ${n+t} ${s+r}`).join(" ")).join(" ")}let B=null;function se(){return B||(B=Promise.resolve().then(()=>xs).catch(e=>{throw B=null,e}),B)}let kt,Et=null;function St(){return kt!==void 0?Promise.resolve(kt):(Et??(Et=se().then(({getFontEmbedCSS:e})=>e(document.body)).then(e=>(kt=e,e)).catch(()=>{Et=null})),Et)}const ni=200,si="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";async function oi(e,t){try{if(t?.aborted)return null;const[{toJpeg:r},i]=await Promise.all([se(),St()]),n=document.body.getBoundingClientRect(),s=fr(),o={x:window.scrollX,y:window.scrollY},a=ui(document.body),l=await r(document.body,{quality:.85,imagePlaceholder:si,resourceUrlResolver:e,fetchRequestInit:t?{signal:t}:void 0,width:s.width,height:s.height,pixelRatio:pi(s),backgroundColor:"#ffffff",skipFonts:!1,skipAutoScale:!1,fontEmbedCSS:i,style:{transform:`translate(${n.left}px, ${n.top}px)`,transformOrigin:"top left"},filter:c=>{if(c instanceof HTMLElement&&c.id===x)return!1;if(!(c instanceof Element))return!0;const h=c.getBoundingClientRect();return h.width===0&&h.height===0?!0:h.top+window.scrollY-o.y<=s.height+ni}});return t?.aborted?null:{dataUrl:l,metrics:s,redactions:a,pageScroll:o}}catch{return null}}async function ai(e,t=[],r){try{const i=t.map(n=>li(n,e.pageScroll));return await di(e.dataUrl,i,e.metrics,e.redactions,r)}catch{return null}}function li(e,t){const r=ci(e,t);return r.x===0&&r.y===0?e:{...e,x:e.x+r.x,y:e.y+r.y,targetRect:e.targetRect&&{...e.targetRect,top:e.targetRect.top+r.y,left:e.targetRect.left+r.x,bottom:e.targetRect.bottom+r.y},drawPath:e.drawPath&&ii(e.drawPath,r.x,r.y)}}function ci(e,t){return e.captureOffsetX!==void 0&&e.captureOffsetY!==void 0?gr({x:e.captureOffsetX,y:e.captureOffsetY},t):D(hi(e))}function hi(e){if(e.targetSelector)try{const t=document.querySelector(e.targetSelector);if(t)return t}catch{}return document.elementsFromPoint?.(e.x,e.y)[0]??null}async function di(e,t,r,i,n){const s=document.createElement("canvas"),o=s.getContext("2d");if(!o)return null;const a=await ri(e);if(!a)return null;s.width=a.naturalWidth||window.innerWidth,s.height=a.naturalHeight||window.innerHeight,o.drawImage(a,0,0);const l=br(r,s.width,s.height);o.fillStyle="#e5e7eb";for(const c of i){const h=pr(l,c);o.fillRect(h.left,h.top,h.width,h.height)}for(const c of t)c.type==="draw"&&c.drawPath?bi(o,c.drawPath,l,n?.primary):c.type==="pin"&&fi(o,J(l,c.x),Z(l,c.y),n);return gi(s)}function ui(e){const t=[];for(const s of mi(e,`.${Q}`))Ct(t,s.getBoundingClientRect(),oe(s));for(const s of e.querySelectorAll("input, textarea, select")){if(ae(s))continue;const o=s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement||s instanceof HTMLSelectElement?s.value:"",a=s.closest(`.${I}`)!==null,l=te(s)||nt(o,s)!==o;!a&&!l||Ct(t,s.getBoundingClientRect(),oe(s),ce)}const r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),i=ee();let n=r.nextNode();for(;n;){const s=n.parentElement,o=n.textContent??"",a=s?.closest(`.${I}`)!==null,l=_(o)!==o||re(n,i);if(s&&!ae(s)&&(a||l)){const c=D(s),h=document.createRange();h.selectNodeContents(n);for(const u of Array.from(h.getClientRects()))Ct(t,u,c,ce)}n=r.nextNode()}return t}function oe(e){return D(qt(e))}function mi(e,t){const r=Array.from(e.querySelectorAll(t));return e.matches(t)?[e,...r]:r}function ae(e){return e.closest(`#${x}`)!==null||e.closest(`.${Q}`)!==null}function Ct(e,t,r,i=0){if(![t.left,t.top,t.width,t.height].every(Number.isFinite))throw new Error("Invalid privacy redaction geometry");t.width<=0||t.height<=0||e.push({left:t.left+r.x-i,top:t.top+r.y-i,width:t.width+i*2,height:t.height+i*2})}function bi(e,t,r,i=Vt){e.save(),e.lineCap="round",e.lineJoin="round";for(const n of ne(t))if(n.length!==0){e.beginPath(),e.moveTo(J(r,n[0][0]),Z(r,n[0][1]));for(let s=1;s<n.length;s++)e.lineTo(J(r,n[s][0]),Z(r,n[s][1]));e.shadowColor="transparent",e.strokeStyle="rgba(15, 23, 42, 0.72)",e.lineWidth=7,e.stroke(),e.strokeStyle="#ffffff",e.lineWidth=5.5,e.stroke(),e.strokeStyle=i,e.lineWidth=3.5,e.stroke()}e.restore()}const le=16e6,ce=2;function pi(e){const t=e.width*e.height;return!Number.isFinite(t)||t<=le?1:Math.sqrt(le/t)}function fi(e,t,r,i){const n=i?.primary??Vt;e.save(),e.shadowColor="rgba(15, 23, 42, 0.68)",e.shadowOffsetY=2,e.shadowBlur=8,e.fillStyle=n,e.beginPath(),e.arc(t,r,11,0,Math.PI*2),e.fill(),e.shadowColor="transparent",e.lineWidth=2,e.strokeStyle="#ffffff",e.stroke(),e.restore()}function gi(e){return new Promise(t=>{try{e.toBlob(r=>t(r),"image/jpeg",.85)}catch{t(null)}})}class yi{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,r,i,n,s)=>(this.emit({name:wi(s),message:String(t),source:r,line:i,col:n,error:s}),this.originalOnError?this.originalOnError.call(window,t,r,i,n,s):!1),window.onerror=this.installedOnError,this.rejectionHandler=t=>{const r=t.reason instanceof Error?t.reason.message:String(t.reason),i=t.reason instanceof Error?t.reason.name:"UnhandledRejection";this.emit({name:i,message:`Unhandled rejection: ${r}`})},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 r of this.listeners)r(t)}}const Tt=new yi;function wi(e){return!e||typeof e!="object"||!("name"in e)?void 0:String(e.name)||void 0}function he(e){const t=vi(e.name)||xi(e.message),r=ki(e);return r?`${t} (${r})`:t}function vi(e){return e&&/^[A-Za-z][A-Za-z0-9]*(?:Error|Exception|Rejection)$/.test(e)?e:""}function xi(e){return e.match(/^([A-Za-z][A-Za-z0-9]*(?:Error|Exception))\b/)?.[1]??"Error"}function ki(e){if(!e.source)return"";try{const t=new URL(e.source,window.location.href).pathname;return e.line==null?t:`${t}:${e.line}:${e.col??0}`}catch{return""}}const Ei=20;class Si{constructor(){this.errors=[],this.unsubscribe=null}start(){this.unsubscribe||(this.unsubscribe=Tt.subscribe(t=>this.record(t)))}record(t){this.addError(he(t))}addError(t){this.errors.length>=Ei||this.errors.includes(t)||this.errors.push(t)}getErrors(){return[...this.errors]}stop(){this.unsubscribe?.(),this.unsubscribe=null}}const st=new Set;let N=null,O=null,$=null,ot=null,U=null,at=null;function de(e){st.add(e),Ci();let t=!1;return()=>{t||(t=!0,st.delete(e),st.size===0&&Ti())}}function _t(e,t){const r={type:e,fromUrl:t,toUrl:location.href};at=r.toUrl;for(const i of[...st])try{i(r)}catch{}}function Ci(){if($)return;at=location.href,U=()=>_t("pop",at??location.href),window.addEventListener("popstate",U),N=history.pushState,O=history.replaceState;const e=N,t=O;$=function(r,i,n){const s=location.href;e.call(history,r,i,n),_t("push",s)},ot=function(r,i,n){const s=location.href;t.call(history,r,i,n),_t("replace",s)},history.pushState=$,history.replaceState=ot}function Ti(){U&&(window.removeEventListener("popstate",U),U=null),N&&history.pushState===$&&(history.pushState=N),O&&history.replaceState===ot&&(history.replaceState=O),N=null,O=null,$=null,ot=null,at=null}const _i=20;function Ai(e){return tt(e)?wt(e):ft(e)}function Li(e){return tt(e)?Yt(e):Ut(e)}class Pi{constructor(){this.breadcrumbs=[],this.active=!1,this.unsubscribeErrors=null,this.unsubscribeNavigation=null,this.lastUrl="",this.boundClickHandler=t=>this.handleClick(t),this.boundChangeHandler=t=>this.handleChange(t)}start(){this.active||(this.active=!0,this.lastUrl=location.href,document.addEventListener("click",this.boundClickHandler,{capture:!0,passive:!0}),document.addEventListener("change",this.boundChangeHandler,{capture:!0,passive:!0}),this.unsubscribeErrors=Tt.subscribe(t=>this.recordError(t)),this.unsubscribeNavigation=de(()=>this.handleNavigation()))}stop(){this.active&&(this.active=!1,document.removeEventListener("click",this.boundClickHandler,!0),document.removeEventListener("change",this.boundChangeHandler,!0),this.unsubscribeErrors?.(),this.unsubscribeErrors=null,this.unsubscribeNavigation?.(),this.unsubscribeNavigation=null)}getBreadcrumbs(){return[...this.breadcrumbs]}add(t){this.breadcrumbs.push(t),this.breadcrumbs.length>_i&&this.breadcrumbs.shift()}handleClick(t){const r=t.target;if(r&&!C(r))try{this.add({type:"ui",category:"ui.click",timestamp:Date.now(),message:Ai(r),data:{selector:Li(r)}})}catch{}}handleChange(t){const r=t.target;if(r&&!C(r))try{const i=r,n=tt(r)?wt(r):i.name||i.placeholder||r.getAttribute("aria-label")||r.tagName;this.add({type:"ui",category:"ui.input",timestamp:Date.now(),message:n,data:{field:n}})}catch{}}recordError(t){const r=he(t);this.add({type:"console",category:"console.error",timestamp:Date.now(),message:r,data:{message:r}})}handleNavigation(){if(!this.active)return;const t=this.lastUrl,r=location.href;if(t===r)return;this.lastUrl=r;const i=F(t),n=F(r);this.add({type:"navigation",category:"navigation",timestamp:Date.now(),message:`${i} → ${n}`,data:{from:i,to:n}})}}const ue="mtb_frustration_state";let At=null;function lt(){try{const e=window.sessionStorage.getItem(ue);return ct(e?JSON.parse(e):At)}catch{return ct(At)}}function me(e){const t=ct(e);At=t;try{window.sessionStorage.setItem(ue,JSON.stringify(t))}catch{}}function Ri(){return lt().dismissedByUser}function Di(){me({...lt(),dismissedByUser:!0})}function ct(e){const t=e??{};return{navTimestamps:Array.isArray(t.navTimestamps)?t.navTimestamps.filter(r=>typeof r=="number"):[],cooldownUntil:typeof t.cooldownUntil=="number"?t.cooldownUntil:0,errorPageUrls:Array.isArray(t.errorPageUrls)?t.errorPageUrls.filter(r=>typeof r=="string").slice(-20):[],dismissedByUser:t.dismissedByUser===!0}}const Mi=4,Ii=1500,Fi=3,Hi=5e3,Lt=500,Bi=2,Ni=3e4,Oi=2e3,$i=1e3,Ui=300,zi=new Set(["A","BUTTON","INPUT","SELECT","TEXTAREA","LABEL","SUMMARY","DETAILS"]),ji=new Set(["button","link","checkbox","radio","tab","menuitem","option","switch","textbox","combobox","listbox","slider","spinbutton"]),qi=new Set(["A","BUTTON","SUMMARY"]),Wi=new Set(["button","link","tab","menuitem"]),be=[/\bnot found\b/,/\bserver error\b/,/^\s*(?:http\s*)?[45]\d{2}\s*$/,/\b(?:error|http|status)\s*[:-]?\s*[45]\d{2}\b/,/\b[45]\d{2}\s*[:-]?\s*error\b/],K=class K{constructor(t){this.clickHistory=[],this.unsubscribeErrors=null,this.active=!1,this.lastInteraction=null,this.cooldownUntil=0,this.navTimestamps=[],this.unsubscribeNavigation=null,this.boundPageLeaveHandler=null,this.boundTurboNavigationHandler=null,this.lastNavigationAt=-1,this.boundSubmitHandler=null,this.boundInvalidHandler=null,this.recentSubmitForms=new WeakSet,this.recentFailedForms=new WeakSet,this.formFailureTimestamps=new WeakMap,this.errorPageUrls=new Set,this.domObserver=null,this.pendingDomChecks=0,this.lastMutationAt=-1,this.pendingTimers=new Set,this.onFrustration=t,this.boundClickHandler=r=>this.handleClick(r)}start(){this.active||(this.active=!0,this.restoreState(),document.addEventListener("click",this.boundClickHandler,!0),this.unsubscribeErrors=Tt.subscribe(()=>{const t=Date.now();if(!this.lastInteraction||t-this.lastInteraction.time>Oi)return;const r=this.lastInteraction;this.lastInteraction=null,this.emitIfReady({signal:"dead_click",target:ht(r.target),detail:"Uncaught error after interaction",timestamp:t})}),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.lastInteraction=null,this.stopNavigationTracking(),this.stopFormTracking(),this.errorPageUrls.clear(),this.clearPendingTimers(),this.pendingDomChecks=0,this.disconnectDomObserver())}schedule(t,r){const i=setTimeout(()=>{this.pendingTimers.delete(i),t()},r);this.pendingTimers.add(i)}clearPendingTimers(){for(const t of this.pendingTimers)clearTimeout(t);this.pendingTimers.clear()}startNavigationTracking(){this.unsubscribeNavigation=de(t=>this.handleNavigation(t)),this.boundPageLeaveHandler=()=>this.noteNavigationStarted(),window.addEventListener("beforeunload",this.boundPageLeaveHandler),window.addEventListener("pagehide",this.boundPageLeaveHandler),this.boundTurboNavigationHandler=()=>this.noteNavigationStarted(),document.addEventListener("turbo:before-visit",this.boundTurboNavigationHandler),document.addEventListener("turbo:submit-start",this.boundTurboNavigationHandler),document.addEventListener("turbo:before-fetch-request",this.boundTurboNavigationHandler)}stopNavigationTracking(){this.unsubscribeNavigation?.(),this.unsubscribeNavigation=null,this.navTimestamps=[],this.boundPageLeaveHandler&&(window.removeEventListener("beforeunload",this.boundPageLeaveHandler),window.removeEventListener("pagehide",this.boundPageLeaveHandler),this.boundPageLeaveHandler=null),this.boundTurboNavigationHandler&&(document.removeEventListener("turbo:before-visit",this.boundTurboNavigationHandler),document.removeEventListener("turbo:submit-start",this.boundTurboNavigationHandler),document.removeEventListener("turbo:before-fetch-request",this.boundTurboNavigationHandler),this.boundTurboNavigationHandler=null),this.lastNavigationAt=-1}noteNavigationStarted(){this.lastNavigationAt=Date.now()}restoreState(){const t=lt();this.navTimestamps=t.navTimestamps,this.cooldownUntil=t.cooldownUntil,this.errorPageUrls=new Set(t.errorPageUrls)}persistState(){const t=lt();me({...t,navTimestamps:this.navTimestamps,cooldownUntil:this.cooldownUntil,errorPageUrls:[...this.errorPageUrls]})}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),this.recentSubmitForms=new WeakSet,this.recentFailedForms=new WeakSet}handleClick(t){const r=t.target;if(!r||C(r))return;this.trackFormSubmitIntent(r),this.trackNativeNavigationIntent(t,r);const i=this.interactionTarget(r),n=Date.now();this.lastInteraction={target:i,time:n},this.clickHistory.push({target:i,time:n});const s=n-Ii;if(this.clickHistory=this.clickHistory.filter(a=>a.time>s),this.clickHistory.filter(a=>a.target===i).length>=Mi){this.clickHistory=[],this.emitHighPriority({signal:"rage_click",target:ht(i),timestamp:n});return}this.checkDeadClickDom(i,n)}handleNavigation(t){const r=Date.now();if(this.noteNavigationStarted(),t.type!=="replace"&&t.fromUrl!==t.toUrl&&t.type==="pop"){this.navTimestamps.push(r);const n=r-Hi;this.navTimestamps=this.navTimestamps.filter(s=>s>n),this.navTimestamps.length>=Fi&&(this.navTimestamps=[],this.emitIfReady({signal:"rapid_navigation",timestamp:r}))}this.persistState(),this.schedule(()=>{this.active&&this.checkErrorPage()},Ui)}handleFormSubmit(t){const r=t.target;r instanceof HTMLFormElement&&(C(r)||(this.rememberSubmitAttempt(r),this.schedule(()=>{this.active&&r.querySelector('[aria-invalid="true"], .is-invalid')&&this.recordFormFailure(r)},Lt)))}trackFormSubmitIntent(t){const r=t.closest("button, input");(r instanceof HTMLButtonElement||r instanceof HTMLInputElement)&&(r.type!=="submit"&&r.type!=="image"||!r.form||C(r.form)||this.rememberSubmitAttempt(r.form))}trackNativeNavigationIntent(t,r){r.closest("a[href]")&&queueMicrotask(()=>{this.active&&!t.defaultPrevented&&this.noteNavigationStarted()})}rememberSubmitAttempt(t){this.recentSubmitForms.add(t),this.schedule(()=>{this.recentSubmitForms.delete(t)},Lt)}recordFormFailure(t){if(this.recentFailedForms.has(t))return;this.recentFailedForms.add(t),this.schedule(()=>this.recentFailedForms.delete(t),Lt);const r=Date.now(),i=r-Ni,n=(this.formFailureTimestamps.get(t)??[]).filter(s=>s>i);n.push(r),this.formFailureTimestamps.set(t,n),!(n.length<Bi)&&(this.formFailureTimestamps.set(t,[]),this.emitIfReady({signal:"form_failure",target:ht(t),timestamp:r}))}handleFormInvalid(t){const r=t.target;if(!r||C(r))return;const i=r.closest("form");!i||!this.recentSubmitForms.has(i)||this.recordFormFailure(i)}checkErrorPage(){const t=location.href;if(this.errorPageUrls.has(t))return;const r=document.title.toLowerCase();if(be.some(n=>n.test(r))){this.errorPageUrls.add(t),this.emitHighPriority({signal:"error_page",detail:document.title,timestamp:Date.now()});return}const i=document.querySelectorAll('h1, h2, [class*="error"], [class*="not-found"], [id*="error"], [id*="not-found"]');for(const n of i){const s=n.textContent??"";if(s.length<200&&be.some(o=>o.test(s.toLowerCase()))){this.errorPageUrls.add(t),this.emitHighPriority({signal:"error_page",detail:s.trim().slice(0,60),timestamp:Date.now()});return}}}checkDeadClickDom(t,r){this.looksInteractive(t)&&(this.pendingDomChecks++,this.ensureDomObserver(),this.schedule(()=>{this.pendingDomChecks--;const i=this.lastMutationAt>=r,n=this.lastNavigationAt>=r;this.pendingDomChecks===0&&this.disconnectDomObserver(),!i&&!n&&this.active&&this.emitIfReady({signal:"dead_click_dom",target:ht(t),timestamp:r})},$i))}ensureDomObserver(){this.domObserver||(this.domObserver=new MutationObserver(()=>{this.lastMutationAt=Date.now()}),this.domObserver.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,characterData:!0}))}disconnectDomObserver(){this.domObserver?.disconnect(),this.domObserver=null}looksInteractive(t){if(qi.has(t.tagName)||t.hasAttribute("onclick"))return!0;const r=t.getAttribute("role");if(r&&Wi.has(r)||window.getComputedStyle(t).cursor==="pointer")return!0;if(t.classList)for(const n of t.classList){const s=n.toLowerCase();if(s.includes("btn")||s.includes("button"))return!0}return!1}interactionTarget(t){let r=t;for(;r&&r!==document.body;){if(this.isIntrinsicInteractive(r))return r;r=r.parentElement}let i=t;for(r=t.parentElement;r&&r!==document.body&&this.looksInteractive(r);)i=r,r=r.parentElement;return i}isIntrinsicInteractive(t){if(zi.has(t.tagName))return!0;const r=t.getAttribute("role");return r&&ji.has(r)||t.hasAttribute("onclick")||t.hasAttribute("tabindex")?!0:t.contentEditable==="true"}emitIfReady(t){const r=Date.now();r<this.cooldownUntil||(this.cooldownUntil=r+K.COOLDOWN_MS,this.persistState(),this.onFrustration(t))}emitHighPriority(t){this.cooldownUntil=Date.now()+K.COOLDOWN_MS,this.persistState(),this.onFrustration(t)}};K.COOLDOWN_MS=6e4;let Pt=K;function ht(e){const t=e.tagName.toLowerCase(),r=e.id?`#${e.id}`:"",i=e.className&&typeof e.className=="string"?"."+e.className.trim().split(/\s+/).slice(0,2).join("."):"",n=e.textContent?.trim().slice(0,30)??"";return`<${t}${r}${i}>${n?` "${n}"`:""}`}class Vi extends Error{constructor(t){super(`HTTP ${t}`),this.name="ApiError",this.status=t}}const Yi=25e3,Xi="https://makethisbetter.dev/api/v1",Ki="sensitive-data-v1";class Gi{constructor(t){this.projectKey=t.projectKey,this.apiUrl=(t.apiUrl??Xi).replace(/\/$/,""),this.retryDelayMs=t.retryDelayMs??1e3,this.userToken=t.userToken,this.userTokenFn=t.userTokenFn}async resolveUserToken(){return this.userTokenFn?this.userTokenFn():this.userToken}async resolveScreenshotResourceUrl(t,r,i,n,s){if(!(n&&!n.startsWith("image/")))try{const o=new URL(i,window.location.href);if(!["http:","https:"].includes(o.protocol)||o.origin===window.location.origin)return;const a=await this.submissionHeaders(r,"application/json"),c=await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/image_proxy_url`,{method:"POST",headers:a,body:JSON.stringify({image_proxy_url:{source:o.href}}),signal:s})).json();return typeof c.url=="string"?c.url:void 0}catch{return}}async authHeaders(t){const r={"X-Project-Key":this.projectKey},i=await this.resolveUserToken();return i&&(r["X-User-Token"]=i),t&&(r["Content-Type"]=t),r}async submissionHeaders(t,r){const i=await this.authHeaders(r);return i["X-Submission-Token"]=t,i}async createSubmissionSession(t,r){const i=Qi(),n=new FormData;if(n.append("feedback[description]",t.description),n.append("feedback[page_url]",t.page_url),n.append("feedback[user_agent]",t.user_agent),n.append("feedback[browser]",t.browser),n.append("feedback[os]",t.os),n.append("feedback[screen_width]",String(t.screen_width)),n.append("feedback[screen_height]",String(t.screen_height)),n.append("feedback[console_errors]",JSON.stringify(t.console_errors)),n.append("feedback[annotations]",JSON.stringify(t.annotations)),t.target_element&&n.append("feedback[target_element]",JSON.stringify(t.target_element)),t.user_id&&n.append("feedback[user_id]",t.user_id),t.reporter_external_id&&n.append("feedback[reporter_external_id]",t.reporter_external_id),t.reporter_email&&n.append("feedback[reporter_email]",t.reporter_email),t.user_email&&n.append("feedback[user_email]",t.user_email),t.user_name&&n.append("feedback[user_name]",t.user_name),t.breadcrumbs&&t.breadcrumbs.length>0&&n.append("feedback[breadcrumbs]",JSON.stringify(t.breadcrumbs)),t.recording_events&&t.recording_events.length>0){const l=JSON.stringify(t.recording_events),c=new Blob([l],{type:"application/json"});n.append("feedback[recording]",c,"interaction-replay.json"),n.append("feedback[recording_duration]",String(t.recording_duration??0))}if(r){const l=r.type==="image/jpeg"?"jpg":"png";n.append("feedback[screenshot]",r,`screenshot.${l}`)}const s=await this.authHeaders();return s["X-Submission-Token"]=i,s["X-MTB-Capture-Policy"]=Ki,s["X-Idempotency-Key"]=Zi(),{...(await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions`,{method:"POST",headers:s,body:n})).json()).submission_session,token:i}}async createIdentityToken(t){const r=await this.authHeaders("application/json");try{return await(await this.fetchWithRetry(`${this.apiUrl}/widget/identity_tokens`,{method:"POST",headers:r,body:JSON.stringify({reporter_external_id:t})})).json()}catch{return null}}async updateReporter(t,r,i){const n=await this.authHeaders("application/json");n["X-Identity-Token"]=i;try{return await this.fetchWithRetry(`${this.apiUrl}/widget/feedbacks/${t}/reporter`,{method:"PATCH",headers:n,body:JSON.stringify({reporter:{email:r}})}),!0}catch{return!1}}async answerClarification(t,r,i){return this.requestClarification(t,r,{message:_(i)})}async requestClarification(t,r,i){const n=await this.submissionHeaders(r,"application/json");return(await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/clarification`,{method:"POST",headers:n,body:JSON.stringify(i)})).json()).clarification}async streamClarification(t,r,i,n){const s=await this.submissionHeaders(r,"application/json");s.Accept="text/event-stream";const o=await fetch(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/clarification`,{method:"POST",headers:s,body:JSON.stringify({}),signal:n}),a=o.headers.get("Content-Type")??"";if(!o.ok||!o.body||!a.includes("text/event-stream"))throw new Error("clarify stream unavailable");return Ji(o.body,i)}async finalizeSubmissionSession(t,r){const i=await this.submissionHeaders(r),n=new AbortController,s=setTimeout(()=>n.abort(),Yi);try{return(await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/feedback`,{method:"POST",headers:i,signal:n.signal})).json()).feedback}finally{clearTimeout(s)}}async uploadScreenshot(t,r,i,n){const s=await this.submissionHeaders(r);delete s["Content-Type"];const o=new FormData;o.append("screenshot",i,"screenshot.jpg"),await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/screenshot`,{method:"PUT",headers:s,body:o,signal:n})}async abandonSubmissionSession(t,r){const i=await this.submissionHeaders(r);await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}`,{method:"DELETE",headers:i})}async fetchWithRetry(t,r,i=1){let n;try{n=await fetch(t,r)}catch(s){if(i>0&&!r.signal?.aborted)return await pe(this.retryDelayMs),this.fetchWithRetry(t,r,i-1);throw s}if(n.ok)return n;if(n.status>=500&&i>0)return await pe(this.retryDelayMs),this.fetchWithRetry(t,r,i-1);throw new Vi(n.status)}}function pe(e){return e<=0?Promise.resolve():new Promise(t=>setTimeout(t,e))}async function Ji(e,t){const r=e.getReader(),i=new TextDecoder;let n="",s=null;const o=a=>{const l=a.split(`
60
- `).find(m=>m.startsWith("event:")),c=a.split(`
61
- `).find(m=>m.startsWith("data:"));if(!c)return;const h=l?.slice(6).trim(),u=JSON.parse(c.slice(5).trim());h==="delta"&&typeof u.text=="string"?t(u.text):h==="done"&&(s={messages:Array.isArray(u.messages)?u.messages:[],suggestions:Array.isArray(u.suggestions)?u.suggestions.filter(m=>typeof m=="string"):[],done:u.done!==!1,failed:u.error===!0})};for(;;){const{done:a,value:l}=await r.read();if(a)break;n+=i.decode(l,{stream:!0});let c;for(;(c=n.indexOf(`
59
+ `}bindEvents(){this.el.querySelector(".mtb-chat-close").addEventListener("click",()=>{this.opts.onCancel()}),this.quickRepliesEl.querySelectorAll(".mtb-chat-qr").forEach(i=>{i.addEventListener("click",()=>{const r=i.dataset.value??i.dataset.quick??"";this.inputEl.value=r,this.sendMessage(r)})}),this.inputEl.addEventListener("input",()=>{this.sendBtn.disabled=!this.inputEl.value.trim(),this.opts.onActivity?.()}),this.inputEl.addEventListener("keydown",i=>{if(!ft(i)&&i.key==="Enter"&&!i.shiftKey){i.preventDefault();const r=this.inputEl.value.trim();r?this.sendMessage(r):this.state==="clarifying"&&this.skipAndSend()}}),this.sendBtn.addEventListener("click",()=>{const i=this.inputEl.value.trim();i&&this.sendMessage(i)});const t=this.el.querySelector(".mtb-chat-screenshot");t&&this.opts.onScreenshotToggle&&t.addEventListener("click",()=>{const i=t.getAttribute("aria-pressed")==="true";t.setAttribute("aria-pressed",String(!i)),t.classList.toggle("mtb-chat-screenshot-off",i),this.opts.onScreenshotToggle(!i)})}async sendMessage(t){if(this.state==="sending"||this.state==="answering")return;if(this.state==="clarifying"){this.handleAnswer(t);return}this.state="sending",this.appendUserBubble(t),this.quickRepliesEl.style.display="none",this.hideCapture(),this.showThinking(),this.setComposerDisabled(!0);let i;try{i=await this.opts.onSubmit(t)}catch{i=null}if(!i){this.removeThinking(),this.setComposerDisabled(!1),this.showRetryableError(this.i18n.error.submit,()=>{this.clearError(),this.sendMessage(t)}),this.state="idle";return}if(this.session=i,!i.ai_clarify_available){this.removeThinking(),this.showDone();return}let r=null,n=!1;this.clarifyAbort=new AbortController;try{r=await this.opts.onClarify(i.id,i.token,a=>{n||(this.removeThinking(),this.startStreamingBubble(),n=!0),this.appendStreamDelta(a)},this.clarifyAbort.signal)}catch{n?this.endStreamingBubble():this.removeThinking(),this.showDone();return}if(n?this.endStreamingBubble():this.removeThinking(),r.done||!r.messages.length){this.showDone();return}const s=r.messages.find(a=>a.role==="assistant");!n&&s&&this.appendAiBubble(s.content),this.renderSuggestions(r.suggestions),this.state="clarifying",this.setComposerDisabled(!1),this.inputEl.value="",this.inputEl.placeholder=this.i18n.clarify.placeholder,this.sendBtn.textContent=this.i18n.clarify.submit??this.i18n.clarify.send,this.sendBtn.disabled=!0,this.showSkip(),this.inputEl.focus({preventScroll:!0}),this.opts.onConversationOpen?.()}handleAnswer(t){const i=this.session;i&&(this.state="done",this.appendUserBubble(t),this.clearSuggestions(),this.hideSkip(),this.setComposerDisabled(!0),this.renderSuccess(),Promise.resolve(this.opts.onAnswer(i.id,i.token,t)).catch(()=>{}).then(()=>this.finalizeInBackground()))}showDone(){this.state="done",this.hideSkip(),this.setComposerDisabled(!0),this.renderSuccess(),this.finalizeInBackground()}renderSuccess(){const t=this.i18n.success;this.messagesEl.remove(),this.quickRepliesEl.remove(),this.composerEl.remove();const i=this.el.querySelector(".mtb-chat-success")??document.createElement("div");i.className="mtb-chat-success mtb-chat-success-simple",i.replaceChildren();const r=document.createElement("div");r.className="mtb-chat-success-icon",r.innerHTML=zi,i.appendChild(r);const n=document.createElement("div");n.className="mtb-chat-success-title",n.textContent=this.session?.ai_clarify_available===!1?t.title_no_ai:t.title,i.appendChild(n);const s=document.createElement("a");s.className="mtb-chat-success-link mtb-chat-success-link-pending",s.href="#",s.textContent=t.track_feedback,s.addEventListener("click",a=>a.preventDefault()),i.appendChild(s),i.parentElement||this.el.appendChild(i),this.attachHandoff()}showFinalizeFailure(t){this.autoCloseTimer&&(clearTimeout(this.autoCloseTimer),this.autoCloseTimer=null);let i=this.el.querySelector(".mtb-chat-success");i||(this.messagesEl.remove(),this.quickRepliesEl.remove(),this.composerEl.remove(),i=document.createElement("div"),this.el.appendChild(i)),i.className="mtb-chat-success mtb-chat-finalize-failure",i.innerHTML=`
60
+ <div class="mtb-chat-success-icon mtb-chat-failure-icon">!</div>
61
+ <div class="mtb-chat-success-title">${d(this.i18n.error.finalize_title)}</div>
62
+ <div class="mtb-chat-finalize-message">${d(this.i18n.error.finalize_message)}</div>
63
+ ${t?`<button class="mtb-chat-finalize-retry" type="button">${d(this.i18n.clarify.retry)}</button>`:""}
64
+ <button class="mtb-chat-finalize-close" type="button">${d(this.i18n.success.close)}</button>
65
+ `,t&&i.querySelector(".mtb-chat-finalize-retry").addEventListener("click",()=>{const r=i.querySelector(".mtb-chat-finalize-retry");r.disabled=!0,r.innerHTML='<span class="mtb-chat-finalize-spinner" aria-label="Retrying"></span>',t()}),i.querySelector(".mtb-chat-finalize-close").addEventListener("click",()=>this.opts.onCancel())}showFinalizeSuccess(){this.state="done",this.renderSuccess()}attachHandoff(){const t=this.el.querySelector(".mtb-chat-success");if(!t)return;this.i18n.success;const i=this.opts.resolveBoardLink?.(),r=t.querySelector(".mtb-chat-success-link-pending");i&&r&&(r.classList.remove("mtb-chat-success-link-pending"),r.addEventListener("click",s=>{s.preventDefault(),i()}));const n=this.opts.resolveEmailCapture?.();n&&!t.querySelector(".mtb-chat-email-card")?(this.autoCloseTimer&&(clearTimeout(this.autoCloseTimer),this.autoCloseTimer=null),t.classList.remove("mtb-chat-success-simple"),t.appendChild(this.buildEmailCard(n))):!n&&!this.autoCloseTimer&&!t.querySelector(".mtb-chat-email-card")&&(this.autoCloseTimer=setTimeout(()=>this.destroy(),Zt))}finalizeInBackground(){Promise.resolve(this.opts.onFinalize()).then(()=>this.attachHandoff()).catch(()=>{})}buildEmailCard(t){const i=this.i18n.success,r=document.createElement("div");r.className="mtb-chat-email-card";const n=document.createElement("div");n.className="mtb-chat-email-row";const s=document.createElement("div");s.className="mtb-chat-email-field";const a=document.createElement("input");a.className="mtb-chat-email-input",a.type="email",a.placeholder=i.email_cta,s.appendChild(a);const o=document.createElement("button");o.className="mtb-chat-email-submit",o.type="button",o.textContent=i.notify,o.disabled=!0;const l=async()=>{const c=a.value.trim();if(!c)return;if(o.disabled=!0,a.disabled=!0,await t.onSubmit(c)){const m=document.createElement("div");m.className="mtb-chat-email-note",m.textContent=i.email_saved,r.replaceChildren(m),this.autoCloseTimer=setTimeout(()=>this.destroy(),Zt);return}a.disabled=!1,o.disabled=!1;const u=r.querySelector(".mtb-chat-email-error")??document.createElement("div");u.className="mtb-chat-email-error",u.textContent=i.email_error,r.appendChild(u)};return a.addEventListener("input",()=>{o.disabled=!a.value.trim()}),a.addEventListener("keydown",c=>{c.key==="Enter"&&a.value.trim()&&l()}),o.addEventListener("click",()=>void l()),n.appendChild(s),n.appendChild(o),r.appendChild(n),r}appendUserBubble(t){const i=document.createElement("div");i.className="mtb-chat-bubble mtb-chat-bubble-user",i.textContent=t,this.messagesEl.appendChild(i),this.messagesEl.scrollTop=this.messagesEl.scrollHeight,this.inputEl.value="",this.sendBtn.disabled=!0}startStreamingBubble(){const t=document.createElement("div");t.className="mtb-chat-ai-row",t.innerHTML=`<div class="mtb-chat-avatar">${et}</div><div class="mtb-chat-bubble mtb-chat-bubble-ai"></div>`,this.messagesEl.appendChild(t),this.streamingBubbleEl=t.querySelector(".mtb-chat-bubble-ai")}appendStreamDelta(t){this.streamingBubbleEl&&(this.streamingBubbleEl.textContent=(this.streamingBubbleEl.textContent??"")+t,this.messagesEl.scrollTop=this.messagesEl.scrollHeight)}endStreamingBubble(){this.streamingBubbleEl=null}appendAiBubble(t){const i=document.createElement("div");i.className="mtb-chat-ai-row",i.innerHTML=`<div class="mtb-chat-avatar">${et}</div><div class="mtb-chat-bubble mtb-chat-bubble-ai"></div>`,i.querySelector(".mtb-chat-bubble-ai").textContent=t,this.messagesEl.appendChild(i),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}renderSuggestions(t){if(this.clearSuggestions(),!t?.length)return;const i=document.createElement("div");i.className="mtb-chat-suggestions";for(const r of t){const n=document.createElement("button");n.className="mtb-chat-sg",n.type="button",n.textContent=r,n.addEventListener("click",()=>{this.inputEl.value=r,this.sendBtn.disabled=!1,this.inputEl.focus({preventScroll:!0})}),i.appendChild(n)}this.messagesEl.appendChild(i),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}clearSuggestions(){this.messagesEl.querySelector(".mtb-chat-suggestions")?.remove()}showThinking(){if(this.messagesEl.querySelector(".mtb-chat-thinking"))return;const t=document.createElement("div");t.className="mtb-chat-ai-row mtb-chat-thinking",t.innerHTML=`<div class="mtb-chat-avatar">${et}</div><div class="mtb-chat-dots"><span></span><span></span><span></span></div>`,this.messagesEl.appendChild(t),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}removeThinking(){this.messagesEl.querySelector(".mtb-chat-thinking")?.remove()}showRetryableError(t,i){this.clearError();const r=document.createElement("div");r.className="mtb-chat-error-row";const n=document.createElement("span");n.className="mtb-chat-error-text",n.textContent=t;const s=document.createElement("button");s.className="mtb-chat-error-retry",s.type="button",s.textContent=this.i18n.clarify.retry,s.addEventListener("click",i),r.appendChild(n),r.appendChild(s),this.messagesEl.appendChild(r),this.messagesEl.scrollTop=this.messagesEl.scrollHeight}clearError(){this.messagesEl.querySelectorAll(".mtb-chat-error-row").forEach(t=>t.remove())}showSkip(){if(this.actionsEl.querySelector(".mtb-chat-skip"))return;const t=document.createElement("button");t.className="mtb-chat-skip",t.type="button",t.title=this.i18n.clarify.skip,t.textContent=this.i18n.clarify.skip_short,t.addEventListener("click",()=>this.skipAndSend()),this.actionsEl.insertBefore(t,this.sendBtn)}skipAndSend(){this.hideSkip(),this.state="done",this.setComposerDisabled(!0),this.renderSuccess(),this.finalizeInBackground()}hideSkip(){this.actionsEl?.querySelector(".mtb-chat-skip")?.remove()}hideCapture(){this.actionsEl.querySelector(".mtb-chat-screenshot")?.remove(),this.actionsEl.querySelector(".mtb-chat-attachment")?.remove()}setComposerDisabled(t){this.inputEl.disabled=t,this.sendBtn.disabled=t,this.composerEl.classList.toggle("mtb-chat-composer-disabled",t)}positionCard(t,i,r,n){const s=Di(n),{vw:a,vh:o,minLeft:l,maxRight:c}=s,h=tt,u=8,m=Mi(Fi,s),v=(this.el.offsetHeight||280)+80;let w,b;const zt=r&&r.width<a*.6&&r.height<o*.6;r&&zt?(w=r.left,b=r.bottom+u,b+v>o-h&&(b=r.top-v-u),b<h&&(b=Math.min(r.bottom+u,o-v-h))):(w=t+12,b=i+12),w+m>c&&(w=c-m),w<l&&(w=l),b<h&&(b=h),b+v>o-h&&(b=o-v-h),b<h&&(b=h),this.el.style.left=`${w}px`,this.el.style.top=`${b}px`,this.el.style.maxHeight=`${o-b-h}px`}submit(t){this.sendMessage(t)}sessionId(){return this.session?.id??null}destroy(){this.clarifyAbort?.abort(),this.autoCloseTimer&&clearTimeout(this.autoCloseTimer),window.removeEventListener("keydown",this.handleEscape),this.sheet.release(),this.focusTrap.release(),this.el.remove(),this.focusTrap.restoreFocus()}}const $i=5e3,Ui='<svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor"><path d="M8.1 14.6L3.8 10.3l1.5-1.5 2.8 2.8 6.6-6.6 1.5 1.5z"/></svg>';class ji{constructor(t,i,r,n){const s=i.success,a=n?.skipFollowup?s.title_no_ai:s.title;this.el=t.el("div","mtb-chat mtb-chat-receipt"),this.el.setAttribute("role","dialog"),this.el.setAttribute("aria-modal","true"),this.el.setAttribute("aria-label",a);const o=document.createElement("div");o.className="mtb-chat-success mtb-chat-success-simple";const l=document.createElement("div");l.className="mtb-chat-success-icon",l.innerHTML=Ui,o.appendChild(l);const c=document.createElement("div");if(c.className="mtb-chat-success-title",c.textContent=a,o.appendChild(c),n?.onViewFeedback){const h=document.createElement("a");h.className="mtb-chat-success-link",h.href="#",h.textContent=s.track_feedback,h.addEventListener("click",u=>{u.preventDefault(),n.onViewFeedback()}),o.appendChild(h)}this.el.appendChild(o),t.append(this.el),this.focusTrap=Jt(this.el),this.autoCloseTimer=setTimeout(r,$i)}destroy(){clearTimeout(this.autoCloseTimer),this.focusTrap.release(),this.el.remove(),this.focusTrap.restoreFocus()}}const g="[Filtered]",qi=/-----BEGIN ((?:[A-Z0-9]+ )*PRIVATE KEY)-----[\s\S]*?-----END \1-----/g,Wi=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g,Vi=[/\bsk-(?:proj-)?[A-Za-z0-9_-]{20,}\b/g,/\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{20,}\b/g,/\bgh[pousr]_[A-Za-z0-9]{30,}\b/g,/\bAKIA[0-9A-Z]{16}\b/g,/\bxox[baprs]-[A-Za-z0-9-]{20,}\b/g],Yi=/\b(?:\d[ -]?){12,18}\d\b/g,Xi=/\bhttps?:\/\/[^\s<>"']+/gi,Ki=new Set(["type","autocomplete","name","id","aria_label","placeholder"]),Gi=new Set(["value","content"]),Ji=new Set(["password","hidden","file"]),Zi=new Set(["current_password","new_password","one_time_code","cc_number","cc_csc","cc_exp","cc_exp_month","cc_exp_year"]),Qi=/(?:^|_)(?:password|passwd|passcode|card_(?:number|no)(?:_[0-9]+)?|credit_card|cc_(?:number|num|csc|cvv|cvc|exp|expiry)|cvv|cvc|csc|security_code|one_time_(?:code|password)|otp(?:_code)?|verification_code|auth(?:entication)?_token|access_token|refresh_token|id_token|token|api_key|client_secret|secret|authorization|cookie|set_cookie|credential|private_key|hidden_value|file_name|filename)(?:$|_(?:value|field|input|confirmation|confirm|header|data|pem)$)/;function _(e){let t=e.replace(qi,g).replace(Wi,g);for(const i of Vi)t=t.replace(i,g);return t=t.replace(Yi,i=>tr(i)?g:i),t.replace(Xi,i=>F(i)||g)}function F(e){try{const t=new URL(e);return`${t.origin}${t.pathname}`}catch{return""}}function it(e,t){if(t&&Qt(t)&&e!=null)return g;if(typeof e=="string")return _(e);if(Array.isArray(e))return e.map(i=>it(i));if(e&&typeof e=="object"){const i=te(e);return Object.fromEntries(Object.entries(e).map(([n,s])=>{const a=i&&Gi.has(H(n))&&s!=null?g:it(s,n);return[_(n),a]}))}return e}function Qt(e){return Qi.test(H(e))}function te(e){return Object.entries(e).some(([t,i])=>{if(typeof i!="string")return!1;const r=H(t);return Ki.has(r)?r==="type"?Ji.has(H(i)):r==="autocomplete"?i.split(/\s+/).some(n=>Zi.has(H(n))):Qt(i):!1})}function H(e){return e.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}function tr(e){const t=e.replace(/\D/g,"");if(t.length<13||t.length>19)return!1;let i=0,r=!1;for(let n=t.length-1;n>=0;n-=1){let s=Number(t[n]);r&&(s*=2,s>9&&(s-=9)),i+=s,r=!r}return i%10===0}function ee(e){return te({type:e.getAttribute("type"),autocomplete:e.getAttribute("autocomplete"),name:e.getAttribute("name"),id:e.id,"aria-label":e.getAttribute("aria-label"),placeholder:e.getAttribute("placeholder")})}function rt(e,t){return e&&(ee(t)?g:_(e))}const er=512;function ie(){return new WeakMap}function re(e,t){let i=e.parentElement;for(;i&&i!==document.body&&i!==document.documentElement;){const r=ne(i,t);if(r==="sensitive")return!0;if(r==="contains-sensitive-child"||r==="too-large")return!1;i=i.parentElement}return!1}function ne(e,t){const i=t.get(e);if(i)return i;const r=e.textContent??"";let n="none";return r.length>er?n="too-large":_(r)!==r&&(n=Array.from(e.children).some(a=>{const o=ne(a,t);return o==="sensitive"||o==="contains-sensitive-child"})?"contains-sensitive-child":"sensitive"),t.set(e,n),n}function ir(e){return new Promise(t=>{const i=new Image;i.onload=()=>t(i),i.onerror=()=>t(null),i.src=e})}function se(e){const t=[];let i=null;const r=e.match(/[ML]\s*[-\d.]+\s+[-\d.]+/g)??[];for(const n of r){const[s,a]=n.slice(1).trim().split(/\s+/).map(Number);Number.isNaN(s)||Number.isNaN(a)||(n[0]==="M"?(i=[[s,a]],t.push(i)):i&&i.push([s,a]))}return t}function rr(e,t,i){return se(e).map(r=>r.map(([n,s],a)=>`${a===0?"M":"L"} ${n+t} ${s+i}`).join(" ")).join(" ")}let B=null;function ae(){return B||(B=Promise.resolve().then(()=>vs).catch(e=>{throw B=null,e}),B)}let Et,St=null;function Ct(){return Et!==void 0?Promise.resolve(Et):(St??(St=ae().then(({getFontEmbedCSS:e})=>e(document.body)).then(e=>(Et=e,e)).catch(()=>{St=null})),St)}const nr=200,sr="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";async function ar(e,t){try{if(t?.aborted)return null;const[{toJpeg:i},r]=await Promise.all([ae(),Ct()]),n=document.body.getBoundingClientRect(),s=fi(),a={x:window.scrollX,y:window.scrollY},o=ur(document.body),l=await i(document.body,{quality:.85,imagePlaceholder:sr,resourceUrlResolver:e,fetchRequestInit:t?{signal:t}:void 0,width:s.width,height:s.height,pixelRatio:pr(s),backgroundColor:"#ffffff",skipFonts:!1,skipAutoScale:!1,fontEmbedCSS:r,style:{transform:`translate(${n.left}px, ${n.top}px)`,transformOrigin:"top left"},filter:c=>{if(c instanceof HTMLElement&&c.id===x)return!1;if(!(c instanceof Element))return!0;const h=c.getBoundingClientRect();return h.width===0&&h.height===0?!0:h.top+window.scrollY-a.y<=s.height+nr}});return t?.aborted?null:{dataUrl:l,metrics:s,redactions:o,pageScroll:a}}catch{return null}}async function or(e,t=[],i){try{const r=t.map(n=>lr(n,e.pageScroll));return await dr(e.dataUrl,r,e.metrics,e.redactions,i)}catch{return null}}function lr(e,t){const i=cr(e,t);return i.x===0&&i.y===0?e:{...e,x:e.x+i.x,y:e.y+i.y,targetRect:e.targetRect&&{...e.targetRect,top:e.targetRect.top+i.y,left:e.targetRect.left+i.x,bottom:e.targetRect.bottom+i.y},drawPath:e.drawPath&&rr(e.drawPath,i.x,i.y)}}function cr(e,t){return e.captureOffsetX!==void 0&&e.captureOffsetY!==void 0?gi({x:e.captureOffsetX,y:e.captureOffsetY},t):D(hr(e))}function hr(e){if(e.targetSelector)try{const t=document.querySelector(e.targetSelector);if(t)return t}catch{}return document.elementsFromPoint?.(e.x,e.y)[0]??null}async function dr(e,t,i,r,n){const s=document.createElement("canvas"),a=s.getContext("2d");if(!a)return null;const o=await ir(e);if(!o)return null;s.width=o.naturalWidth||window.innerWidth,s.height=o.naturalHeight||window.innerHeight,a.drawImage(o,0,0);const l=bi(i,s.width,s.height);a.fillStyle="#e5e7eb";for(const c of r){const h=pi(l,c);a.fillRect(h.left,h.top,h.width,h.height)}for(const c of t)c.type==="draw"&&c.drawPath?br(a,c.drawPath,l,n?.primary):c.type==="pin"&&fr(a,G(l,c.x),J(l,c.y),n);return gr(s)}function ur(e){const t=[];for(const s of mr(e,`.${Z}`))Tt(t,s.getBoundingClientRect(),oe(s));for(const s of e.querySelectorAll("input, textarea, select")){if(le(s))continue;const a=s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement||s instanceof HTMLSelectElement?s.value:"",o=s.closest(`.${I}`)!==null,l=ee(s)||rt(a,s)!==a;!o&&!l||Tt(t,s.getBoundingClientRect(),oe(s),he)}const i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),r=ie();let n=i.nextNode();for(;n;){const s=n.parentElement,a=n.textContent??"",o=s?.closest(`.${I}`)!==null,l=_(a)!==a||re(n,r);if(s&&!le(s)&&(o||l)){const c=D(s),h=document.createRange();h.selectNodeContents(n);for(const u of Array.from(h.getClientRects()))Tt(t,u,c,he)}n=i.nextNode()}return t}function oe(e){return D(Wt(e))}function mr(e,t){const i=Array.from(e.querySelectorAll(t));return e.matches(t)?[e,...i]:i}function le(e){return e.closest(`#${x}`)!==null||e.closest(`.${Z}`)!==null}function Tt(e,t,i,r=0){if(![t.left,t.top,t.width,t.height].every(Number.isFinite))throw new Error("Invalid privacy redaction geometry");t.width<=0||t.height<=0||e.push({left:t.left+i.x-r,top:t.top+i.y-r,width:t.width+r*2,height:t.height+r*2})}function br(e,t,i,r=Yt){e.save(),e.lineCap="round",e.lineJoin="round";for(const n of se(t))if(n.length!==0){e.beginPath(),e.moveTo(G(i,n[0][0]),J(i,n[0][1]));for(let s=1;s<n.length;s++)e.lineTo(G(i,n[s][0]),J(i,n[s][1]));e.shadowColor="transparent",e.strokeStyle="rgba(15, 23, 42, 0.72)",e.lineWidth=7,e.stroke(),e.strokeStyle="#ffffff",e.lineWidth=5.5,e.stroke(),e.strokeStyle=r,e.lineWidth=3.5,e.stroke()}e.restore()}const ce=16e6,he=2;function pr(e){const t=e.width*e.height;return!Number.isFinite(t)||t<=ce?1:Math.sqrt(ce/t)}function fr(e,t,i,r){const n=r?.primary??Yt;e.save(),e.shadowColor="rgba(15, 23, 42, 0.68)",e.shadowOffsetY=2,e.shadowBlur=8,e.fillStyle=n,e.beginPath(),e.arc(t,i,11,0,Math.PI*2),e.fill(),e.shadowColor="transparent",e.lineWidth=2,e.strokeStyle="#ffffff",e.stroke(),e.restore()}function gr(e){return new Promise(t=>{try{e.toBlob(i=>t(i),"image/jpeg",.85)}catch{t(null)}})}class wr{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,i,r,n,s)=>(this.emit({name:yr(s),message:String(t),source:i,line:r,col:n,error:s}),this.originalOnError?this.originalOnError.call(window,t,i,r,n,s):!1),window.onerror=this.installedOnError,this.rejectionHandler=t=>{const i=t.reason instanceof Error?t.reason.message:String(t.reason),r=t.reason instanceof Error?t.reason.name:"UnhandledRejection";this.emit({name:r,message:`Unhandled rejection: ${i}`})},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 i of this.listeners)i(t)}}const _t=new wr;function yr(e){return!e||typeof e!="object"||!("name"in e)?void 0:String(e.name)||void 0}function de(e){const t=vr(e.name)||xr(e.message),i=kr(e);return i?`${t} (${i})`:t}function vr(e){return e&&/^[A-Za-z][A-Za-z0-9]*(?:Error|Exception|Rejection)$/.test(e)?e:""}function xr(e){return e.match(/^([A-Za-z][A-Za-z0-9]*(?:Error|Exception))\b/)?.[1]??"Error"}function kr(e){if(!e.source)return"";try{const t=new URL(e.source,window.location.href).pathname;return e.line==null?t:`${t}:${e.line}:${e.col??0}`}catch{return""}}const Er=20;class Sr{constructor(){this.errors=[],this.unsubscribe=null}start(){this.unsubscribe||(this.unsubscribe=_t.subscribe(t=>this.record(t)))}record(t){this.addError(de(t))}addError(t){this.errors.length>=Er||this.errors.includes(t)||this.errors.push(t)}getErrors(){return[...this.errors]}stop(){this.unsubscribe?.(),this.unsubscribe=null}}const nt=new Set;let N=null,O=null,z=null,st=null,$=null,at=null;function ue(e){nt.add(e),Cr();let t=!1;return()=>{t||(t=!0,nt.delete(e),nt.size===0&&Tr())}}function At(e,t){const i={type:e,fromUrl:t,toUrl:location.href};at=i.toUrl;for(const r of[...nt])try{r(i)}catch{}}function Cr(){if(z)return;at=location.href,$=()=>At("pop",at??location.href),window.addEventListener("popstate",$),N=history.pushState,O=history.replaceState;const e=N,t=O;z=function(i,r,n){const s=location.href;e.call(history,i,r,n),At("push",s)},st=function(i,r,n){const s=location.href;t.call(history,i,r,n),At("replace",s)},history.pushState=z,history.replaceState=st}function Tr(){$&&(window.removeEventListener("popstate",$),$=null),N&&history.pushState===z&&(history.pushState=N),O&&history.replaceState===st&&(history.replaceState=O),N=null,O=null,z=null,st=null,at=null}const _r=20;function Ar(e){return Q(e)?vt(e):gt(e)}function Lr(e){return Q(e)?Xt(e):Ut(e)}class Pr{constructor(){this.breadcrumbs=[],this.active=!1,this.unsubscribeErrors=null,this.unsubscribeNavigation=null,this.lastUrl="",this.boundClickHandler=t=>this.handleClick(t),this.boundChangeHandler=t=>this.handleChange(t)}start(){this.active||(this.active=!0,this.lastUrl=location.href,document.addEventListener("click",this.boundClickHandler,{capture:!0,passive:!0}),document.addEventListener("change",this.boundChangeHandler,{capture:!0,passive:!0}),this.unsubscribeErrors=_t.subscribe(t=>this.recordError(t)),this.unsubscribeNavigation=ue(()=>this.handleNavigation()))}stop(){this.active&&(this.active=!1,document.removeEventListener("click",this.boundClickHandler,!0),document.removeEventListener("change",this.boundChangeHandler,!0),this.unsubscribeErrors?.(),this.unsubscribeErrors=null,this.unsubscribeNavigation?.(),this.unsubscribeNavigation=null)}getBreadcrumbs(){return[...this.breadcrumbs]}add(t){this.breadcrumbs.push(t),this.breadcrumbs.length>_r&&this.breadcrumbs.shift()}handleClick(t){const i=t.target;if(i&&!C(i))try{this.add({type:"ui",category:"ui.click",timestamp:Date.now(),message:Ar(i),data:{selector:Lr(i)}})}catch{}}handleChange(t){const i=t.target;if(i&&!C(i))try{const r=i,n=Q(i)?vt(i):r.name||r.placeholder||i.getAttribute("aria-label")||i.tagName;this.add({type:"ui",category:"ui.input",timestamp:Date.now(),message:n,data:{field:n}})}catch{}}recordError(t){const i=de(t);this.add({type:"console",category:"console.error",timestamp:Date.now(),message:i,data:{message:i}})}handleNavigation(){if(!this.active)return;const t=this.lastUrl,i=location.href;if(t===i)return;this.lastUrl=i;const r=F(t),n=F(i);this.add({type:"navigation",category:"navigation",timestamp:Date.now(),message:`${r} → ${n}`,data:{from:r,to:n}})}}const me="mtb_frustration_state";let Lt=null;function ot(){try{const e=window.sessionStorage.getItem(me);return lt(e?JSON.parse(e):Lt)}catch{return lt(Lt)}}function be(e){const t=lt(e);Lt=t;try{window.sessionStorage.setItem(me,JSON.stringify(t))}catch{}}function Rr(){return ot().dismissedByUser}function Dr(){be({...ot(),dismissedByUser:!0})}function lt(e){const t=e??{};return{navTimestamps:Array.isArray(t.navTimestamps)?t.navTimestamps.filter(i=>typeof i=="number"):[],cooldownUntil:typeof t.cooldownUntil=="number"?t.cooldownUntil:0,errorPageUrls:Array.isArray(t.errorPageUrls)?t.errorPageUrls.filter(i=>typeof i=="string").slice(-20):[],dismissedByUser:t.dismissedByUser===!0}}const Mr=4,Ir=1500,Fr=3,Hr=5e3,Pt=500,Br=2,Nr=3e4,Or=2e3,zr=1e3,$r=300,Ur=new Set(["A","BUTTON","INPUT","SELECT","TEXTAREA","LABEL","SUMMARY","DETAILS"]),jr=new Set(["button","link","checkbox","radio","tab","menuitem","option","switch","textbox","combobox","listbox","slider","spinbutton"]),qr=new Set(["A","BUTTON","SUMMARY"]),Wr=new Set(["button","link","tab","menuitem"]),pe=[/\bnot found\b/,/\bserver error\b/,/^\s*(?:http\s*)?[45]\d{2}\s*$/,/\b(?:error|http|status)\s*[:-]?\s*[45]\d{2}\b/,/\b[45]\d{2}\s*[:-]?\s*error\b/],X=class X{constructor(t){this.clickHistory=[],this.unsubscribeErrors=null,this.active=!1,this.lastInteraction=null,this.cooldownUntil=0,this.navTimestamps=[],this.unsubscribeNavigation=null,this.boundPageLeaveHandler=null,this.boundTurboNavigationHandler=null,this.lastNavigationAt=-1,this.boundSubmitHandler=null,this.boundInvalidHandler=null,this.recentSubmitForms=new WeakSet,this.recentFailedForms=new WeakSet,this.formFailureTimestamps=new WeakMap,this.errorPageUrls=new Set,this.domObserver=null,this.pendingDomChecks=0,this.lastMutationAt=-1,this.pendingTimers=new Set,this.onFrustration=t,this.boundClickHandler=i=>this.handleClick(i)}start(){this.active||(this.active=!0,this.restoreState(),document.addEventListener("click",this.boundClickHandler,!0),this.unsubscribeErrors=_t.subscribe(()=>{const t=Date.now();if(!this.lastInteraction||t-this.lastInteraction.time>Or)return;const i=this.lastInteraction;this.lastInteraction=null,this.emitIfReady({signal:"dead_click",target:ct(i.target),detail:"Uncaught error after interaction",timestamp:t})}),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.lastInteraction=null,this.stopNavigationTracking(),this.stopFormTracking(),this.errorPageUrls.clear(),this.clearPendingTimers(),this.pendingDomChecks=0,this.disconnectDomObserver())}schedule(t,i){const r=setTimeout(()=>{this.pendingTimers.delete(r),t()},i);this.pendingTimers.add(r)}clearPendingTimers(){for(const t of this.pendingTimers)clearTimeout(t);this.pendingTimers.clear()}startNavigationTracking(){this.unsubscribeNavigation=ue(t=>this.handleNavigation(t)),this.boundPageLeaveHandler=()=>this.noteNavigationStarted(),window.addEventListener("beforeunload",this.boundPageLeaveHandler),window.addEventListener("pagehide",this.boundPageLeaveHandler),this.boundTurboNavigationHandler=()=>this.noteNavigationStarted(),document.addEventListener("turbo:before-visit",this.boundTurboNavigationHandler),document.addEventListener("turbo:submit-start",this.boundTurboNavigationHandler),document.addEventListener("turbo:before-fetch-request",this.boundTurboNavigationHandler)}stopNavigationTracking(){this.unsubscribeNavigation?.(),this.unsubscribeNavigation=null,this.navTimestamps=[],this.boundPageLeaveHandler&&(window.removeEventListener("beforeunload",this.boundPageLeaveHandler),window.removeEventListener("pagehide",this.boundPageLeaveHandler),this.boundPageLeaveHandler=null),this.boundTurboNavigationHandler&&(document.removeEventListener("turbo:before-visit",this.boundTurboNavigationHandler),document.removeEventListener("turbo:submit-start",this.boundTurboNavigationHandler),document.removeEventListener("turbo:before-fetch-request",this.boundTurboNavigationHandler),this.boundTurboNavigationHandler=null),this.lastNavigationAt=-1}noteNavigationStarted(){this.lastNavigationAt=Date.now()}restoreState(){const t=ot();this.navTimestamps=t.navTimestamps,this.cooldownUntil=t.cooldownUntil,this.errorPageUrls=new Set(t.errorPageUrls)}persistState(){const t=ot();be({...t,navTimestamps:this.navTimestamps,cooldownUntil:this.cooldownUntil,errorPageUrls:[...this.errorPageUrls]})}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),this.recentSubmitForms=new WeakSet,this.recentFailedForms=new WeakSet}handleClick(t){const i=t.target;if(!i||C(i))return;this.trackFormSubmitIntent(i),this.trackNativeNavigationIntent(t,i);const r=this.interactionTarget(i),n=Date.now();this.lastInteraction={target:r,time:n},this.clickHistory.push({target:r,time:n});const s=n-Ir;if(this.clickHistory=this.clickHistory.filter(o=>o.time>s),this.clickHistory.filter(o=>o.target===r).length>=Mr){this.clickHistory=[],this.emitHighPriority({signal:"rage_click",target:ct(r),timestamp:n});return}this.checkDeadClickDom(r,n)}handleNavigation(t){const i=Date.now();if(this.noteNavigationStarted(),t.type!=="replace"&&t.fromUrl!==t.toUrl&&t.type==="pop"){this.navTimestamps.push(i);const n=i-Hr;this.navTimestamps=this.navTimestamps.filter(s=>s>n),this.navTimestamps.length>=Fr&&(this.navTimestamps=[],this.emitIfReady({signal:"rapid_navigation",timestamp:i}))}this.persistState(),this.schedule(()=>{this.active&&this.checkErrorPage()},$r)}handleFormSubmit(t){const i=t.target;i instanceof HTMLFormElement&&(C(i)||(this.rememberSubmitAttempt(i),this.schedule(()=>{this.active&&i.querySelector('[aria-invalid="true"], .is-invalid')&&this.recordFormFailure(i)},Pt)))}trackFormSubmitIntent(t){const i=t.closest("button, input");(i instanceof HTMLButtonElement||i instanceof HTMLInputElement)&&(i.type!=="submit"&&i.type!=="image"||!i.form||C(i.form)||this.rememberSubmitAttempt(i.form))}trackNativeNavigationIntent(t,i){i.closest("a[href]")&&queueMicrotask(()=>{this.active&&!t.defaultPrevented&&this.noteNavigationStarted()})}rememberSubmitAttempt(t){this.recentSubmitForms.add(t),this.schedule(()=>{this.recentSubmitForms.delete(t)},Pt)}recordFormFailure(t){if(this.recentFailedForms.has(t))return;this.recentFailedForms.add(t),this.schedule(()=>this.recentFailedForms.delete(t),Pt);const i=Date.now(),r=i-Nr,n=(this.formFailureTimestamps.get(t)??[]).filter(s=>s>r);n.push(i),this.formFailureTimestamps.set(t,n),!(n.length<Br)&&(this.formFailureTimestamps.set(t,[]),this.emitIfReady({signal:"form_failure",target:ct(t),timestamp:i}))}handleFormInvalid(t){const i=t.target;if(!i||C(i))return;const r=i.closest("form");!r||!this.recentSubmitForms.has(r)||this.recordFormFailure(r)}checkErrorPage(){const t=location.href;if(this.errorPageUrls.has(t))return;const i=document.title.toLowerCase();if(pe.some(n=>n.test(i))){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 n of r){const s=n.textContent??"";if(s.length<200&&pe.some(a=>a.test(s.toLowerCase()))){this.errorPageUrls.add(t),this.emitHighPriority({signal:"error_page",detail:s.trim().slice(0,60),timestamp:Date.now()});return}}}checkDeadClickDom(t,i){this.looksInteractive(t)&&(this.pendingDomChecks++,this.ensureDomObserver(),this.schedule(()=>{this.pendingDomChecks--;const r=this.lastMutationAt>=i,n=this.lastNavigationAt>=i;this.pendingDomChecks===0&&this.disconnectDomObserver(),!r&&!n&&this.active&&this.emitIfReady({signal:"dead_click_dom",target:ct(t),timestamp:i})},zr))}ensureDomObserver(){this.domObserver||(this.domObserver=new MutationObserver(()=>{this.lastMutationAt=Date.now()}),this.domObserver.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!0,characterData:!0}))}disconnectDomObserver(){this.domObserver?.disconnect(),this.domObserver=null}looksInteractive(t){if(qr.has(t.tagName)||t.hasAttribute("onclick"))return!0;const i=t.getAttribute("role");if(i&&Wr.has(i)||window.getComputedStyle(t).cursor==="pointer")return!0;if(t.classList)for(const n of t.classList){const s=n.toLowerCase();if(s.includes("btn")||s.includes("button"))return!0}return!1}interactionTarget(t){let i=t;for(;i&&i!==document.body;){if(this.isIntrinsicInteractive(i))return i;i=i.parentElement}let r=t;for(i=t.parentElement;i&&i!==document.body&&this.looksInteractive(i);)r=i,i=i.parentElement;return r}isIntrinsicInteractive(t){if(Ur.has(t.tagName))return!0;const i=t.getAttribute("role");return i&&jr.has(i)||t.hasAttribute("onclick")||t.hasAttribute("tabindex")?!0:t.contentEditable==="true"}emitIfReady(t){const i=Date.now();i<this.cooldownUntil||(this.cooldownUntil=i+X.COOLDOWN_MS,this.persistState(),this.onFrustration(t))}emitHighPriority(t){this.cooldownUntil=Date.now()+X.COOLDOWN_MS,this.persistState(),this.onFrustration(t)}};X.COOLDOWN_MS=6e4;let Rt=X;function ct(e){const t=e.tagName.toLowerCase(),i=e.id?`#${e.id}`:"",r=e.className&&typeof e.className=="string"?"."+e.className.trim().split(/\s+/).slice(0,2).join("."):"",n=e.textContent?.trim().slice(0,30)??"";return`<${t}${i}${r}>${n?` "${n}"`:""}`}class Vr extends Error{constructor(t){super(`HTTP ${t}`),this.name="ApiError",this.status=t}}const Yr=25e3,Xr="https://makethisbetter.dev/api/v1",Kr="sensitive-data-v1";class Gr{constructor(t){this.projectKey=t.projectKey,this.apiUrl=(t.apiUrl??Xr).replace(/\/$/,""),this.retryDelayMs=t.retryDelayMs??1e3,this.userToken=t.userToken,this.userTokenFn=t.userTokenFn}async resolveUserToken(){return this.userTokenFn?this.userTokenFn():this.userToken}async resolveScreenshotResourceUrl(t,i,r,n,s){if(!(n&&!n.startsWith("image/")))try{const a=new URL(r,window.location.href);if(!["http:","https:"].includes(a.protocol)||a.origin===window.location.origin)return;const o=await this.submissionHeaders(i,"application/json"),c=await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/image_proxy_url`,{method:"POST",headers:o,body:JSON.stringify({image_proxy_url:{source:a.href}}),signal:s})).json();return typeof c.url=="string"?c.url:void 0}catch{return}}async authHeaders(t){const i={"X-Project-Key":this.projectKey},r=await this.resolveUserToken();return r&&(i["X-User-Token"]=r),t&&(i["Content-Type"]=t),i}async submissionHeaders(t,i){const r=await this.authHeaders(i);return r["X-Submission-Token"]=t,r}async createSubmissionSession(t,i){const r=Qr(),n=new FormData;if(n.append("feedback[description]",t.description),n.append("feedback[page_url]",t.page_url),n.append("feedback[user_agent]",t.user_agent),n.append("feedback[browser]",t.browser),n.append("feedback[os]",t.os),n.append("feedback[screen_width]",String(t.screen_width)),n.append("feedback[screen_height]",String(t.screen_height)),n.append("feedback[console_errors]",JSON.stringify(t.console_errors)),n.append("feedback[annotations]",JSON.stringify(t.annotations)),t.target_element&&n.append("feedback[target_element]",JSON.stringify(t.target_element)),t.user_id&&n.append("feedback[user_id]",t.user_id),t.reporter_external_id&&n.append("feedback[reporter_external_id]",t.reporter_external_id),t.reporter_email&&n.append("feedback[reporter_email]",t.reporter_email),t.user_email&&n.append("feedback[user_email]",t.user_email),t.user_name&&n.append("feedback[user_name]",t.user_name),t.breadcrumbs&&t.breadcrumbs.length>0&&n.append("feedback[breadcrumbs]",JSON.stringify(t.breadcrumbs)),t.recording_events&&t.recording_events.length>0){const l=JSON.stringify(t.recording_events),c=new Blob([l],{type:"application/json"});n.append("feedback[recording]",c,"interaction-replay.json"),n.append("feedback[recording_duration]",String(t.recording_duration??0))}if(i){const l=i.type==="image/jpeg"?"jpg":"png";n.append("feedback[screenshot]",i,`screenshot.${l}`)}const s=await this.authHeaders();return s["X-Submission-Token"]=r,s["X-MTB-Capture-Policy"]=Kr,s["X-Idempotency-Key"]=Zr(),{...(await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions`,{method:"POST",headers:s,body:n})).json()).submission_session,token:r}}async createIdentityToken(t){const i=await this.authHeaders("application/json");try{return await(await this.fetchWithRetry(`${this.apiUrl}/widget/identity_tokens`,{method:"POST",headers:i,body:JSON.stringify({reporter_external_id:t})})).json()}catch{return null}}async updateReporter(t,i,r){const n=await this.authHeaders("application/json");n["X-Identity-Token"]=r;try{return await this.fetchWithRetry(`${this.apiUrl}/widget/feedbacks/${t}/reporter`,{method:"PATCH",headers:n,body:JSON.stringify({reporter:{email:i}})}),!0}catch{return!1}}async answerClarification(t,i,r){return this.requestClarification(t,i,{message:_(r)})}async requestClarification(t,i,r){const n=await this.submissionHeaders(i,"application/json");return(await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/clarification`,{method:"POST",headers:n,body:JSON.stringify(r)})).json()).clarification}async streamClarification(t,i,r,n){const s=await this.submissionHeaders(i,"application/json");s.Accept="text/event-stream";const a=await fetch(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/clarification`,{method:"POST",headers:s,body:JSON.stringify({}),signal:n}),o=a.headers.get("Content-Type")??"";if(!a.ok||!a.body||!o.includes("text/event-stream"))throw new Error("clarify stream unavailable");return Jr(a.body,r)}async finalizeSubmissionSession(t,i){const r=await this.submissionHeaders(i),n=new AbortController,s=setTimeout(()=>n.abort(),Yr);try{return(await(await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/feedback`,{method:"POST",headers:r,signal:n.signal})).json()).feedback}finally{clearTimeout(s)}}async uploadScreenshot(t,i,r,n){const s=await this.submissionHeaders(i);delete s["Content-Type"];const a=new FormData;a.append("screenshot",r,"screenshot.jpg"),await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}/screenshot`,{method:"PUT",headers:s,body:a,signal:n})}async abandonSubmissionSession(t,i){const r=await this.submissionHeaders(i);await this.fetchWithRetry(`${this.apiUrl}/widget/feedback_submission_sessions/${t}`,{method:"DELETE",headers:r})}async fetchWithRetry(t,i,r=1){let n;try{n=await fetch(t,i)}catch(s){if(r>0&&!i.signal?.aborted)return await fe(this.retryDelayMs),this.fetchWithRetry(t,i,r-1);throw s}if(n.ok)return n;if(n.status>=500&&r>0)return await fe(this.retryDelayMs),this.fetchWithRetry(t,i,r-1);throw new Vr(n.status)}}function fe(e){return e<=0?Promise.resolve():new Promise(t=>setTimeout(t,e))}async function Jr(e,t){const i=e.getReader(),r=new TextDecoder;let n="",s=null;const a=o=>{const l=o.split(`
66
+ `).find(m=>m.startsWith("event:")),c=o.split(`
67
+ `).find(m=>m.startsWith("data:"));if(!c)return;const h=l?.slice(6).trim(),u=JSON.parse(c.slice(5).trim());h==="delta"&&typeof u.text=="string"?t(u.text):h==="done"&&(s={messages:Array.isArray(u.messages)?u.messages:[],suggestions:Array.isArray(u.suggestions)?u.suggestions.filter(m=>typeof m=="string"):[],done:u.done!==!1,failed:u.error===!0})};for(;;){const{done:o,value:l}=await i.read();if(o)break;n+=r.decode(l,{stream:!0});let c;for(;(c=n.indexOf(`
62
68
 
63
- `))!==-1;){const h=n.slice(0,c);n=n.slice(c+2);try{o(h)}catch{}}}if(n+=i.decode(),n.trim())try{o(n)}catch{}if(!s)throw new Error("clarify stream ended before done");return s}function Zi(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function Qi(){if(typeof crypto>"u"||typeof crypto.getRandomValues!="function")throw new Error("Secure random generation is unavailable");const e=crypto.getRandomValues(new Uint8Array(32));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}const fe="mtb_anon_id",ge="mtb_reporter_email",ye="mtb_board_url";let we=null,ve=null,xe=null;function ke(){try{const e=window.localStorage.getItem(fe);if(e?.startsWith("anon_"))return e;const t=Se();return window.localStorage.setItem(fe,t),t}catch{return we??(we=Se()),we}}function Ee(){try{return window.localStorage.getItem(ge)??void 0}catch{return ve??void 0}}function tn(e){ve=e;try{window.localStorage.setItem(ge,e)}catch{}}function en(){try{return window.localStorage.getItem(ye)??void 0}catch{return xe??void 0}}function z(e){xe=e;try{window.localStorage.setItem(ye,e)}catch{}}function Se(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`anon_${crypto.randomUUID()}`:`anon_${`${Date.now().toString(16)}-${Math.random().toString(16).slice(2,10)}`}`}const j={en:{tab:"Feedback",toolbar:{markup:"Mark up",record:"Record",hint:"Click to comment, drag to draw",hintTouch:"Drag to mark what's wrong",hintRecord:"Recording your screen",exit:"Exit"},popup:{about:"About",placeholder:"Describe the issue or suggestion...",submit:"Submit",sending:"Sending...",cancel:"Cancel",close:"Close",my_feedback:"My feedback",screenshot_label:"Attach screenshot",screenshot_hint:"Passwords and other sensitive fields are covered automatically.",screenshot_short:"Screenshot",screenshot_locked_hint:"Your drawing is baked onto the screenshot, so it is always attached. Sensitive fields are covered automatically.",recording_label:"Recording",recording_locked_hint:"A replay of what the page showed and how it was used — always included with a recording. No camera or microphone. Sensitive fields are covered automatically.",quickOptions:[{emoji:"🐛",label:"Broken",value:"Something's broken"},{emoji:"💡",label:"Suggestion",value:"I have a suggestion"},{emoji:"🤔",label:"Confused",value:"I'm confused"}]},success:{title:"Thanks, your feedback is in.",title_no_ai:"Thanks! We've received your feedback.",close:"Close",email_saved:"You'll get an email when it's resolved.",email_error:"Couldn't save your email. Please try again.",track_feedback:"Track your feedback",email_cta:"Email me when it's fixed",notify:"Notify"},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"},draw:{note_placeholder:"Add a note to your drawing",undo:"Undo",redo:"Redo",cancel:"Cancel",submit:"Submit"},record:{stop:"Stop",timer_label:"Recording",max_reached:"Maximum recording time reached",replay_label:"screen-recording.json",play:"Play recording",close:"Close",preview_unavailable:"Preview unavailable"},clarify:{title:"Make This Better AI",subtitle:"Sharpening your feedback",thinking:"Thinking...",placeholder:"Add details, then submit",send:"Send",submit:"Submit",send_feedback:"Send feedback",skip:"Skip & submit",skip_short:"Skip",cancel:"Cancel — don't send feedback",retry:"Retry",error:"Couldn't load the question. Send your feedback as is.",expired:"This feedback session expired before it could be sent. Please close the widget and submit again."}},"zh-CN":{tab:"反馈",toolbar:{markup:"标注",record:"录屏",hint:"点击标注,拖动绘制",hintTouch:"用手指圈出问题",hintRecord:"正在录制屏幕",exit:"退出"},popup:{about:"关于",placeholder:"描述问题或建议...",submit:"提交",sending:"发送中...",cancel:"取消",close:"关闭",my_feedback:"我的反馈",screenshot_label:"附带页面截图",screenshot_hint:"密码等敏感字段会自动打码。",screenshot_short:"截图",screenshot_locked_hint:"圈画会画在截图上,所以必定附带。敏感字段会自动打码。",recording_label:"录制",recording_locked_hint:"页面画面与操作过程的回放,录制内容必定随反馈提交。不含摄像头和麦克风,敏感字段会自动打码。",quickOptions:[{emoji:"🐛",label:"有问题",value:"出问题了"},{emoji:"💡",label:"建议",value:"我有一个建议"},{emoji:"🤔",label:"疑问",value:"我有点疑问"}]},success:{title:"收到了,谢谢你的反馈。",title_no_ai:"感谢!我们已收到您的反馈。",close:"关闭",email_saved:"问题解决后您会收到邮件通知。",email_error:"邮箱保存失败,请重试。",track_feedback:"查看处理进度",email_cta:"解决后邮件通知我",notify:"通知我"},error:{submit:"提交失败,请重试。"},pet:{bubble:"需要帮助吗?"},frustration:{prompt:"遇到问题了?告诉我们。",action:"标注",dismiss:"关闭"},annotation:{drawing:"绘制",element:"元素"},draw:{note_placeholder:"给你的绘制添加说明",undo:"撤销",redo:"重做",cancel:"取消",submit:"提交"},record:{stop:"停止",timer_label:"录制中",max_reached:"已达到最长录制时间",replay_label:"screen-recording.json",play:"播放录屏",close:"关闭",preview_unavailable:"暂无法预览"},clarify:{title:"Make This Better AI",subtitle:"正在完善你的反馈",thinking:"思考中...",placeholder:"补充说明后提交",send:"发送",submit:"提交",send_feedback:"发送反馈",skip:"跳过并提交",skip_short:"跳过",cancel:"取消并不发送",retry:"重试",error:"追问加载失败,可以直接发送反馈。",expired:"这条反馈在发送前已过期。请关闭组件后重新提交。"}},ja:{tab:"フィードバック",toolbar:{markup:"マークアップ",record:"録画",hint:"クリックでコメント、ドラッグで描画",hintTouch:"ドラッグして問題箇所を囲んでください",hintRecord:"画面を録画中",exit:"終了"},popup:{about:"概要",placeholder:"問題や提案を入力してください...",submit:"送信",sending:"送信中...",cancel:"キャンセル",close:"閉じる",my_feedback:"自分のフィードバック",screenshot_label:"スクリーンショットを添付",screenshot_hint:"パスワードなどの機密項目は自動的に隠されます。",screenshot_short:"スクリーンショット",screenshot_locked_hint:"描き込みはスクリーンショット上に焼き込まれるため、必ず添付されます。機密項目は自動的に隠されます。",recording_label:"記録",recording_locked_hint:"ページの表示と操作の再現記録で、必ず添付されます。カメラやマイクは含まれず、機密項目は自動的に隠されます。",quickOptions:[{emoji:"🐛",label:"不具合",value:"不具合があります"},{emoji:"💡",label:"提案",value:"提案があります"},{emoji:"🤔",label:"不明点",value:"わかりにくいです"}]},success:{title:"フィードバックを受け取りました。ありがとうございます。",title_no_ai:"ありがとうございます!フィードバックを受け付けました。",close:"閉じる",email_saved:"解決次第メールでお知らせします。",email_error:"メールアドレスを保存できませんでした。もう一度お試しください。",track_feedback:"対応状況を確認",email_cta:"解決したらメールで知らせる",notify:"通知"},error:{submit:"送信に失敗しました。もう一度お試しください。"},pet:{bubble:"お困りですか?"},frustration:{prompt:"うまくいかないことがありますか?お知らせください。",action:"注釈",dismiss:"閉じる"},annotation:{drawing:"描画",element:"要素"},draw:{note_placeholder:"描画にメモを追加",undo:"元に戻す",redo:"やり直す",cancel:"キャンセル",submit:"送信"},record:{stop:"停止",timer_label:"録画中",max_reached:"最大記録時間に達しました",replay_label:"screen-recording.json",play:"録画を再生",close:"閉じる",preview_unavailable:"プレビューは利用できません"},clarify:{title:"Make This Better AI",subtitle:"フィードバックを整えています",thinking:"考え中...",placeholder:"詳細を追加して送信",send:"送信",submit:"送信する",send_feedback:"フィードバックを送信",skip:"スキップして送信",skip_short:"スキップ",cancel:"キャンセル — 送信しない",retry:"再試行",error:"質問を読み込めませんでした。そのままフィードバックを送信できます。",expired:"このフィードバックは送信される前に有効期限が切れました。ウィジェットを閉じて、もう一度送信してください。"}},ko:{tab:"피드백",toolbar:{markup:"마크업",record:"녹화",hint:"클릭하여 댓글, 드래그하여 그리기",hintTouch:"드래그해서 문제가 있는 곳을 표시하세요",hintRecord:"화면 녹화 중",exit:"나가기"},popup:{about:"정보",placeholder:"문제 또는 제안 사항을 설명해 주세요...",submit:"제출",sending:"전송 중...",cancel:"취소",close:"닫기",my_feedback:"내 피드백",screenshot_label:"스크린샷 첨부",screenshot_hint:"비밀번호 등 민감한 입력란은 자동으로 가려집니다.",screenshot_short:"스크린샷",screenshot_locked_hint:"그린 표시는 스크린샷 위에 합쳐지므로 항상 첨부됩니다. 민감한 입력란은 자동으로 가려집니다.",recording_label:"기록",recording_locked_hint:"페이지 화면과 조작 과정의 재현 기록으로, 항상 첨부됩니다. 카메라와 마이크는 포함되지 않으며 민감한 입력란은 자동으로 가려집니다.",quickOptions:[{emoji:"🐛",label:"오류",value:"문제가 있어요"},{emoji:"💡",label:"제안",value:"제안이 있어요"},{emoji:"🤔",label:"혼란",value:"헷갈려요"}]},success:{title:"피드백이 접수되었습니다. 감사합니다.",title_no_ai:"감사합니다! 피드백을 접수했습니다.",close:"닫기",email_saved:"해결되면 이메일로 알려드립니다.",email_error:"이메일을 저장하지 못했습니다. 다시 시도해 주세요.",track_feedback:"처리 상황 보기",email_cta:"해결되면 이메일로 알림",notify:"알림"},error:{submit:"제출에 실패했습니다. 다시 시도해 주세요."},pet:{bubble:"도움이 필요하신가요?"},frustration:{prompt:"문제가 있으신가요? 알려 주세요.",action:"주석",dismiss:"닫기"},annotation:{drawing:"그리기",element:"요소"},draw:{note_placeholder:"그림에 메모 추가",undo:"실행 취소",redo:"다시 실행",cancel:"취소",submit:"보내기"},record:{stop:"중지",timer_label:"녹화 중",max_reached:"최대 녹화 시간에 도달했습니다",replay_label:"screen-recording.json",play:"녹화 재생",close:"닫기",preview_unavailable:"미리보기를 사용할 수 없습니다"},clarify:{title:"Make This Better AI",subtitle:"피드백을 다듬는 중",thinking:"생각 중...",placeholder:"자세히 적은 뒤 제출",send:"보내기",submit:"제출",send_feedback:"피드백 보내기",skip:"건너뛰고 보내기",skip_short:"건너뛰기",cancel:"취소 — 보내지 않기",retry:"재시도",error:"질문을 불러오지 못했습니다. 피드백을 그대로 보내세요.",expired:"이 피드백 세션은 전송되기 전에 만료되었습니다. 위젯을 닫고 다시 보내 주세요."}},es:{tab:"Comentarios",toolbar:{markup:"Anotar",record:"Grabar",hint:"Clic para comentar, arrastrar para dibujar",hintTouch:"Arrastra para marcar el problema",hintRecord:"Grabando pantalla",exit:"Salir"},popup:{about:"Acerca de",placeholder:"Describe el problema o sugerencia...",submit:"Enviar",sending:"Enviando...",cancel:"Cancelar",close:"Cerrar",my_feedback:"Mis comentarios",screenshot_label:"Adjuntar captura de pantalla",screenshot_hint:"Las contraseñas y otros campos sensibles se ocultan automáticamente.",screenshot_short:"Captura",screenshot_locked_hint:"Tu dibujo se integra en la captura, por eso siempre se adjunta. Los campos sensibles se ocultan automáticamente.",recording_label:"Grabación",recording_locked_hint:"Una reproducción de lo que mostraba la página y cómo se usó; siempre se adjunta. Sin cámara ni micrófono. Los campos sensibles se ocultan automáticamente.",quickOptions:[{emoji:"🐛",label:"Error",value:"Algo no funciona"},{emoji:"💡",label:"Sugerencia",value:"Tengo una sugerencia"},{emoji:"🤔",label:"Confuso",value:"Estoy confundido"}]},success:{title:"Gracias, hemos recibido tu comentario.",title_no_ai:"¡Gracias! Hemos recibido tu comentario.",close:"Cerrar",email_saved:"Recibirás un correo cuando se resuelva.",email_error:"No se pudo guardar tu correo. Inténtalo de nuevo.",track_feedback:"Seguir mi comentario",email_cta:"Avísame por correo cuando se arregle",notify:"Avisarme"},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"},draw:{note_placeholder:"Añade una nota a tu dibujo",undo:"Deshacer",redo:"Rehacer",cancel:"Cancelar",submit:"Enviar"},record:{stop:"Detener",timer_label:"Grabando",max_reached:"Tiempo máximo de grabación alcanzado",replay_label:"screen-recording.json",play:"Reproducir grabación",close:"Cerrar",preview_unavailable:"Vista previa no disponible"},clarify:{title:"Make This Better AI",subtitle:"Afinando tus comentarios",thinking:"Pensando...",placeholder:"Añade detalles y envía",send:"Enviar",submit:"Enviar",send_feedback:"Enviar comentario",skip:"Omitir y enviar",skip_short:"Omitir",cancel:"Cancelar — no enviar",retry:"Reintentar",error:"No se pudo cargar la pregunta. Envía tus comentarios tal cual.",expired:"Esta sesión de comentarios caducó antes de poder enviarse. Cierra el widget y envíalo de nuevo."}},fr:{tab:"Avis",toolbar:{markup:"Annoter",record:"Enregistrer",hint:"Cliquer pour commenter, glisser pour dessiner",hintTouch:"Faites glisser pour marquer le problème",hintRecord:"Enregistrement de l'écran",exit:"Quitter"},popup:{about:"À propos",placeholder:"Décrivez le problème ou votre suggestion...",submit:"Envoyer",sending:"Envoi en cours...",cancel:"Annuler",close:"Fermer",my_feedback:"Mes avis",screenshot_label:"Joindre une capture d'écran",screenshot_hint:"Les mots de passe et autres champs sensibles sont masqués automatiquement.",screenshot_short:"Capture",screenshot_locked_hint:"Votre dessin est intégré à la capture, elle est donc toujours jointe. Les champs sensibles sont masqués automatiquement.",recording_label:"Enregistrement",recording_locked_hint:"Une relecture de ce que la page affichait et de son utilisation — toujours jointe. Ni caméra ni micro. Les champs sensibles sont masqués automatiquement.",quickOptions:[{emoji:"🐛",label:"Bug",value:"Quelque chose ne fonctionne pas"},{emoji:"💡",label:"Suggestion",value:"J'ai une suggestion"},{emoji:"🤔",label:"Confus",value:"Je suis perplexe"}]},success:{title:"Merci, votre retour est bien arrivé.",title_no_ai:"Merci ! Nous avons bien reçu votre avis.",close:"Fermer",email_saved:"Vous recevrez un e-mail une fois résolu.",email_error:"Impossible d'enregistrer votre e-mail. Veuillez réessayer.",track_feedback:"Suivre mon retour",email_cta:"M’avertir par e-mail une fois corrigé",notify:"Avertir"},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"},draw:{note_placeholder:"Ajoutez une note à votre dessin",undo:"Annuler",redo:"Rétablir",cancel:"Annuler",submit:"Envoyer"},record:{stop:"Arrêter",timer_label:"Enregistrement",max_reached:"Durée maximale d'enregistrement atteinte",replay_label:"screen-recording.json",play:"Lire l'enregistrement",close:"Fermer",preview_unavailable:"Aperçu indisponible"},clarify:{title:"Make This Better AI",subtitle:"Affinement de votre retour",thinking:"Réflexion...",placeholder:"Ajoutez des détails, puis envoyez",send:"Envoyer",submit:"Soumettre",send_feedback:"Envoyer le retour",skip:"Ignorer et envoyer",skip_short:"Ignorer",cancel:"Annuler — ne pas envoyer",retry:"Réessayer",error:"Impossible de charger la question. Envoyez votre avis tel quel.",expired:"Cette session de retour a expiré avant d'avoir pu être envoyée. Fermez le widget et renvoyez-la."}},de:{tab:"Feedback",toolbar:{markup:"Markieren",record:"Aufnehmen",hint:"Klicken zum Kommentieren, ziehen zum Zeichnen",hintTouch:"Ziehen, um das Problem zu markieren",hintRecord:"Bildschirm wird aufgenommen",exit:"Beenden"},popup:{about:"Info",placeholder:"Beschreiben Sie das Problem oder Ihren Vorschlag...",submit:"Absenden",sending:"Wird gesendet...",cancel:"Abbrechen",close:"Schließen",my_feedback:"Mein Feedback",screenshot_label:"Screenshot anhängen",screenshot_hint:"Passwörter und andere sensible Felder werden automatisch abgedeckt.",screenshot_short:"Screenshot",screenshot_locked_hint:"Deine Zeichnung wird in den Screenshot eingebrannt, daher wird er immer angehängt. Sensible Felder werden automatisch abgedeckt.",recording_label:"Aufzeichnung",recording_locked_hint:"Eine Wiedergabe dessen, was die Seite zeigte und wie sie bedient wurde — immer angehängt. Keine Kamera, kein Mikrofon. Sensible Felder werden automatisch abgedeckt.",quickOptions:[{emoji:"🐛",label:"Fehler",value:"Etwas funktioniert nicht"},{emoji:"💡",label:"Vorschlag",value:"Ich habe einen Vorschlag"},{emoji:"🤔",label:"Unklar",value:"Ich bin verwirrt"}]},success:{title:"Danke, Ihr Feedback ist angekommen.",title_no_ai:"Vielen Dank! Wir haben Ihr Feedback erhalten.",close:"Schließen",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.",track_feedback:"Feedback verfolgen",email_cta:"E-Mail, sobald es behoben ist",notify:"Melden"},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"},draw:{note_placeholder:"Fügen Sie Ihrer Zeichnung eine Notiz hinzu",undo:"Rückgängig",redo:"Wiederholen",cancel:"Abbrechen",submit:"Absenden"},record:{stop:"Stopp",timer_label:"Aufnahme",max_reached:"Maximale Aufnahmedauer erreicht",replay_label:"screen-recording.json",play:"Aufnahme abspielen",close:"Schließen",preview_unavailable:"Vorschau nicht verfügbar"},clarify:{title:"Make This Better AI",subtitle:"Wir schärfen dein Feedback",thinking:"Einen Moment...",placeholder:"Details ergänzen, dann absenden",send:"Senden",submit:"Absenden",send_feedback:"Feedback senden",skip:"Überspringen & senden",skip_short:"Überspringen",cancel:"Abbrechen — nicht senden",retry:"Erneut versuchen",error:"Die Frage konnte nicht geladen werden. Senden Sie Ihr Feedback einfach so.",expired:"Diese Feedback-Sitzung ist abgelaufen, bevor sie gesendet werden konnte. Bitte schließe das Widget und sende erneut."}}};function Ce(e){if(j[e])return j[e];const t=e.split("-")[0];return j[t]?j[t]:j.en}const rn=60,Te=["value","content"],nn=Object.fromEntries(["button","checkbox","color","date","datetime-local","email","file","hidden","image","month","number","password","radio","range","reset","search","select","submit","tel","text","textarea","time","url","week"].map(e=>[e,!0])),sn="https://cdn.jsdelivr.net/npm/@rrweb/record@2.1.0/umd/record.min.js",on="sha384-MrD66HBNSykaP2N95+6hQCFlF5oH2tvL3TD/zyvHNkP/sAFWZx98DX9MEDy8MdVT";let q=null;function an(){return q||(q=cn().catch(t=>{throw q=null,t}),q)}function ln(e,t){const r=it(e);return Rt(r,t,ee()),r}function Rt(e,t,r){if(Array.isArray(e)){e.forEach(a=>Rt(a,t,r));return}if(!_e(e))return;const i=_e(e.attributes)?e.attributes:null,n=i&&Te.some(a=>typeof i[a]=="string"),o=(typeof e.text=="string"||typeof e.textContent=="string"||typeof e.value=="string"||n)&&typeof e.id=="number"?t.mirror.getNode(e.id):null;if(o instanceof Element){if(typeof e.text=="string"&&(e.text=nt(e.text,o)),i)for(const a of Te){const l=i[a];typeof l=="string"&&(i[a]=nt(l,o))}}else o?.nodeType===Node.TEXT_NODE&&re(o,r)&&(typeof e.textContent=="string"&&(e.textContent=g),typeof e.value=="string"&&(e.value=g));Object.values(e).forEach(a=>Rt(a,t,r))}function _e(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ae(){const e=globalThis;return e.rrwebRecord?.record??e.rrweb?.record}function cn(){return new Promise((e,t)=>{const r=Ae();if(r){e(r);return}const i=document.createElement("script");i.src=sn,i.integrity=on,i.crossOrigin="anonymous",i.onload=()=>{const n=Ae();n?e(n):t(new Error("rrweb record global not found after script load"))},i.onerror=()=>t(new Error("Failed to load rrweb from CDN")),document.head.appendChild(i)})}class hn{constructor(t,r){this.events=[],this.stopFn=null,this.startedAt=0,this.timer=null,this.clickHandler=null,this.stopped=!1,this.destroyed=!1,this.shadow=t,this.onMaxReached=r}async start(){const t=await an();this.destroyed||(this.startedAt=Date.now(),this.stopped=!1,this.stopFn=t({emit:r=>{if(!this.stopped)try{this.events.push(ln(r,t))}catch{}},maskAllInputs:!1,maskInputOptions:nn,maskInputFn:(r,i)=>i.closest(`.${I}`)?g:nt(r,i),maskTextFn:()=>g,blockClass:Q,maskTextClass:I}),this.clickHandler=r=>{this.showClickRipple(r.clientX,r.clientY),t.addCustomEvent?.("mtb-click",{x:r.clientX,y:r.clientY,target:r.target instanceof HTMLElement?r.target.tagName:""})},document.addEventListener("click",this.clickHandler,!0),this.timer=setTimeout(()=>{this.onMaxReached?.()},rn*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.max(1,Math.round((Date.now()-this.startedAt)/1e3))}destroy(){this.destroyed=!0,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,r){const i=this.shadow.el("div","mtb-click-ripple");i.style.left=`${t}px`,i.style.top=`${r}px`,this.shadow.append(i),i.addEventListener("animationend",()=>i.remove())}}class dn{constructor(t,r,i,n){this.intervalId=null,this.getDuration=i,this.el=t.el("div","mtb-record-bar"),this.el.innerHTML=`
69
+ `))!==-1;){const h=n.slice(0,c);n=n.slice(c+2);try{a(h)}catch{}}}if(n+=r.decode(),n.trim())try{a(n)}catch{}if(!s)throw new Error("clarify stream ended before done");return s}function Zr(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function Qr(){if(typeof crypto>"u"||typeof crypto.getRandomValues!="function")throw new Error("Secure random generation is unavailable");const e=crypto.getRandomValues(new Uint8Array(32));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}const ge="mtb_anon_id",we="mtb_reporter_email",ye="mtb_board_url";let ve=null,xe=null,ke=null;function Ee(){try{const e=window.localStorage.getItem(ge);if(e?.startsWith("anon_"))return e;const t=Ce();return window.localStorage.setItem(ge,t),t}catch{return ve??(ve=Ce()),ve}}function Se(){try{return window.localStorage.getItem(we)??void 0}catch{return xe??void 0}}function tn(e){xe=e;try{window.localStorage.setItem(we,e)}catch{}}function en(){try{return window.localStorage.getItem(ye)??void 0}catch{return ke??void 0}}function U(e){ke=e;try{window.localStorage.setItem(ye,e)}catch{}}function Ce(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`anon_${crypto.randomUUID()}`:`anon_${`${Date.now().toString(16)}-${Math.random().toString(16).slice(2,10)}`}`}const j={en:{tab:"Feedback",toolbar:{markup:"Mark up",record:"Record",hint:"Click to comment, drag to draw",hintTouch:"Drag to mark what's wrong",hintRecord:"Recording your screen",exit:"Exit"},popup:{about:"About",placeholder:"Describe the issue or suggestion...",submit:"Submit",sending:"Sending...",cancel:"Cancel",close:"Close",my_feedback:"My feedback",screenshot_label:"Attach screenshot",screenshot_hint:"Passwords and other sensitive fields are covered automatically.",screenshot_short:"Screenshot",screenshot_locked_hint:"Your drawing is baked onto the screenshot, so it is always attached. Sensitive fields are covered automatically.",recording_label:"Recording",recording_locked_hint:"A replay of what the page showed and how it was used — always included with a recording. No camera or microphone. Sensitive fields are covered automatically.",quickOptions:[{emoji:"🐛",label:"Broken",value:"Something's broken"},{emoji:"💡",label:"Suggestion",value:"I have a suggestion"},{emoji:"🤔",label:"Confused",value:"I'm confused"}]},success:{title:"Thanks, your feedback is in.",title_no_ai:"Thanks! We've received your feedback.",close:"Close",email_saved:"You'll get an email when it's resolved.",email_error:"Couldn't save your email. Please try again.",track_feedback:"Track your feedback",email_cta:"Email me when it's fixed",notify:"Notify"},error:{submit:"Failed to submit. Please try again.",finalize_title:"We couldn't send this yet.",finalize_message:"Your feedback is still saved. Please try again."},pet:{bubble:"Need help?"},frustration:{prompt:"Something not working? Tell us.",action:"Annotate",dismiss:"Dismiss"},annotation:{drawing:"Drawing",element:"element"},draw:{note_placeholder:"Add a note to your drawing",undo:"Undo",redo:"Redo",cancel:"Cancel",submit:"Submit"},record:{stop:"Stop",timer_label:"Recording",max_reached:"Maximum recording time reached",replay_label:"screen-recording.json",play:"Play recording",close:"Close",preview_unavailable:"Preview unavailable"},clarify:{title:"Make This Better AI",subtitle:"Sharpening your feedback",thinking:"Thinking...",placeholder:"Add details, then submit",send:"Send",submit:"Submit",send_feedback:"Send feedback",skip:"Skip & submit",skip_short:"Skip",cancel:"Cancel — don't send feedback",retry:"Retry",error:"Couldn't load the question. Send your feedback as is.",expired:"This feedback session expired before it could be sent. Please close the widget and submit again."}},"zh-CN":{tab:"反馈",toolbar:{markup:"标注",record:"录屏",hint:"点击标注,拖动绘制",hintTouch:"用手指圈出问题",hintRecord:"正在录制屏幕",exit:"退出"},popup:{about:"关于",placeholder:"描述问题或建议...",submit:"提交",sending:"发送中...",cancel:"取消",close:"关闭",my_feedback:"我的反馈",screenshot_label:"附带页面截图",screenshot_hint:"密码等敏感字段会自动打码。",screenshot_short:"截图",screenshot_locked_hint:"圈画会画在截图上,所以必定附带。敏感字段会自动打码。",recording_label:"录制",recording_locked_hint:"页面画面与操作过程的回放,录制内容必定随反馈提交。不含摄像头和麦克风,敏感字段会自动打码。",quickOptions:[{emoji:"🐛",label:"有问题",value:"出问题了"},{emoji:"💡",label:"建议",value:"我有一个建议"},{emoji:"🤔",label:"疑问",value:"我有点疑问"}]},success:{title:"收到了,谢谢你的反馈。",title_no_ai:"感谢!我们已收到您的反馈。",close:"关闭",email_saved:"问题解决后您会收到邮件通知。",email_error:"邮箱保存失败,请重试。",track_feedback:"查看处理进度",email_cta:"解决后邮件通知我",notify:"通知我"},error:{submit:"提交失败,请重试。",finalize_title:"暂时无法发送。",finalize_message:"你的反馈仍已保存,请重试。"},pet:{bubble:"需要帮助吗?"},frustration:{prompt:"遇到问题了?告诉我们。",action:"标注",dismiss:"关闭"},annotation:{drawing:"绘制",element:"元素"},draw:{note_placeholder:"给你的绘制添加说明",undo:"撤销",redo:"重做",cancel:"取消",submit:"提交"},record:{stop:"停止",timer_label:"录制中",max_reached:"已达到最长录制时间",replay_label:"screen-recording.json",play:"播放录屏",close:"关闭",preview_unavailable:"暂无法预览"},clarify:{title:"Make This Better AI",subtitle:"正在完善你的反馈",thinking:"思考中...",placeholder:"补充说明后提交",send:"发送",submit:"提交",send_feedback:"发送反馈",skip:"跳过并提交",skip_short:"跳过",cancel:"取消并不发送",retry:"重试",error:"追问加载失败,可以直接发送反馈。",expired:"这条反馈在发送前已过期。请关闭组件后重新提交。"}},ja:{tab:"フィードバック",toolbar:{markup:"マークアップ",record:"録画",hint:"クリックでコメント、ドラッグで描画",hintTouch:"ドラッグして問題箇所を囲んでください",hintRecord:"画面を録画中",exit:"終了"},popup:{about:"概要",placeholder:"問題や提案を入力してください...",submit:"送信",sending:"送信中...",cancel:"キャンセル",close:"閉じる",my_feedback:"自分のフィードバック",screenshot_label:"スクリーンショットを添付",screenshot_hint:"パスワードなどの機密項目は自動的に隠されます。",screenshot_short:"スクリーンショット",screenshot_locked_hint:"描き込みはスクリーンショット上に焼き込まれるため、必ず添付されます。機密項目は自動的に隠されます。",recording_label:"記録",recording_locked_hint:"ページの表示と操作の再現記録で、必ず添付されます。カメラやマイクは含まれず、機密項目は自動的に隠されます。",quickOptions:[{emoji:"🐛",label:"不具合",value:"不具合があります"},{emoji:"💡",label:"提案",value:"提案があります"},{emoji:"🤔",label:"不明点",value:"わかりにくいです"}]},success:{title:"フィードバックを受け取りました。ありがとうございます。",title_no_ai:"ありがとうございます!フィードバックを受け付けました。",close:"閉じる",email_saved:"解決次第メールでお知らせします。",email_error:"メールアドレスを保存できませんでした。もう一度お試しください。",track_feedback:"対応状況を確認",email_cta:"解決したらメールで知らせる",notify:"通知"},error:{submit:"送信に失敗しました。もう一度お試しください。",finalize_title:"まだ送信できませんでした。",finalize_message:"フィードバックは保存されています。もう一度お試しください。"},pet:{bubble:"お困りですか?"},frustration:{prompt:"うまくいかないことがありますか?お知らせください。",action:"注釈",dismiss:"閉じる"},annotation:{drawing:"描画",element:"要素"},draw:{note_placeholder:"描画にメモを追加",undo:"元に戻す",redo:"やり直す",cancel:"キャンセル",submit:"送信"},record:{stop:"停止",timer_label:"録画中",max_reached:"最大記録時間に達しました",replay_label:"screen-recording.json",play:"録画を再生",close:"閉じる",preview_unavailable:"プレビューは利用できません"},clarify:{title:"Make This Better AI",subtitle:"フィードバックを整えています",thinking:"考え中...",placeholder:"詳細を追加して送信",send:"送信",submit:"送信する",send_feedback:"フィードバックを送信",skip:"スキップして送信",skip_short:"スキップ",cancel:"キャンセル — 送信しない",retry:"再試行",error:"質問を読み込めませんでした。そのままフィードバックを送信できます。",expired:"このフィードバックは送信される前に有効期限が切れました。ウィジェットを閉じて、もう一度送信してください。"}},ko:{tab:"피드백",toolbar:{markup:"마크업",record:"녹화",hint:"클릭하여 댓글, 드래그하여 그리기",hintTouch:"드래그해서 문제가 있는 곳을 표시하세요",hintRecord:"화면 녹화 중",exit:"나가기"},popup:{about:"정보",placeholder:"문제 또는 제안 사항을 설명해 주세요...",submit:"제출",sending:"전송 중...",cancel:"취소",close:"닫기",my_feedback:"내 피드백",screenshot_label:"스크린샷 첨부",screenshot_hint:"비밀번호 등 민감한 입력란은 자동으로 가려집니다.",screenshot_short:"스크린샷",screenshot_locked_hint:"그린 표시는 스크린샷 위에 합쳐지므로 항상 첨부됩니다. 민감한 입력란은 자동으로 가려집니다.",recording_label:"기록",recording_locked_hint:"페이지 화면과 조작 과정의 재현 기록으로, 항상 첨부됩니다. 카메라와 마이크는 포함되지 않으며 민감한 입력란은 자동으로 가려집니다.",quickOptions:[{emoji:"🐛",label:"오류",value:"문제가 있어요"},{emoji:"💡",label:"제안",value:"제안이 있어요"},{emoji:"🤔",label:"혼란",value:"헷갈려요"}]},success:{title:"피드백이 접수되었습니다. 감사합니다.",title_no_ai:"감사합니다! 피드백을 접수했습니다.",close:"닫기",email_saved:"해결되면 이메일로 알려드립니다.",email_error:"이메일을 저장하지 못했습니다. 다시 시도해 주세요.",track_feedback:"처리 상황 보기",email_cta:"해결되면 이메일로 알림",notify:"알림"},error:{submit:"제출에 실패했습니다. 다시 시도해 주세요.",finalize_title:"아직 전송하지 못했습니다.",finalize_message:"피드백은 저장되어 있습니다. 다시 시도해 주세요."},pet:{bubble:"도움이 필요하신가요?"},frustration:{prompt:"문제가 있으신가요? 알려 주세요.",action:"주석",dismiss:"닫기"},annotation:{drawing:"그리기",element:"요소"},draw:{note_placeholder:"그림에 메모 추가",undo:"실행 취소",redo:"다시 실행",cancel:"취소",submit:"보내기"},record:{stop:"중지",timer_label:"녹화 중",max_reached:"최대 녹화 시간에 도달했습니다",replay_label:"screen-recording.json",play:"녹화 재생",close:"닫기",preview_unavailable:"미리보기를 사용할 수 없습니다"},clarify:{title:"Make This Better AI",subtitle:"피드백을 다듬는 중",thinking:"생각 중...",placeholder:"자세히 적은 뒤 제출",send:"보내기",submit:"제출",send_feedback:"피드백 보내기",skip:"건너뛰고 보내기",skip_short:"건너뛰기",cancel:"취소 — 보내지 않기",retry:"재시도",error:"질문을 불러오지 못했습니다. 피드백을 그대로 보내세요.",expired:"이 피드백 세션은 전송되기 전에 만료되었습니다. 위젯을 닫고 다시 보내 주세요."}},es:{tab:"Comentarios",toolbar:{markup:"Anotar",record:"Grabar",hint:"Clic para comentar, arrastrar para dibujar",hintTouch:"Arrastra para marcar el problema",hintRecord:"Grabando pantalla",exit:"Salir"},popup:{about:"Acerca de",placeholder:"Describe el problema o sugerencia...",submit:"Enviar",sending:"Enviando...",cancel:"Cancelar",close:"Cerrar",my_feedback:"Mis comentarios",screenshot_label:"Adjuntar captura de pantalla",screenshot_hint:"Las contraseñas y otros campos sensibles se ocultan automáticamente.",screenshot_short:"Captura",screenshot_locked_hint:"Tu dibujo se integra en la captura, por eso siempre se adjunta. Los campos sensibles se ocultan automáticamente.",recording_label:"Grabación",recording_locked_hint:"Una reproducción de lo que mostraba la página y cómo se usó; siempre se adjunta. Sin cámara ni micrófono. Los campos sensibles se ocultan automáticamente.",quickOptions:[{emoji:"🐛",label:"Error",value:"Algo no funciona"},{emoji:"💡",label:"Sugerencia",value:"Tengo una sugerencia"},{emoji:"🤔",label:"Confuso",value:"Estoy confundido"}]},success:{title:"Gracias, hemos recibido tu comentario.",title_no_ai:"¡Gracias! Hemos recibido tu comentario.",close:"Cerrar",email_saved:"Recibirás un correo cuando se resuelva.",email_error:"No se pudo guardar tu correo. Inténtalo de nuevo.",track_feedback:"Seguir mi comentario",email_cta:"Avísame por correo cuando se arregle",notify:"Avisarme"},error:{submit:"Error al enviar. Por favor, inténtalo de nuevo.",finalize_title:"Aún no pudimos enviarlo.",finalize_message:"Tu comentario sigue guardado. Inténtalo de nuevo."},pet:{bubble:"¿Necesitas ayuda?"},frustration:{prompt:"¿Algo no funciona? Cuéntanos.",action:"Anotar",dismiss:"Cerrar"},annotation:{drawing:"Dibujo",element:"elemento"},draw:{note_placeholder:"Añade una nota a tu dibujo",undo:"Deshacer",redo:"Rehacer",cancel:"Cancelar",submit:"Enviar"},record:{stop:"Detener",timer_label:"Grabando",max_reached:"Tiempo máximo de grabación alcanzado",replay_label:"screen-recording.json",play:"Reproducir grabación",close:"Cerrar",preview_unavailable:"Vista previa no disponible"},clarify:{title:"Make This Better AI",subtitle:"Afinando tus comentarios",thinking:"Pensando...",placeholder:"Añade detalles y envía",send:"Enviar",submit:"Enviar",send_feedback:"Enviar comentario",skip:"Omitir y enviar",skip_short:"Omitir",cancel:"Cancelar — no enviar",retry:"Reintentar",error:"No se pudo cargar la pregunta. Envía tus comentarios tal cual.",expired:"Esta sesión de comentarios caducó antes de poder enviarse. Cierra el widget y envíalo de nuevo."}},fr:{tab:"Avis",toolbar:{markup:"Annoter",record:"Enregistrer",hint:"Cliquer pour commenter, glisser pour dessiner",hintTouch:"Faites glisser pour marquer le problème",hintRecord:"Enregistrement de l'écran",exit:"Quitter"},popup:{about:"À propos",placeholder:"Décrivez le problème ou votre suggestion...",submit:"Envoyer",sending:"Envoi en cours...",cancel:"Annuler",close:"Fermer",my_feedback:"Mes avis",screenshot_label:"Joindre une capture d'écran",screenshot_hint:"Les mots de passe et autres champs sensibles sont masqués automatiquement.",screenshot_short:"Capture",screenshot_locked_hint:"Votre dessin est intégré à la capture, elle est donc toujours jointe. Les champs sensibles sont masqués automatiquement.",recording_label:"Enregistrement",recording_locked_hint:"Une relecture de ce que la page affichait et de son utilisation — toujours jointe. Ni caméra ni micro. Les champs sensibles sont masqués automatiquement.",quickOptions:[{emoji:"🐛",label:"Bug",value:"Quelque chose ne fonctionne pas"},{emoji:"💡",label:"Suggestion",value:"J'ai une suggestion"},{emoji:"🤔",label:"Confus",value:"Je suis perplexe"}]},success:{title:"Merci, votre retour est bien arrivé.",title_no_ai:"Merci ! Nous avons bien reçu votre avis.",close:"Fermer",email_saved:"Vous recevrez un e-mail une fois résolu.",email_error:"Impossible d'enregistrer votre e-mail. Veuillez réessayer.",track_feedback:"Suivre mon retour",email_cta:"M’avertir par e-mail une fois corrigé",notify:"Avertir"},error:{submit:"Échec de l'envoi. Veuillez réessayer.",finalize_title:"Nous n'avons pas encore pu l'envoyer.",finalize_message:"Votre retour est toujours enregistré. 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"},draw:{note_placeholder:"Ajoutez une note à votre dessin",undo:"Annuler",redo:"Rétablir",cancel:"Annuler",submit:"Envoyer"},record:{stop:"Arrêter",timer_label:"Enregistrement",max_reached:"Durée maximale d'enregistrement atteinte",replay_label:"screen-recording.json",play:"Lire l'enregistrement",close:"Fermer",preview_unavailable:"Aperçu indisponible"},clarify:{title:"Make This Better AI",subtitle:"Affinement de votre retour",thinking:"Réflexion...",placeholder:"Ajoutez des détails, puis envoyez",send:"Envoyer",submit:"Soumettre",send_feedback:"Envoyer le retour",skip:"Ignorer et envoyer",skip_short:"Ignorer",cancel:"Annuler — ne pas envoyer",retry:"Réessayer",error:"Impossible de charger la question. Envoyez votre avis tel quel.",expired:"Cette session de retour a expiré avant d'avoir pu être envoyée. Fermez le widget et renvoyez-la."}},de:{tab:"Feedback",toolbar:{markup:"Markieren",record:"Aufnehmen",hint:"Klicken zum Kommentieren, ziehen zum Zeichnen",hintTouch:"Ziehen, um das Problem zu markieren",hintRecord:"Bildschirm wird aufgenommen",exit:"Beenden"},popup:{about:"Info",placeholder:"Beschreiben Sie das Problem oder Ihren Vorschlag...",submit:"Absenden",sending:"Wird gesendet...",cancel:"Abbrechen",close:"Schließen",my_feedback:"Mein Feedback",screenshot_label:"Screenshot anhängen",screenshot_hint:"Passwörter und andere sensible Felder werden automatisch abgedeckt.",screenshot_short:"Screenshot",screenshot_locked_hint:"Deine Zeichnung wird in den Screenshot eingebrannt, daher wird er immer angehängt. Sensible Felder werden automatisch abgedeckt.",recording_label:"Aufzeichnung",recording_locked_hint:"Eine Wiedergabe dessen, was die Seite zeigte und wie sie bedient wurde — immer angehängt. Keine Kamera, kein Mikrofon. Sensible Felder werden automatisch abgedeckt.",quickOptions:[{emoji:"🐛",label:"Fehler",value:"Etwas funktioniert nicht"},{emoji:"💡",label:"Vorschlag",value:"Ich habe einen Vorschlag"},{emoji:"🤔",label:"Unklar",value:"Ich bin verwirrt"}]},success:{title:"Danke, Ihr Feedback ist angekommen.",title_no_ai:"Vielen Dank! Wir haben Ihr Feedback erhalten.",close:"Schließen",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.",track_feedback:"Feedback verfolgen",email_cta:"E-Mail, sobald es behoben ist",notify:"Melden"},error:{submit:"Senden fehlgeschlagen. Bitte versuchen Sie es erneut.",finalize_title:"Wir konnten dies noch nicht senden.",finalize_message:"Ihr Feedback ist weiterhin gespeichert. 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"},draw:{note_placeholder:"Fügen Sie Ihrer Zeichnung eine Notiz hinzu",undo:"Rückgängig",redo:"Wiederholen",cancel:"Abbrechen",submit:"Absenden"},record:{stop:"Stopp",timer_label:"Aufnahme",max_reached:"Maximale Aufnahmedauer erreicht",replay_label:"screen-recording.json",play:"Aufnahme abspielen",close:"Schließen",preview_unavailable:"Vorschau nicht verfügbar"},clarify:{title:"Make This Better AI",subtitle:"Wir schärfen dein Feedback",thinking:"Einen Moment...",placeholder:"Details ergänzen, dann absenden",send:"Senden",submit:"Absenden",send_feedback:"Feedback senden",skip:"Überspringen & senden",skip_short:"Überspringen",cancel:"Abbrechen — nicht senden",retry:"Erneut versuchen",error:"Die Frage konnte nicht geladen werden. Senden Sie Ihr Feedback einfach so.",expired:"Diese Feedback-Sitzung ist abgelaufen, bevor sie gesendet werden konnte. Bitte schließe das Widget und sende erneut."}}};function Te(e){if(j[e])return j[e];const t=e.split("-")[0];return j[t]?j[t]:j.en}const rn=60,_e=["value","content"],nn=Object.fromEntries(["button","checkbox","color","date","datetime-local","email","file","hidden","image","month","number","password","radio","range","reset","search","select","submit","tel","text","textarea","time","url","week"].map(e=>[e,!0])),sn="https://cdn.jsdelivr.net/npm/@rrweb/record@2.1.0/umd/record.min.js",an="sha384-MrD66HBNSykaP2N95+6hQCFlF5oH2tvL3TD/zyvHNkP/sAFWZx98DX9MEDy8MdVT";let q=null;function on(){return q||(q=cn().catch(t=>{throw q=null,t}),q)}function ln(e,t){const i=it(e);return Dt(i,t,ie()),i}function Dt(e,t,i){if(Array.isArray(e)){e.forEach(o=>Dt(o,t,i));return}if(!Ae(e))return;const r=Ae(e.attributes)?e.attributes:null,n=r&&_e.some(o=>typeof r[o]=="string"),a=(typeof e.text=="string"||typeof e.textContent=="string"||typeof e.value=="string"||n)&&typeof e.id=="number"?t.mirror.getNode(e.id):null;if(a instanceof Element){if(typeof e.text=="string"&&(e.text=rt(e.text,a)),r)for(const o of _e){const l=r[o];typeof l=="string"&&(r[o]=rt(l,a))}}else a?.nodeType===Node.TEXT_NODE&&re(a,i)&&(typeof e.textContent=="string"&&(e.textContent=g),typeof e.value=="string"&&(e.value=g));Object.values(e).forEach(o=>Dt(o,t,i))}function Ae(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Le(){const e=globalThis;return e.rrwebRecord?.record??e.rrweb?.record}function cn(){return new Promise((e,t)=>{const i=Le();if(i){e(i);return}const r=document.createElement("script");r.src=sn,r.integrity=an,r.crossOrigin="anonymous",r.onload=()=>{const n=Le();n?e(n):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 hn{constructor(t,i){this.events=[],this.stopFn=null,this.startedAt=0,this.timer=null,this.clickHandler=null,this.stopped=!1,this.destroyed=!1,this.shadow=t,this.onMaxReached=i}async start(){const t=await on();this.destroyed||(this.startedAt=Date.now(),this.stopped=!1,this.stopFn=t({emit:i=>{if(!this.stopped)try{this.events.push(ln(i,t))}catch{}},maskAllInputs:!1,maskInputOptions:nn,maskInputFn:(i,r)=>r.closest(`.${I}`)?g:rt(i,r),maskTextFn:()=>g,blockClass:Z,maskTextClass:I}),this.clickHandler=i=>{this.showClickRipple(i.clientX,i.clientY),t.addCustomEvent?.("mtb-click",{x:i.clientX,y:i.clientY,target:i.target instanceof HTMLElement?i.target.tagName:""})},document.addEventListener("click",this.clickHandler,!0),this.timer=setTimeout(()=>{this.onMaxReached?.()},rn*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.max(1,Math.round((Date.now()-this.startedAt)/1e3))}destroy(){this.destroyed=!0,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,i){const r=this.shadow.el("div","mtb-click-ripple");r.style.left=`${t}px`,r.style.top=`${i}px`,this.shadow.append(r),r.addEventListener("animationend",()=>r.remove())}}class dn{constructor(t,i,r,n){this.intervalId=null,this.getDuration=r,this.el=t.el("div","mtb-record-bar"),this.el.innerHTML=`
64
70
  <span class="mtb-record-dot"></span>
65
71
  <span class="mtb-record-timer">00:00</span>
66
- <button class="mtb-record-stop" type="button">${d(r.record.stop)}</button>
67
- `,t.append(this.el),this.timerEl=this.el.querySelector(".mtb-record-timer"),this.el.querySelector(".mtb-record-stop").addEventListener("click",n),this.intervalId=setInterval(()=>this.updateTimer(),1e3)}updateTimer(){const t=this.getDuration(),r=String(Math.floor(t/60)).padStart(2,"0"),i=String(t%60).padStart(2,"0");this.timerEl.textContent=`${r}:${i}`}destroy(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.el.remove()}}class un{constructor(){this.session=null,this.bar=null,this.result=null}async start(t,r,i){this.session=new hn(t,i),this.bar=new dn(t,r,()=>this.session?.getDuration()??0,i),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 mn{constructor(t,r,i){this.el=t.el("div","mtb-failure"),this.el.style.right="20px",this.el.style.bottom="20px",this.el.setAttribute("role","alert");const n=i.onRetry?`<div class="mtb-failure-actions">
68
- <button class="mtb-clarify-retry mtb-failure-retry" type="button">${d(r.clarify.retry)}</button>
69
- </div>`:"";this.el.innerHTML=`
70
- <button class="mtb-failure-close" type="button" title="${d(r.success.close)}" aria-label="${d(r.success.close)}">
71
- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
72
- <path d="M18 6L6 18M6 6l12 12"/>
73
- </svg>
74
- </button>
75
- <div class="mtb-failure-icon">
76
- <svg width="23" height="23" viewBox="0 0 24 24" fill="none" stroke="#dc2626" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
77
- <path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>
78
- <line x1="12" y1="9" x2="12" y2="13"/>
79
- <line x1="12" y1="17" x2="12.01" y2="17"/>
80
- </svg>
81
- </div>
82
- <div class="mtb-failure-title">${d(r.error.submit)}</div>
83
- ${n}
84
- `,t.append(this.el),i.onRetry&&this.el.querySelector(".mtb-failure-retry").addEventListener("click",i.onRetry),this.el.querySelector(".mtb-failure-close").addEventListener("click",i.onClose)}destroy(){this.el.remove()}}function bn(){return{page_url:F(window.location.href),user_agent:navigator.userAgent,browser:pn(),os:fn(),screen_width:window.screen.width,screen_height:window.screen.height}}function pn(){const e=navigator.userAgent;return/Edg\//.test(e)?`Edge ${e.match(/Edg\/(\S+)/)?.[1]??""}`:/OPR\//.test(e)?`Opera ${e.match(/OPR\/(\S+)/)?.[1]??""}`:/Chrome\//.test(e)?`Chrome ${e.match(/Chrome\/(\S+)/)?.[1]??""}`:/Safari\//.test(e)&&/Version\//.test(e)?`Safari ${e.match(/Version\/(\S+)/)?.[1]??""}`:/Firefox\//.test(e)?`Firefox ${e.match(/Firefox\/(\S+)/)?.[1]??""}`:"Unknown"}function fn(){const e=navigator.userAgent;return/Windows NT 10/.test(e)?"Windows 10/11":/Windows NT/.test(e)?"Windows":/Mac OS X 10_15|macOS 1[56789]/.test(e)||/Mac OS X/.test(e)?"macOS":/Android/.test(e)?`Android ${e.match(/Android (\d+)/)?.[1]??""}`:/iPhone|iPad|iPod/.test(e)?"iOS":/Linux/.test(e)?"Linux":"Unknown"}function gn(e){const{description:t,pageContext:r,consoleErrors:i,annotation:n,user:s,recording:o,anonId:a,anonEmail:l,breadcrumbs:c}=e;return{...it({description:t,...r,page_url:F(r.page_url),console_errors:i,annotations:n?[n]:[],target_element:n?.targetSelector?{selector:n.targetSelector,text:n.targetText??"",name:n.targetName??""}:void 0,recording_events:o?.events,recording_duration:o?.duration,breadcrumbs:c}),user_id:s?.id,user_email:s?.email,user_name:s?.name,reporter_external_id:s?void 0:a,reporter_email:s?void 0:l}}const yn=300,wn=5e3;class vn{constructor(t,r){this.deps=t,this.host=r,this.activeSubmission=null,this.pendingSubmissionRequest=null,this.submissionAttempt=0,this.pendingScreenshotTask=null,this.screenshotAbortController=null,this.failure=null,this.screenshotEnabled=!0}isScreenshotEnabled(){return this.screenshotEnabled}resetScreenshotConsent(){this.screenshotEnabled=!0}setScreenshotEnabled(t){if(this.screenshotEnabled=t,t){this.warmScreenshotDeps();return}this.screenshotAbortController?.abort()}warmScreenshotDeps(){this.screenshotEnabled&&St()}start(t,r,i){const n=++this.submissionAttempt,s=this.createSubmission(t,r,i,n);return this.pendingSubmissionRequest=s,s}async createSubmission(t,r,i,n){if(await Le(),n!==this.submissionAttempt)return null;const s=bn(),o=gn({description:t,pageContext:s,consoleErrors:this.deps.consoleCollector.getErrors(),annotation:r,user:this.deps.user(),recording:i,anonId:ke(),anonEmail:Ee(),breadcrumbs:this.deps.breadcrumbCollector.getBreadcrumbs()});let a;try{a=this.deps.apiClient.createSubmissionSession(o,null)}catch{return null}let l=null;if(this.screenshotEnabled){const h=new AbortController;l=h,this.screenshotAbortController?.abort(),this.screenshotAbortController=h;const m=(async()=>{try{const v=await oi(async(Ot,Es)=>{const Ze=await a;if(!(h.signal.aborted||n!==this.submissionAttempt))return this.deps.apiClient.resolveScreenshotResourceUrl(Ze.id,Ze.token,Ot,Es,h.signal)},h.signal);if(h.signal.aborted||n!==this.submissionAttempt||!v)return;const y=await ai(v,r?[r]:[],this.deps.brandColors);if(h.signal.aborted||n!==this.submissionAttempt||!y)return;const b=await a;if(h.signal.aborted||n!==this.submissionAttempt)return;await this.deps.apiClient.uploadScreenshot(b.id,b.token,y,h.signal)}catch{}})().finally(()=>{this.pendingScreenshotTask===m&&(this.pendingScreenshotTask=null),this.screenshotAbortController===h&&(this.screenshotAbortController=null)});this.pendingScreenshotTask=m}let c;try{if(c=await a,n!==this.submissionAttempt)return l?.abort(),await this.deps.apiClient.abandonSubmissionSession(c.id,c.token).catch(()=>{}),null;this.activeSubmission=c}catch{return l?.abort(),null}return c}async finalize(){const t=this.submissionAttempt;this.resetScreenshotConsent();const r=this.host.isBackground(),i=this.activeSubmission??await(this.pendingSubmissionRequest??Promise.resolve(null));if(t!==this.submissionAttempt)return;if(!i){if(r)return this.showFinalizeFailure({canRetry:!1});throw new Error("No active submission session")}if(await this.waitForScreenshot(),t!==this.submissionAttempt)return;const n=r?Promise.resolve():new Promise(o=>setTimeout(o,yn));let s;try{s=await this.deps.apiClient.finalizeSubmissionSession(i.id,i.token)}catch(o){if(r)return this.showFinalizeFailure({canRetry:!0});throw o}await Promise.all([n,Le()]),!(t!==this.submissionAttempt||this.activeSubmission!==i)&&(this.activeSubmission=null,this.pendingSubmissionRequest=null,this.host.onFinalized(s,i))}async waitForScreenshot(){const t=this.pendingScreenshotTask;if(!t)return;let r;const i=await Promise.race([t.then(()=>!0),new Promise(n=>{r=setTimeout(()=>n(!1),wn)})]);r!==void 0&&clearTimeout(r),i||(this.screenshotAbortController?.abort(),this.pendingScreenshotTask===t&&(this.pendingScreenshotTask=null))}showFinalizeFailure(t){this.host.onReleaseForFailureCard(),this.failure?.destroy(),this.failure=new mn(this.deps.shadow(),this.deps.messages(),{onRetry:t.canRetry?()=>this.retryBackgroundFinalization():void 0,onClose:()=>this.dismissFinalizeFailure()})}retryBackgroundFinalization(){this.dismissFinalizeFailure(),this.host.onReenterBackground(),this.finalize().catch(()=>this.showFinalizeFailure({canRetry:!0}))}dismissFinalizeFailure(){this.failure?.destroy(),this.failure=null}abandon(){this.submissionAttempt+=1,this.screenshotAbortController?.abort(),this.screenshotAbortController=null,this.pendingScreenshotTask=null,this.resetScreenshotConsent();const t=this.activeSubmission;this.activeSubmission=null,this.pendingSubmissionRequest=null,t&&this.deps.apiClient.abandonSubmissionSession(t.id,t.token).catch(()=>{})}}function Le(){return new Promise(e=>requestAnimationFrame(()=>setTimeout(e,0)))}function dt(e){e.preventDefault(),e.stopPropagation()}class k{constructor(t){this.host=t,this.launcherLit=!0,this.acceptsFrustrationPrompt=!1}enter(){}exit(){}handleOpen(){}handleClose(){this.host.exitAll()}handleEscape(t){}handleTabClick(){this.host.exitAll()}handleToolbarModeChange(t){}handleDrawStroke(){}}class W extends k{constructor(){super(...arguments),this.kind="idle",this.launcherLit=!1,this.acceptsFrustrationPrompt=!0}handleOpen(){this.host.dismissFrustrationPrompt(),this.host.dismissSuccess(),this.host.transitionTo(new E(this.host))}handleClose(){}handleTabClick(){this.handleOpen()}}class E extends k{constructor(){super(...arguments),this.kind="annotating"}enter(){if(!this.host.hasAnnotationChrome()){this.host.mountAnnotationChrome();return}this.host.destroyRecordingManager(),this.host.teardownDrawBar(),this.host.ensureSession()}handleEscape(t){dt(t),this.host.exitAll()}handleToolbarModeChange(t){t==="record"?this.host.transitionTo(new Dt(this.host)):this.host.transitionTo(new E(this.host))}handleDrawStroke(){this.host.transitionTo(new xn(this.host,T()?"sheet":"bar"))}}class Dt extends k{constructor(){super(...arguments),this.kind="recording"}enter(){this.host.clearCurrentAnnotation(),this.host.teardownDrawBar(),this.host.destroySession(),this.host.startRecorder()}handleEscape(t){dt(t),this.host.stopRecordingIntoNote()}handleToolbarModeChange(t){t!=="record"&&this.host.transitionTo(new E(this.host))}}class xn extends k{constructor(t,r){super(t),this.surface=r,this.kind="drawing"}enter(){this.surface==="sheet"?this.host.mountDrawSheet():(this.host.mountDrawBar(),this.host.refreshDrawBar())}handleEscape(t){dt(t),this.host.cancelDraw()}handleToolbarModeChange(t){t==="record"?this.host.transitionTo(new Dt(this.host)):this.host.transitionTo(new E(this.host))}handleDrawStroke(){this.surface==="bar"&&this.host.refreshDrawBar()}}class Pe extends k{constructor(t,r){super(t),this.opts=r,this.kind="popup"}enter(){this.host.mountNotePopup(this.opts)}handleEscape(t){dt(t),this.host.exitAll()}handleToolbarModeChange(t){t==="record"?this.host.transitionTo(new Dt(this.host)):(this.host.dismissNotePopup(),this.host.transitionTo(new E(this.host)))}}class Mt extends k{constructor(){super(...arguments),this.kind="clarifying"}handleToolbarModeChange(t){this.host.revertToolbarDuringClarify()}}class Re extends k{constructor(){super(...arguments),this.kind="submitting",this.launcherLit=!1}enter(){this.host.releaseClarifyUi()}handleTabClick(){}}const kn=/^#[0-9a-f]{6}$/i;function En(e){return e===void 0?void 0:typeof e!="object"||e===null||![e.primary,e.hover,e.active,e.onPrimary].every(r=>typeof r=="string"&&kn.test(r))?De():{primary:e.primary.toLowerCase(),hover:e.hover.toLowerCase(),active:e.active.toLowerCase(),onPrimary:e.onPrimary.toLowerCase()}}function De(){console.warn("[MakeThisBetter] brandColors requires primary, hover, active, and onPrimary as six-digit hex colors.")}function Me(){const{hostname:e}=window.location;return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e.endsWith(".localhost")||e.endsWith(".local")||e.endsWith(".test")}class Sn{constructor(t){this.tab=null,this.toolbar=null,this.session=null,this.drawBar=null,this.dim=null,this.pageOffset=new sr,this.chatPopup=null,this.scrollLock=null,this.success=null,this.frustrationPrompt=null,this.frustrationDetector=null,this.state=new W(this),this.via="pin",this.currentAnnotation=null,this.lastPopupPos=null,this.recordingManager=null,this.touchHintShown=!1,this.lastHandoff={},this.handleKeydown=r=>{r.key==="Escape"&&(pt(r)||this.state.handleEscape(r))},this.stopRecordingIntoNote=()=>{this.recordingManager&&(this.recordingManager.stop(),this.via="record",this.transitionTo(new Pe(this,{x:window.innerWidth/2,y:window.innerHeight/2,targetName:this.messages.record.timer_label})))},this.config=t,t.projectKey||console.warn("[MakeThisBetter] projectKey is missing. Feedback submission will be rejected."),this.brandColors=En(t.brandColors),this.messages=Ce(t.locale??document.documentElement.lang??"en"),this.apiClient=new Gi({projectKey:t.projectKey,apiUrl:t.apiUrl,userToken:t.userToken,userTokenFn:t.userTokenFn}),this.consoleCollector=new Si,this.consoleCollector.start(),this.breadcrumbCollector=new Pi,this.breadcrumbCollector.start(),this.lifecycle=new vn({apiClient:this.apiClient,consoleCollector:this.consoleCollector,breadcrumbCollector:this.breadcrumbCollector,brandColors:this.brandColors,shadow:()=>this.shadow,messages:()=>this.messages,user:()=>this.config.user},{isBackground:()=>this.state.kind==="submitting",onReleaseForFailureCard:()=>{this.chatPopup?.destroy(),this.chatPopup=null,this.transitionTo(new W(this))},onReenterBackground:()=>this.transitionTo(new Re(this)),onFinalized:(r,i)=>this.handleFinalized(r,i)});try{this.buildUI()}catch(r){this.consoleCollector.stop(),this.breadcrumbCollector.stop(),console.warn("[MakeThisBetter] Widget failed to start:",r);return}t.frustrationDetection!==!1&&(this.frustrationDetector=new Pt(()=>this.handleFrustration()),this.frustrationDetector.start()),document.addEventListener("keydown",this.handleKeydown,!0)}transitionTo(t){const r=this.state;this.state=t,r.exit(),t.enter(),this.tab?.setActive(t.launcherLit)}buildUI(){if(this.shadow=new gt(this.config.theme??"auto",this.brandColors),this.config.entryMode==="api"){Me()&&console.warn('[MakeThisBetter] entryMode: "api" renders no launcher. Call MakeThisBetter.open() from your own UI.');return}if(T()){Me()&&console.warn("[MakeThisBetter] No launcher is rendered on touch devices. Call MakeThisBetter.open() from your own mobile UI.");return}this.mountTab()}mountTab(){this.tab||!this.shadow||(this.tab=new er(this.shadow,this.messages,this.config.position??"right",()=>this.state.handleTabClick(),this.config.tabText))}open(){this.shadow&&this.state.handleOpen()}close(){this.state.handleClose()}showLauncher(){T()||(this.mountTab(),this.tab?.setActive(this.state.launcherLit))}hideLauncher(){this.tab?.destroy(),this.tab=null}setLocale(t){this.config.locale=t,this.messages=Ce(t),this.tab?.setMessages(this.messages)}handleFrustration(){!this.state.acceptsFrustrationPrompt||this.frustrationPrompt||Ri()||(this.frustrationPrompt=new ir(this.shadow,this.messages,{onTell:()=>{this.dismissFrustrationPrompt(),this.state.handleOpen()},onDismiss:()=>{Di(),this.dismissFrustrationPrompt()},onAutoHide:()=>this.dismissFrustrationPrompt()}))}dismissSuccess(){this.success?.destroy(),this.success=null,this.chatPopup?.destroy(),this.chatPopup=null}dismissFrustrationPrompt(){this.frustrationPrompt?.destroy(),this.frustrationPrompt=null}hasAnnotationChrome(){return this.toolbar!==null}mountAnnotationChrome(){St();const t=T();this.toolbar=new dr(this.shadow,this.messages,()=>this.exitAll(),r=>this.state.handleToolbarModeChange(r),this.config.position??"right",!t||!this.touchHintShown),t&&(this.touchHintShown=!0),this.ensureSession(),t&&this.toolbar&&this.pageOffset.reserve(this.toolbar.height())}ensureSession(){this.session||(this.session=new Tr(this.shadow,this.messages,{onPin:(t,r)=>{this.currentAnnotation=t,this.via="pin",this.transitionTo(new Pe(this,{x:t.x,y:t.y,targetName:r,targetRect:t.targetRect}))},onDrawStroke:()=>this.state.handleDrawStroke()}))}destroySession(){this.session?.destroy(),this.session=null}clearCurrentAnnotation(){this.currentAnnotation=null}startRecorder(){this.recordingManager=new un,this.recordingManager.start(this.shadow,this.messages,this.stopRecordingIntoNote).catch(t=>{console.warn("[MakeThisBetter] Interaction replay unavailable, falling back to markup:",t),this.state.kind==="recording"&&(this.toolbar?.setMode("markup"),this.state.handleToolbarModeChange("markup"))})}destroyRecordingManager(){this.recordingManager?.destroy(),this.recordingManager=null}mountDrawBar(){this.engageScrollLock(),this.drawBar=new Rr(this.shadow,{messages:this.messages,onUndo:()=>this.handleDrawUndoRedo("undo"),onRedo:()=>this.handleDrawUndoRedo("redo"),onCancel:()=>this.cancelDraw(),onSubmit:t=>this.handleDrawSubmit(t),onActivity:()=>this.lifecycle.warmScreenshotDeps()}),this.lifecycle.setScreenshotEnabled(!0),this.lifecycle.warmScreenshotDeps()}mountDrawSheet(){this.engageScrollLock();let t=!1;this.chatPopup=new xt(this.shadow,{targetName:this.messages.annotation.drawing,x:window.innerWidth/2,y:window.innerHeight/2,messages:this.messages,position:this.config.position??"right",onSubmit:async r=>{const i=this.session?.getDrawAnnotation();if(!i)return this.cancelDraw(),null;t=!0,this.currentAnnotation=i,this.via="draw",this.session?.dismissInteraction(),this.teardownDrawBar();const n=this.recordingManager?.getRecording()??void 0,s=await this.lifecycle.start(r||this.messages.annotation.drawing,i,n);return s?.board_url&&z(s.board_url),s},onClarify:async(r,i,n,s)=>this.apiClient.streamClarification(r,i,n,s),onAnswer:(r,i,n)=>this.apiClient.answerClarification(r,i,n),onFinalize:()=>this.lifecycle.finalize(),onCancel:()=>t?this.exitAll():this.cancelDraw(),onConversationOpen:()=>this.transitionTo(new Mt(this)),onActivity:()=>this.lifecycle.warmScreenshotDeps(),resolveBoardLink:()=>this.buildViewFeedbackHandler()??this.buildMyFeedbackHandler(),resolveEmailCapture:()=>this.buildEmailCapture()}),this.lifecycle.setScreenshotEnabled(!0),this.lifecycle.warmScreenshotDeps()}handleDrawUndoRedo(t){t==="undo"?this.session?.undoDraw():this.session?.redoDraw(),this.refreshDrawBar()}refreshDrawBar(){this.session&&this.drawBar?.setUndoRedo(this.session.canUndoDraw(),this.session.canRedoDraw())}cancelDraw(){this.session?.clearDraw(),this.releaseScrollLock(),this.teardownDrawBar(),this.chatPopup?.destroy(),this.chatPopup=null,this.dim?.destroy(),this.dim=null,this.transitionTo(new E(this))}teardownDrawBar(){this.drawBar?.destroy(),this.drawBar=null}handleDrawSubmit(t){const r=this.session?.getDrawAnnotation();if(!r){this.cancelDraw();return}this.currentAnnotation=r,this.via="draw",this.session?.dismissInteraction();const i=t||this.messages.annotation.drawing,n=this.recordingManager?.getRecording()??void 0;this.teardownDrawBar(),this.releaseScrollLock(),this.dim?.destroy(),this.dim=null,this.mountChatAfterSubmit(i,r,n)}mountChatAfterSubmit(t,r,i){this.dim=new zt(this.shadow,()=>this.exitAll()),this.engageScrollLock(),this.chatPopup=new xt(this.shadow,{targetName:r?.targetName??this.messages.annotation.drawing,x:this.lastPopupPos?.x??window.innerWidth/2,y:this.lastPopupPos?.y??window.innerHeight/2,messages:this.messages,position:this.config.position??"right",onSubmit:async()=>{const n=await this.lifecycle.start(t,r,i);return n?.board_url&&z(n.board_url),n},onClarify:async(n,s,o,a)=>this.apiClient.streamClarification(n,s,o,a),onAnswer:(n,s,o)=>this.apiClient.answerClarification(n,s,o),onFinalize:()=>this.lifecycle.finalize(),onCancel:()=>this.exitAll(),onConversationOpen:()=>this.transitionTo(new Mt(this)),resolveBoardLink:()=>this.buildViewFeedbackHandler()??this.buildMyFeedbackHandler(),resolveEmailCapture:()=>this.buildEmailCapture()}),this.chatPopup.submit(t)}mountNotePopup({x:t,y:r,targetName:i,targetRect:n}){this.lastPopupPos={x:t,y:r},this.teardownDrawBar(),this.session?.dismissInteraction(),this.chatPopup?.destroy(),this.chatPopup=null,this.dim?.destroy(),this.dim=null,this.dim=new zt(this.shadow,()=>this.exitAll());const s=this.recordingManager?.getRecording();s&&this.lifecycle.setScreenshotEnabled(!0);const o=this.currentAnnotation,a=this.recordingManager?.getRecording()??void 0;this.chatPopup=new xt(this.shadow,{targetName:i,x:t,y:r,targetRect:n,messages:this.messages,position:this.config.position??"right",onSubmit:async l=>{this.currentAnnotation=o??this.currentAnnotation;const c=await this.lifecycle.start(l,this.currentAnnotation,a);return c?.board_url&&z(c.board_url),c},onClarify:async(l,c,h,u)=>this.apiClient.streamClarification(l,c,h,u),onAnswer:(l,c,h)=>this.apiClient.answerClarification(l,c,h),onFinalize:()=>(this.teardownSubmittingUi(),this.transitionTo(new Re(this)),this.lifecycle.finalize()),onCancel:()=>this.exitAll(),onConversationOpen:()=>this.transitionTo(new Mt(this)),onActivity:()=>this.lifecycle.warmScreenshotDeps(),resolveBoardLink:()=>this.buildViewFeedbackHandler()??this.buildMyFeedbackHandler(),resolveEmailCapture:()=>this.buildEmailCapture(),...s?{recordingSeconds:s.duration}:{onScreenshotToggle:l=>this.lifecycle.setScreenshotEnabled(l),screenshotEnabled:this.lifecycle.isScreenshotEnabled()}}),this.engageScrollLock(),this.lifecycle.warmScreenshotDeps()}dismissNotePopup(){this.chatPopup?.destroy(),this.chatPopup=null,this.dim?.destroy(),this.dim=null,this.releaseScrollLock(),this.clearCurrentAnnotation(),this.destroySession()}engageScrollLock(){this.scrollLock||(this.scrollLock=cr())}releaseScrollLock(){this.scrollLock?.release(),this.scrollLock=null}buildMyFeedbackHandler(){if(!this.config.user&&en())return async()=>{const t=await this.apiClient.createIdentityToken(ke());!t?.identity_token||!t.board_url||(z(t.board_url),window.open(`${t.board_url}?identity=${encodeURIComponent(t.identity_token)}`,"_blank"))}}teardownSubmittingUi(){this.teardownDrawBar(),this.releaseScrollLock(),this.dim?.destroy(),this.dim=null,this.session?.hideHighlight(),this.session?.destroy(),this.session=null,this.recordingManager?.destroy(),this.recordingManager=null}revertToolbarDuringClarify(){this.toolbar?.setMode(this.via==="record"?"record":"markup")}releaseClarifyUi(){this.teardownToolbar(),this.currentAnnotation=null}handleFinalized(t,r){if(this.lastHandoff={feedbackId:t.id,boardUrl:t.board_url,identityToken:t.identity_token},t.board_url&&z(t.board_url),!(this.chatPopup&&this.chatPopup.sessionId()!==r.id)&&!(!this.chatPopup&&this.state.kind!=="submitting"&&this.state.kind!=="clarifying")){if(this.chatPopup){this.teardownSubmittingUi(),this.teardownToolbar(),this.lifecycle.resetScreenshotConsent(),this.transitionTo(new W(this));return}this.teardownToolbar(),this.lifecycle.resetScreenshotConsent(),this.showSuccess({skipFollowup:r.ai_clarify_available===!1})}}showSuccess(t){this.lifecycle.dismissFinalizeFailure(),this.transitionTo(new W(this)),this.success=new jr(this.shadow,this.messages,()=>{this.success?.destroy(),this.success=null},{...t,onViewFeedback:this.buildViewFeedbackHandler()})}buildEmailCapture(){if(this.config.user)return;const{feedbackId:t,identityToken:r}=this.lastHandoff;if(!(!t||!r)&&!Ee())return{onSubmit:async i=>{const n=await this.apiClient.updateReporter(t,i,r);return n&&tn(i),n}}}buildViewFeedbackHandler(){const{boardUrl:t,identityToken:r}=this.lastHandoff;if(t){if(r)return()=>{window.open(`${t}?identity=${encodeURIComponent(r)}`,"_blank")};if(this.config.userToken||this.config.userTokenFn)return async()=>{try{const i=await this.apiClient.resolveUserToken();i&&window.open(`${t}?identity=${encodeURIComponent(i)}`,"_blank")}catch{}}}}teardownToolbar(){this.pageOffset.release(),this.toolbar?.destroy(),this.toolbar=null}exitAll(){this.lifecycle.abandon(),this.via="pin",this.transitionTo(new W(this)),this.teardownToolbar(),this.teardownDrawBar(),this.releaseScrollLock(),this.session?.hideHighlight(),this.session?.destroy(),this.session=null,this.dim?.destroy(),this.dim=null,this.chatPopup?.destroy(),this.chatPopup=null,this.currentAnnotation=null,this.recordingManager?.destroy(),this.recordingManager=null}destroy(){document.removeEventListener("keydown",this.handleKeydown,!0),this.exitAll(),this.consoleCollector.stop(),this.breadcrumbCollector.stop(),this.frustrationDetector?.stop(),this.dismissFrustrationPrompt(),this.success?.destroy(),this.lifecycle.dismissFinalizeFailure(),this.tab?.destroy(),this.recordingManager?.destroy(),this.shadow?.destroy()}}let S=null,A=null,L=null;function Cn(){L&&(document.removeEventListener("DOMContentLoaded",L),L=null)}function V(e){Cn(),S?.destroy(),S=e?new Sn(e):null}const Ie={init(e){typeof document>"u"||(V(),A=e,document.readyState==="loading"?(L=()=>{L=null,V(e)},document.addEventListener("DOMContentLoaded",L,{once:!0})):V(e))},destroy(){V(),A=null},setLocale(e){A&&(A.locale=e),S?.setLocale(e)},open(){S?.open()},close(){S?.close()},showLauncher(){S?.showLauncher()},hideLauncher(){S?.hideLauncher()}};typeof window<"u"&&(window.MakeThisBetter=Ie,document.addEventListener("turbo:load",()=>{const e=document.getElementById(x);A&&(!e||!e.shadowRoot)&&(e?.remove(),V(A))}));function Tn(e,t){if(e.match(/^[a-z]+:\/\//i))return e;if(e.match(/^\/\//))return window.location.protocol+e;if(e.match(/^[a-z]+:/i))return e;const r=document.implementation.createHTMLDocument(),i=r.createElement("base"),n=r.createElement("a");return r.head.appendChild(i),r.body.appendChild(n),t&&(i.href=t),n.href=e,n.href}const _n=(()=>{let e=0;const t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(e+=1,`u${t()}${e}`)})();function w(e){const t=[];for(let r=0,i=e.length;r<i;r++)t.push(e[r]);return t}let P=null;function Fe(e={}){return P||(e.includeStyleProperties?(P=e.includeStyleProperties,P):(P=w(window.getComputedStyle(document.documentElement)),P))}function ut(e,t){const i=(e.ownerDocument.defaultView||window).getComputedStyle(e).getPropertyValue(t);return i?parseFloat(i.replace("px","")):0}function An(e){const t=ut(e,"border-left-width"),r=ut(e,"border-right-width");return e.clientWidth+t+r}function Ln(e){const t=ut(e,"border-top-width"),r=ut(e,"border-bottom-width");return e.clientHeight+t+r}function It(e,t={}){const r=t.width||An(e),i=t.height||Ln(e);return{width:r,height:i}}function Pn(){let e,t;try{t=process}catch{}const r=t&&t.env?t.env.devicePixelRatio:null;return r&&(e=parseInt(r,10),Number.isNaN(e)&&(e=1)),e||window.devicePixelRatio||1}const f=16384;function Rn(e){(e.width>f||e.height>f)&&(e.width>f&&e.height>f?e.width>e.height?(e.height*=f/e.width,e.width=f):(e.width*=f/e.height,e.height=f):e.width>f?(e.height*=f/e.width,e.width=f):(e.width*=f/e.height,e.height=f))}function Dn(e,t={}){return e.toBlob?new Promise(r=>{e.toBlob(r,t.type?t.type:"image/png",t.quality?t.quality:1)}):new Promise(r=>{const i=window.atob(e.toDataURL(t.type?t.type:void 0,t.quality?t.quality:void 0).split(",")[1]),n=i.length,s=new Uint8Array(n);for(let o=0;o<n;o+=1)s[o]=i.charCodeAt(o);r(new Blob([s],{type:t.type?t.type:"image/png"}))})}function mt(e){return new Promise((t,r)=>{const i=new Image;i.onload=()=>{i.decode().then(()=>{requestAnimationFrame(()=>t(i))})},i.onerror=r,i.crossOrigin="anonymous",i.decoding="async",i.src=e})}async function Mn(e){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(e)).then(encodeURIComponent).then(t=>`data:image/svg+xml;charset=utf-8,${t}`)}async function In(e,t,r){const i="http://www.w3.org/2000/svg",n=document.createElementNS(i,"svg"),s=document.createElementNS(i,"foreignObject");return n.setAttribute("width",`${t}`),n.setAttribute("height",`${r}`),n.setAttribute("viewBox",`0 0 ${t} ${r}`),s.setAttribute("width","100%"),s.setAttribute("height","100%"),s.setAttribute("x","0"),s.setAttribute("y","0"),s.setAttribute("externalResourcesRequired","true"),n.appendChild(s),s.appendChild(e),Mn(n)}const p=(e,t)=>{if(e instanceof t)return!0;const r=Object.getPrototypeOf(e);return r===null?!1:r.constructor.name===t.name||p(r,t)};function Fn(e){const t=e.getPropertyValue("content");return`${e.cssText} content: '${t.replace(/'|"/g,"")}';`}function Hn(e,t){return Fe(t).map(r=>{const i=e.getPropertyValue(r),n=e.getPropertyPriority(r);return`${r}: ${i}${n?" !important":""};`}).join(" ")}function Bn(e,t,r,i){const n=`.${e}:${t}`,s=r.cssText?Fn(r):Hn(r,i);return document.createTextNode(`${n}{${s}}`)}function He(e,t,r,i){const n=window.getComputedStyle(e,r),s=n.getPropertyValue("content");if(s===""||s==="none")return;const o=_n();try{t.className=`${t.className} ${o}`}catch{return}const a=document.createElement("style");a.appendChild(Bn(o,r,n,i)),t.appendChild(a)}function Nn(e,t,r){He(e,t,":before",r),He(e,t,":after",r)}const Be="application/font-woff",Ne="image/jpeg",On={woff:Be,woff2:Be,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:Ne,jpeg:Ne,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function $n(e){const t=/\.([^./]*?)$/g.exec(e);return t?t[1]:""}function Ft(e){const t=$n(e).toLowerCase();return On[t]||""}function Un(e){return e.split(/,/)[1]}function Ht(e){return e.search(/^(data:)/)!==-1}function zn(e,t){return`data:${t};base64,${e}`}async function Oe(e,t,r){const i=await fetch(e,t);if(!i.ok)throw new Error(`Resource "${i.url}" returned HTTP ${i.status}`);const n=await i.blob();return new Promise((s,o)=>{const a=new FileReader;a.onerror=o,a.onloadend=()=>{try{s(r({res:i,result:a.result}))}catch(l){o(l)}},a.readAsDataURL(n)})}const Bt={};function jn(e,t,r){let i=e.replace(/\?.*/,"");return r&&(i=e),/ttf|otf|eot|woff2?/i.test(i)&&(i=i.replace(/.*\//,"")),t?`[${t}]${i}`:i}async function Nt(e,t,r){const i=jn(e,t,r.includeQueryParams);if(Bt[i]!=null)return Bt[i];r.cacheBust&&(e+=(/\?/.test(e)?"&":"?")+new Date().getTime());let n;try{const s=a=>Oe(a,r.fetchRequestInit,({res:l,result:c})=>(t||(t=l.headers.get("Content-Type")||""),Un(c)));let o;try{o=await s(e)}catch(a){const l=await r.resourceUrlResolver?.(e,t);if(!l||l===e)throw a;o=await s(l)}n=zn(o,t)}catch(s){n=r.imagePlaceholder||"";let o=`Failed to fetch resource: ${e}`;s&&(o=typeof s=="string"?s:s.message),o&&console.warn(o)}return Bt[i]=n,n}async function qn(e){const t=e.toDataURL();return t==="data:,"?e.cloneNode(!1):mt(t)}async function Wn(e,t){if(e.currentSrc){const s=document.createElement("canvas"),o=s.getContext("2d");s.width=e.clientWidth,s.height=e.clientHeight,o?.drawImage(e,0,0,s.width,s.height);const a=s.toDataURL();return mt(a)}const r=e.poster,i=Ft(r),n=await Nt(r,i,t);return mt(n)}async function Vn(e,t){var r;try{if(!((r=e?.contentDocument)===null||r===void 0)&&r.body)return await bt(e.contentDocument.body,t,!0)}catch{}return e.cloneNode(!1)}async function Yn(e,t){return p(e,HTMLCanvasElement)?qn(e):p(e,HTMLVideoElement)?Wn(e,t):p(e,HTMLIFrameElement)?Vn(e,t):e.cloneNode($e(e))}const Xn=e=>e.tagName!=null&&e.tagName.toUpperCase()==="SLOT",$e=e=>e.tagName!=null&&e.tagName.toUpperCase()==="SVG";async function Kn(e,t,r){var i,n;if($e(t))return t;let s=[];return Xn(e)&&e.assignedNodes?s=w(e.assignedNodes()):p(e,HTMLIFrameElement)&&(!((i=e.contentDocument)===null||i===void 0)&&i.body)?s=w(e.contentDocument.body.childNodes):s=w(((n=e.shadowRoot)!==null&&n!==void 0?n:e).childNodes),s.length===0||p(e,HTMLVideoElement)||await s.reduce((o,a)=>o.then(()=>bt(a,r)).then(l=>{l&&t.appendChild(l)}),Promise.resolve()),t}function Gn(e,t,r){const i=t.style;if(!i)return;const n=window.getComputedStyle(e);n.cssText?(i.cssText=n.cssText,i.transformOrigin=n.transformOrigin):Fe(r).forEach(s=>{let o=n.getPropertyValue(s);s==="font-size"&&o.endsWith("px")&&(o=`${Math.floor(parseFloat(o.substring(0,o.length-2)))-.1}px`),p(e,HTMLIFrameElement)&&s==="display"&&o==="inline"&&(o="block"),s==="d"&&t.getAttribute("d")&&(o=`path(${t.getAttribute("d")})`),i.setProperty(s,o,n.getPropertyPriority(s))})}function Jn(e,t){p(e,HTMLTextAreaElement)&&(t.innerHTML=e.value),p(e,HTMLInputElement)&&t.setAttribute("value",e.value)}function Zn(e,t){if(p(e,HTMLSelectElement)){const r=t,i=Array.from(r.children).find(n=>e.value===n.getAttribute("value"));i&&i.setAttribute("selected","")}}function Qn(e,t,r){return p(t,Element)&&(Gn(e,t,r),Nn(e,t,r),Jn(e,t),Zn(e,t)),t}async function ts(e,t){const r=e.querySelectorAll?e.querySelectorAll("use"):[];if(r.length===0)return e;const i={};for(let s=0;s<r.length;s++){const a=r[s].getAttribute("xlink:href");if(a){const l=e.querySelector(a),c=document.querySelector(a);!l&&c&&!i[a]&&(i[a]=await bt(c,t,!0))}}const n=Object.values(i);if(n.length){const s="http://www.w3.org/1999/xhtml",o=document.createElementNS(s,"svg");o.setAttribute("xmlns",s),o.style.position="absolute",o.style.width="0",o.style.height="0",o.style.overflow="hidden",o.style.display="none";const a=document.createElementNS(s,"defs");o.appendChild(a);for(let l=0;l<n.length;l++)a.appendChild(n[l]);e.appendChild(o)}return e}async function bt(e,t,r){return!r&&t.filter&&!t.filter(e)?null:Promise.resolve(e).then(i=>Yn(i,t)).then(i=>Kn(e,i,t)).then(i=>Qn(e,i,t)).then(i=>ts(i,t))}const Ue=/url\((['"]?)([^'"]+?)\1\)/g,es=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,rs=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function is(e){const t=e.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function ns(e){const t=[];return e.replace(Ue,(r,i,n)=>(t.push(n),r)),t.filter(r=>!Ht(r))}async function ss(e,t,r,i,n){try{const s=r?Tn(t,r):t,o=Ft(t);let a;return n||(a=await Nt(s,o,i)),e.replace(is(t),`$1${a}$3`)}catch{}return e}function os(e,{preferredFontFormat:t}){return t?e.replace(rs,r=>{for(;;){const[i,,n]=es.exec(r)||[];if(!n)return"";if(n===t)return`src: ${i};`}}):e}function ze(e){return e.search(Ue)!==-1}async function je(e,t,r){if(!ze(e))return e;const i=os(e,r);return ns(i).reduce((s,o)=>s.then(a=>ss(a,o,t,r)),Promise.resolve(i))}async function R(e,t,r){var i;const n=(i=t.style)===null||i===void 0?void 0:i.getPropertyValue(e);if(n){const s=await je(n,null,r);return t.style.setProperty(e,s,t.style.getPropertyPriority(e)),!0}return!1}async function as(e,t){await R("background",e,t)||await R("background-image",e,t),await R("mask",e,t)||await R("-webkit-mask",e,t)||await R("mask-image",e,t)||await R("-webkit-mask-image",e,t)}async function ls(e,t){const r=p(e,HTMLImageElement);if(!(r&&!Ht(e.src))&&!(p(e,SVGImageElement)&&!Ht(e.href.baseVal)))return;const i=r?e.src:e.href.baseVal,n=await Nt(i,Ft(i),t);await new Promise((s,o)=>{e.onload=s,e.onerror=t.onImageErrorHandler?(...l)=>{try{s(t.onImageErrorHandler(...l))}catch(c){o(c)}}:o;const a=e;a.decode&&(a.decode=s),a.loading==="lazy"&&(a.loading="eager"),r?(e.srcset="",e.src=n):e.href.baseVal=n})}async function cs(e,t){const i=w(e.childNodes).map(n=>qe(n,t));await Promise.all(i).then(()=>e)}async function qe(e,t){p(e,Element)&&(await as(e,t),await ls(e,t),await cs(e,t))}function hs(e,t){const{style:r}=e;t.backgroundColor&&(r.backgroundColor=t.backgroundColor),t.width&&(r.width=`${t.width}px`),t.height&&(r.height=`${t.height}px`);const i=t.style;return i!=null&&Object.keys(i).forEach(n=>{r[n]=i[n]}),e}const We={};async function Ve(e){let t=We[e];if(t!=null)return t;const i=await(await fetch(e)).text();return t={url:e,cssText:i},We[e]=t,t}async function Ye(e,t){let r=e.cssText;const i=/url\(["']?([^"')]+)["']?\)/g,s=(r.match(/url\([^)]+\)/g)||[]).map(async o=>{let a=o.replace(i,"$1");return a.startsWith("https://")||(a=new URL(a,e.url).href),Oe(a,t.fetchRequestInit,({result:l})=>(r=r.replace(o,`url(${l})`),[o,l]))});return Promise.all(s).then(()=>r)}function Xe(e){if(e==null)return[];const t=[],r=/(\/\*[\s\S]*?\*\/)/gi;let i=e.replace(r,"");const n=new RegExp("((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})","gi");for(;;){const l=n.exec(i);if(l===null)break;t.push(l[0])}i=i.replace(n,"");const s=/@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=s.exec(i);if(l===null){if(l=a.exec(i),l===null)break;s.lastIndex=a.lastIndex}else a.lastIndex=s.lastIndex;t.push(l[0])}return t}async function ds(e,t){const r=[],i=[];return e.forEach(n=>{if("cssRules"in n)try{w(n.cssRules||[]).forEach((s,o)=>{if(s.type===CSSRule.IMPORT_RULE){let a=o+1;const l=s.href,c=Ve(l).then(h=>Ye(h,t)).then(h=>Xe(h).forEach(u=>{try{n.insertRule(u,u.startsWith("@import")?a+=1:n.cssRules.length)}catch(m){console.error("Error inserting rule from remote css",{rule:u,error:m})}})).catch(h=>{console.error("Error loading remote css",h.toString())});i.push(c)}})}catch(s){const o=e.find(a=>a.href==null)||document.styleSheets[0];n.href!=null&&i.push(Ve(n.href).then(a=>Ye(a,t)).then(a=>Xe(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",s)}}),Promise.all(i).then(()=>(e.forEach(n=>{if("cssRules"in n)try{w(n.cssRules||[]).forEach(s=>{r.push(s)})}catch(s){console.error(`Error while reading CSS rules from ${n.href}`,s)}}),r))}function us(e){return e.filter(t=>t.type===CSSRule.FONT_FACE_RULE).filter(t=>ze(t.style.getPropertyValue("src")))}async function ms(e,t){if(e.ownerDocument==null)throw new Error("Provided element is not within a Document");const r=w(e.ownerDocument.styleSheets),i=await ds(r,t);return us(i)}function Ke(e){return e.trim().replace(/["']/g,"")}function bs(e){const t=new Set;function r(i){(i.style.fontFamily||getComputedStyle(i).fontFamily).split(",").forEach(s=>{t.add(Ke(s))}),Array.from(i.children).forEach(s=>{s instanceof HTMLElement&&r(s)})}return r(e),t}async function Ge(e,t){const r=await ms(e,t),i=bs(e);return(await Promise.all(r.filter(s=>i.has(Ke(s.style.fontFamily))).map(s=>{const o=s.parentStyleSheet?s.parentStyleSheet.href:null;return je(s.cssText,o,t)}))).join(`
85
- `)}async function ps(e,t){const r=t.fontEmbedCSS!=null?t.fontEmbedCSS:t.skipFonts?null:await Ge(e,t);if(r){const i=document.createElement("style"),n=document.createTextNode(r);i.appendChild(n),e.firstChild?e.insertBefore(i,e.firstChild):e.appendChild(i)}}async function Je(e,t={}){const{width:r,height:i}=It(e,t),n=await bt(e,t,!0);return await ps(n,t),await qe(n,t),hs(n,t),await In(n,r,i)}async function Y(e,t={}){const{width:r,height:i}=It(e,t),n=await Je(e,t),s=await mt(n),o=document.createElement("canvas"),a=o.getContext("2d"),l=t.pixelRatio||Pn(),c=t.canvasWidth||r,h=t.canvasHeight||i;return o.width=c*l,o.height=h*l,t.skipAutoScale||Rn(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(s,0,0,o.width,o.height),o}async function fs(e,t={}){const{width:r,height:i}=It(e,t);return(await Y(e,t)).getContext("2d").getImageData(0,0,r,i).data}async function gs(e,t={}){return(await Y(e,t)).toDataURL()}async function ys(e,t={}){return(await Y(e,t)).toDataURL("image/jpeg",t.quality||1)}async function ws(e,t={}){const r=await Y(e,t);return await Dn(r)}async function vs(e,t={}){return Ge(e,t)}const xs=Object.freeze(Object.defineProperty({__proto__:null,getFontEmbedCSS:vs,toBlob:ws,toCanvas:Y,toJpeg:ys,toPixelData:fs,toPng:gs,toSvg:Je},Symbol.toStringTag,{value:"Module"}));return Ie}();
72
+ <button class="mtb-record-stop" type="button">${d(i.record.stop)}</button>
73
+ `,t.append(this.el),this.timerEl=this.el.querySelector(".mtb-record-timer"),this.el.querySelector(".mtb-record-stop").addEventListener("click",n),this.intervalId=setInterval(()=>this.updateTimer(),1e3)}updateTimer(){const t=this.getDuration(),i=String(Math.floor(t/60)).padStart(2,"0"),r=String(t%60).padStart(2,"0");this.timerEl.textContent=`${i}:${r}`}destroy(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.el.remove()}}class un{constructor(){this.session=null,this.bar=null,this.result=null}async start(t,i,r){this.session=new hn(t,r),this.bar=new dn(t,i,()=>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}}function mn(){return{page_url:F(window.location.href),user_agent:navigator.userAgent,browser:bn(),os:pn(),screen_width:window.screen.width,screen_height:window.screen.height}}function bn(){const e=navigator.userAgent;return/Edg\//.test(e)?`Edge ${e.match(/Edg\/(\S+)/)?.[1]??""}`:/OPR\//.test(e)?`Opera ${e.match(/OPR\/(\S+)/)?.[1]??""}`:/Chrome\//.test(e)?`Chrome ${e.match(/Chrome\/(\S+)/)?.[1]??""}`:/Safari\//.test(e)&&/Version\//.test(e)?`Safari ${e.match(/Version\/(\S+)/)?.[1]??""}`:/Firefox\//.test(e)?`Firefox ${e.match(/Firefox\/(\S+)/)?.[1]??""}`:"Unknown"}function pn(){const e=navigator.userAgent;return/Windows NT 10/.test(e)?"Windows 10/11":/Windows NT/.test(e)?"Windows":/Mac OS X 10_15|macOS 1[56789]/.test(e)||/Mac OS X/.test(e)?"macOS":/Android/.test(e)?`Android ${e.match(/Android (\d+)/)?.[1]??""}`:/iPhone|iPad|iPod/.test(e)?"iOS":/Linux/.test(e)?"Linux":"Unknown"}function fn(e){const{description:t,pageContext:i,consoleErrors:r,annotation:n,user:s,recording:a,anonId:o,anonEmail:l,breadcrumbs:c}=e;return{...it({description:t,...i,page_url:F(i.page_url),console_errors:r,annotations:n?[n]:[],target_element:n?.targetSelector?{selector:n.targetSelector,text:n.targetText??"",name:n.targetName??""}:void 0,recording_events:a?.events,recording_duration:a?.duration,breadcrumbs:c}),user_id:s?.id,user_email:s?.email,user_name:s?.name,reporter_external_id:s?void 0:o,reporter_email:s?void 0:l}}const gn=300,wn=5e3;class yn{constructor(t,i){this.deps=t,this.host=i,this.activeSubmission=null,this.pendingSubmissionRequest=null,this.submissionAttempt=0,this.pendingScreenshotTask=null,this.screenshotAbortController=null,this.screenshotEnabled=!0}isScreenshotEnabled(){return this.screenshotEnabled}resetScreenshotConsent(){this.screenshotEnabled=!0}setScreenshotEnabled(t){if(this.screenshotEnabled=t,t){this.warmScreenshotDeps();return}this.screenshotAbortController?.abort()}warmScreenshotDeps(){this.screenshotEnabled&&Ct()}start(t,i,r){const n=++this.submissionAttempt,s=this.createSubmission(t,i,r,n);return this.pendingSubmissionRequest=s,s}async createSubmission(t,i,r,n){if(await Pe(),n!==this.submissionAttempt)return null;const s=mn(),a=fn({description:t,pageContext:s,consoleErrors:this.deps.consoleCollector.getErrors(),annotation:i,user:this.deps.user(),recording:r,anonId:Ee(),anonEmail:Se(),breadcrumbs:this.deps.breadcrumbCollector.getBreadcrumbs()});let o;try{o=this.deps.apiClient.createSubmissionSession(a,null)}catch{return null}let l=null;if(this.screenshotEnabled){const h=new AbortController;l=h,this.screenshotAbortController?.abort(),this.screenshotAbortController=h;const m=(async()=>{try{const v=await ar(async(zt,ks)=>{const Ze=await o;if(!(h.signal.aborted||n!==this.submissionAttempt))return this.deps.apiClient.resolveScreenshotResourceUrl(Ze.id,Ze.token,zt,ks,h.signal)},h.signal);if(h.signal.aborted||n!==this.submissionAttempt||!v)return;const w=await or(v,i?[i]:[],this.deps.brandColors);if(h.signal.aborted||n!==this.submissionAttempt||!w)return;const b=await o;if(h.signal.aborted||n!==this.submissionAttempt)return;await this.deps.apiClient.uploadScreenshot(b.id,b.token,w,h.signal)}catch{}})().finally(()=>{this.pendingScreenshotTask===m&&(this.pendingScreenshotTask=null),this.screenshotAbortController===h&&(this.screenshotAbortController=null)});this.pendingScreenshotTask=m}let c;try{if(c=await o,n!==this.submissionAttempt)return l?.abort(),await this.deps.apiClient.abandonSubmissionSession(c.id,c.token).catch(()=>{}),null;this.activeSubmission=c}catch{return l?.abort(),null}return c}async finalize(){const t=this.submissionAttempt;this.resetScreenshotConsent();const i=this.host.isBackground(),r=this.activeSubmission??await(this.pendingSubmissionRequest??Promise.resolve(null));if(t!==this.submissionAttempt)return;if(!r){if(i)return this.showFinalizeFailure({canRetry:!1});throw new Error("No active submission session")}if(await this.waitForScreenshot(),t!==this.submissionAttempt)return;const n=i?Promise.resolve():new Promise(a=>setTimeout(a,gn));let s;try{s=await this.deps.apiClient.finalizeSubmissionSession(r.id,r.token)}catch(a){if(i)return this.showFinalizeFailure({canRetry:!0});throw a}await Promise.all([n,Pe()]),!(t!==this.submissionAttempt||this.activeSubmission!==r)&&(this.activeSubmission=null,this.pendingSubmissionRequest=null,this.host.onFinalized(s,r))}async waitForScreenshot(){const t=this.pendingScreenshotTask;if(!t)return;let i;const r=await Promise.race([t.then(()=>!0),new Promise(n=>{i=setTimeout(()=>n(!1),wn)})]);i!==void 0&&clearTimeout(i),r||(this.screenshotAbortController?.abort(),this.pendingScreenshotTask===t&&(this.pendingScreenshotTask=null))}showFinalizeFailure(t){this.host.onFinalizeFailure(t.canRetry?()=>this.retryBackgroundFinalization():void 0)}retryBackgroundFinalization(){this.host.onReenterBackground(),this.finalize().catch(()=>this.showFinalizeFailure({canRetry:!0}))}abandon(){this.submissionAttempt+=1,this.screenshotAbortController?.abort(),this.screenshotAbortController=null,this.pendingScreenshotTask=null,this.resetScreenshotConsent();const t=this.activeSubmission;this.activeSubmission=null,this.pendingSubmissionRequest=null,t&&this.deps.apiClient.abandonSubmissionSession(t.id,t.token).catch(()=>{})}}function Pe(){return new Promise(e=>requestAnimationFrame(()=>setTimeout(e,0)))}function ht(e){e.preventDefault(),e.stopPropagation()}class k{constructor(t){this.host=t,this.launcherLit=!0,this.acceptsFrustrationPrompt=!1}enter(){}exit(){}handleOpen(){}handleClose(){this.host.exitAll()}handleEscape(t){}handleTabClick(){this.host.exitAll()}handleToolbarModeChange(t){}handleDrawStroke(){}}class dt extends k{constructor(){super(...arguments),this.kind="idle",this.launcherLit=!1,this.acceptsFrustrationPrompt=!0}handleOpen(){this.host.dismissFrustrationPrompt(),this.host.dismissSuccess(),this.host.transitionTo(new E(this.host))}handleClose(){}handleTabClick(){this.handleOpen()}}class E extends k{constructor(){super(...arguments),this.kind="annotating"}enter(){if(!this.host.hasAnnotationChrome()){this.host.mountAnnotationChrome();return}this.host.destroyRecordingManager(),this.host.teardownDrawBar(),this.host.ensureSession()}handleEscape(t){ht(t),this.host.exitAll()}handleToolbarModeChange(t){t==="record"?this.host.transitionTo(new Mt(this.host)):this.host.transitionTo(new E(this.host))}handleDrawStroke(){this.host.transitionTo(new vn(this.host,T()?"sheet":"bar"))}}class Mt extends k{constructor(){super(...arguments),this.kind="recording"}enter(){this.host.clearCurrentAnnotation(),this.host.teardownDrawBar(),this.host.destroySession(),this.host.startRecorder()}handleEscape(t){ht(t),this.host.stopRecordingIntoNote()}handleToolbarModeChange(t){t!=="record"&&this.host.transitionTo(new E(this.host))}}class vn extends k{constructor(t,i){super(t),this.surface=i,this.kind="drawing"}enter(){this.surface==="sheet"?this.host.mountDrawSheet():(this.host.mountDrawBar(),this.host.refreshDrawBar())}handleEscape(t){ht(t),this.host.cancelDraw()}handleToolbarModeChange(t){t==="record"?this.host.transitionTo(new Mt(this.host)):this.host.transitionTo(new E(this.host))}handleDrawStroke(){this.surface==="bar"&&this.host.refreshDrawBar()}}class Re extends k{constructor(t,i){super(t),this.opts=i,this.kind="popup"}enter(){this.host.mountNotePopup(this.opts)}handleEscape(t){ht(t),this.host.exitAll()}handleToolbarModeChange(t){t==="record"?this.host.transitionTo(new Mt(this.host)):(this.host.dismissNotePopup(),this.host.transitionTo(new E(this.host)))}}class It extends k{constructor(){super(...arguments),this.kind="clarifying"}handleToolbarModeChange(t){this.host.revertToolbarDuringClarify()}}class ut extends k{constructor(){super(...arguments),this.kind="submitting",this.launcherLit=!1}enter(){this.host.releaseClarifyUi()}handleTabClick(){}}const xn=/^#[0-9a-f]{6}$/i;function kn(e){return e===void 0?void 0:typeof e!="object"||e===null||![e.primary,e.hover,e.active,e.onPrimary].every(i=>typeof i=="string"&&xn.test(i))?De():{primary:e.primary.toLowerCase(),hover:e.hover.toLowerCase(),active:e.active.toLowerCase(),onPrimary:e.onPrimary.toLowerCase()}}function De(){console.warn("[MakeThisBetter] brandColors requires primary, hover, active, and onPrimary as six-digit hex colors.")}function Me(){const{hostname:e}=window.location;return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e.endsWith(".localhost")||e.endsWith(".local")||e.endsWith(".test")}class En{constructor(t){this.tab=null,this.toolbar=null,this.session=null,this.drawBar=null,this.dim=null,this.pageOffset=new si,this.chatPopup=null,this.scrollLock=null,this.success=null,this.frustrationPrompt=null,this.frustrationDetector=null,this.state=new dt(this),this.via="pin",this.currentAnnotation=null,this.lastPopupPos=null,this.recordingManager=null,this.touchHintShown=!1,this.lastHandoff={},this.handleKeydown=i=>{i.key==="Escape"&&(ft(i)||this.state.handleEscape(i))},this.stopRecordingIntoNote=()=>{this.recordingManager&&(this.recordingManager.stop(),this.via="record",this.transitionTo(new Re(this,{x:window.innerWidth/2,y:window.innerHeight/2,targetName:this.messages.record.timer_label})))},this.config=t,t.projectKey||console.warn("[MakeThisBetter] projectKey is missing. Feedback submission will be rejected."),this.brandColors=kn(t.brandColors),this.messages=Te(t.locale??document.documentElement.lang??"en"),this.apiClient=new Gr({projectKey:t.projectKey,apiUrl:t.apiUrl,userToken:t.userToken,userTokenFn:t.userTokenFn}),this.consoleCollector=new Sr,this.consoleCollector.start(),this.breadcrumbCollector=new Pr,this.breadcrumbCollector.start(),this.lifecycle=new yn({apiClient:this.apiClient,consoleCollector:this.consoleCollector,breadcrumbCollector:this.breadcrumbCollector,brandColors:this.brandColors,shadow:()=>this.shadow,messages:()=>this.messages,user:()=>this.config.user},{isBackground:()=>this.state.kind==="submitting",onFinalizeFailure:i=>this.chatPopup?.showFinalizeFailure(i),onReenterBackground:()=>this.transitionTo(new ut(this)),onFinalized:(i,r)=>this.handleFinalized(i,r)});try{this.buildUI()}catch(i){this.consoleCollector.stop(),this.breadcrumbCollector.stop(),console.warn("[MakeThisBetter] Widget failed to start:",i);return}t.frustrationDetection!==!1&&(this.frustrationDetector=new Rt(()=>this.handleFrustration()),this.frustrationDetector.start()),document.addEventListener("keydown",this.handleKeydown,!0)}transitionTo(t){const i=this.state;this.state=t,i.exit(),t.enter(),this.tab?.setActive(t.launcherLit)}buildUI(){if(this.shadow=new wt(this.config.theme??"auto",this.brandColors),this.config.entryMode==="api"){Me()&&console.warn('[MakeThisBetter] entryMode: "api" renders no launcher. Call MakeThisBetter.open() from your own UI.');return}if(T()){Me()&&console.warn("[MakeThisBetter] No launcher is rendered on touch devices. Call MakeThisBetter.open() from your own mobile UI.");return}this.mountTab()}mountTab(){this.tab||!this.shadow||(this.tab=new ei(this.shadow,this.messages,this.config.position??"right",()=>this.state.handleTabClick(),this.config.tabText))}open(){this.shadow&&this.state.handleOpen()}close(){this.state.handleClose()}showLauncher(){T()||(this.mountTab(),this.tab?.setActive(this.state.launcherLit))}hideLauncher(){this.tab?.destroy(),this.tab=null}setLocale(t){this.config.locale=t,this.messages=Te(t),this.tab?.setMessages(this.messages)}handleFrustration(){!this.state.acceptsFrustrationPrompt||this.frustrationPrompt||Rr()||(this.frustrationPrompt=new ri(this.shadow,this.messages,{onTell:()=>{this.dismissFrustrationPrompt(),this.state.handleOpen()},onDismiss:()=>{Dr(),this.dismissFrustrationPrompt()},onAutoHide:()=>this.dismissFrustrationPrompt()}))}dismissSuccess(){this.success?.destroy(),this.success=null,this.chatPopup?.destroy(),this.chatPopup=null}dismissFrustrationPrompt(){this.frustrationPrompt?.destroy(),this.frustrationPrompt=null}hasAnnotationChrome(){return this.toolbar!==null}mountAnnotationChrome(){Ct();const t=T();this.toolbar=new di(this.shadow,this.messages,()=>this.exitAll(),i=>this.state.handleToolbarModeChange(i),this.config.position??"right",!t||!this.touchHintShown),t&&(this.touchHintShown=!0),this.ensureSession(),t&&this.toolbar&&this.pageOffset.reserve(this.toolbar.height())}ensureSession(){this.session||(this.session=new Ti(this.shadow,this.messages,{onPin:(t,i)=>{this.currentAnnotation=t,this.via="pin",this.transitionTo(new Re(this,{x:t.x,y:t.y,targetName:i,targetRect:t.targetRect}))},onDrawStroke:()=>this.state.handleDrawStroke()}))}destroySession(){this.session?.destroy(),this.session=null}clearCurrentAnnotation(){this.currentAnnotation=null}startRecorder(){this.recordingManager=new un,this.recordingManager.start(this.shadow,this.messages,this.stopRecordingIntoNote).catch(t=>{console.warn("[MakeThisBetter] Interaction replay unavailable, falling back to markup:",t),this.state.kind==="recording"&&(this.toolbar?.setMode("markup"),this.state.handleToolbarModeChange("markup"))})}destroyRecordingManager(){this.recordingManager?.destroy(),this.recordingManager=null}mountDrawBar(){this.engageScrollLock(),this.drawBar=new Ri(this.shadow,{messages:this.messages,onUndo:()=>this.handleDrawUndoRedo("undo"),onRedo:()=>this.handleDrawUndoRedo("redo"),onCancel:()=>this.cancelDraw(),onSubmit:t=>this.handleDrawSubmit(t),onActivity:()=>this.lifecycle.warmScreenshotDeps()}),this.lifecycle.setScreenshotEnabled(!0),this.lifecycle.warmScreenshotDeps()}mountDrawSheet(){this.engageScrollLock();let t=!1;this.chatPopup=new kt(this.shadow,{targetName:this.messages.annotation.drawing,x:window.innerWidth/2,y:window.innerHeight/2,messages:this.messages,position:this.config.position??"right",onSubmit:async i=>{const r=this.session?.getDrawAnnotation();if(!r)return this.cancelDraw(),null;t=!0,this.currentAnnotation=r,this.via="draw",this.session?.dismissInteraction(),this.teardownDrawBar();const n=this.recordingManager?.getRecording()??void 0,s=await this.lifecycle.start(i||this.messages.annotation.drawing,r,n);return s?.board_url&&U(s.board_url),s},onClarify:async(i,r,n,s)=>this.apiClient.streamClarification(i,r,n,s),onAnswer:(i,r,n)=>this.apiClient.answerClarification(i,r,n),onFinalize:()=>(this.transitionTo(new ut(this)),this.lifecycle.finalize()),onCancel:()=>t?this.exitAll():this.cancelDraw(),onConversationOpen:()=>this.transitionTo(new It(this)),onActivity:()=>this.lifecycle.warmScreenshotDeps(),resolveBoardLink:()=>this.buildViewFeedbackHandler()??this.buildMyFeedbackHandler(),resolveEmailCapture:()=>this.buildEmailCapture()}),this.lifecycle.setScreenshotEnabled(!0),this.lifecycle.warmScreenshotDeps()}handleDrawUndoRedo(t){t==="undo"?this.session?.undoDraw():this.session?.redoDraw(),this.refreshDrawBar()}refreshDrawBar(){this.session&&this.drawBar?.setUndoRedo(this.session.canUndoDraw(),this.session.canRedoDraw())}cancelDraw(){this.session?.clearDraw(),this.releaseScrollLock(),this.teardownDrawBar(),this.chatPopup?.destroy(),this.chatPopup=null,this.dim?.destroy(),this.dim=null,this.transitionTo(new E(this))}teardownDrawBar(){this.drawBar?.destroy(),this.drawBar=null}handleDrawSubmit(t){const i=this.session?.getDrawAnnotation();if(!i){this.cancelDraw();return}this.currentAnnotation=i,this.via="draw",this.session?.dismissInteraction();const r=t||this.messages.annotation.drawing,n=this.recordingManager?.getRecording()??void 0;this.teardownDrawBar(),this.releaseScrollLock(),this.dim?.destroy(),this.dim=null,this.mountChatAfterSubmit(r,i,n)}mountChatAfterSubmit(t,i,r){this.dim=new jt(this.shadow,()=>this.exitAll()),this.engageScrollLock(),this.chatPopup=new kt(this.shadow,{targetName:i?.targetName??this.messages.annotation.drawing,x:this.lastPopupPos?.x??window.innerWidth/2,y:this.lastPopupPos?.y??window.innerHeight/2,messages:this.messages,position:this.config.position??"right",onSubmit:async()=>{const n=await this.lifecycle.start(t,i,r);return n?.board_url&&U(n.board_url),n},onClarify:async(n,s,a,o)=>this.apiClient.streamClarification(n,s,a,o),onAnswer:(n,s,a)=>this.apiClient.answerClarification(n,s,a),onFinalize:()=>(this.transitionTo(new ut(this)),this.lifecycle.finalize()),onCancel:()=>this.exitAll(),onConversationOpen:()=>this.transitionTo(new It(this)),resolveBoardLink:()=>this.buildViewFeedbackHandler()??this.buildMyFeedbackHandler(),resolveEmailCapture:()=>this.buildEmailCapture()}),this.chatPopup.submit(t)}mountNotePopup({x:t,y:i,targetName:r,targetRect:n}){this.lastPopupPos={x:t,y:i},this.teardownDrawBar(),this.session?.dismissInteraction(),this.chatPopup?.destroy(),this.chatPopup=null,this.dim?.destroy(),this.dim=null,this.dim=new jt(this.shadow,()=>this.exitAll());const s=this.recordingManager?.getRecording();s&&this.lifecycle.setScreenshotEnabled(!0);const a=this.currentAnnotation,o=this.recordingManager?.getRecording()??void 0;this.chatPopup=new kt(this.shadow,{targetName:r,x:t,y:i,targetRect:n,messages:this.messages,position:this.config.position??"right",onSubmit:async l=>{this.currentAnnotation=a??this.currentAnnotation;const c=await this.lifecycle.start(l,this.currentAnnotation,o);return c?.board_url&&U(c.board_url),c},onClarify:async(l,c,h,u)=>this.apiClient.streamClarification(l,c,h,u),onAnswer:(l,c,h)=>this.apiClient.answerClarification(l,c,h),onFinalize:()=>(this.teardownSubmittingUi(),this.transitionTo(new ut(this)),this.lifecycle.finalize()),onCancel:()=>this.exitAll(),onConversationOpen:()=>this.transitionTo(new It(this)),onActivity:()=>this.lifecycle.warmScreenshotDeps(),resolveBoardLink:()=>this.buildViewFeedbackHandler()??this.buildMyFeedbackHandler(),resolveEmailCapture:()=>this.buildEmailCapture(),...s?{recordingSeconds:s.duration}:{onScreenshotToggle:l=>this.lifecycle.setScreenshotEnabled(l),screenshotEnabled:this.lifecycle.isScreenshotEnabled()}}),this.engageScrollLock(),this.lifecycle.warmScreenshotDeps()}dismissNotePopup(){this.chatPopup?.destroy(),this.chatPopup=null,this.dim?.destroy(),this.dim=null,this.releaseScrollLock(),this.clearCurrentAnnotation(),this.destroySession()}engageScrollLock(){this.scrollLock||(this.scrollLock=ci())}releaseScrollLock(){this.scrollLock?.release(),this.scrollLock=null}buildMyFeedbackHandler(){if(!this.config.user&&en())return async()=>{const t=await this.apiClient.createIdentityToken(Ee());!t?.identity_token||!t.board_url||(U(t.board_url),window.open(`${t.board_url}?identity=${encodeURIComponent(t.identity_token)}`,"_blank"))}}teardownSubmittingUi(){this.teardownDrawBar(),this.releaseScrollLock(),this.dim?.destroy(),this.dim=null,this.session?.hideHighlight(),this.session?.destroy(),this.session=null,this.recordingManager?.destroy(),this.recordingManager=null}revertToolbarDuringClarify(){this.toolbar?.setMode(this.via==="record"?"record":"markup")}releaseClarifyUi(){this.teardownToolbar(),this.currentAnnotation=null}handleFinalized(t,i){if(this.lastHandoff={feedbackId:t.id,boardUrl:t.board_url,identityToken:t.identity_token},t.board_url&&U(t.board_url),!(this.chatPopup&&this.chatPopup.sessionId()!==i.id)&&!(!this.chatPopup&&this.state.kind!=="submitting"&&this.state.kind!=="clarifying")){if(this.chatPopup){this.chatPopup.showFinalizeSuccess(),this.teardownSubmittingUi(),this.teardownToolbar(),this.lifecycle.resetScreenshotConsent(),this.transitionTo(new dt(this));return}this.teardownToolbar(),this.lifecycle.resetScreenshotConsent(),this.showSuccess({skipFollowup:i.ai_clarify_available===!1})}}showSuccess(t){this.transitionTo(new dt(this)),this.success=new ji(this.shadow,this.messages,()=>{this.success?.destroy(),this.success=null},{...t,onViewFeedback:this.buildViewFeedbackHandler()})}buildEmailCapture(){if(this.config.user)return;const{feedbackId:t,identityToken:i}=this.lastHandoff;if(!(!t||!i)&&!Se())return{onSubmit:async r=>{const n=await this.apiClient.updateReporter(t,r,i);return n&&tn(r),n}}}buildViewFeedbackHandler(){const{boardUrl:t,identityToken:i}=this.lastHandoff;if(t){if(i)return()=>{window.open(`${t}?identity=${encodeURIComponent(i)}`,"_blank")};if(this.config.userToken||this.config.userTokenFn)return async()=>{try{const r=await this.apiClient.resolveUserToken();r&&window.open(`${t}?identity=${encodeURIComponent(r)}`,"_blank")}catch{}}}}teardownToolbar(){this.pageOffset.release(),this.toolbar?.destroy(),this.toolbar=null}exitAll(){this.lifecycle.abandon(),this.via="pin",this.transitionTo(new dt(this)),this.teardownToolbar(),this.teardownDrawBar(),this.releaseScrollLock(),this.session?.hideHighlight(),this.session?.destroy(),this.session=null,this.dim?.destroy(),this.dim=null,this.chatPopup?.destroy(),this.chatPopup=null,this.currentAnnotation=null,this.recordingManager?.destroy(),this.recordingManager=null}destroy(){document.removeEventListener("keydown",this.handleKeydown,!0),this.exitAll(),this.consoleCollector.stop(),this.breadcrumbCollector.stop(),this.frustrationDetector?.stop(),this.dismissFrustrationPrompt(),this.success?.destroy(),this.tab?.destroy(),this.recordingManager?.destroy(),this.shadow?.destroy()}}let S=null,A=null,L=null;function Sn(){L&&(document.removeEventListener("DOMContentLoaded",L),L=null)}function W(e){Sn(),S?.destroy(),S=e?new En(e):null}const Ie={init(e){typeof document>"u"||(W(),A=e,document.readyState==="loading"?(L=()=>{L=null,W(e)},document.addEventListener("DOMContentLoaded",L,{once:!0})):W(e))},destroy(){W(),A=null},setLocale(e){A&&(A.locale=e),S?.setLocale(e)},open(){S?.open()},close(){S?.close()},showLauncher(){S?.showLauncher()},hideLauncher(){S?.hideLauncher()}};typeof window<"u"&&(window.MakeThisBetter=Ie,document.addEventListener("turbo:load",()=>{const e=document.getElementById(x);A&&(!e||!e.shadowRoot)&&(e?.remove(),W(A))}));function Cn(e,t){if(e.match(/^[a-z]+:\/\//i))return e;if(e.match(/^\/\//))return window.location.protocol+e;if(e.match(/^[a-z]+:/i))return e;const i=document.implementation.createHTMLDocument(),r=i.createElement("base"),n=i.createElement("a");return i.head.appendChild(r),i.body.appendChild(n),t&&(r.href=t),n.href=e,n.href}const Tn=(()=>{let e=0;const t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(e+=1,`u${t()}${e}`)})();function y(e){const t=[];for(let i=0,r=e.length;i<r;i++)t.push(e[i]);return t}let P=null;function Fe(e={}){return P||(e.includeStyleProperties?(P=e.includeStyleProperties,P):(P=y(window.getComputedStyle(document.documentElement)),P))}function mt(e,t){const r=(e.ownerDocument.defaultView||window).getComputedStyle(e).getPropertyValue(t);return r?parseFloat(r.replace("px","")):0}function _n(e){const t=mt(e,"border-left-width"),i=mt(e,"border-right-width");return e.clientWidth+t+i}function An(e){const t=mt(e,"border-top-width"),i=mt(e,"border-bottom-width");return e.clientHeight+t+i}function Ft(e,t={}){const i=t.width||_n(e),r=t.height||An(e);return{width:i,height:r}}function Ln(){let e,t;try{t=process}catch{}const i=t&&t.env?t.env.devicePixelRatio:null;return i&&(e=parseInt(i,10),Number.isNaN(e)&&(e=1)),e||window.devicePixelRatio||1}const f=16384;function Pn(e){(e.width>f||e.height>f)&&(e.width>f&&e.height>f?e.width>e.height?(e.height*=f/e.width,e.width=f):(e.width*=f/e.height,e.height=f):e.width>f?(e.height*=f/e.width,e.width=f):(e.width*=f/e.height,e.height=f))}function Rn(e,t={}){return e.toBlob?new Promise(i=>{e.toBlob(i,t.type?t.type:"image/png",t.quality?t.quality:1)}):new Promise(i=>{const r=window.atob(e.toDataURL(t.type?t.type:void 0,t.quality?t.quality:void 0).split(",")[1]),n=r.length,s=new Uint8Array(n);for(let a=0;a<n;a+=1)s[a]=r.charCodeAt(a);i(new Blob([s],{type:t.type?t.type:"image/png"}))})}function bt(e){return new Promise((t,i)=>{const r=new Image;r.onload=()=>{r.decode().then(()=>{requestAnimationFrame(()=>t(r))})},r.onerror=i,r.crossOrigin="anonymous",r.decoding="async",r.src=e})}async function Dn(e){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(e)).then(encodeURIComponent).then(t=>`data:image/svg+xml;charset=utf-8,${t}`)}async function Mn(e,t,i){const r="http://www.w3.org/2000/svg",n=document.createElementNS(r,"svg"),s=document.createElementNS(r,"foreignObject");return n.setAttribute("width",`${t}`),n.setAttribute("height",`${i}`),n.setAttribute("viewBox",`0 0 ${t} ${i}`),s.setAttribute("width","100%"),s.setAttribute("height","100%"),s.setAttribute("x","0"),s.setAttribute("y","0"),s.setAttribute("externalResourcesRequired","true"),n.appendChild(s),s.appendChild(e),Dn(n)}const p=(e,t)=>{if(e instanceof t)return!0;const i=Object.getPrototypeOf(e);return i===null?!1:i.constructor.name===t.name||p(i,t)};function In(e){const t=e.getPropertyValue("content");return`${e.cssText} content: '${t.replace(/'|"/g,"")}';`}function Fn(e,t){return Fe(t).map(i=>{const r=e.getPropertyValue(i),n=e.getPropertyPriority(i);return`${i}: ${r}${n?" !important":""};`}).join(" ")}function Hn(e,t,i,r){const n=`.${e}:${t}`,s=i.cssText?In(i):Fn(i,r);return document.createTextNode(`${n}{${s}}`)}function He(e,t,i,r){const n=window.getComputedStyle(e,i),s=n.getPropertyValue("content");if(s===""||s==="none")return;const a=Tn();try{t.className=`${t.className} ${a}`}catch{return}const o=document.createElement("style");o.appendChild(Hn(a,i,n,r)),t.appendChild(o)}function Bn(e,t,i){He(e,t,":before",i),He(e,t,":after",i)}const Be="application/font-woff",Ne="image/jpeg",Nn={woff:Be,woff2:Be,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:Ne,jpeg:Ne,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function On(e){const t=/\.([^./]*?)$/g.exec(e);return t?t[1]:""}function Ht(e){const t=On(e).toLowerCase();return Nn[t]||""}function zn(e){return e.split(/,/)[1]}function Bt(e){return e.search(/^(data:)/)!==-1}function $n(e,t){return`data:${t};base64,${e}`}async function Oe(e,t,i){const r=await fetch(e,t);if(!r.ok)throw new Error(`Resource "${r.url}" returned HTTP ${r.status}`);const n=await r.blob();return new Promise((s,a)=>{const o=new FileReader;o.onerror=a,o.onloadend=()=>{try{s(i({res:r,result:o.result}))}catch(l){a(l)}},o.readAsDataURL(n)})}const Nt={};function Un(e,t,i){let r=e.replace(/\?.*/,"");return i&&(r=e),/ttf|otf|eot|woff2?/i.test(r)&&(r=r.replace(/.*\//,"")),t?`[${t}]${r}`:r}async function Ot(e,t,i){const r=Un(e,t,i.includeQueryParams);if(Nt[r]!=null)return Nt[r];i.cacheBust&&(e+=(/\?/.test(e)?"&":"?")+new Date().getTime());let n;try{const s=o=>Oe(o,i.fetchRequestInit,({res:l,result:c})=>(t||(t=l.headers.get("Content-Type")||""),zn(c)));let a;try{a=await s(e)}catch(o){const l=await i.resourceUrlResolver?.(e,t);if(!l||l===e)throw o;a=await s(l)}n=$n(a,t)}catch(s){n=i.imagePlaceholder||"";let a=`Failed to fetch resource: ${e}`;s&&(a=typeof s=="string"?s:s.message),a&&console.warn(a)}return Nt[r]=n,n}async function jn(e){const t=e.toDataURL();return t==="data:,"?e.cloneNode(!1):bt(t)}async function qn(e,t){if(e.currentSrc){const s=document.createElement("canvas"),a=s.getContext("2d");s.width=e.clientWidth,s.height=e.clientHeight,a?.drawImage(e,0,0,s.width,s.height);const o=s.toDataURL();return bt(o)}const i=e.poster,r=Ht(i),n=await Ot(i,r,t);return bt(n)}async function Wn(e,t){var i;try{if(!((i=e?.contentDocument)===null||i===void 0)&&i.body)return await pt(e.contentDocument.body,t,!0)}catch{}return e.cloneNode(!1)}async function Vn(e,t){return p(e,HTMLCanvasElement)?jn(e):p(e,HTMLVideoElement)?qn(e,t):p(e,HTMLIFrameElement)?Wn(e,t):e.cloneNode(ze(e))}const Yn=e=>e.tagName!=null&&e.tagName.toUpperCase()==="SLOT",ze=e=>e.tagName!=null&&e.tagName.toUpperCase()==="SVG";async function Xn(e,t,i){var r,n;if(ze(t))return t;let s=[];return Yn(e)&&e.assignedNodes?s=y(e.assignedNodes()):p(e,HTMLIFrameElement)&&(!((r=e.contentDocument)===null||r===void 0)&&r.body)?s=y(e.contentDocument.body.childNodes):s=y(((n=e.shadowRoot)!==null&&n!==void 0?n:e).childNodes),s.length===0||p(e,HTMLVideoElement)||await s.reduce((a,o)=>a.then(()=>pt(o,i)).then(l=>{l&&t.appendChild(l)}),Promise.resolve()),t}function Kn(e,t,i){const r=t.style;if(!r)return;const n=window.getComputedStyle(e);n.cssText?(r.cssText=n.cssText,r.transformOrigin=n.transformOrigin):Fe(i).forEach(s=>{let a=n.getPropertyValue(s);s==="font-size"&&a.endsWith("px")&&(a=`${Math.floor(parseFloat(a.substring(0,a.length-2)))-.1}px`),p(e,HTMLIFrameElement)&&s==="display"&&a==="inline"&&(a="block"),s==="d"&&t.getAttribute("d")&&(a=`path(${t.getAttribute("d")})`),r.setProperty(s,a,n.getPropertyPriority(s))})}function Gn(e,t){p(e,HTMLTextAreaElement)&&(t.innerHTML=e.value),p(e,HTMLInputElement)&&t.setAttribute("value",e.value)}function Jn(e,t){if(p(e,HTMLSelectElement)){const i=t,r=Array.from(i.children).find(n=>e.value===n.getAttribute("value"));r&&r.setAttribute("selected","")}}function Zn(e,t,i){return p(t,Element)&&(Kn(e,t,i),Bn(e,t,i),Gn(e,t),Jn(e,t)),t}async function Qn(e,t){const i=e.querySelectorAll?e.querySelectorAll("use"):[];if(i.length===0)return e;const r={};for(let s=0;s<i.length;s++){const o=i[s].getAttribute("xlink:href");if(o){const l=e.querySelector(o),c=document.querySelector(o);!l&&c&&!r[o]&&(r[o]=await pt(c,t,!0))}}const n=Object.values(r);if(n.length){const s="http://www.w3.org/1999/xhtml",a=document.createElementNS(s,"svg");a.setAttribute("xmlns",s),a.style.position="absolute",a.style.width="0",a.style.height="0",a.style.overflow="hidden",a.style.display="none";const o=document.createElementNS(s,"defs");a.appendChild(o);for(let l=0;l<n.length;l++)o.appendChild(n[l]);e.appendChild(a)}return e}async function pt(e,t,i){return!i&&t.filter&&!t.filter(e)?null:Promise.resolve(e).then(r=>Vn(r,t)).then(r=>Xn(e,r,t)).then(r=>Zn(e,r,t)).then(r=>Qn(r,t))}const $e=/url\((['"]?)([^'"]+?)\1\)/g,ts=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,es=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function is(e){const t=e.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function rs(e){const t=[];return e.replace($e,(i,r,n)=>(t.push(n),i)),t.filter(i=>!Bt(i))}async function ns(e,t,i,r,n){try{const s=i?Cn(t,i):t,a=Ht(t);let o;return n||(o=await Ot(s,a,r)),e.replace(is(t),`$1${o}$3`)}catch{}return e}function ss(e,{preferredFontFormat:t}){return t?e.replace(es,i=>{for(;;){const[r,,n]=ts.exec(i)||[];if(!n)return"";if(n===t)return`src: ${r};`}}):e}function Ue(e){return e.search($e)!==-1}async function je(e,t,i){if(!Ue(e))return e;const r=ss(e,i);return rs(r).reduce((s,a)=>s.then(o=>ns(o,a,t,i)),Promise.resolve(r))}async function R(e,t,i){var r;const n=(r=t.style)===null||r===void 0?void 0:r.getPropertyValue(e);if(n){const s=await je(n,null,i);return t.style.setProperty(e,s,t.style.getPropertyPriority(e)),!0}return!1}async function as(e,t){await R("background",e,t)||await R("background-image",e,t),await R("mask",e,t)||await R("-webkit-mask",e,t)||await R("mask-image",e,t)||await R("-webkit-mask-image",e,t)}async function os(e,t){const i=p(e,HTMLImageElement);if(!(i&&!Bt(e.src))&&!(p(e,SVGImageElement)&&!Bt(e.href.baseVal)))return;const r=i?e.src:e.href.baseVal,n=await Ot(r,Ht(r),t);await new Promise((s,a)=>{e.onload=s,e.onerror=t.onImageErrorHandler?(...l)=>{try{s(t.onImageErrorHandler(...l))}catch(c){a(c)}}:a;const o=e;o.decode&&(o.decode=s),o.loading==="lazy"&&(o.loading="eager"),i?(e.srcset="",e.src=n):e.href.baseVal=n})}async function ls(e,t){const r=y(e.childNodes).map(n=>qe(n,t));await Promise.all(r).then(()=>e)}async function qe(e,t){p(e,Element)&&(await as(e,t),await os(e,t),await ls(e,t))}function cs(e,t){const{style:i}=e;t.backgroundColor&&(i.backgroundColor=t.backgroundColor),t.width&&(i.width=`${t.width}px`),t.height&&(i.height=`${t.height}px`);const r=t.style;return r!=null&&Object.keys(r).forEach(n=>{i[n]=r[n]}),e}const We={};async function Ve(e){let t=We[e];if(t!=null)return t;const r=await(await fetch(e)).text();return t={url:e,cssText:r},We[e]=t,t}async function Ye(e,t){let i=e.cssText;const r=/url\(["']?([^"')]+)["']?\)/g,s=(i.match(/url\([^)]+\)/g)||[]).map(async a=>{let o=a.replace(r,"$1");return o.startsWith("https://")||(o=new URL(o,e.url).href),Oe(o,t.fetchRequestInit,({result:l})=>(i=i.replace(a,`url(${l})`),[a,l]))});return Promise.all(s).then(()=>i)}function Xe(e){if(e==null)return[];const t=[],i=/(\/\*[\s\S]*?\*\/)/gi;let r=e.replace(i,"");const n=new RegExp("((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})","gi");for(;;){const l=n.exec(r);if(l===null)break;t.push(l[0])}r=r.replace(n,"");const s=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,a="((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})",o=new RegExp(a,"gi");for(;;){let l=s.exec(r);if(l===null){if(l=o.exec(r),l===null)break;s.lastIndex=o.lastIndex}else o.lastIndex=s.lastIndex;t.push(l[0])}return t}async function hs(e,t){const i=[],r=[];return e.forEach(n=>{if("cssRules"in n)try{y(n.cssRules||[]).forEach((s,a)=>{if(s.type===CSSRule.IMPORT_RULE){let o=a+1;const l=s.href,c=Ve(l).then(h=>Ye(h,t)).then(h=>Xe(h).forEach(u=>{try{n.insertRule(u,u.startsWith("@import")?o+=1:n.cssRules.length)}catch(m){console.error("Error inserting rule from remote css",{rule:u,error:m})}})).catch(h=>{console.error("Error loading remote css",h.toString())});r.push(c)}})}catch(s){const a=e.find(o=>o.href==null)||document.styleSheets[0];n.href!=null&&r.push(Ve(n.href).then(o=>Ye(o,t)).then(o=>Xe(o).forEach(l=>{a.insertRule(l,a.cssRules.length)})).catch(o=>{console.error("Error loading remote stylesheet",o)})),console.error("Error inlining remote css file",s)}}),Promise.all(r).then(()=>(e.forEach(n=>{if("cssRules"in n)try{y(n.cssRules||[]).forEach(s=>{i.push(s)})}catch(s){console.error(`Error while reading CSS rules from ${n.href}`,s)}}),i))}function ds(e){return e.filter(t=>t.type===CSSRule.FONT_FACE_RULE).filter(t=>Ue(t.style.getPropertyValue("src")))}async function us(e,t){if(e.ownerDocument==null)throw new Error("Provided element is not within a Document");const i=y(e.ownerDocument.styleSheets),r=await hs(i,t);return ds(r)}function Ke(e){return e.trim().replace(/["']/g,"")}function ms(e){const t=new Set;function i(r){(r.style.fontFamily||getComputedStyle(r).fontFamily).split(",").forEach(s=>{t.add(Ke(s))}),Array.from(r.children).forEach(s=>{s instanceof HTMLElement&&i(s)})}return i(e),t}async function Ge(e,t){const i=await us(e,t),r=ms(e);return(await Promise.all(i.filter(s=>r.has(Ke(s.style.fontFamily))).map(s=>{const a=s.parentStyleSheet?s.parentStyleSheet.href:null;return je(s.cssText,a,t)}))).join(`
74
+ `)}async function bs(e,t){const i=t.fontEmbedCSS!=null?t.fontEmbedCSS:t.skipFonts?null:await Ge(e,t);if(i){const r=document.createElement("style"),n=document.createTextNode(i);r.appendChild(n),e.firstChild?e.insertBefore(r,e.firstChild):e.appendChild(r)}}async function Je(e,t={}){const{width:i,height:r}=Ft(e,t),n=await pt(e,t,!0);return await bs(n,t),await qe(n,t),cs(n,t),await Mn(n,i,r)}async function V(e,t={}){const{width:i,height:r}=Ft(e,t),n=await Je(e,t),s=await bt(n),a=document.createElement("canvas"),o=a.getContext("2d"),l=t.pixelRatio||Ln(),c=t.canvasWidth||i,h=t.canvasHeight||r;return a.width=c*l,a.height=h*l,t.skipAutoScale||Pn(a),a.style.width=`${c}`,a.style.height=`${h}`,t.backgroundColor&&(o.fillStyle=t.backgroundColor,o.fillRect(0,0,a.width,a.height)),o.drawImage(s,0,0,a.width,a.height),a}async function ps(e,t={}){const{width:i,height:r}=Ft(e,t);return(await V(e,t)).getContext("2d").getImageData(0,0,i,r).data}async function fs(e,t={}){return(await V(e,t)).toDataURL()}async function gs(e,t={}){return(await V(e,t)).toDataURL("image/jpeg",t.quality||1)}async function ws(e,t={}){const i=await V(e,t);return await Rn(i)}async function ys(e,t={}){return Ge(e,t)}const vs=Object.freeze(Object.defineProperty({__proto__:null,getFontEmbedCSS:ys,toBlob:ws,toCanvas:V,toJpeg:gs,toPixelData:ps,toPng:fs,toSvg:Je},Symbol.toStringTag,{value:"Module"}));return Ie}();
86
75
  //# sourceMappingURL=makethisbetter.js.map