PageSourceSearch

https://app.mystories.com/assets/index-DsauasB0.js

js mystories.com collected 2026-09-26 04:54:38 UTC 86,907 bytes, 8 lines download raw bytes

1
2!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="3cdea213-4161-5b4e-bf1f-1562ba2eb3c1")}catch(e){}}();
3import{d5 as $e,c5 as e,cP as vt,ci as Zt,d7 as Ce,p as ze,cl as a,K as Jt,d2 as gs,S as Rt,a$ as Nt,am as Re,be as H,M as xs,o as We,aj as Ve,a8 as at,af as ys,c$ as ct,d3 as ws,C as vs,L as _s,H as Qt,bF as js,w as bs,bs as Ue,d1 as Ss,d0 as kt,b8 as Es,b1 as Rs,s as Ns,A as ks,N as Cs,r as Ts,F as As,O as Ls,W as Ct,J as Is,G as Ps,ck as Tt,l as Ms,b3 as Ds,d8 as Os,E as Us,m as Fs,da as Bs,db as $s,bc as Ws,ag as Hs,bB as zs,cT as qs,cZ as Vs,u as Ys,b as Ks}from"./vendor-CQ6qs0ww.js";import{i as ft,b as gt,u as Gs,g as tt}from"./usePreviewPdf-DI7jvclB.js";import{U as Xs,C as oe,ak as Zs,ar as es,j as ts,ad as ss,a7 as Ge,ah as Ie,Z as xt,al as re,O as Js,W as Qs,ap as er,aj as tr,am as sr,an as rr,$ as or,a8 as At,a4 as Lt}from"./index-B-ChgSZ8.js";import{u as nr}from"./useToastMessage-Bxp_LkN-.js";import{B as _t}from"./index-CB4tAT7r.js";import{a as De}from"./constants-BTwGl91r.js";import{M as Be,B as Le,r as Oe,n as Fe,q as ar,t as dt,o as ir,m as lr,h as rs,y as st,e as cr,P as dr,A as ur}from"./vendor-antd-CWsARabp.js";import"./vendor-sentry-Bq4DuZkL.js";function ht(t){return{type:Xs,payload:{book:t}}}const hr=({visible:t,onDiscard:r,onSave:s,onCancel:n})=>{const{t:o}=$e("common",{keyPrefix:"modals.unsavedStoryChanges"});
3return e.jsx(Be,{title:o("title"),width:650,open:t,centered:!0,onCancel:n,className:"unsaved-changes-modal",footer:[e.jsx(Le,{onClick:r,children:o("closeWithoutSavingBtn")},"discard"),e.jsxs("div",{className:"unsaved-changes-modal-buttons",children:[e.jsx(Le,{type:"primary",onClick:()=>s(!0),children:o("saveDraftBtn")},"save-draft"),e.jsx(Le,{type:"primary",onClick:()=>s(!1),children:o("markAsCompleteBtn")},"save-complete")]},"actions")],children:e.jsx("p",{children:o("message")})})},pr=({visible:t,onSave:r,onCancel:s})=>{const{t:n}=$e("common",{keyPrefix:"modals.unsavedStoryChanges"});return e.jsx(Be,{title:n("titleSave"),open:t,width:650,centered:!0,onCancel:s,className:"save-warning-modal",footer:[e.jsx(Le,{type:"primary",onClick:()=>r(!0),children:n("saveDraftBtn")},"save-draft"),e.jsx(Le,{type:"primary",onClick:()=>r(!1),children:n("markAsCompleteBtn")},"save")],children:e.jsx("p",{children:n("message")})})},mr=({visible:t})=>{const{t:r}=$e(),s=vt(),n=()=>{Zs(),s(es(null)),s(Zt(ts.LOGIN))};return e.jsx(Be,{className:"token-expired-modal",open:t,closable:!1,centered:!0,maskClosable:!1,footer:[e.jsx(oe,{type:"primary",onClick:n,children:r("common:cta.login")},"login")],children:e.jsx("div",{children:e.jsx("p",{children:r("common:errors.sessionExpired")})})})},fr=({loading:t,visible:r,lastSavedAt:s,onRestore:n,onCancel:o})=>{const{t:l}=$e();return e.jsx(Be,{title:l("common:modals.restoreChanges.title"),open:r,width:650,centered:!0,onCancel:o,className:"save-warning-modal",footer:[e.jsx(Le,{type:"primary",onClick:()=>o(),children:l("common:cta.cancel")},"cancel"),e.jsx(Le,{type:"primary",disabled:t,onClick:()=>n(),children:l("common:cta.restore")},"save")],children:e.jsx("p",{children:l("common:modals.restoreChanges.description",{lastSavedAt:s?s.toLocaleDateString(void 0,{month:"long",day:"numeric",year:"numeric"}):null})})})},gr=["Enter a title","Ange en titel","Insira um título","Legg inn en tittel","Voer een titel in","Inserire un titolo","הזן כותרת","Donnez un titre","Kirjoita otsikko","Escriba un título","Geben Sie einen Titel ein","Indtast en titel"],xr=t=>gr.includes(t),Qe=(t=[])=>{let r=0;return t.some(s=>{var n;return s.kind==="paragraph"?(r++,Array.isArray(s.children)&&s.children.some(o=>o.text&&o.text!=="")):s.kind==="image"?!!s.url||!!s.src||!!((n=s.image)!=null&&n.url):s.kind==="imageRow"?(s.images||[]).some(o=>!!(o!=null&&o.url)):!1})||r>1},yr=({questionTitle:t,selectedQuestion:r,answerList:s})=>!(!r||r.titleKey||ft(r)||gt(r)||t!==r.title||!xr(r.title)||Qe(s)||Qe(r.answer)),It=(t,r,s)=>{var o,l,m,g,p,E,_,A;if(!s)return!1;if(s!==t.title)return!0;const n=t.answer;if(n.length!==r.length)return!0;for(let C=0;C<n.length;C++){const D=n[C],M=r[C];
3if(D.kind!==M.kind)return!0;if(D.kind==="paragraph"){const R=D.children||[],B=M.children||[];if(!wr(R,B))return!0}if(D.kind==="image"){const R=((o=D.image)==null?void 0:o.url)||"",B=((l=M.image)==null?void 0:l.url)||"",ce=((m=D.image)==null?void 0:m.caption)||"",X=((g=M.image)==null?void 0:g.caption)||"",I=((p=D.image)==null?void 0:p.width)||"",de=((E=M.image)==null?void 0:E.width)||"",O=Number((_=D.image)==null?void 0:_.rotation)||0,ne=Number((A=M.image)==null?void 0:A.rotation)||0;if(R!==B||ce!==X||I!==de||O!==ne)return!0}if(D.kind==="imageRow"){const R=D.images||[],B=M.images||[],ce=D.caption||"",X=M.caption||"";if(ce!==X||R.length!==B.length)return!0;for(let I=0;I<R.length;I++){const de=R[I]||{},O=B[I]||{};if((de.url||"")!==(O.url||"")||(de.width||"")!==(O.width||"")||(Number(de.rotation)||0)!==(Number(O.rotation)||0))return!0}}}return!1},wr=(t,r)=>{if(t.length!==r.length)return!1;for(let s=0;s<t.length;s++){const n=t[s],o=r[s],l=Object.keys(n).sort(),m=Object.keys(o).sort();if(l.length!==m.length||!l.every((g,p)=>g===m[p]))return!1;for(const g of l)if(n[g]!==o[g])return!1}return!0},yt=(t=[])=>(t||[]).reduce((r,s)=>{var n;return(s==null?void 0:s.kind)==="image"||(s==null?void 0:s.type)==="image"?r+1:(s==null?void 0:s.kind)==="imageRow"||(s==null?void 0:s.type)==="imageRow"?r+(((n=s.images)==null?void 0:n.length)||0):r},0),Pt=20,qe=t=>{if(t<=0)return[];const r=`${Math.floor(100/t)}%`;return Array.from({length:t},()=>r)},rt=(t=[])=>{const r=t.map(({width:n,height:o,aspectRatio:l})=>Number.isFinite(l)&&l>0?l:Number.isFinite(n)&&Number.isFinite(o)&&o>0?n/o:1),s=r.reduce((n,o)=>n+o,0);return s<=0?qe(t.length):r.map(n=>`${(n/s*100).toFixed(2)}%`)},jt=t=>((Number(t)||0)%360+360)%360,Mt=t=>(jt(t)+90)%360,ot=({width:t,height:r},s=0)=>{const n=jt(s);return n===90||n===270?{width:r,height:t}:{width:t,height:r}},Je=t=>new Promise((r,s)=>{if(!t){s(new Error("Missing image url"));return}const n=new Image,o=()=>{if(n.naturalWidth>0&&n.naturalHeight>0){r({width:n.naturalWidth,height:n.naturalHeight});return}s(new Error(`Invalid image size: ${t}`))};n.onload=()=>{typeof n.decode=="function"?n.decode().then(o).catch(o):o()},n.onerror=()=>s(new Error(`Failed to load image: ${t}`)),n.src=t}),wt=20,Dt=3,os=t=>{ze.isElement(t)&&(t.id||(t.id=Ce()),t.children.forEach(os))},vr=t=>{const{apply:r}=t;return t.apply=s=>s.type==="insert_node"?(os(s.node),r(s)):(s.type==="split_node"&&(s.properties.id=Ce()),r(s)),t},ns=a.createContext(null),_r=()=>a.useContext(ns);function jr(){return e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"18",height:"18",viewBox:"8 8 36 36",fill:"none","aria-hidden":!0,children:[e.jsx("rect",{x:"11",y:"13",width:"18",height:"15",rx:"2.5",stroke:"currentColor",strokeWidth:"2.6"}),e.jsx("rect",{x:"16",y:"18",width:"18",height:"15",rx:"2.5",fill:"#E8E8E8",stroke:"currentColor",strokeWidth:"2.6"}
3),e.jsx("circle",{cx:"22",cy:"23",r:"1.8",fill:"currentColor"}),e.jsx("path",{d:"M18 31L23 26L26.5 29.5L30 26L34 30.5V31C34 32.1 33.1 33 32 33H20C18.9 33 18 32.1 18 31Z",fill:"currentColor"}),e.jsx("circle",{cx:"35.5",cy:"35.5",r:"7",fill:"#E8E8E8"}),e.jsx("path",{d:"M35.5 31.5V39.5M31.5 35.5H39.5",stroke:"currentColor",strokeWidth:"2.8",strokeLinecap:"round"})]})}function br(){return e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"18",height:"18",viewBox:"6 6 36 36",fill:"none","aria-hidden":!0,children:[e.jsx("rect",{x:"7.5",y:"17",width:"11",height:"14",rx:"1.5",stroke:"currentColor",strokeWidth:"1.8"}),e.jsx("rect",{x:"29.5",y:"17",width:"11",height:"14",rx:"1.5",stroke:"currentColor",strokeWidth:"1.8"}),e.jsx("path",{d:"M24 11V37",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round"}),e.jsx("path",{d:"M20.5 14.5L24 11L27.5 14.5",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("path",{d:"M20.5 33.5L24 37L27.5 33.5",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})]})}function Sr(){return e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"18",height:"18",viewBox:"0 0 24 24",fill:"none","aria-hidden":!0,children:[e.jsx("path",{d:"M19.78 10.22A8 8 0 1 1 12 4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",fill:"none"}),e.jsx("path",{d:"M12 1.25L16.25 4L12 6.75",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})]})}const Ot=({isVisible:t,onRotate:r,onDelete:s,t:n})=>e.jsxs("div",{className:`image-slot-actions${t?"":" hidden"}`,children:[e.jsx(Oe,{title:n("common:tooltips.storyEditor.rotatePhoto"),mouseEnterDelay:.2,children:e.jsx("span",{className:"image-chip-tooltip-wrap",children:e.jsx("button",{type:"button",className:"image-rotate-btn","aria-label":n("common:tooltips.storyEditor.rotatePhoto"),onMouseDown:o=>{o.preventDefault(),r()},children:e.jsx(Sr,{})})})}),e.jsx(Oe,{title:n("common:tooltips.storyEditor.deletePhoto"),mouseEnterDelay:.2,children:e.jsx("span",{className:"image-chip-tooltip-wrap",children:e.jsx("button",{type:"button",className:"image-remove-btn","aria-label":n("common:tooltips.storyEditor.deletePhoto"),onMouseDown:o=>{o.preventDefault(),s()},children:e.jsx(Jt.FaRegTrashAlt,{})})})})]}),Er=({isFocused:t})=>e.jsxs(e.Fragment,{children:[e.jsx("div",{className:`image-top-left-dot ${t?"":"hidden"}`}),e.jsx("div",{className:`image-top-right-dot ${t?"":"hidden"}`}),e.jsx("div",{className:`image-bottom-left-dot ${t?"":"hidden"}`}),e.jsx("div",{className:`image-bottom-right-dot ${t?"":"hidden"}`})]}),Ut=({url:t,alt:r,rotation:s=0,isFocused:n,showDots:o,maxHeight:l,publicId:m,fileName:g,variant:p="standalone",children:E=null})=>{const _=jt(s),A=_===90||_===270,[C,D]=a.useState(null);a.useEffect(()=>{let ce=!1;return D(null),Je(t).then(X=>{ce||D(X)}).catch(()=>{}),()=>{ce=!0}},[t]);const M=C!=null?A?`${C.height} / ${C.width}`:`${C.width} / ${C.height}`:void 0,R=C==null?{width:"100%",height:"auto",display:"block",maxHeight:l,objectFit:"contain"}:_===0?{width:"100%",height:"auto",display:"block",maxHeight:l,objectFit:"contain"}:A?{position:"absolute",left:"50%",top:"50%",width:`${C.width/C.height*100}%`,height:`${C.height/C.width*100}%`,maxWidth:"none",maxHeight:"none",objectFit:"fill",transform:`translate(-50%, -50%) rotate(${_}deg)`}:{position:"absolute",left:"50%",top:"50%",width:"100%",height:"100%",objectFit:"contain",transform:`translate(-50%, -50%) rotate(${_}deg)`},B=["image-rotation-frame",p==="row"?"image-rotation-frame--row":"image-rotation-frame--standalone",n?"image-rotation-frame--focused":"",_?`image-rotation-frame--rot-${_}`:""].filter(Boolean).join(" ");return e.jsxs("div",{className:B,style:{width:"100%",maxHeight:l,aspectRatio:M,position:"relative"},children:[E,e.jsx("img",{className:"image",src:t,alt:r,"data-public-id":m,"data-file-name":g,style:R,draggable:!1}),o&&(_===0||C!=null)&&e.jsx(Er,{isFocused:n})]})},Ft=85,Ke=1200,Ye=20,pt=(t,r)=>({url:t.url,public_id:t.public_id,fileName:t.fileName,width:r,...t.rotation?{rotation:t.rotation}:{}}),Ze=(t,r)=>{const s=parseFloat(String(t||"").replace("%",""));return Number.isFinite(s)?s:r},Bt=({caption:t,onCaptionChange:r,isMobileLayout:s,t:n})=>{const[o,l]=a.useState(t||""),m=a.useRef(!1);return a.useEffect(()=>{m.current||l(t||"")},[t]),e.jsxs("div",{className:"image-caption",children:[e.jsx(ar,{className:"image-caption-input",styles:{textarea:{textAlign:"center"}},value:o,autoSize:{minRows:s?1:2,maxRows:5},onChange:g=>{const p=g.target.value;m.current=!0,l(p),r(p),requestAnimationFrame(()=>{m.current=!1})},onBlur:()=>{m.current=!1}
3,placeholder:n("common:inputs.imageCaption.placeholder"),maxLength:Ft}),e.jsx("div",{className:"image-caption-counter",children:`${o.length}/${Ft}`})]})},$t=({isFocused:t,disabled:r,onImageUpload:s,onUploadStart:n,onUploadError:o,imageActions:l})=>{const{t:m}=$e();if(!l||r||l.currentImages>=l.maxImages)return null;const p=m("common:tooltips.storyEditor.addPhotoToRow");return e.jsx(_t,{bare:!0,className:"image-add-beside-upload",maxImages:l.maxImages,currentImages:l.currentImages,bookId:l.bookId,teamId:l.teamId,onImageUpload:s,onUploadStart:n,onUploadError:o,questionTitle:l.questionTitle,children:({uploading:E})=>e.jsx(Oe,{title:E?"Uploading…":p,mouseEnterDelay:.2,children:e.jsx("span",{className:"image-chip-tooltip-wrap",children:e.jsx("button",{type:"button",className:`image-add-beside-btn${!t&&!E?" hidden":""}`,"aria-label":E?"Uploading photo":p,"aria-busy":E,disabled:E,onMouseDown:_=>_.preventDefault(),children:E?e.jsx(xs.FaSpinner,{className:"image-upload-spinner"}):e.jsx(jr,{})})})})})},Wt=({previewUrl:t,widthPercent:r,widthPx:s})=>e.jsx("div",{className:"image-row-slot image-row-slot--pending",style:{width:s??`${r}%`},"aria-busy":"true","aria-label":"Uploading photo",children:e.jsxs("div",{className:"image-row-slot-media image-row-slot-media--pending",children:[e.jsx("img",{className:"image",src:t,alt:"",draggable:!1,style:{width:"100%",height:"auto",display:"block",maxHeight:Ke,objectFit:"contain"}}),e.jsx("div",{className:"image-pending-overlay",children:e.jsx(Fe,{size:"large"})})]})}),Ht=({attributes:t,children:r,element:s,isRtl:n})=>{var z,ke;const{t:o,i18n:l}=$e(),m=n??((z=ss[l.language])==null?void 0:z.rtl)??!1,g=Ge(),p=gs(),E=_r(),_=a.useRef(null),[A,C]=a.useState(!1),[D,M]=a.useState(null),[R,B]=a.useState(!1),[ce,X]=a.useState(!1),[I,de]=a.useState(0),[O,ne]=a.useState(null),[ue,xe]=a.useState(null),we=a.useRef(null),f=()=>{we.current&&(URL.revokeObjectURL(we.current),we.current=null),ne(null),xe(null)},Q=w=>{f();const b=URL.createObjectURL(w);we.current=b,ne(b);const S=s.type==="imageRow"?(s.images||[]).map(x=>x.url):[s.url],j=qe(S.length+1);xe(j),Promise.all([...S,b].map(x=>Je(x))).then(x=>{if(we.current!==b)return;const y=s.type==="imageRow"?(s.images||[]).map(U=>U.rotation||0):[s.rotation||0],L=x.map((U,T)=>ot(U,T<y.length?y[T]:0));xe(rt(L))}).catch(x=>{console.warn("Failed to size pending upload preview for equal heights",x)})};a.useEffect(()=>()=>{we.current&&URL.revokeObjectURL(we.current)},[]),a.useEffect(()=>{const w=_.current;if(!w||typeof ResizeObserver>"u")return;const b=()=>{var L;const x=(s.type==="imageRow"&&((L=s.images)==null?void 0:L.length)||1)+(O?1:0),y=Pt*Math.max(x-1,0);de(Math.max(w.offsetWidth-y,0))};b();const S=new ResizeObserver(b);return S.observe(w),()=>S.disconnect()},[(ke=s.images)==null?void 0:ke.length,s.type,O]);const _e=()=>{const w=Re.findPath(p,s);H.removeNodes(p,{at:w})},Y=async w=>{try{const b=Re.findPath(p,s),S=[{url:s.url,public_id:s.public_id,fileName:s.fileName},{url:w.url,public_id:w.public_id,fileName:w.fileName}];let j=qe(2);try{const L=(await Promise.all(S.map(U=>Je(U.url)))).map((U,T)=>ot(U,T===0&&s.rotation||0));j=rt(L)}catch(y){console.warn("Failed to size image row for equal heights",y)}const x={id:Ce(),type:"imageRow",caption:s.caption||"",images:[pt(s,j[0]),pt(w,j[1])],children:[{text:""}]};H.removeNodes(p,{at:b}),H.insertNodes(p,x,{at:b})}finally{f()}},pe=async w=>{try{const b=Re.findPath(p,s),S=s.images||[];if(S.length>=Dt)return;const j=[...S,pt(w,qe(S.length+1)[0])];let x=qe(j.length);try{const L=(await Promise.all(j.map(U=>Je(U.url)))).map((U,T)=>{var q;return ot(U,((q=S[T])==null?void 0:q.rotation)||0)});x=rt(L)}catch(y){console.warn("Failed to size image row for equal heights",y)}H.setNodes(p,{images:j.map((y,L)=>({...y,width:x[L]}))},{at:b})}finally{f()}},me=w=>{const b=Re.findPath(p,s),S=(s.images||[]).filter((x,y)=>y!==w);if(S.length===0){H.removeNodes(p,{at:b});return}if(S.length===1){const x=S[0];H.removeNodes(p,{at:b}),H.insertNodes(p,{id:Ce(),type:"image",url:x.url,public_id:x.public_id,fileName:x.fileName,caption:s.caption||"",width:"75%",...x.rotation?{rotation:x.rotation}:{},children:[{text:""}]},{at:b});return}const j=qe(S.length);H.setNodes(p,{images:S.map((x,y)=>({...x,width:j[y]}))},{at:b})},ee=w=>{const b=Re.findPath(p,s);H.setNodes(p,{caption:w},{at:b})},fe=()=>{const w=Re.findPath(p,s),b=Mt(s.rotation);H.setNodes(p,{rotation:b||void 0},{at:w})},be=async w=>{var x;let b;try{b=Re.findPath(p,s)}catch(y){console.warn("Failed to locate image row for rotate",y);return}const j=(s.images||[]).map((y,L)=>{if(L!==w)return y;const U=Mt(y.rotation);if(!U){const{rotation:T,...q}=y;return q}return{...y,rotation:U}});H.setNodes(p,{images:j},{at:b});try{const L=(await Promise.all(j.map(te=>Je(te.url)))).map((te,ye)=>{var ge;return ot(te,((ge=j[ye])==null?void 0:ge.rotation)||0)}),U=rt(L),T=(x=We.node(p,b))==null?void 0:x[0];if(!T||T.type!=="imageRow")return;const q=T.images||j;H.setNodes(p,{images:q.map((te,ye)=>({...te,width:U[ye]}))},{at:b})}catch(y){console.warn("Failed to resize image row after rotate",y)}},Ne=async()=>{var S;const w=s.images||[];if(w.length<2||ce)return;let b;try{b=Re.findPath(p,s)}
3catch(j){console.warn("Failed to locate image row for match heights",j);return}X(!0);try{const x=(await Promise.all(w.map(T=>Je(T.url)))).map((T,q)=>{var te;return ot(T,((te=w[q])==null?void 0:te.rotation)||0)}),y=rt(x),L=(S=We.node(p,b))==null?void 0:S[0];if(!L||L.type!=="imageRow")return;const U=L.images||w;H.setNodes(p,{images:U.map((T,q)=>({...T,width:y[q]}))},{at:b})}catch(j){console.warn("Failed to match image row heights",j)}finally{X(!1)}},je=(w,b)=>{const S=Re.findPath(p,s),j=s.images||[];if(j.length<2||!_.current)return;const y=Pt*(j.length-1),L=_.current.offsetWidth-y;if(L<=0)return;const U=100/j.length,T=j.map(c=>Ze(c.width,U));let q=b.offsetWidth/L*100;const te=Ye*(j.length-1);q=Math.max(Ye,Math.min(q,100-te));const ye=q-T[w];T[w]=q;const ge=w<j.length-1?w+1:w-1;T[ge]=Math.max(Ye,T[ge]-ye);const Se=T.reduce((c,u)=>c+u,0),i=T.map(c=>c/Se*100);H.setNodes(p,{images:j.map((c,u)=>({...c,width:`${i[u].toFixed(2)}%`}))},{at:S})};if(s.type==="imageRow"){const w=s.images||[],b=w.length<Dt,S=w.length+(O?1:0),j=O&&(ue==null?void 0:ue.length)===S?ue:O?qe(S):null,x=`${Math.floor(100/Math.max(S,1))}%`;return e.jsxs("div",{className:"story-editor-image-container story-editor-image-row",...t,contentEditable:!1,tabIndex:0,onFocus:()=>B(!0),onBlur:()=>B(!1),children:[e.jsx("div",{className:`image-row-toolbar ${!R&&!O?"hidden":""}`,children:e.jsxs("div",{className:"image-row-toolbar-actions",children:[t.dragHandleProps&&e.jsx(Oe,{title:w.length>1?o("common:tooltips.storyEditor.movePhotos"):o("common:tooltips.storyEditor.movePhoto"),mouseEnterDelay:.2,children:e.jsx("span",{className:"image-chip-tooltip-wrap",children:e.jsx("div",{className:"image-drag-handle",contentEditable:!1,"aria-label":w.length>1?o("common:tooltips.storyEditor.movePhotos"):o("common:tooltips.storyEditor.movePhoto"),...t.dragHandleProps,onMouseDown:y=>{var L,U;y.preventDefault(),(U=(L=t.dragHandleProps).onMouseDown)==null||U.call(L,y)},children:e.jsx(Rt.GrDrag,{})})})}),e.jsx($t,{isFocused:R,disabled:!b,onImageUpload:pe,onUploadStart:Q,onUploadError:f,imageActions:E}),e.jsx(Oe,{title:o("common:tooltips.storyEditor.matchPhotoHeights"),mouseEnterDelay:.2,children:e.jsx("span",{className:"image-chip-tooltip-wrap",children:e.jsx("button",{type:"button",className:"image-match-height-btn","aria-label":o("common:tooltips.storyEditor.matchPhotoHeights"),disabled:ce||w.length<2||!!O,onMouseDown:y=>{y.preventDefault(),Ne()},children:e.jsx(br,{})})})})]})}),e.jsxs("div",{className:"image-row-slots",ref:_,children:[w.map((y,L)=>{const U=Ze((j==null?void 0:j[L])||y.width,parseFloat(x)),T=I>0?Math.max(I*U/100,1):void 0,q=S-1,te=I>0?I*Ye/100:`${Ye}%`,ye=I>0?I*(100-Ye*q)/100:`${100-Ye*q}%`,ge=R&&!O;return e.jsx(Nt,{className:"image-row-slot image-resizable",size:{width:T??`${U}%`,height:"auto"},minWidth:te,maxWidth:ye,enable:ge?{top:!1,right:!0,bottom:!1,left:!0,topRight:!0,bottomRight:!0,bottomLeft:!0,topLeft:!0}:{top:!1,right:!1,bottom:!1,left:!1,topRight:!1,bottomRight:!1,bottomLeft:!1,topLeft:!1},handleStyles:{topRight:{zIndex:2},bottomRight:{zIndex:2},bottomLeft:{zIndex:2},topLeft:{zIndex:2},right:{zIndex:2},left:{zIndex:2}},onResize:(Se,i,c)=>{c.style.height="auto"},onResizeStop:(Se,i,c)=>{c.style.height="auto",je(L,c)},children:e.jsx("div",{className:"image-row-slot-media",children:e.jsx(Ut,{url:y.url,alt:s.caption||"",rotation:y.rotation,isFocused:R&&!O,showDots:R&&!O,maxHeight:Ke,publicId:y.public_id,fileName:y.fileName,variant:"row",children:e.jsx(Ot,{isVisible:R&&!O,onRotate:()=>be(L),onDelete:()=>{M(L),C(!0)},t:o})})})},`${y.public_id||y.url}-${L}`)}),O&&e.jsx(Wt,{previewUrl:O,widthPercent:Ze(j==null?void 0:j[w.length],parseFloat(x)),widthPx:I>0?Math.max(I*Ze(j==null?void 0:j[w.length],parseFloat(x))/100,1):void 0})]}),e.jsx(Bt,{caption:s.caption,isMobileLayout:g,t:o,onCaptionChange:ee}),e.jsx(Be,{className:"image-delete-modal",title:o("common:modals.editorDeletePhoto.title"),open:A,onCancel:()=>{C(!1),M(null)},onOk:()=>{D!=null&&me(D),C(!1),M(null)},okText:o("common:modals.editorDeletePhoto.ctaDelete"),cancelText:o("common:cta.cancel"),centered:!0}),e.jsx("p",{}),r]})}if(s.type==="image"){const w=!!s.pending,b=O&&(ue==null?void 0:ue.length)===2?ue:qe(2),S=Ze(b[0],50),j=Ze(b[1],50),x=O&&I>0?Math.max(I*S/100,1):void 0,y=O&&I>0?Math.max(I*j/100,1):void 0;return e.jsxs("div",{className:`story-editor-image-container${O?" story-editor-image-row":""}`,...t,contentEditable:!1,tabIndex:0,onFocus:()=>B(!0),onBlur:()=>B(!1),children:[e.jsx("div",{className:`${O?"image-row-toolbar":"image-standalone-toolbar"}${!R&&!O||w?" hidden":""}`,children:e.jsxs("div",{className:O?"image-row-toolbar-actions":"image-standalone-toolbar-actions",children:[t.dragHandleProps&&e.jsx(Oe,{title:o("common:tooltips.storyEditor.movePhoto"),mouseEnterDelay:.2,children:e.jsx("span",{className:"image-chip-tooltip-wrap",children:e.jsx("div",{className:"image-drag-handle",contentEditable:!1,"aria-label":o("common:tooltips.storyEditor.movePhoto"),...t.dragHandleProps,onMouseDown:L=>{var U,T;L.preventDefault(),(T=(U=t.dragHandleProps).onMouseDown)==null||T.call(U,L)},children:e.jsx(Rt.GrDrag,{})})})}),e.jsx($t,{isFocused:R||!!O,disabled:!1,onImageUpload:Y,onUploadStart:Q,onUploadError:f,imageActions:E})]})}),O?e.jsxs("div",{className:"image-row-slots",ref:_,children:[e.jsx("div",{className:"image-row-slot",style:{width:x??`${S}%`},children:e.jsx("div",{className:"image-row-slot-media image-row-slot-media--focused",children:e.jsx("img",{className:"image",src:s.url,alt:s.caption||"","data-public-id":s.public_id,"data-file-name":s.fileName,style:{width:"100%",height:"auto",display:"block",maxHeight:Ke,objectFit:"contain"},draggable:!1})})}),e.jsx(Wt,{previewUrl:O,widthPercent:j,widthPx:y})]}):e.jsx("div",{className:`image-resizable-wrapper${w?" image-resizable-wrapper--pending":""}`,"aria-busy":w||void 0,"aria-label":w?"Uploading photo":void 0,children:e.jsxs(Nt,{className:"image-resizable",defaultSize:{width:s.width||"75%",height:"auto"},size:{width:s.width||"75%",height:"auto"},maxWidth:"100%",maxHeight:Ke,minWidth:"25%",lockAspectRatio:!0,enable:R&&!w?void 0:{top:!1,right:!1,bottom:!1,left:!1,topRight:!1,bottomRight:!1,bottomLeft:!1,topLeft:!1},onResizeStop:(L,U,T)=>{const q=T.parentElement;if(!q)return;const te=q.offsetWidth;let ye=T.offsetWidth;const ge=T.offsetHeight;if(ge>Ke){const c=Ke/ge;ye=ye*c}const Se=`${Math.min(ye/te*100,100).toFixed(2)}%`,i=Re.findPath(p,s);H.setNodes(p,{width:Se},{at:i})},style:{display:"inline-block",marginBottom:"4px"},children:[e.jsx(Ut,{url:s.url,alt:s.caption||"",rotation:s.rotation,isFocused:R&&!w,showDots:R&&!w,maxHeight:Ke,publicId:s.public_id,fileName:s.fileName,variant:"standalone",children:e.jsx(Ot,{isVisible:R&&!w,onRotate:fe,onDelete:()=>C(!0),t:o})}),w&&e.jsx("div",{className:"image-pending-overlay",children:e.jsx(Fe,{size:"large"})})]})}),e.jsx(Bt,{caption:s.caption,isMobileLayout:g,t:o,onCaptionChange:L=>{if(w)return;const U=Re.findPath(p,s);H.setNodes(p,{caption:L},{at:U})}}),e.jsx(Be,{className:"image-delete-modal",title:o("common:modals.editorDeletePhoto.title"),open:A,onCancel:()=>C(!1),onOk:()=>{_e(),C(!1)},okText:o("common:modals.editorDeletePhoto.ctaDelete"),cancelText:o("common:cta.cancel"),centered:!0}),e.jsx("p",{}),r]})}const ae=s.align==="center"?"center":m?"right":s.align||"left";return e.jsx("p",{className:"story-editor-text-container",...t,style:{...t.style||{},textAlign:ae},children:r})},Rr=3e3,Nr=200,kr={QUESTION_RATE_LIMIT:"aiEditor.errors.questionRateLimit",CONCURRENT_REQUEST:"aiEditor.errors.concurrentRequest",USER_RATE_LIMIT:"aiEditor.errors.userRateLimit",BURST_RATE_LIMIT:"aiEditor.errors.burstRateLimit",BAD_RESPONSE:"aiEditor.errors.badResponse",INVALID_DIRECTION:"aiEditor.errors.invalidDirection",TIMEOUT:"aiEditor.errors.timeout",AI_NOT_CONFIGURED:"aiEditor.errors.notConfigured",INTERNAL_ERROR:"aiEditor.errors.internalError"},Cr=t=>new Promise(r=>setTimeout(r,t));function zt(t){const r=t.errorCode||"INTERNAL_ERROR",s=new Error(t.error||r);return s.response={data:{error:r,errorKey:kr[r]||"aiEditor.errors.generic"}},s}async function as(t){var s,n,o,l;let r=0;for(;r<Nr;){r+=1;try{const g=(await xt(`ai-editor/jobs/${t}`)).data;if(g.status==="processed")return g;if(g.status==="failed")throw zt(g)}catch(m){if((n=(s=m==null?void 0:m.response)==null?void 0:s.data)!=null&&n.error||(l=(o=m==null?void 0:m.response)==null?void 0:o.data)!=null&&l.errorKey)throw m}await Cr(Rr)}throw zt({errorCode:"TIMEOUT"})}const Tr=async({bookId:t,questionId:r,text:s})=>{const n=await Ie("ai-editor/fix-errors",{bookId:t,questionId:r,text:s});return as(n.data.jobId)},Ar=async({bookId:t,questionId:r,text:s,direction:n,scope:o})=>{const l=await Ie("ai-editor/adjust-style",{bookId:t,questionId:r,text:s,direction:n,scope:o});return as(l.data.jobId)},Lr=["tighten","elaborate","warmer","lighter","conversational"],Ir=async()=>(await Ie("user/ai-editor-consent")).data,bt=`
4
5`;function ut(t){const r=[];for(let s=0;s<t.children.length;s++){const n=t.children[s];n.type==="paragraph"&&r.push({path:[s],text:at.string(n)})}return r}function it(t){return ut(t).map(r=>r.text).join(bt)}const Pr=3;function Mr(t){return typeof t!="string"||!t.trim()?0:t.trim().split(/\s+/).filter(r=>/[a-zA-Z]/.test(r)).length}function qt(t,{scope:r="whole_story",selectionText:s=""}={}){const n=r==="selection"?s:it(t);return Mr(n)>=Pr}function is(t){const{selection:r}=t;return!r||Ve.isCollapsed(r)?"":We.string(t,r)}function Dr(t){const{selection:r}=t;return!r||Ve.isCollapsed(r)?null:r}function Or(t){const r=Dr(t),s=r?is(t):"";return{range:r,text:s}}function St(t,r,s){const n=ut(t);let o=0;for(let l=0;l<n.length;l++){const m=n[l],g=o,p=o+m.text.length;if(s<=g)break;
5if(r<p&&s>g){const E=Math.max(0,r-g),_=Math.min(m.text.length,s-g);return ls(t,m.path,E,_)}o=p+(l<n.length-1?bt.length:0)}return null}function ls(t,r,s,n){let o=0,l=null,m=null;for(const[g,p]of at.children(t,r)){const E=g.text||"",_=o,A=o+E.length;!l&&s>=_&&s<=A&&(l={path:p,offset:s-_}),!m&&n>=_&&n<=A&&(m={path:p,offset:n-_}),o=A}return!l||!m?null:{anchor:l,focus:m}}function Ur(t,r,s){const n=at.get(t,r),o=at.string(n).length;if(o===0){if(!s)return;H.insertText(t,s,{at:{path:[...r,0],offset:0}});return}const l=ls(t,r,0,o);l&&(H.select(t,l),H.insertText(t,s))}function Fr(t,r,s){const n=[];for(const o of r){const l=St(t,o.startOffset,o.endOffset);l&&n.push({...l,aiErrorUnderline:!0,aiErrorType:o.type,aiHighlighted:o.id===s,correctionId:o.id})}return n}function Br(t,r){return r?[{...r,aiStyleSelection:!0}]:[]}const lt=/\w/;function $r(t,r){var l,m;if(!t)return r;const s=((l=t.match(/^\s+/))==null?void 0:l[0])||"",n=((m=t.match(/\s+$/))==null?void 0:m[0])||"";let o=r.trim();return s&&(o=s+o),n&&(o=o+n),o}function Vt(t,r){var n;const s=ut(t);for(let o=0;o<s.length;o++){const m=s[o].path;if(r.path[0]!==m[0])continue;let g=0;for(let E=0;E<o;E++)g+=s[E].text.length+bt.length;let p=0;for(const[E,_]of at.children(t,m)){const A=[...m,..._];if(ys.equals(r.path,A))return g+p+r.offset;p+=((n=E.text)==null?void 0:n.length)||0}}return null}function cs(t,r,s,n){let o=n;const l=r>0?t[r-1]:"",m=s<t.length?t[s]:"";return l&&lt.test(l)&&o&&lt.test(o[0])&&!o.startsWith(" ")&&(o=` ${o}`),m&&lt.test(m)&&o&&lt.test(o[o.length-1])&&!o.endsWith(" ")&&(o=`${o} `),o}function Wr(t,r,s){return s.length-(r-t)}function Hr(t,r,s){return s?t.filter(n=>n.id!==r.id).map(n=>n.startOffset>=r.endOffset?{...n,startOffset:n.startOffset+s,endOffset:n.endOffset+s}:n):t.filter(n=>n.id!==r.id)}function Yt(t,r){const s=St(t,r.startOffset,r.endOffset);if(!s)return{applied:!1,delta:0};const n=it(t),o=cs(n,r.startOffset,r.endOffset,r.corrected);return H.select(t,s),H.insertText(t,o),{applied:!0,delta:Wr(r.startOffset,r.endOffset,o)}}function zr(t,r,s,n){const o=s||t.selection;if(!o||Ve.isCollapsed(o))return!1;const l=n??We.string(t,o);let m=$r(l,r);if(!/^\s/.test(l)){const[p,E]=Ve.edges(o),_=it(t),A=Vt(t,p),C=Vt(t,E);A!=null&&C!=null&&(m=cs(_,Math.min(A,C),Math.max(A,C),m))}return H.select(t,o),H.insertText(t,m),!0}function qr(t,r){const s=r.split(/\n\n+/).map(o=>o.trim()).filter(Boolean),n=ut(t).map(o=>o.path);if(!n.length)return!1;if(n.forEach((o,l)=>{Ur(t,o,s[l]||"")}),s.length>n.length){const o=n[n.length-1][0]+1;s.slice(n.length).forEach((l,m)=>{H.insertNodes(t,{id:Ce(),type:"paragraph",children:[{text:l}]},{at:[o+m]})})}return!0}function Vr(t,r){var n,o;const s=St(t,r.startOffset,r.endOffset);if(s)try{const l=Re.toDOMRange(t,s);(o=(n=l==null?void 0:l.startContainer)==null?void 0:n.parentElement)==null||o.scrollIntoView({behavior:"smooth",block:"center"})}catch{}}const Yr={QUESTION_RATE_LIMIT:"aiEditor.errors.questionRateLimit",CONCURRENT_REQUEST:"aiEditor.errors.concurrentRequest",USER_RATE_LIMIT:"aiEditor.errors.userRateLimit",BURST_RATE_LIMIT:"aiEditor.errors.burstRateLimit",BAD_RESPONSE:"aiEditor.errors.badResponse",INVALID_DIRECTION:"aiEditor.errors.invalidDirection",TIMEOUT:"aiEditor.errors.timeout",AI_NOT_CONFIGURED:"aiEditor.errors.notConfigured",INTERNAL_ERROR:"aiEditor.errors.internalError",EMPTY_TEXT:"aiEditor.errors.emptyText",TEXT_TOO_LONG:"aiEditor.errors.textTooLong",SELECTION_TOO_LONG:"aiEditor.errors.selectionTooLong"};function Kt(t){var o;const r=((o=t==null?void 0:t.response)==null?void 0:o.data)||{},s=r.errorKey||Yr[r.error]||"aiEditor.errors.generic",n={};return r.maxLength!=null&&(n.maxLength=r.maxLength),{errorKey:s,params:n}}function ds(t,r,s){return s(`features:${t||"aiEditor.errors.generic"}`,{defaultValue:s("features:aiEditor.errors.generic"),...r||{}})}function Kr({open:t,loading:r,onContinue:s,onCancel:n,t:o}){return e.jsx(Be,{className:"story-answer-ai-editor-consent-modal",title:o("features:aiEditor.consent.title"),open:t,centered:!0,width:560,onCancel:n,footer:[e.jsx(oe,{variant:De,onClick:n,children:o("common:cta.cancel")},"cancel"),e.jsx(oe,{type:"primary",loading:r,onClick:s,children:o("features:aiEditor.consent.continue")},"continue")],children:e.jsx("p",{children:o("features:aiEditor.consent.description")})})}const Te={ERRORS:"errors",STYLE:"style"},Et=a.createContext(null);function le(t,r,s={}){re(t,r,s)}function Gr({editor:t,bookId:r,questionId:s,isMobile:n,isOpen:o,onOpenChange:l,onDecorationsChange:m,children:g}){const{t:p}=$e(),E=vt(),_=ct(({AuthReducer:v})=>
5v.userDetails),[A,C]=a.useState(!1),[D,M]=a.useState(!1),[R,B]=a.useState(Te.ERRORS),[ce,X]=a.useState("idle"),[I,de]=a.useState([]),[O,ne]=a.useState(0),[ue,xe]=a.useState(null),[we,f]=a.useState(null),[Q,_e]=a.useState(null),[Y,pe]=a.useState("idle"),[me,ee]=a.useState(""),[fe,be]=a.useState("whole_story"),[Ne,je]=a.useState(null),[ae,z]=a.useState(null),[ke,w]=a.useState(null),[b,S]=a.useState(""),j=qt(t,{scope:fe,selectionText:b}),x=!!ae,y=a.useRef(o),L=a.useRef(R),U=a.useRef(Y),T=a.useRef(ae),q=a.useRef(!1);y.current=o,L.current=R,U.current=Y,T.current=ae;const te=a.useCallback(({autoSelectScope:v=!1}={})=>{const{range:N,text:P}=Or(t);if(N&&P.trim()){T.current&&Ve.equals(T.current,N)||(z(N),S(P)),v&&!q.current&&be("selection");return}if(T.current&&(z(null),S("")),q.current=!1,v){be("whole_story");return}be(F=>F==="selection"?"whole_story":F)},[t]),ye=a.useRef(te);ye.current=te;const ge=a.useMemo(()=>{const v=Fr(t,I,ue),N=R===Te.STYLE&&fe==="selection"&&ae?Br(t,ae):[];return[...v,...N]},[t,I,ue,R,fe,ae]);a.useEffect(()=>{m==null||m(ge)},[ge,m]),a.useEffect(()=>{if(!o){z(null),q.current=!1;return}q.current=!1,te({autoSelectScope:!0})},[o,te]),a.useEffect(()=>{if(!t)return;const{onChange:v}=t;return t.onChange=()=>{if(v(),!y.current)return;const N=L.current===Te.STYLE,P=U.current;N&&(P==="loading"||P==="result")||Re.isFocused(t)&&ye.current({autoSelectScope:N})},()=>{t.onChange=v}},[t]);const Se=a.useCallback(()=>{l(!1),le("ai_editor","panel_closed")},[l]),i=a.useCallback(()=>{X("idle"),de([]),ne(0),xe(null),f(null)},[]),c=a.useCallback(()=>{_e(null),pe("idle"),ee(""),je(null),w(null)},[]),u=a.useCallback(()=>{i(),c(),Se()},[Se,i,c]),J=a.useCallback(()=>{l(!0),le("ai_editor","panel_opened")},[l]),ie=a.useCallback(()=>{if(o){u();return}if(!(_!=null&&_.aiEditorConsentAgreedAt)){C(!0),le("ai_editor","consent_popup_view");return}J()},[o,J,u,_==null?void 0:_.aiEditorConsentAgreedAt]),ve=a.useCallback(async()=>{var v,N;M(!0);try{const{aiEditorConsentAgreedAt:P}=await Ir();E(es({..._,aiEditorConsentAgreedAt:P})),C(!1),le("ai_editor","consent_granted"),J()}catch(P){le("ai_editor","consent_save_failure",{error:((N=(v=P==null?void 0:P.response)==null?void 0:v.data)==null?void 0:N.error)||(P==null?void 0:P.message)})}finally{M(!1)}},[E,J,_]),Ee=a.useCallback(()=>{C(!1),le("ai_editor","consent_declined")},[]),He=a.useCallback(v=>{B(v),v===Te.STYLE&&te({autoSelectScope:!0}),le("ai_editor","mode_switched",{mode:v})},[te]),et=a.useCallback(v=>{v==="selection"&&!ae||((Y==="result"||Y==="notAStory")&&(ee(""),pe("idle"),_e(null),je(null),w(null)),v==="whole_story"?q.current=!0:q.current=!1,be(v))},[ae,Y]),Xe=a.useCallback(async()=>{var N,P,F,K;if(!j)return;f(null),de([]),ne(0),xe(null),X("loading"),le("ai_editor","fix_errors_run");const v=Date.now();try{const Z=it(t),G=await Tr({bookId:r,questionId:s,text:Z}),Pe=G.corrections||[];de(Pe),ne(0),G.isMeaningful===!1?(X("notAStory"),le("ai_editor","fix_errors_not_a_story")):(X(Pe.length?"results":"noIssues"),Pe.length||le("ai_editor","fix_errors_no_issues")),le("ai_editor","api_call_success",{mode:"errors",latency_ms:G.latencyMs??Date.now()-v})}catch(Z){X("error"),f(Kt(Z)),le("ai_editor","api_call_failure",{mode:"errors",error_kind:((P=(N=Z==null?void 0:Z.response)==null?void 0:N.data)==null?void 0:P.error)||"other",latency_ms:Date.now()-v}),le("ai_editor","error_shown",{kind:((K=(F=Z==null?void 0:Z.response)==null?void 0:F.data)==null?void 0:K.error)||"other"})}},[r,j,t,s]),Ae=a.useCallback(v=>{const{applied:N,delta:P}=Yt(t,v);N&&(de(F=>Hr(F,v,P)),ne(F=>F+1),le("ai_editor","fix_accepted",{type:v.type}))},[t]),h=a.useCallback(v=>{de(N=>N.filter(P=>P.id!==v.id)),ne(N=>N+1),le("ai_editor","fix_skipped",{type:v.type})},[]),$=a.useCallback(()=>{const v=[...I].sort((N,P)=>P.startOffset-N.startOffset);v.forEach(N=>Yt(t,N)),de([]),ne(N=>N+v.length),le("ai_editor","accept_all_clicked")},[I,t]);a.useEffect(()=>{ce==="results"&&I.length===0&&(X("done"),le("ai_editor","fix_errors_done"))},[I.length,ce]);const he=a.useCallback(async v=>{var K,Z,G,Pe;const N=fe;if(N==="selection"&&!ae)return;const P=N==="selection"?b||is(t):it(t);if(!qt(t,{scope:N,selectionText:P}))return;_e(v),je(null),pe("loading"),ee(""),w(N==="selection"?ae:null),le("ai_editor","style_chip_clicked",{direction:v,scope:N});const F=Date.now();try{const Me=await Ar({bookId:r,questionId:s,text:P,direction:v,scope:N});Me.isMeaningful===!1?(ee(""),pe("notAStory"),le("ai_editor","style_not_a_story",{direction:v,scope:N})):(ee(Me.rewrite||""),pe("result")),le("ai_editor","api_call_success",{mode:"style",direction:v,latency_ms:Me.latencyMs??Date.now()-F})}catch(Me){pe("error"),je(Kt(Me)),le("ai_editor","api_call_failure",{mode:"style",direction:v,error_kind:((Z=(K=Me==null?void 0:Me.response)==null?void 0:K.data)==null?void 0:Z.error)||"other",latency_ms:Date.now()-F}),le("ai_editor","error_shown",{kind:((Pe=(G=Me==null?void 0:Me.response)==null?void 0:G.data)==null?void 0:Pe.error)||"other"})}},[r,t,ae,s,fe,b]),V=a.useCallback(()=>
5{if(!me)return;(fe==="selection"?zr(t,me,ke,b):qr(t,me))&&(le("ai_editor","style_rewrite_kept",{direction:Q,scope:fe}),c(),z(null),S(""),be("whole_story"),q.current=!1,H.deselect(t))},[t,c,ke,Q,me,fe,b]),d=a.useCallback(()=>{le("ai_editor","style_rewrite_discarded",{direction:Q}),c()},[c,Q]),k=a.useCallback(()=>{le("ai_editor","try_another_direction_clicked"),ee(""),pe("idle"),_e(null)},[]),W=a.useCallback(v=>{xe(v.id),Vr(t,v),n&&setTimeout(()=>xe(null),1500)},[t,n]),se={t:p,isMobile:n,isOpen:o,mode:R,fixState:ce,corrections:I,reviewedCount:O,highlightedId:ue,fixError:we,styleDirection:Q,styleState:Y,styleRewrite:me,styleScope:fe,styleError:Ne,canRunAiEdit:j,hasFrozenSelection:x,setHighlightedId:xe,handleTogglePanel:ie,handleModeSwitch:He,handleStyleScopeChange:et,runFixErrors:Xe,acceptCorrection:Ae,skipCorrection:h,acceptAllCorrections:$,runStyleRewrite:he,applyStyleRewrite:V,discardStyleRewrite:d,tryAnotherDirection:k,onCardTap:W,requestClose:u};return e.jsxs(Et.Provider,{value:se,children:[g,e.jsx(Kr,{open:A,loading:D,onContinue:ve,onCancel:Ee,t:p})]})}function us(){const t=a.useContext(Et);if(!t)throw new Error("useStoryAnswerAiEditor must be used within StoryAnswerAiEditorProvider");return t}function Xr(){const t=a.useContext(Et);return t?{setHighlightedId:t.setHighlightedId,onCardTap:t.onCardTap,corrections:t.corrections}:null}const Zr={grammar:"ai-error-underline--grammar",spelling:"ai-error-underline--spelling",punctuation:"ai-error-underline--punctuation"},Jr=({attributes:t,children:r,leaf:s})=>{const n=Xr();if(s.bold&&(r=e.jsx("strong",{children:r})),s.italic&&(r=e.jsx("em",{children:r})),s.underline&&(r=e.jsx("u",{children:r})),s.aiErrorUnderline){const o=Zr[s.aiErrorType]||"";r=e.jsx("span",{className:["ai-error-underline",o,s.aiHighlighted?"ai-error-underline--highlighted":""].filter(Boolean).join(" "),onMouseEnter:()=>{s.correctionId&&(n==null||n.setHighlightedId(s.correctionId))},onMouseLeave:()=>n==null?void 0:n.setHighlightedId(null),onClick:()=>{var l;if(s.correctionId&&(n!=null&&n.onCardTap)){const m=(l=n.corrections)==null?void 0:l.find(g=>g.id===s.correctionId);m&&n.onCardTap(m)}},children:r})}return s.aiStyleSelection&&(r=e.jsx("span",{className:"ai-style-selection",children:r})),e.jsx("span",{...t,children:r})},Qr=({attributes:t,element:r,children:s,renderElement:n})=>{const l=(r.type==="image"||r.type==="imageRow")&&!r.pending,{attributes:m,listeners:g,setNodeRef:p,transform:E,transition:_,isDragging:A}=ws({id:r.id,disabled:!l}),C={transform:E?vs.Transform.toString(E):void 0,transition:_,opacity:A?.3:1,border:A?"1px dashed #ccc":void 0,background:A?"#f8f8f8":void 0};return e.jsx("div",{...t,children:e.jsx("div",{className:"sortable-element-wrapper",ref:p,style:C,children:n({element:r,children:s,attributes:{...t,dragHandleProps:l?{...m,...g}:null}})})})},eo="data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20width='200'%20height='100'%20viewBox='0%200%20200%20100'%3e%3c!--%20Left%20Tall%20Bar%20--%3e%3crect%20x='10'%20y='10'%20width='20'%20height='80'%20rx='10'%20fill='%234D3600'%20/%3e%3c!--%20Inner%20Left%20Bar%20--%3e%3crect%20x='50'%20y='25'%20width='20'%20height='50'%20rx='10'%20fill='%234D3600'%20/%3e%3c!--%20Center%20Bar%20--%3e%3crect%20x='90'%20y='30'%20width='20'%20height='40'%20rx='10'%20fill='%234D3600'%20/%3e%3c!--%20Inner%20Right%20Bar%20--%3e%3crect%20x='130'%20y='25'%20width='20'%20height='50'%20rx='10'%20fill='%234D3600'%20/%3e%3c!--%20Right%20Tall%20Bar%20--%3e%3crect%20x='170'%20y='10'%20width='20'%20height='80'%20rx='10'%20fill='%234D3600'%20/%3e%3c/svg%3e",to="data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20width='200'%20height='100'%20viewBox='0%200%20200%20100'%3e%3c!--%20Left%20Tall%20Bar%20--%3e%3cg%20transform='translate(20,%2050)'%3e%3crect%20x='-10'%20y='-40'%20width='20'%20height='80'%20rx='10'%20fill='%234D3600'%3e%3canimateTransform%20attributeName='transform'%20type='scale'%20values='1,1;1,0.3;1,1'%20dur='1.2s'%20repeatCount='indefinite'/%3e%3c/rect%3e%3c/g%3e%3c!--%20Inner%20Left%20Bar%20--%3e%3cg%20transform='translate(60,%2050)'%3e%3crect%20x='-10'%20y='-25'%20width='20'%20height='50'%20rx='10'%20fill='%234D3600'%3e%3canimateTransform%20attributeName='transform'%20type='scale'%20values='1,0.7;1,1;
51,0.7'%20dur='1s'%20repeatCount='indefinite'/%3e%3c/rect%3e%3c/g%3e%3c!--%20Center%20Bar%20--%3e%3cg%20transform='translate(100,%2050)'%3e%3crect%20x='-10'%20y='-20'%20width='20'%20height='40'%20rx='10'%20fill='%234D3600'%3e%3canimateTransform%20attributeName='transform'%20type='scale'%20values='1,1;1,0.5;1,1'%20dur='0.8s'%20repeatCount='indefinite'/%3e%3c/rect%3e%3c/g%3e%3c!--%20Inner%20Right%20Bar%20--%3e%3cg%20transform='translate(140,%2050)'%3e%3crect%20x='-10'%20y='-25'%20width='20'%20height='50'%20rx='10'%20fill='%234D3600'%3e%3canimateTransform%20attributeName='transform'%20type='scale'%20values='1,0.6;1,1;1,0.6'%20dur='1s'%20repeatCount='indefinite'/%3e%3c/rect%3e%3c/g%3e%3c!--%20Right%20Tall%20Bar%20--%3e%3cg%20transform='translate(180,%2050)'%3e%3crect%20x='-10'%20y='-40'%20width='20'%20height='80'%20rx='10'%20fill='%234D3600'%3e%3canimateTransform%20attributeName='transform'%20type='scale'%20values='1,1;1,0.3;1,1'%20dur='1.2s'%20repeatCount='indefinite'/%3e%3c/rect%3e%3c/g%3e%3c/svg%3e",so="/assets/pause-icon-BNcbsd_R.svg",ro="/assets/record-icon-BmQg1A9Z.svg";async function oo(){try{return(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(r=>r.stop()),!0}catch(t){return console.warn("[speech-to-text] microphone permission error:",t.message||t),!1}}async function no({bookId:t,questionId:r,blob:s,transcript:n,mimeType:o,t:l,recordingsLength:m}){try{const{data:g}=await Ie("question/generate-audio-upload-url",{bookId:t,questionId:r,mimeType:o});if(g.uploadUrl&&g.url){const p=await fetch(g.uploadUrl,{method:"PUT",headers:{"Content-Type":o},body:s});if(!p.ok)throw new Error(`S3 upload failed: ${p.status} ${p.statusText}`);const{data:E}=await Ie("question/save-audio",{title:`${l("features:audio.recordingName")} ${m+1}`,bookId:t,questionId:r,url:g.url,transcript:n,mimeType:o});return re("speech_to_text","audio_file_upload_success"),E}}catch(g){throw re("speech_to_text","audio_file_upload_error",{error:g.message||g.stack}),console.error("[speech-to-text] failed to upload audio:",g.message||g),g}}async function ao(t,r){const n=await(await fetch(decodeURIComponent(t))).blob(),o=window.URL.createObjectURL(n),l=document.createElement("a");l.href=o,l.download=r?`${r}.webm`:"recording.webm",document.body.appendChild(l),l.click(),document.body.removeChild(l),re("speech_to_text","audio_download_click")}const io=t=>{const r=Math.floor(t/60).toString().padStart(2,"0"),s=(t%60).toString().padStart(2,"0");return`${r}:${s}`},{Title:lo,Text:mt,Paragraph:nt}=dt,co=900,uo=3e3,ho=200,hs=a.forwardRef(({bookId:t,questionId:r,onTrascriptionReady:s},n)=>{const{t:o}=$e(),[l,m]=a.useState(!1),[g,p]=a.useState(!1),[E,_]=a.useState(!1),[A,C]=a.useState([]),[D,M]=a.useState(!1),[R,B]=a.useState("permission"),[ce,X]=a.useState(!1),[I,de]=a.useState(!1),[O,ne]=a.useState(0),[ue,xe]=a.useState(null),[we,f]=a.useState(""),[Q,_e]=a.useState(!1),[Y,pe]=a.useState(null),[me,ee]=a.useState(!1),[fe,be]=a.useState(!1),[Ne,je]=a.useState(!1),ae=a.useRef(null),z=a.useRef(null),ke=a.useRef([]),w=a.useRef(null),b=a.useRef(null),S=a.useRef(null),j=a.useRef(null);a.useEffect(()=>{U()},[r]),a.useEffect(()=>()=>{T(),S.current&&(S.current.pause(),S.current.currentTime=0)},[]);const x=h=>{re("speech_to_text","audio_play_click"),S.current&&S.current!==h.target&&(S.current.pause(),S.current.currentTime=0),S.current=h.target},y=h=>{S.current===h.target&&(S.current=null)},L=h=>{S.current===h.target&&h.target.currentTime===h.target.duration&&(S.current=null)},U=async()=>{if(!r||r==="new")return;const{data:h}=await xt("question/get-audio",{bookId:t,questionId:r});h.questionAudio&&h.questionAudio.length?C(h.questionAudio):C([])},T=()=>{j.current&&(clearInterval(j.current),j.current=null)},q=h=>{T();let $=0;j.current=setInterval(async()=>{if($+=1,$>ho){T(),st.error("Transcription timed out"),u();return}try{const{data:he}=await xt("question/get-audio",{bookId:t,questionId:r});if(he!=null&&he.questionAudio){C(he.questionAudio);const V=he.questionAudio.find(d=>d.id===h);(V==null?void 0:V.transcriptionStatus)==="processed"&&(T(),V!=null&&V.transcription&&s(V.transcription),u()),(V==null?void 0:V.transcriptionStatus)==="failed"&&(T(),st.error((V==null?void 0:V.transcriptionError)||"Transcription failed"),u())}}catch{}},uo)},te=async()=>{await oo()&&(m(!0),B("ready"))},ye=()=>{var h;ee(!1),re("speech_to_text","stop_recording_click"),B("uploading"),X(!1),clearInterval(b.current),((h=z.current)==null?void 0:h.state)!=="inactive"&&z.current.stop(),z.current.onstop=async()=>
5{ae.current.getTracks().forEach(V=>V.stop());const $=new Blob(ke.current,{type:z.current.mimeType}),he=z.current.mimeType.split(";")[0].trim();try{p(!0);const V=await no({bookId:t,questionId:r,blob:$,transcript:void 0,mimeType:he,t:o,recordingsLength:A.length});V&&(C(d=>[...d,V]),q(V.id))}catch(V){st.error(V.message||V)}finally{p(!1)}}},ge=(h=!1)=>{var $;re("speech_to_text","pause_recording_click"),(($=z.current)==null?void 0:$.state)==="recording"&&(z.current.pause(),w.current.enabled=!1),de(!0),clearInterval(b.current),h&&ee(!0)},Se=()=>setInterval(()=>{ne(h=>{const $=h+1;return $>=co&&(re("speech_to_text","recording_limit_reached"),ge(!0)),$})},1e3),i=async()=>{fe||(be(!0),ee(!1),re("speech_to_text","start_recording_click"),ae.current=await navigator.mediaDevices.getUserMedia({audio:!0}),w.current=ae.current.getAudioTracks()[0],z.current=new MediaRecorder(ae.current),ke.current=[],z.current.ondataavailable=h=>{h.data.size>0&&ke.current.push(h.data)},z.current.start(),X(!0),de(!1),ne(0),b.current=Se(),B("recording"),be(!1))},c=()=>{var h;re("speech_to_text","resume_recording_click"),((h=z.current)==null?void 0:h.state)==="paused"&&(z.current.resume(),w.current.enabled=!0),de(!1),b.current=Se()},u=()=>{var h;M(!1),B("permission"),ne(0),clearInterval(b.current),T(),z.current&&((h=z.current)==null?void 0:h.state)!=="inactive"&&z.current.stop(),ae.current&&ae.current.getTracks().forEach($=>$.stop())},J=async(h,$)=>{try{await Ie("question/update-audio-title",{bookId:t,questionId:r,audioId:h,title:$}),C(he=>he.map(V=>V.id===h?{...V,title:$}:V))}catch(he){console.error("[speech-to-text-qa] failed to update audio title:",he.message||he)}finally{xe(null),f("")}},ie=async()=>{if(re("speech_to_text","delete_audio_click"),_e(!1),!(!t||!r||!Y)){_(!0);try{await Js(`question/delete-audio/${t}/${r}/${Y}`),C(h=>h.filter($=>$.id!==Y))}catch(h){console.error("[speech-to-text-qa] failed to delete recording:",h.message||h)}finally{pe(null),_(!1)}}},ve=()=>{pe(null),_e(!1)},Ee=()=>{be(!1),re("speech_to_text","editor_record_button_click"),M(!0),l?B("ready"):re("speech_to_text","permission_popup_view")},He=(h,$)=>{re("speech_to_text","edit_audio_title_click"),xe(h),f($)},et=async(h,$)=>{je(!0);try{await Ie("question/update-audio-print-inclusion",{bookId:t,questionId:r,audioId:h,includeInPrintedBook:$}),C(he=>he.map(V=>V.id===h?{...V,includeInPrintedBook:$}:V))}catch(he){st.error(he.message||o("features:audio.printInclusionUpdateError"))}finally{je(!1)}},Xe=async h=>{je(!0);try{await Ie("question/update-audio-print-inclusion",{bookId:t,questionId:r,includeAll:h}),C($=>$.map(he=>({...he,includeInPrintedBook:h})))}catch($){st.error($.message||o("features:audio.printInclusionUpdateError"))}finally{je(!1)}},Ae=h=>{const $=h.includeInPrintedBook===!1;et(h.id,$)};return a.useImperativeHandle(n,()=>({handleRunSpeechToText:()=>Ee()})),e.jsxs("div",{className:"speech-to-text",children:[e.jsxs(Be,{className:`speech-to-text-modal ${R==="recording"&&"modal-recording"}`,open:D,title:o(R==="recording"?"common:modals.recording.title":R==="uploading"?"common:modals.recordingUpload.title":"common:modals.recordPermissions.title"),onCancel:u,footer:R==="permission"?[e.jsx(Le,{onClick:u,children:o("common:cta.cancel")},"permission-cancel"),e.jsx(Le,{type:"primary",onClick:te,children:o("common:modals.recordPermissions.ctaAllow")},"permission-allow")]:R==="ready"?[e.jsx(Le,{onClick:u,children:o("common:cta.cancel")},"ready-cancel"),e.jsx(Le,{type:"primary",loading:fe,onClick:i,children:o("common:modals.recordStory.ctaStart")},"ready-start")]:R==="recording"?[e.jsx(Le,{loading:g,type:"primary",onClick:ye,children:o(me?"common:modals.recording.ctaTranscribe":"common:modals.recording.ctaStop")},"recording-stop")]:[],centered:!0,children:[R==="permission"&&e.jsx(nt,{children:o("common:modals.recordPermissions.descriptionAi")}),R==="ready"&&e.jsxs(e.Fragment,{children:[e.jsx(nt,{children:o("common:modals.recordStory.descriptionAi")}),e.jsx(nt,{children:o("common:modals.recordStory.descriptionLimitAi")})]}),R==="recording"&&e.jsxs("div",{className:"speech-to-text-recording-ui",children:[e.jsx(ir,{value:`${io(O)} / 15:00`}),I||!ce?e.jsx("img",{className:"wave-icon",src:eo,alt:"audio wave"}):e.jsx("img",{className:"wave-icon",src:to,alt:"audio wave animated"}),e.jsx(lr,{children:e.jsx("div",{className:me?"recording-control-disabled":"",onClick:me?()=>{}:I?()=>c():()=>ge(),children:I?e.jsx("img",{className:"recorder-control-icon",src:ro}):e.jsx("img",{className:"recorder-control-icon",src:so})})})]}),R==="uploading"&&e.jsxs("div",{className:"speech-to-text-uploading-ui",children:[e.jsx(dt,{children:e.jsx(nt,{variant:"P5/Regular",children:o("common:modals.recordingUpload.description")})}),e.jsx(Fe,{size:"large"})]})]}),A.length>0&&e.jsxs("div",{className:"audio-recordings-section",children:[e.jsx(lo,{className:"recordings-title",level:3,children:o("features:audio.title")}),e.jsx(mt,{className:"audio-print-inclusion-note",children:o("features:audio.printInclusionNote")}),A.length>=2&&e.jsxs("div",{className:"audio-print-inclusion-bulk",children:[e.jsx("button",{type:"button",disabled:Ne,onClick:()=>Xe(!0),children:o("features:audio.includeAll")}),e.jsx("span",{"aria-hidden":"true",children:"·"}),e.jsx("button",{type:"button",disabled:Ne,onClick:()=>Xe(!1),children:o("features:audio.excludeAll")})]}),e.jsx(Fe,{spinning:E||Ne,children:e.jsx("div",{className:"audio-recordings-list",children:A.map(h=>e.jsxs("div",{className:"audio-recording-card",children:[e.jsx("button",{type:"button",className:"audio-remove-btn",onMouseDown:()=>{pe(h.id),_e(!0)},children:e.jsx(Jt.FaRegTrashAlt,{})}),e.jsx("div",{className:"audio-title-wrapper",children:ue===h.id?e.jsxs(e.Fragment,{children:[e.jsx(rs,{size:"small",className:"audio-title-input",value:we,onChange:$=>f($.target.value),onPressEnter:()=>J(h.id,we),autoFocus:!0}),e.jsx(_s.FaSave,{onClick:()=>J(h.id,we),style:{cursor:"pointer"}})]}):e.jsxs(e.Fragment,{children:[e.jsx(mt,{strong:!0,children:h.title||"N/A"}),e.jsx(Qt.FaPencilAlt,{onClick:()=>He(h.id,h.title),style:{cursor:"pointer"}})]})}),e.jsx(dt,{className:"audio-recorded-on",children:o("features:audio.recordedOn",{date:js(h.createdAt).format("MMMM D, YYYY")})}),e.jsx(nt,{className:"audio-transcription",ellipsis:{rows:2,expandable:"collapsible",symbol
5:$=>o($?"common:cta.less":"common:cta.more")},children:h.transcriptionStatus&&h.transcriptionStatus!=="processed"?e.jsxs("span",{children:[e.jsx(Fe,{size:"small",style:{marginRight:8}}),o("common:modals.recordingUpload.description")]}):h.transcription}),e.jsxs("div",{className:"audio-player-wrapper",children:[e.jsx("audio",{src:h.presignedUrl,controls:!0,onPlay:x,onEnded:y,onPause:L},`audio-player-${h.id}`),e.jsx(bs.FaDownload,{className:"audio-download-btn",style:{cursor:"pointer"},onClick:()=>ao(h.presignedUrl,h.title)})]}),e.jsxs("div",{className:`audio-print-inclusion${h.includeInPrintedBook===!1?" is-off":""}`,children:[e.jsx(mt,{strong:!0,children:o("features:audio.includeInPrintedBook")}),e.jsx("button",{type:"button",className:`audio-print-inclusion-switch${h.includeInPrintedBook===!1?" is-off":""}`,role:"switch","aria-checked":h.includeInPrintedBook!==!1,"aria-label":o("features:audio.includeInPrintedBook"),disabled:Ne,onClick:()=>Ae(h),children:e.jsx("i",{})})]})]},h.id))})})]}),e.jsx(Be,{className:"recording-delete-modal",title:o("common:modals.recordingDelete.title"),open:Q,onCancel:ve,onOk:ie,okText:o("common:cta.delete"),cancelText:o("common:cta.cancel"),centered:!0})]})});hs.displayName="StoryAnswerSpeechToTextAi";function po(){return e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[e.jsx("path",{d:"M4.5 1 L5.5 3.5 L8 4.5 L5.5 5.5 L4.5 8 L3.5 5.5 L1 4.5 L3.5 3.5 Z"}),e.jsx("path",{d:"M15 4 L21 10 L10 21 L5 21 L5 16 Z"}),e.jsx("path",{d:"M13 6 L19 12"})]})}function mo(){return e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[e.jsx("circle",{cx:"12",cy:"12",r:"9.5"}),e.jsx("path",{d:"M7.5 12.5 L10.5 15.5 L16.5 9"})]})}function fo(){return e.jsxs("svg",{width:"38",height:"38",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[e.jsx("path",{d:"M4 5 a2 2 0 0 1 2 -2 h6 v17 h-6 a2 2 0 0 1 -2 -2 z"}),e.jsx("path",{d:"M20 5 a2 2 0 0 0 -2 -2 h-6 v17 h6 a2 2 0 0 0 2 -2 z"}),e.jsx("path",{d:"M8 8 h2"}),e.jsx("path",{d:"M8 11 h2"}),e.jsx("path",{d:"M14 8 h2"}),e.jsx("path",{d:"M14 11 h2"})]})}function go(){return e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:[e.jsx("circle",{cx:"11",cy:"11",r:"7"}),e.jsx("path",{d:"M16 16l4.5 4.5"})]})}const xo="data:image/svg+xml,%3csvg%20width='48'%20height='40'%20viewBox='0%200%2048%2040'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M27%204L28.35%209.65L34%2011L28.35%2012.35L27%2018L25.65%2012.35L20%2011L25.65%209.65L27%204Z'%20fill='%23815A4C'%20/%3e%3cpath%20d='M14%2010L14.9%2013.7L18.6%2014.6L14.9%2015.5L14%2019.2L13.1%2015.5L9.4%2014.6L13.1%2013.7L14%2010Z'%20fill='%23815A4C'%20opacity='0.85'%20/%3e%3cpath%20d='M22%2024L22.6%2026.4L25%2027L22.6%2027.6L22%2030L21.4%2027.6L19%2027L21.4%2026.4L22%2024Z'%20fill='%23815A4C'%20opacity='0.7'%20/%3e%3c/svg%3e",yo={tighten:"tightening",elaborate:"elaborating",warmer:"makingWarmer",lighter:"makingLighter",conversational:"makingConversational"};function wo(){const{t,isMobile:r,isOpen:s,handleTogglePanel:n}=us();return e.jsx(Oe,{title:r?t("features:aiEditor.title"):"",children:e.jsxs(oe,{variant:De,className:Ue("story-answer-ai-editor__toolbar-btn",{"story-answer-ai-editor__toolbar-btn--active":s,"story-answer-ai-editor__toolbar-btn--icon-only":r}),onClick:n,"aria-label":t("features:aiEditor.title"),children:[e.jsx(po,{}),!r&&t("features:aiEditor.title")]})})}function Gt(){const{t,isMobile:r,isOpen:s,mode:n,fixState:o,corrections:l,reviewedCount:m,highlightedId:g,fixError:p,styleDirection:E,styleState:_,styleRewrite:A,styleScope:C,styleError:D,canRunAiEdit:M,hasFrozenSelection:R,setHighlightedId:B,handleModeSwitch:ce,handleStyleScopeChange:X,runFixErrors:I,acceptCorrection:de,skipCorrection:O,acceptAllCorrections:ne,runStyleRewrite:ue,a
5pplyStyleRewrite:xe,discardStyleRewrite:we,tryAnotherDirection:f,onCardTap:Q,requestClose:_e}=us();if(!s)return null;const Y=e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"story-answer-ai-editor__modes",children:[e.jsx("button",{type:"button",className:Ue("story-answer-ai-editor__mode-tab",{active:n===Te.ERRORS}),onClick:()=>ce(Te.ERRORS),children:t("features:aiEditor.fixErrors")}),e.jsx("button",{type:"button",className:Ue("story-answer-ai-editor__mode-tab",{active:n===Te.STYLE}),onClick:()=>ce(Te.STYLE),children:t("features:aiEditor.adjustStyle")})]}),e.jsxs("div",{className:"story-answer-ai-editor__body",children:[n===Te.ERRORS&&e.jsx(vo,{t,canRunAiEdit:M,fixState:o,corrections:l,reviewedCount:m,fixError:p,highlightedId:g,onHighlight:B,onRun:I,onAccept:de,onSkip:O,onAcceptAll:ne,onCardTap:Q,onRetry:I}),n===Te.STYLE&&e.jsx(_o,{t,canRunAiEdit:M,hasFrozenSelection:R,styleState:_,styleDirection:E,styleScope:C,styleRewrite:A,styleError:D,onScopeChange:X,onPickDirection:ue,onRetry:()=>E&&ue(E)})]}),n===Te.ERRORS&&["idle","loading","noIssues","notAStory","done"].includes(o)&&e.jsxs("div",{className:"story-answer-ai-editor__footer",children:[o==="idle"&&e.jsx(Oe,{title:M?"":t("features:aiEditor.writeAtLeastASentence"),children:e.jsx("span",{className:"story-answer-ai-editor__footer-btn-wrap",children:e.jsx(oe,{disabled:!M,onClick:I,children:t("features:aiEditor.findErrors")})})}),o==="loading"&&e.jsx(oe,{disabled:!0,loading:!0,children:t("features:aiEditor.analyzing")}),(o==="noIssues"||o==="notAStory")&&e.jsx(oe,{variant:De,onClick:I,children:t("features:aiEditor.runAgain")}),o==="done"&&e.jsx(oe,{variant:De,onClick:I,children:t("features:aiEditor.findErrorsAgain")})]}),n===Te.STYLE&&_==="notAStory"&&e.jsx("div",{className:"story-answer-ai-editor__footer",children:e.jsx(oe,{variant:De,onClick:()=>E&&ue(E),children:t("features:aiEditor.runAgain")})}),n===Te.STYLE&&_==="result"&&e.jsxs("div",{className:"story-answer-ai-editor__footer story-answer-ai-editor__footer--stacked",children:[e.jsx(oe,{onClick:xe,children:t("features:aiEditor.useVersion")}),e.jsx(oe,{variant:De,onClick:f,children:t("features:aiEditor.tryAnother")}),e.jsx("button",{type:"button",className:"story-answer-ai-editor__link-btn",onClick:we,children:t("features:aiEditor.discard")})]})]}),pe=e.jsxs("aside",{className:"story-answer-ai-editor__panel",children:[e.jsxs("div",{className:"story-answer-ai-editor__head",children:[e.jsx("span",{className:"story-answer-ai-editor__title",children:t("features:aiEditor.title")}),e.jsx("button",{type:"button",className:"story-answer-ai-editor__close",onClick:_e,"aria-label":t("common:cta.close"),children:"×"})]}),Y]});return e.jsx(e.Fragment,{children:r?e.jsx("div",{className:"story-answer-ai-editor__sheet-backdrop",onClick:_e,children:e.jsxs("div",{className:"story-answer-ai-editor__sheet",onClick:me=>me.stopPropagation(),children:[e.jsx("div",{className:"story-answer-ai-editor__sheet-handle"}),e.jsxs("div",{className:"story-answer-ai-editor__head",children:[e.jsx("span",{className:"story-answer-ai-editor__title",children:t("features:aiEditor.title")}),e.jsx("button",{type:"button",className:"story-answer-ai-editor__close",onClick:_e,"aria-label":t("common:cta.close"),children:"×"})]}),Y]})}):pe})}function Xt({t}){return e.jsxs("div",{className:"story-answer-ai-editor__scope-note story-answer-ai-editor__scope-note--locked",children:[e.jsx("span",{className:"story-answer-ai-editor__scope-
5dot"}),e.jsx("span",{dangerouslySetInnerHTML:{__html:t("features:aiEditor.fixErrorsScope")}})]})}function ps({t}){return e.jsxs("div",{className:"story-answer-ai-editor__done",children:[e.jsx("div",{className:"story-answer-ai-editor__done-icon story-answer-ai-editor__done-icon--book",children:e.jsx(fo,{})}),e.jsx("h3",{children:t("features:aiEditor.notAStoryTitle")}),e.jsx("p",{children:t("features:aiEditor.notAStoryMessage")})]})}function vo({t,canRunAiEdit:r,fixState:s,corrections:n,reviewedCount:o,fixError:l,highlightedId:m,onHighlight:g,onRun:p,onAccept:E,onSkip:_,onAcceptAll:A,onCardTap:C,onRetry:D}){return s==="idle"?e.jsxs(e.Fragment,{children:[e.jsx(Xt,{t}),e.jsxs("div",{className:"story-answer-ai-editor__empty",children:[e.jsx("div",{className:"story-answer-ai-editor__empty-icon",children:e.jsx(go,{})}),e.jsx("p",{dangerouslySetInnerHTML:{__html:t("features:aiEditor.fixErrorsHint")}})]})]}):s==="loading"?e.jsxs(e.Fragment,{children:[e.jsx(Xt,{t}),e.jsxs("div",{className:"story-answer-ai-editor__loading",children:[e.jsx(Fe,{}),e.jsx("p",{children:t("features:aiEditor.reviewing")})]})]}):s==="error"?e.jsxs("div",{className:"story-answer-ai-editor__error",children:[e.jsx("p",{children:ds(l==null?void 0:l.errorKey,l==null?void 0:l.params,t)}),e.jsx("button",{type:"button",className:"story-answer-ai-editor__link-btn",onClick:D,children:t("features:aiEditor.retry")})]}):s==="notAStory"?e.jsx(ps,{t}):s==="noIssues"?e.jsxs("div",{className:"story-answer-ai-editor__done",children:[e.jsx("div",{className:"story-answer-ai-editor__done-icon story-answer-ai-editor__done-icon--check",children:e.jsx(mo,{})}),e.jsx("h3",{children:t("features:aiEditor.noIssuesTitle")}),e.jsx("p",{children:t("features:aiEditor.noIssuesMessage")})]}):s==="done"?e.jsxs("div",{className:"story-answer-ai-editor__done",children:[e.jsx("div",{className:"story-answer-ai-editor__done-icon",children:e.jsx("img",{src:xo,alt:"","aria-hidden":!0})}),e.jsx("h3",{children:t("features:aiEditor.allDoneTitle")}),e.jsx("p",{children:t("features:aiEditor.allDoneMessage",{count:o})})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"story-answer-ai-editor__progress",children:[e.jsx("span",{dangerouslySetInnerHTML:{__html:t("features:aiEditor.remaining",{remaining:n.length,total:n.length+o})}}),n.length>0&&e.jsx("button",{type:"button",className:"story-answer-ai-editor__link-btn",onClick:A,children:t("features:aiEditor.acceptAll")})]}),n.map(M=>e.jsxs("div",{className:Ue("story-answer-ai-editor__card",{highlighted:m===M.id}),onMouseEnter:()=>g(M.id),onMouseLeave:()=>g(null),onClick:()=>C(M),children:[e.jsx("span",{className:`story-answer-ai-editor__badge story-answer-ai-editor__badge--${M.type}`,children:M.type}),e.jsx("div",{className:Ue("story-answer-ai-editor__card-from",`story-answer-ai-editor__card-from--${M.type}`),children:`"${M.original}"`}),e.jsx("div",{className:"story-answer-ai-editor__card-arrow",children:"↓"}),e.jsx("div",{className:"story-answer-ai-editor__card-to",children:`"${M.corrected}"`}),M.explanation&&e.jsx("div",{className:"story-answer-ai-editor__card-explain",children:M.explanation}),e.jsxs("div",{className:"story-answer-ai-editor__card-actions",children:[e.jsx(oe,{onClick:R=>{R.stopPropagation(),E(M)},children:t("features:aiEditor.accept")}),e.jsx(oe,{variant:De,onClick:R=>{R.stopPropagation(),_(M)},children:t("features:aiEditor.skip")})]})]},M.id))]})}function _o({t,canRunAiEdit:r,hasFrozenSelection:s,styleState:n,styleDirection:o,styleScope:l,styleRewrite:m,styleError:g,onScopeChange:p,onPickDirection:E,onRetry:_}){const A=t(l==="selection"?"features:aiEditor.scopeSelection":"features:aiEditor.scopeWholeStory"),C=n==="result"&&o?t(`features:aiEditor.styleResultScope.${o}`,{scope:A}):null;return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"story-answer-ai-editor__section-label",children:t("features:aiEditor.rewriteLabel")}),e.jsxs("div",{className:"story-answer-ai-editor__scope-pick",children:[e.jsx(Oe,{title:s?"":t("features:aiEditor.selectTextFirst"),children:e.jsx("span",{className:"story-answer-ai-editor__scope-btn-wrap",children:e.jsx("button",{type:"button",className:Ue("story-answer-ai-editor__scope-btn",{active:l==="selection",disabled:!s}
5),disabled:!s,onClick:()=>p("selection"),children:t("features:aiEditor.scopeSelectionLabel")})})}),e.jsx("button",{type:"button",className:Ue("story-answer-ai-editor__scope-btn",{active:l==="whole_story"}),onClick:()=>p("whole_story"),children:t("features:aiEditor.scopeWholeStoryLabel")})]}),e.jsx("div",{className:"story-answer-ai-editor__section-label",children:t("features:aiEditor.directionLabel")}),e.jsx("div",{className:"story-answer-ai-editor__chips",children:Lr.map(D=>e.jsx(Oe,{title:r?"":t("features:aiEditor.writeAtLeastASentence"),children:e.jsx("button",{type:"button",disabled:!r||n==="loading",className:Ue("story-answer-ai-editor__chip",{active:o===D}),onClick:()=>E(D),children:t(`features:aiEditor.directions.${D}`)})},D))}),n==="idle"&&e.jsx("p",{className:"story-answer-ai-editor__hint",children:t("features:aiEditor.styleHint")}),n==="loading"&&e.jsxs("div",{className:"story-answer-ai-editor__loading",children:[e.jsx(Fe,{}),e.jsx("p",{children:t(`features:aiEditor.loading.${yo[o]}`)})]}),n==="error"&&e.jsxs("div",{className:"story-answer-ai-editor__error",children:[e.jsx("p",{children:ds(g==null?void 0:g.errorKey,g==null?void 0:g.params,t)}),e.jsx("button",{type:"button",className:"story-answer-ai-editor__link-btn",onClick:_,children:t("features:aiEditor.retry")})]}),n==="notAStory"&&e.jsx(ps,{t}),n==="result"&&m&&e.jsxs(e.Fragment,{children:[C&&e.jsx("div",{className:"story-answer-ai-editor__result-heading",dangerouslySetInnerHTML:{__html:C}}),e.jsx("div",{className:"story-answer-ai-editor__rewrite",children:m})]})]})}const jo=()=>a.useMemo(()=>vr(Bs($s(zs()))),[]),ms=a.forwardRef(({value:t,onChange:r,status:s,bookId:n,questionId:o,onImageUpload:l,questionTitle:m,onQuestionTitleChange:g,formattingToolbarPortalEl:p,onAiPanelOpenChange:E},_)=>{var ge,Se;const{t:A,i18n:C}=$e(),D=((ge=ss[C.language])==null?void 0:ge.rtl)??!1,M=a.useRef(),{userDetails:R}=ct(({AuthReducer:i})=>i),[B,ce]=a.useState(!1),[X,I]=a.useState(!1),[de,O]=a.useState(!1),[ne,ue]=a.useState(!1),[xe,we]=a.useState([]),f=jo(),Q=Ge();a.useEffect(()=>{E==null||E(ne)},[ne,E]);const _e=Ss(kt(Hs,{activationConstraint:{distance:5}}),kt(Ws,{activationConstraint:{delay:250,tolerance:5}}));a.useEffect(()=>{"MediaRecorder"in window&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window)&&ce(!0)},[]),a.useEffect(()=>{if(!R)return;const i=new Date("2025-07-28T00:00:00.000+00:00"),c=new Date(R.createdAt);!Qs("is_new_editor_draft_popup_shown")&&c<i&&(er("is_new_editor_draft_popup_shown",!0),I(!0))},[R]);const Y=a.useMemo(()=>(s!=="new"&&O(!0),t.map(i=>i.kind==="image"?{id:i.id||Ce(),type:"image",url:i.image.url,public_id:i.image.public_id,fileName:i.image.fileName,caption:i.image.caption||"",width:i.image.width||"75%",...i.image.rotation?{rotation:i.image.rotation}:{},children:[{text:""}]}:i.kind==="imageRow"?{id:i.id||Ce(),type:"imageRow",caption:i.caption||"",images:(i.images||[]).map(c=>({url:c.url,public_id:c.public_id,fileName:c.fileName,width:c.width,...c.rotation?{rotation:c.rotation}:{}})),children:[{text:""}]}:i.kind==="paragraph"&&!i.children.length?{id:i.id||Ce(),type:"paragraph",children:[{text:i.text||""}],align:i.align}:{id:i.id||Ce(),type:"paragraph",children:i.children,align:i.align})),[t]),[pe,me]=a.useState(null),ee=a.useRef(null),fe=a.useCallback(()=>{const i=ee.current;if(!i)return;const c=f.children.findIndex(u=>u.id===i.id);c>=0&&H.removeNodes(f,{at:[c]}),URL.revokeObjectURL(i.objectUrl),ee.current=null},[f]),be=a.useCallback(i=>{fe();const c=URL.createObjectURL(i),u=Ce();ee.current={id:u,objectUrl:c},H.insertNodes(f,{id:u,type:"image",pending:!0,url:c,public_id:"",fileName:i.name||"",caption:"",width:"75%",children:[{text:""}]}),f.next()||H.insertNodes(f,{id:Ce(),type:"paragraph",children:[{text:""}]})},[fe,f]),Ne=a.useCallback(i=>{const c=ee.current;if(c){const u=f.children.findIndex(J=>J.id===c.id);if(u>=0){H.setNodes(f,{pending:!1,url:i.url,public_id:i.public_id,fileName:i.fileName,caption:i.caption||""},{at:[u]}),URL.revokeObjectURL(c.objectUrl),ee.current=null;return}URL.revokeObjectURL(c.objectUrl),ee.current=null}H.insertNodes(f,{id:Ce(),type:"image",url:i.url,public_id:i.public_id,fileName:i.fileName,caption:i.caption||"",width:"75%",children:[{text:""}]}),f.next()||H.insertNodes(f,{id:Ce(),type:"paragraph",children:[{text:""}]})},[f]);a.useEffect(()=>()=>{var i;(i=ee.current)!=null&&i.objectUrl&&URL.revokeObjectURL(ee.current.objectUrl)},[]);const je=i=>{H.insertNodes(f,{id:Ce(),type:"paragraph",children:[{text:i}]},{at:[f.children.length]}),setTimeout(()=>{const c=document.getElementById("story-editor-content");
5if(c){const u=c.getBoundingClientRect(),ie=(window.scrollY||window.pageYOffset)+u.bottom-window.innerHeight+20;window.scrollTo({top:ie,behavior:"smooth"})}})},ae=i=>{var c;(c=ee.current)!=null&&c.objectUrl&&(URL.revokeObjectURL(ee.current.objectUrl),ee.current=null);for(let u=i.children.length-1;u>=0;u--)H.removeNodes(i,{at:[u]})};a.useImperativeHandle(_,()=>({handleImageUploadStart:be,handleImageUploaded:Ne,handleImageUploadError:fe,clearEditorValue:()=>ae(f)}));const z=i=>{r(i.filter(c=>!(c.type==="image"&&c.pending)).map(c=>c.type==="image"?{kind:"image",image:{url:c.url,public_id:c.public_id,fileName:c.fileName,caption:c.caption,width:c.width,...c.rotation?{rotation:c.rotation}:{}}}:c.type==="imageRow"?{kind:"imageRow",caption:c.caption||"",images:(c.images||[]).map(u=>({url:u.url,public_id:u.public_id,fileName:u.fileName,width:u.width,...u.rotation?{rotation:u.rotation}:{}}))}:{kind:"paragraph",children:c.children,text:ze.isElement(c)?c.children.map(u=>u.text).join(""):"",align:c.align})),O(i.some(c=>c.type==="paragraph"?c.children.some(u=>u.text.trim().length>0):!1))},ke=i=>{var c;(c=i.active)!=null&&c.id&&(Re.blur(f),me(i.active.id))},w=i=>{const{active:c,over:u}=i;if(c.id===(u==null?void 0:u.id)){me(null);return}const J=f.children.findIndex(ve=>!ve||!u?!1:ve.id===u.id),ie=c.id;J>=0&&H.moveNodes(f,{at:[],match:ve=>ve.id===ie,to:[J]}),me(null)},b=(i,c,u)=>{S(i,c)?i.removeMark(c):i.addMark(c,!0)},S=(i,c)=>{const u=i.getMarks();return u?u[c]===!0:!1},j=(i,c)=>{const{selection:u}=i;if(!u)return;const[J]=Array.from(We.nodes(i,{at:u,match:ie=>ze.isElement(ie)&&ie.type==="paragraph"}));if(J){const[ie]=J,ve=ie.align||"left";if(c==="left")H.setNodes(i,{align:void 0},{at:u,match:Ee=>ze.isElement(Ee)&&Ee.type==="paragraph"});else{const Ee=ve===c?void 0:c;H.setNodes(i,{align:Ee},{at:u,match:He=>ze.isElement(He)&&He.type==="paragraph"})}}},x=(i,c)=>{const{selection:u}=i;if(!u)return!1;const[J]=Array.from(We.nodes(i,{at:u,match:ie=>ze.isElement(ie)&&ie.type==="paragraph"}));if(J){const[ie]=J;return(ie.align||"left")===c}return!1},y=i=>{const{selection:c}=f;if(!c)return;const[u]=Ve.edges(c);if(i.key==="Backspace"&&Ve.isCollapsed(c)&&We.isStart(f,u,u.path)){const J=We.above(f,{match:Ee=>ze.isElement(Ee),at:u});if(!J)return;const[,ie]=J,ve=We.previous(f,{at:ie});ve&&ze.isElement(ve[0])&&(ve[0].type==="image"||ve[0].type==="imageRow")&&i.preventDefault()}},L=()=>{M.current.handleRunSpeechToText()},U=a.useCallback(([i,c])=>Es.isText(i)?xe.map(u=>{const{anchor:J,focus:ie,...ve}=u,Ee=Ve.intersection({anchor:J,focus:ie},{anchor:{path:c,offset:0},focus:{path:c,offset:i.text.length}});return Ee?{...Ee,...ve}:null}).filter(Boolean):[],[xe]),T={editor:f,bookId:n,questionId:o,isMobile:Q,isOpen:ne,onOpenChange:ue,onDecorationsChange:we},q=ne&&!Q,te=pe&&f.children.find(i=>i.id===pe),ye={bookId:n,teamId:(Se=R==null?void 0:R.defaultTeam)==null?void 0:Se._id,questionTitle:m,maxImages:wt,currentImages:yt(t)};return e.jsx(e.Fragment,{children:t.length?e.jsx(Gr,{...T,children:e.jsxs(ns.Provider,{value:ye,children:[e.jsx("div",{className:"story-editor-body",children:e.jsxs("div",{className:"story-editor-main-column",children:[g&&e.jsxs(e.Fragment,{children:[e.jsx(rs.TextArea,{className:"question-title-input",value:m,onChange:i=>g(i.target.value),autoSize:{minRows:1,maxRows:5},placeholder:A("common:inputs.question.placeholder"),maxLength:100}),e.jsx(cr,{className:"divider"})]}),e.jsx("div",{className:"story-section",children:e.jsxs(Rs,{editor:f,initialValue:Y,onChange:z,children:[(()=>{var c;const i=e.jsxs("div",{className:"toolbar",children:[e.jsxs("div",{className:"toolbar-formatting",children:[e.jsx(oe,{onMouseDown:u=>{u.preventDefault(),b(f,"bold")},children:e.jsx(Ns.FaBold,{})}),e.jsx(oe,{onMouseDown:u=>{u.preventDefault(),b(f,"italic")},children:e.jsx(ks.FaItalic,{})}),e.jsx(oe,{onMouseDown:u=>{u.preventDefault(),b(f,"underline")},children:e.jsx(Cs.FaUnderline,{})}),e.jsx("div",{className:"toolbar-formatting-divider"}),!Ge()&&e.jsx(oe,{onMouseDown:u=>{u.preventDefault(),j(f,"left")},className:x(f,"left")?"active":"",children:e.jsx("span",{className:"toolbar-icon-align-left",children:e.jsx(Ts.FaAlignLeft,{})})}),!Ge()&&e.jsx(oe,{onMouseDown:u=>{u.preventDefault(),j(f,"center")},className:x(f,"center")?"active":"",children:e.jsx(As.FaAlignCenter,{})}),!Ge()&&e.jsx("div",{className:"toolbar-formatting-divider"}),e.jsx(oe,{disabled:f.history.undos.length===0,onMouseDown:u=>{u.preventDefault(),Ct.undo(f)},children:e.jsx(Ls.FaUndo,{})}),!Ge()&&e.jsx(oe,{disabled:f.history.redos.length===0,onMouseDown:u=>{u.preventDefault(),Ct.redo(f)},children:e.jsx(Is.FaRedo,{})})]}),e.jsxs("div",{className:"toolbar-photo-record-container",children:[!Q&&e.jsx(_t,{maxImages:wt,currentImages:yt(t),bookId:n,teamId:(c=R==null?void 0:R.defaultTeam)==null?void 0:c._id,onImageUpload:l,onUploadStart:be,onUploadError:fe,questionTitle:m,children:A("common:cta.addPhoto")}),e.jsx(Oe,{title:B?"":A("features:audio.notSupported"),mouseEnterDelay:.1,placement:"top",trigger:["hover"],children:e.jsx("span",{children:e.jsxs(oe,{disabled:!B,variant:De,className:B?"":"speech-to-text-btn-disabled",onClick:u=>L(),children:[e.jsx(Ps.FaMicrophone,{}),!Q&&e.jsx(e.Fragment,{children:A("features:audio.ctaRecord")})]})})}),e.jsx(wo,{})]})]});return p?Tt.createPortal(i,p):i})(),e.jsxs(Ms,{sensors:_e,onDragStart:ke,onDragEnd:w,children:[e.jsx(Ds,{items:f.children.map(i=>i.id),strategy:Os,children:e.jsxs("div",{id:"story-editor-content",className:`answer-input-wrapper${D?" answer-input-wrapper--rtl":""}`,dir:D?"rtl":"ltr",children:[e.jsx(Qt.FaPencilAlt,{style:{display:de?"none":"block"}}),e.jsx(Us,{className:`editor${D?" editor--rtl":""}`,dir:D?"rtl":"ltr",decorate:U,style:D?{direction:"rtl",textAlign:"right"}:void 0,spellCheck:!ne,placeholder:A("common:inputs.answer.placeholderAudio"),renderElement:i=>{const u=Re.findPath(f,i.element).length===1,J=e.jsx(Ht,{...i,isRtl:D});return u?e.jsx(Qr,{...i,renderElement:ie=>e.jsx(Ht,{...ie,isRtl:D})}):J},renderLeaf:i=>e.jsx(Jr,{...i}),onKeyDown:i=>y(i)})]})}),Tt.createPortal(e.jsx(Fs,{adjustScale:!1,children:te&&e.jsx("div",{className:"drag-overlay",children:" "})}),document.body)]})]})})]})}),q&&e.jsx(Gt,{}),Q&&e.jsx(Gt,{}),e.jsx(hs,{ref:M,bookId:n,questionId:o,onTrascriptionReady:je}),e.jsx(Be,{className:"new-editor-modal",title:A("common:modals.newEditor.title"),open:X,width:600,onCancel:()=>I(!1),centered:!0,getContainer:!1,modalRender:i=>e.jsx("div",{id:"new-editor-popup",children:i}),footer:[e.jsx(oe,{id:"new-editor-done-button",type:"primary",onClick:()=>I(!1),children:A("common:cta:close")},"done")],children:e.jsx(dt.Text,{variant:"P4/Regular",children:A("common:modals.newEditor.description")})})]})}):e.jsx(e.Fragment,{})})});ms.displayName="StoryAnswerEditor";const bo=(t,r=1e3,s=[])=>{const n=a.useRef();a.useEffect(()=>{n.current=t},[t]),a.useEffect(()=>{function o(){n.current()}if(typeof r=="number"){let l=setInterval(o,r);return()=>clearInterval(l)}},[r,...s])},fs=81,So=fs,Io=()=>{var V;const{t,i18n:r}=$e(),s=Ge(),n=a.useRef(),[o,l]=a.useState(null),[m,g]=a.useState(!1),p=a.useRef(null),E=a.useRef(null),_=a.useRef(0),A=a.useRef(!1),[C,D]=a.use
5State(!1),[M,R]=a.useState(""),[B,ce]=a.useState(""),[X,I]=a.useState([]),[de,O]=a.useState(!1),[ne,ue]=a.useState(!1),[xe,we]=a.useState(0),{userDetails:f}=ct(({AuthReducer:d})=>d),Q=ct(tr.analyticsContextSelector),_e=qs(),{questionId:Y}=Vs(),[pe,me]=a.useState(!1),[ee,fe]=a.useState(!1),[be,Ne]=a.useState(!1),[je,ae]=a.useState(!1),[z,ke]=a.useState(null),[w,b]=a.useState(!1),S=vt(),{showMessage:j}=nr(),x=a.useMemo(()=>{var k,W,se,v;const d=(W=(k=f==null?void 0:f.defaultTeam)==null?void 0:k.books)==null?void 0:W.flatMap(N=>N.questions).find(N=>N._id===Y);if(!d)_e.push(ts.DASHBOARD);else if(d&&(!d.answer||!d.answer.length))d.answer=[{kind:"paragraph",children:[{text:""}]}];else{const N=[];for(let P=0;P<d.answer.length;P++)N.push({...d.answer[P]}),(d.answer[P].kind==="image"||d.answer[P].kind==="imageRow")&&(P===d.answer.length-1||((se=d.answer[P+1])==null?void 0:se.kind)==="image"||((v=d.answer[P+1])==null?void 0:v.kind)==="imageRow")&&N.push({kind:"paragraph",text:"",children:[{text:""}]});d.answer=N}return d},[f,Y]),y=a.useMemo(()=>{var d,k,W;return(W=(k=(d=f==null?void 0:f.defaultTeam)==null?void 0:d.books)==null?void 0:k.find(se=>se.questions.some(v=>v._id===Y)))==null?void 0:W._id},[f,Y]),[L,,,U]=Gs({bookId:y,questionId:Y,source:"story_editor"}),T=()=>`story-editor-${y}-${Y}`,q=(d,k)=>{if(typeof window>"u"||!window.localStorage)return console.warn("[story-editor] localStorage is not available. Skipping save."),!1;const W=JSON.stringify(k),se=()=>{try{return localStorage.setItem(d,W),!0}catch(F){if(((F==null?void 0:F.message)||"").toLowerCase().includes("exceeded the quota"))return!1;throw F}};try{if(se())return!0}catch(F){throw F}const v=`story-editor-${y}-`,N=[];for(let F=0;F<localStorage.length;F++){const K=localStorage.key(F);if(K&&K.startsWith(v)&&K!==d)try{const Z=localStorage.getItem(K);if(Z){const G=JSON.parse(Z);N.push({key:K,savedAt:G.savedAt?new Date(G.savedAt).getTime():0})}}catch{N.push({key:K,savedAt:0})}}N.sort((F,K)=>F.savedAt-K.savedAt);for(const{key:F}of N){localStorage.removeItem(F);try{if(se())return!0}catch(K){throw K}}const P=[];for(let F=0;F<localStorage.length;F++){const K=localStorage.key(F);if(K&&K.startsWith("story-editor-")&&K!==d)try{const Z=localStorage.getItem(K);if(Z){const G=JSON.parse(Z);P.push({key:K,savedAt:G.savedAt?new Date(G.savedAt).getTime():0})}}catch{P.push({key:K,savedAt:0})}}P.sort((F,K)=>F.savedAt-K.savedAt);for(const{key:F}of P){localStorage.removeItem(F);try{if(se())return!0}catch(K){throw K}}return console.warn("[story-editor] Unable to save to localStorage after clearing all story entries. Skipping localStorage save."),!1},te=async()=>{if(yr({questionTitle:B,selectedQuestion:x,answerList:i(X)}))try{await Ie("question/delete",{bookId:y,questionId:Y}),S(or()),localStorage.removeItem(T()),re("story_editor","empty_blank_story_deleted",Q)}catch(d){console.error("[story-editor] failed to delete empty blank story:",d.message||d)}S(Zt("/")),re("story_editor","back_to_dashboard",{...Q,questionStoryType:tt(x)}),xe>0&&re("story_editor","story_autosave_count",{...Q,count:xe,questionStoryType:tt(x)})},ye=()=>{je?O(!0):te()},ge=async d=>{await u(!1,d),await te()},Se=d=>{ce(d)},i=d=>d.map(k=>k.kind==="paragraph"&&!k.children.length?{...k,children:[{text:k.text||""}]}:{...k}),c=async()=>{var P,F,K,Z;if(!je)return;const d=At(f)?"buyer":"recipient",k=Lt(f)?"other":"self",W=i(X),se=Qe(W),v={bookId:y,questionId:Y,title:B,answer:se?[...W]:[],isDraft:!!se},N=!ft(x)&&!gt(x)?"story_created":v.isDraft?"draft_saved":"story_completed";se&&re("story_editor",N,{...Q,questionStoryType:tt(x),questionTitle:x.title,questionNewTitle:B,source:"editor",mode:"auto",userRole:d,appUsageMode:k});try{const G=await Ie("question/update",v);S(ht(G.data)),we(Pe=>Pe+1)}catch(G){const Pe=((F=(P=G.response)==null?void 0:P.data)==null?void 0:F.message)??(typeof((K=G.response)==null?void 0:K.data)=="string"?G.response.data:void 0);re("story_editor","story_autosave_error",{error:G.message||String(G),...G.code&&{errorCode:G.code},...G.response&&{status:G.response.status,statusText:G.response.statusText,...Pe&&{serverMessage:Pe}},hasResponse:!!G.response,hasRequest:!!G.request}),console.error("[story-editor] autosave error:",G.message||G),((Z=G.response)==null?void 0:Z.status)===401&&(re("story_editor","show_token_expired_modal"),D(!0))}},u=async(d=!1,k=!1)=>{var K;ue(!1);const W=At(f)?"buyer":"recipient",se=Lt(f)?"other":"self",v=ft(x)||gt(x)?k?"draft_saved":"story_completed":"story_created";me(!0);const N=i(X),P=Qe(N);P&&re("story_editor",v,{...Q,questionStoryType:tt(x),questionTitle:x.title,questionNewTitle:B,source:"editor",userRole:W,mode:"manual",appUsageMode:se});const F={bookId:y,questionId:Y,title:B,answer:P?[...N]:[],isDraft:k};try{const Z=await Ie("question/update",F);S(ht(Z.data));const G={title:B,answer:X,isDraft:k,savedAt:new Date};d||j(t("features:story.pages.home.notifications.storySaved")),ke(G),q(T(),G)}catch(Z){((Z==null?void 0:Z.message)||"").toLowerCase().includes("skipping localstorage save")||(re("story_editor","story_save_error",{error:Z.message||Z}),console.error("[story-editor] save error:",Z.message||Z),((K=Z.response)==null?void 0:K.status)===401&&(re("story_editor","show_token_expired_modal"),D(!0)))}re("story_editor","save_success",{...Q,questionStoryType:tt(x),questionTitle:x.title,questionNewTitle:B}),me(!1)},J=d=>{n.current.handleImageUploaded(d)},ie=d=>{var k,W;(W=(k=n.current).handleImageUploadStart)==null||W.call(k,d)},ve=()=>{var d,k;(k=(d=n.current).handleImageUploadError)==null||k.call(d)},Ee=async()=>{Ne(!1),fe(!0),je&&await u(!0,!0),fe(!1),U()},He=()=>{const d=i(X);Qe(d)?ue(!0):u(!1,!1)},et=()=>{re("story_editor","restore_last_saved_click",{...Q,bookId:y,questionId:Y}),Ne(!1),z&&b(!0)},Xe=async()=>{me(!0),ce(z.title),I(z.answer);
5const d=i(z.answer),k=Qe(d);try{const W={bookId:y,questionId:Y,title:z.title,answer:k?[...d]:[],isDraft:z.isDraft},se=await Ie("question/update",W);S(ht(se.data)),j(t("features:story.pages.home.notifications.storyRestored")),re("story_editor","restore_last_saved_success",{...Q,bookId:y,questionId:Y}),k&&n.current.clearEditorValue()}catch(W){console.error("[story-editor] restore error:",W.message||W)}finally{me(!1),b(!1)}};a.useEffect(()=>{sr("story_editor",{...Q,language:r.language}),rr()},[Q]),a.useEffect(()=>{if(!x)return;ce(x.title);const d=x.answer;d&&d.length>0?I(d):I([{kind:"paragraph",children:[{text:""}]}]),ae(It(x,d,B))},[x]),a.useEffect(()=>{x&&ae(It(x,X,B))},[X,B]),bo(()=>{c()},30*1e3),a.useEffect(()=>{if(!y||!Y)return;const d=localStorage.getItem(T());if(d)try{const k=JSON.parse(d);ke({...k,savedAt:k.savedAt?new Date(k.savedAt):null})}catch(k){console.error("Failed to parse lastSavedVersion from localStorage:",k)}},[y,Y]),a.useEffect(()=>{if(!s)return;const d=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=d}},[s]),a.useEffect(()=>{if(s)return document.body.classList.add("story-editor-page-mobile"),document.body.style.setProperty("--story-editor-site-header-hide-progress","0"),_.current=0,A.current=!1,()=>{document.body.classList.remove("story-editor-page-mobile"),document.body.classList.remove("story-editor-site-header-fully-collapsed"),document.body.style.removeProperty("--story-editor-site-header-hide-progress")}},[s]);const Ae=a.useCallback(()=>{const d=p.current,k=E.current;if(!d||!k)return;const W=document.querySelector(".page-wrapper-outer.header-outer"),se=W?Math.ceil(W.getBoundingClientRect().bottom):0,v=Math.ceil(k.getBoundingClientRect().bottom),N=Math.max(se,v);d.style.setProperty("--story-editor-ai-panel-top",`${N}px`)},[]);a.useLayoutEffect(()=>{var W;if(s||!m){(W=p.current)==null||W.style.removeProperty("--story-editor-ai-panel-top");return}Ae(),window.addEventListener("scroll",Ae,{passive:!0,capture:!0}),window.addEventListener("resize",Ae);const d=new ResizeObserver(Ae);E.current&&d.observe(E.current);const k=requestAnimationFrame(Ae);return()=>{var se;cancelAnimationFrame(k),window.removeEventListener("scroll",Ae,!0),window.removeEventListener("resize",Ae),d.disconnect(),(se=p.current)==null||se.style.removeProperty("--story-editor-ai-panel-top")}},[m,s,Ae]);const h=a.useCallback(()=>{const d=p.current;if(!d||typeof window>"u")return;const k=window.visualViewport,W=k&&Math.max(0,window.innerHeight-k.height)>72,se=_.current,v=W?0:fs*(1-se);if(k){const N=Math.max(96,k.height-v);d.style.setProperty("top",`${k.offsetTop+v}px`),d.style.setProperty("left",`${k.offsetLeft}px`),d.style.setProperty("width",`${k.width}px`),d.style.setProperty("height",`${N}px`),d.style.setProperty("bottom","auto")}else d.style.setProperty("top",`${v}px`),d.style.setProperty("left","0"),d.style.setProperty("width","100%"),d.style.removeProperty("height"),d.style.setProperty("bottom","0")},[]);a.useLayoutEffect(()=>{if(!s)return;const d=window.visualViewport;return h(),d&&(d.addEventListener("resize",h),d.addEventListener("scroll",h)),window.addEventListener("resize",h),()=>{d&&(d.removeEventListener("resize",h),d.removeEventListener("scroll",h)),window.removeEventListener("resize",h);const k=p.current;k&&["top","left","width","height","bottom"].forEach(W=>{k.style.removeProperty(W)})}},[s,h]);const $=a.useCallback(d=>{if(!s)return;const k=d.currentTarget.scrollTop,W=Math.min(1,Math.max(0,k/So));_.current=W,document.body.style.setProperty("--story-editor-site-header-hide-progress",String(W));const se=W>=1;se!==A.current&&(A.current=se,document.body.classList.toggle("story-editor-site-header-fully-collapsed",se)),h()},[s,h]);if(!Y||!x)return null;const he=e.jsx("div",{className:"actions",ref:s?void 0:E,children:e.jsxs("div",{className:"actions-inner",children:[e.jsx("div",{className:"left",children:e.jsxs("div",{className:"close-btn",onClick:ye,children:[e.jsx("span",{className:"close-btn-icon",children:e.jsx(Ys.FaChevronLeft,{})}),e.jsx("div",{className:"close-text",children:t("common:cta.back")})]})}),e.jsxs("div",{className:"right",children:[!s&&e.jsx(e.Fragment,{children:e.jsxs(oe,{className:"preview-btn",variant:De,onClick:Ee,disabled:L||ee,children:[(L||ee)&&e.jsx(Fe,{size:"small"})," ",t("common:cta.preview")]})}),s&&e.jsx(_t,{maxImages:wt,currentImages:yt(X),bookId:y,teamId:(V=f==null?void 0:f.defaultTeam)==null?void 0:V._id,onImageUpload:J,onUploadStart:ie,onUploadError:ve,questionTitle:B,children:t("common:cta.addPhoto")}),e.jsx(oe,{className:Ue("save-btn",{visible:M.length>2}),onClick:()=>He(),disabled:pe,children:t("common:cta.save")}),e.jsx(dr,{placement:"bottomLeft",visible:be,onVisibleChange:Ne,className:"mobile-story-actions-popover",trigger:"click",content:e.jsxs("div",{className:"mobile-story-actions",children:[s&&e.jsxs(oe,{className:"preview-btn",variant:De,onClick:Ee,disabled:L||ee,children:[(L||ee)&&e.jsx(Fe,{size:"small"})," ",t("common:cta.preview")]}),e.jsxs(oe,{className:"preview-btn",variant:De,onClick:et,disabled:pe||!z,children:[pe&&e.jsx(Fe,{size:"small"})," ",t("common:cta.restoreLastSaved")]})]}),children:e.jsx(Ks.BsThreeDotsVertical,{style:{fontSize:24,marginRight:10,marginLeft:15,padding:"0 1px",cursor:"pointer"}})})]})]})});return e.jsxs("div",{ref:p,className:Ue("view-edit-story",{"view-edit-story--mobile-editor-shell":s,"view-edit-story--ai-panel-open":m&&!s}),children:[s?he:e.jsx(ur,{style:{width:"100%",zIndex:999},offsetTop:0,children:he}),s&&e.jsx("div",{ref:l,className:"mobile-story-toolbar-host"}),e.jsx("div",{className:"inner",onScroll:s?$:void 0,children:e.jsx("div",{className:"story-card",children:e.jsx(ms,{status:x.status,value:X,ref:n,bookId:y,questionId:Y,onCh
5ange:d=>{I(d)},onImageUpload:J,questionTitle:B,onQuestionTitleChange:Se,formattingToolbarPortalEl:s?o:null,onAiPanelOpenChange:g})})}),e.jsx(hr,{visible:de,onCancel:()=>O(!1),onDiscard:()=>void te(),onSave:d=>ge(d)}),e.jsx(pr,{visible:ne,onCancel:()=>ue(!1),onSave:async d=>{await u(!1,d)}}),e.jsx(fr,{visible:w,lastSavedAt:z?z.savedAt:null,loading:pe,onCancel:()=>b(!1),onRestore:()=>Xe()}),e.jsx(mr,{visible:C})]})};export{Io as default};
6//# sourceMappingURL=index-DsauasB0.js.map
7
8//# debugId=3cdea213-4161-5b4e-bf1f-1562ba2eb3c1

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.