1(globalThis.webpackChunkcenterpiece_ui=globalThis.webpackChunkcenterpiece_ui||[]).push([[864],{4462(e,t,s){"use strict";s.r(t),s.d(t,{default:()=>Ks});var n=s(9950),i=s(8429),o=s(8182),r=s(2203),l=s(7111);const a=s.p+"static/media/SIA-logo-sider.ef52ff4296b31dba72a39474bfabe4fc.svg";var c=s(4043),d=s(5234),u=s(7148),h=s(4414);const p=e=>{let{value:t,onChange:s,disabled:n}=e;return(0,h.jsxs)("div",{className:"feedback-thumbs",style:{pointerEvents:n?"none":"auto"},children:[(0,h.jsx)("span",{className:"thumb-btn"+("up"===t?" selected up":""),onClick:()=>s("up"===t?null:"up"),"aria-label":"Thumbs up",title:"Indicates that you agree with the response",children:(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-thumbs-up"})}),(0,h.jsx)("div",{className:"thumb-divider"}),(0,h.jsx)("span",{className:"thumb-btn"+("down"===t?" selected down":""),onClick:()=>s("down"===t?null:"down"),"aria-label":"Thumbs down",title:"Indicates that you disagree with the response",children:(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-thumbs-down"})})]})};var m=s(7797);const f=e=>{let{open:t,onClose:s,onCancel:i,onSubmit:l,onChange:a,title:f="How Sia is working for you?",description:v="Please document your feedback in as much detail as possible. If you're reporting a bug, please describe the steps you took and bug behavior.",initialThumb:g=null,showThumbs:y=!0}=e;const[x,b]=(0,n.useState)(""),[I,w]=(0,n.useState)(g),[j,S]=(0,n.useState)(!1);(0,n.useEffect)(()=>{w(g)},[g]);const C=()=>{b(""),w(null),s()},k=()=>{i?(b(""),w(null),i()):C()};return(0,h.jsxs)(c.A,{className:"vc-filters-modal feedback",visible:t,onCancel:k,footer:(0,h.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 0 0 0"},children:[(0,h.jsx)("div",{style:{minWidth:0},children:y&&(0,h.jsx)(p,{value:I,onChange:e=>{w(e),null===a||void 0===a||a(e)}})}),(0,h.jsxs)(d.A,{children:[(0,h.jsxs)(o.A,{type:"default",color:"primary",onClick:k,children:[(0,h.jsx)(r.A,{type:"solid",size:"16",icon:"fa-xmark"})," Cancel"]}),(0,h.jsxs)(o.A,{type:"default",color:"primary",onClick:async()=>{try{S(!0),await(null===l||void 0===l?void 0:l(x,I))}catch(e){m.A.handle(e)}finally{S(!1),b(""),w(null),C()}},disabled:j,loading:j,children:[(0,h.jsx)(r.A,{type:"solid",size:"16",icon:"fa-check"})," Submit"]})]})]}),title:(0,h.jsx)("div",{className:"vc-filters-modal__header",children:(0,h.jsxs)(d.A,{children:[(0,h.jsx)(r.A,{type:"solid",size:"20",icon:"fa-comment-dots"}),(0,h.jsx)("span",{children:f})]})}),width:540,destroyOnClose:!0,children:[(0,h.jsx)("div",{className:"vc-filters-modal__desc",children:v}),(0,h.jsx)(u.A,{className:"vc-filters-modal__textarea",placeholder:"Write your feedback here",value:x,onChange:e=>b(e.target.value),rows:3})]})};var v=s(4200),g=s(3671);async function y(e){if(!e.userQuery||!e.sessionId)throw new Error("Invalid request parameters");await w("processUserQuery",{timeout:3e5})(e)}async function x(e){if(!e.studyId)throw new Error("Study ID is required");return{sessionId:(await w("createVCChatSession")(e)).data.sessionId}}async function b(e){return(await w("submitVCFeedback")(e)).data.success}async function I(e){if(!e.studyId||!e.sessionId)throw new Error("studyId and sessionId are required");return(await w("generateChatTitle")(e)).data}function w(e,t){const s=g.A.getInstance();return"true"==={NODE_ENV:"production",PUBLIC_URL:"",WDS_SOCKET_HOST:void 0,WDS_SOCKET_PATH:void 0,WDS_SOCKET_PORT:void 0,FAST_REFRESH:!0,REACT_APP_VERSION:"31.1.1"}.REACT_APP_USE_FIREBASE_EMULATORS?(0,v.Qg)((0,v.Uz)(s.app),e,t):(0,v.Qg)((0,v.Uz)(s.app,"us-west3"),e,t)}var j=s(971),S=s(4590),C=s(6220),k=s(760);const A="vcStudiesMetadata";class N extends k.A{async fetchAllStudyMetadata(){try{const e=(0,C.rJ)(this.getUserDocRef(),A).withConverter(E);return(await(0,C.GG)(e)).docs.map(e=>e.data())}catch(e){return m.A.handle(e),[]}}async fetchStudyHeader(e){try{const t=(0,C.H9)(this.getUserDocRef(),A,e).withConverter(E),s=await(0,C.x7)(t);return s.exists()?s.data():null}catch(t){return m.A.handle(t),null}}async fetchDefaultStudyHeader(){try{const e=(0,C.rJ)(this.getUserDocRef(),A).withConverter(E),t=(0,C.P)(e,(0,C.My)("hasAccess","desc"),(0,C.AB)(1)),s=await(0,C.GG)(t);return s.empty?null:s.docs[0].data()}catch(e){return m.A.handle(e),null}}async updateStudyMetadata(e,t,s){const n=(0,C.H9)(this.getUserDocRef(),A,e).withConverter(E);await(0,C.mZ)(n,{studyName:t,studyDescription:s})}}const E={toFirestore:e=>({studyName:e.studyName,studyDescription:e.studyDescription}),fromFirestore(e){const t=e.data();
1return{studyId:e.id,studyName:t.studyName||"Workspace",studyDescription:t.studyDescription||"",sessionList:t.sessionList||[],hasAccess:t.hasAccess||!1}}};var F=s(7270);const O=e=>{let{open:t,onClose:s}=e;const o=(0,i.Zp)(),[l,a]=(0,n.useState)(""),[u,p]=(0,n.useState)([]),[m,f]=(0,n.useState)(!0);(0,n.useEffect)(()=>{t&&(async()=>{const e=(await(new N).fetchAllStudyMetadata()).map(e=>({id:e.studyId,title:e.studyName,description:e.studyDescription}));p(e),f(!1)})()},[t]);const v=u.filter(e=>e.title.toLowerCase().includes(l.toLowerCase())||e.description.toLowerCase().includes(l.toLowerCase()));return(0,h.jsxs)(c.A,{className:"vc-filters-modal workspace",visible:t,onCancel:s,destroyOnClose:!0,width:540,footer:null,title:(0,h.jsx)("div",{className:"vc-filters-modal__header",children:(0,h.jsxs)(d.A,{children:[(0,h.jsx)(r.A,{type:"solid",size:"16",icon:"fa-arrows-rotate"}),(0,h.jsx)("span",{children:"Switch Workspace"})]})}),children:[(0,h.jsx)("div",{className:"vc-filters-modal__desc",children:"Select a workspace from the list below to switch your current context."}),(0,h.jsx)(S.A,{placeholder:"Search workspaces",value:l,onChange:e=>a(e.target.value)}),m?(0,h.jsx)("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"200px",width:"100%"},children:(0,h.jsx)(r.A,{type:"solid",size:"20",icon:"fa-spinner",style:{color:"var(--tertiary3-5)",animation:"spin 3s linear infinite"}})}):(0,h.jsx)("div",{className:"workspace-list",children:v.map(e=>(0,h.jsxs)("div",{className:"workspace-item",onClick:()=>{s(),o(`${F.du.VC}/${e.id}`)},children:[(0,h.jsx)("div",{className:"workspace-item-title",children:e.title}),(0,h.jsx)("div",{className:"workspace-item-desc",children:e.description})]},e.id))})]})},$=e=>{let{title:t,onNewChatClick:s,readonly:i}=e;const[l,a]=(0,n.useState)(!1);return(0,h.jsxs)("div",{className:"workspace-detail-section",children:[(0,h.jsxs)("div",{className:"workspace-left",children:[(0,h.jsxs)("div",{className:"row-1",children:[(0,h.jsxs)("span",{className:"workspace-icon",children:[(0,h.jsx)(r.A,{type:"solid",size:"10",icon:"fa-grid-2"}),"WORKSPACE"]}),(0,h.jsx)("div",{className:"v-divider",children:(0,h.jsx)(r.A,{type:"solid",size:"10",icon:"fa-pipe"})}),(0,h.jsx)(j.A,{content:"Switch workspace",placement:"right",children:(0,h.jsxs)(o.A,{className:"workspace-switch",onClick:()=>a(!0),children:[(0,h.jsx)(r.A,{type:"solid",size:"10",icon:"fa-arrows-rotate"}),"Switch"]})})]}),(0,h.jsx)("div",{className:"selected-workspace",children:t})]}),i?null:(0,h.jsx)("div",{className:"workspace-right",children:(0,h.jsx)(j.A,{content:"Start a new chat",placement:"right",children:(0,h.jsx)(o.A,{className:"workspace-new-chat",icononly:!0,title:"Edit workspace title",onClick:s,children:(0,h.jsx)(r.A,{type:"solid",size:"16",icon:"fa-pen-to-square"})})})}),(0,h.jsx)(O,{open:l,onClose:()=>a(!1)})]})};var T=s(6419);const D=e=>{switch(e.category){case"Underserved":return"vc-row-underserved";case"Overserved":return"vc-row-overserved";case"Underserved Tablestakes":case"Overserved Tablestakes":return"vc-row-tablestakes";default:return""}},R=e=>{if(e.customTitle)return e.customTitle;try{return(0,T.y)(e.createdAt.toDate().toISOString(),!0)}catch(t){return e.docRef.id}},P=(e,t)=>{const{segment:s,filterCut:n}=e.groupParameter;let i="";return s&&(i+=`Segment ${s}`),n&&(i+=z(n,t)),i},z=(e,t)=>{if(!e||0===e.length)return null;const s=new Map(t.map(e=>[`${e.filterId}|${e.optId}`,e])),n=e.map(e=>{const t=s.get(`${e.profileQId}|${e.profileOptionId}`);return t?`${t.filterDesc}: ${t.optDesc}`:`[${e.profileQId}:${e.profileOptionId}]`}).filter(e=>e.length>0);return n.length>0?n.join(" | "):null},L=e=>{let{author:t,votes:s,onVote:i,compact:o=!1}=e;const l=s.filter(e=>"up"===e.thumb).length,a=s.filter(e=>"down"===e.thumb).length,c=t?s.find(e=>e.author.id===t.id):null,d="up"===(null===c||void 0===c?void 0:c.thumb),u="down"===(null===c||void 0===c?void 0:c.thumb),[p,m]=(0,n.use
1State)(!1),f=(0,n.useRef)(!1),v=async e=>{if(i&&t&&!f.current){if(null===e){if(!s.find(e=>e.author.id===t.id))return}f.current=!0,m(!0);try{await i(e)}finally{f.current=!1,m(!1)}}};return(0,h.jsxs)("div",{className:"vc-saved-insight-votes"+(o?" compact":""),children:[(0,h.jsxs)("span",{className:`vc-saved-insight-thumb-btn ${i&&!p?"interactive":""}${p?" disabled":""} vc-saved-insight-thumb-btn--up${d?" selected up":""}`,"aria-label":"Saved insight upvotes","aria-disabled":p,onClick:()=>v(d?null:"up"),children:[(0,h.jsx)(r.A,{type:"solid",size:"10",icon:"fa-arrow-up"}),(0,h.jsx)("span",{className:"vc-saved-insight-thumb-count",children:l})]}),(0,h.jsx)("div",{className:"vc-saved-insight-thumb-divider"}),(0,h.jsxs)("span",{className:`vc-saved-insight-thumb-btn ${i&&!p?"interactive":""}${p?" disabled":""} vc-saved-insight-thumb-btn--down${u?" selected down":""}`,"aria-label":"Saved insight downvotes","aria-disabled":p,onClick:()=>v(u?null:"down"),children:[(0,h.jsx)(r.A,{type:"solid",size:"10",icon:"fa-arrow-down"}),(0,h.jsx)("span",{className:"vc-saved-insight-thumb-count",children:a})]})]})},_=e=>{let{disableCTAs:t,sessionList:s,interviewId:i,setInterviewId:c,workspaceTitle:d,readOnly:u,initialCollapsed:p=!1,mobileHeaderHidden:m=!1,savedInsights:v,savedInsightVotes:g,selectedSavedInsightId:y=null,onSelectSavedInsight:x,openGroups:I,setOpenGroups:w}=e;const[j,S]=(0,n.useState)(p),[C,k]=(0,n.useState)(!1);(0,n.useEffect)(()=>{S(p)},[p]);const A=e=>{w(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])};return(0,h.jsxs)("div",{style:t?{pointerEvents:"none",opacity:.6}:{},className:`vc-sider${j?" collapsed":""}${m?" mobile-header-hidden":""}`,children:[(0,h.jsx)("div",{className:"vc-sider-collapse-btn-wrapper",children:(0,h.jsx)(o.A,{className:"vc-sider-collapse-btn",icononly:!0,onClick:()=>S(e=>!e),title:j?"Expand Sia's sidebar":"Collapse Sia's sidebar",children:(0,h.jsx)(r.A,{type:"solid",size:"14",icon:j?"fa-sidebar":"fa-angles-left"})})}),(0,h.jsx)("div",{className:"vc-logo",children:(0,h.jsx)("img",{src:a,alt:"Sia"})}),(0,h.jsx)($,{title:d,onNewChatClick:()=>c(""),readonly:u}),(0,h.jsxs)("div",{className:"vc-sider-scrollable-sections",children:[(0,h.jsxs)("div",{className:"vc-accordion-group recent-chats"+(I.includes("recent")?" expanded":""),children:[(0,h.jsxs)("div",{className:"vc-accordion-header",onClick:()=>A("recent"),children:[(0,h.jsx)(r.A,{icon:"fa-notes",type:"solid",size:"10",className:"vc-accordion-icon"}),(0,h.jsx)("span",{className:"vc-accordion-label",children:"Recent Chats"}),(0,h.jsx)(r.A,{icon:I.includes("recent")?"fa-angle-down":"fa-angle-up",size:"12"})]}),(0,h.jsx)("div",{className:"vc-accordion-content"+(I.includes("recent")?"":" collapsed"),children:I.includes("recent")&&(0,h.jsx)("div",{style:{display:"flex",flexDirection:0===s.length?"column":"column-reverse",gap:"8px"},children:0===s.length?(0,h.jsx)("div",{className:"vc-sider-section-empty",children:"No chats to show."}):s.sort((e,t)=>e.updatedAt.toDate().getTime()-t.updatedAt.toDate().getTime()).map(e=>{const t=!y&&e.docRef.id===i;return(0,h.jsx)(o.A,{type:t?"primary":"default",onClick:()=>c(e.docRef.id),className:"vc-chat-title "+(t?"selected":""),children:R(e)},e.docRef.id)})})})]}),(0,h.jsxs)("div",{className:"vc-accordion-group saved-insights"+(I.includes("savedInsights")?" expanded":""),children:[(0,h.jsxs)("div",{className:"vc-accordion-header",onClick:()=>A("savedInsights"),children:[(0,h.jsx)(r.A,{icon:"fa-bar-chart",type:"solid",size:"10",className:"vc-accordion-icon"}),(0,h.jsx)("span",{className:"vc-accordion-label",children:"Saved Insights"}),(0,h.jsx)(r.A,{icon:I.includes("savedInsights")?"fa-angle-down":"fa-angle-up",size:"12"})]}),(0,h.jsx)("div",{className:"vc-accordion-content"+(I.includes("savedInsights")?"":" collapsed"),children:I.includes("savedInsights")&&(0,h.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:0===v.length?(0,h.jsx)("div",{className:"vc-sider-section-empty",children:"No saved insights to show."}):v.map(e=>{var t;const s=!!y&&y===e.id;return(0,h.jsxs)(o.A,{type:"default",className:"vc-chat-title vc-saved-insight-title "+(s?"selected":""),onClick:()=>x(e),children:[(0,h.jsx)("span",{className:"vc-saved-insight-title__label",children:e.title}),(0,h.jsx)(L,{compact:!0,votes:null!==(t=g[e.id])&&void 0!==t?t:[]})]},e.id)})})})]})]}),(0,h.jsx)("div",{className:"vc-experience-btn-wrapper",children:(0,h.jsx)(o.A,{className:"vc-experience-btn",onClick:()=>k(!0),children:(0,h.jsxs)("div",{className:"vc-experience-content",children:[(0,h.jsxs)("div",{className:"vc-experience-header-row",children:[(0,h.jsx)("span",{className:"vc-experience-title",children:"How Sia is working for you?"}),(0,h.jsxs)("span",{className:"vc-experience-icon",children:[(0,h.jsx)(r.A,{type:"solid",size:"30",icon:"fa-comment-dots"}),(0,h.jsx)("span",{className:"vc-external-icon",children:(0,h.jsx)(r.A,{type:"solid",size:"14",icon:"fa-circle-arrow-up-right"})})]})]}),(0,h.jsx)("div",{className:"vc-experience-subtext",children:"Share your experience"})]})})}),(0,h.jsx)(f,{open:C,onClose:()=>k(!1),onSubmit:async e=>{await b({feedbackType:"sia_general_feedback",feedbackText:e}),l.A.show({type:"success",content:"Feedback submitted"})},title:"How Sia is working for you?",description:"Please share your overall experience with Sia. Your feedback helps us improve the platform and make it more useful for you.",showThumbs:!1})]})};var M=s(3238),Q=s(2211),U=s(7788);const H=e=>{let{open:t,onClose:s,onSave:i,studyId:a,sessionId:u,interactionId:p,insightType:m="response"}=e;
1const[f,v]=(0,n.useState)(""),[g,y]=(0,n.useState)(!1),x=(0,n.useRef)(null),b=(0,n.useMemo)(()=>f.trim().length>0,[f]);(0,n.useEffect)(()=>{if(!t)return;const e=window.setTimeout(()=>{var e,t;const s=null!==(e=null===(t=x.current)||void 0===t?void 0:t.querySelector("input"))&&void 0!==e?e:null;null===s||void 0===s||s.focus()},0);return()=>window.clearTimeout(e)},[t]);const I=()=>{g||(v(""),s())},w=async()=>{if(b&&!g)try{y(!0),await(null===i||void 0===i?void 0:i({sourceStudyId:a,sourceSessionId:u,sourceInteractionId:p,title:f.trim(),insightType:m})),l.A.show({content:"Insight saved.",type:"success"}),I()}finally{y(!1)}};return(0,h.jsx)(c.A,{className:"vc-save-insight-modal",width:400,visible:t,destroyOnClose:!0,footer:null,onCancel:I,title:null,children:(0,h.jsx)("div",{ref:x,children:(0,h.jsxs)(d.A,{direction:"vertical",size:16,style:{width:"100%"},children:[(0,h.jsxs)("div",{className:"vc-save-insight-modal__title",children:[(0,h.jsx)(r.A,{type:"solid",size:"16",icon:"fa-floppy-disk"}),(0,h.jsx)("span",{children:"Save Insight"})]}),(0,h.jsx)("p",{className:"vc-save-insight-modal__desc",children:"Saved insights can be accessible from sidebar."}),(0,h.jsx)(U.A,{placeholder:"Name Insight title",value:f,disabled:g,onChange:e=>v(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),w())}}),(0,h.jsx)("div",{className:"vc-save-insight-modal__actions",children:(0,h.jsx)(o.A,{type:"default",color:"secondary-1",onClick:w,disabled:!b||g,loading:g,children:"Save"})})]})})})};var B=s(9307);const G=e=>{let{studyId:t,disableCTAs:s,disableDelete:i,sessionHeader:l,updateThreadSettings:a,showSummary:u,onDeleteChat:p,workspaceTitle:m,readOnly:f,isMobile:v=!1,onNewChat:g,onSaveInsight:y,onDeleteInsight:x,selectedSavedInsight:b=null,chatHasSharedInsights:I=!1}=e;const[w,S]=n.useState(!1),[C,k]=n.useState(!1),[A,N]=n.useState(!1),[E,F]=n.useState(!1),[O,$]=n.useState(!1),D=!!b,P=!D&&I,z=(new B.A).getCurrentUserId(),L=!!b&&b.savedBy.uid===z,_=()=>(0,h.jsxs)("label",{className:"vc-insights-summary-label",children:[(0,h.jsx)(M.A,{disabled:f||s||D,checked:u,onChange:async e=>{try{N(!0),await a({showInsightsSummary:e,showRecommendations:!1})}finally{N(!1)}},size:"small",loading:A}),(0,h.jsx)("span",{children:"Insights Summary"})]}),U=e=>{const t=(0,h.jsxs)(o.A,{type:"link",size:"small",className:"vc-delete-btn",onClick:()=>S(!0),title:P?void 0:"Delete this chat",disabled:s||i||P,children:[(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-trash"}),e&&" Delete Chat"]});return P?(0,h.jsx)(j.A,{content:"Delete the associated Insights before deleting this item.",placement:"bottom",trigger:"hover",children:(0,h.jsx)("span",{style:{display:"inline-block"},children:t})}):t},G=b?`${b.savedBy.uid===z?"You":b.savedBy.name} saved it as Insight on ${(0,T.dl)(b.savedAt)}`:"",V=(0,h.jsxs)("div",{className:"vc-chat-actions-menu",onClick:()=>F(!1),children:[(0,h.jsx)("div",{className:"vc-chat-actions-menu-item",children:_()}),!D&&(0,h.jsx)("div",{className:"vc-chat-actions-menu-item",children:(0,h.jsxs)(o.A,{type:"link",size:"small",className:"vc-chat-save-btn",disabled:s||f,onClick:()=>$(!0),children:[(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-floppy-disk"}),"Save as Chat"]})}),(0,h.jsx)("div",{className:"vc-chat-actions-menu-item",children:U(!0)})]});return(0,h.jsxs)("div",{className:"vc-chat-header",children:[(0,h.jsxs)(d.A,{children:[!v&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)("div",{className:"chat-workspace-title",children:[(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-grid-2"})," ",m,f&&(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-lock"})]}),(0,h.jsx)(r.A,{type:"regular",size:"12",icon:"fa-angle-right"})]}),(0,h.jsxs)("div",{className:"chat-title",children:[(0,h.jsx)(r.A,{type:"regular",size:"12",icon:"fa-file"}),b?b.title:l?R(l):"Untitled"]}),!v&&(b&&"chat"===b.insightType?(0,h.jsxs)("span",{className:"vc-chat-header-insight-tag",children:[G,x&&L?(0,h.jsxs)(h.Fragment,{children:[" ",(0,h.jsx)(o.A,{type:"link",size:"small",onClick:()=>x(b),children:(0,h.jsx)(r.A,{type:"solid",size:"10",icon:"fa-trash"})})]}):null]}):!D&&null!==l&&void 0!==l&&l.docRef?(0,h.jsx)(o.A,{type:"default",size:"small",className:"vc-chat-header-save-btn",onClick:()=>$(!0),disabled:s||f,title:"Save as Chat",children:(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-floppy-disk"})}):null)]}),v?(0,h.jsxs)("div",{className:"mobile-chat-actions",children:[g&&(0,h.jsx)(o.A,{type:"link",size:"small",className:"mobile-action-btn",icononly:!0,onClick:g,title:"Start a new chat","aria-label":"Start a new chat",disabled:s||f,children:(0,h.jsx)(r.A,{type:"regular",size:"16",icon:"fa-pen-to-square"})}),!D&&(0,h.jsx)(Q.A,{overlay:V,trigger:["click"],visible:E,onVisibleChange:e=>F(e),placement:"bottomRight",children:(0,h.jsx)(o.A,{type:"link",size:"small",className:"mobile-action-btn",icononly:!0,onClick:()=>F(e=>!e),"aria-label":"Chat actions",title:"Chat actions",children:(0,h.jsx)(r.A,{type:"regular",size:"16",icon:"fa-ellipsis-vertical"})})})]}):(0,h.jsx)("div",{className:"chat-actions",children:!D&&(0,h.jsx)(d.A,{children:(0,h.jsxs)(d.A,{children:[_(),(0,h.jsx)("div",{className:"v-divider",children:(0,h.jsx)(r.A,{type:"regular",size:"12",icon:"fa-pipe"})}),U(!0)]})})}),(0,h.jsx)(c.A,{className:"vc-delete-modal",type:"error",title:(0,h.jsxs)(d.A,{children:[(0,h.jsx)(r.A,{type:"solid",size:"14",icon:"fa-trash"}),"Delete Chat"]}),visible:w,onCancel:()=>S(!1),onOk:async()=>
1{if(!C)try{k(!0),await p(),S(!1)}finally{k(!1)}},okText:"Delete",cancelText:"Cancel",confirmLoading:C,children:(0,h.jsx)("p",{children:"Are you sure you want to delete this chat? This action cannot be undone."})}),!D&&(null===l||void 0===l?void 0:l.docRef)&&(0,h.jsx)(H,{studyId:t,sessionId:l.docRef.id,interactionId:null,open:O,onClose:()=>$(!1),insightType:"chat",onSave:y})]})};var V=s(857),W=s(8200);const q=e=>{let{elemKey:t,title:s,usedOutcomes:i,categoriesCovered:o,outcomesList:r}=e;const[l,a]=(0,n.useState)({appropriatelyServed:0,underserved:0,underservedTableStakes:0,overserved:0,overservedTableStakes:0});(0,n.useEffect)(()=>{a({appropriatelyServed:i.filter(e=>"Appropriately served"===e.category).length,underserved:i.filter(e=>"Underserved"===e.category||"Underserved Tablestakes"===e.category).length,underservedTableStakes:i.filter(e=>"Underserved Tablestakes"===e.category).length,overserved:i.filter(e=>"Overserved"===e.category||"Overserved Tablestakes"===e.category).length,overservedTableStakes:i.filter(e=>"Overserved Tablestakes"===e.category).length})},[i]);const c=[{title:"ID",dataIndex:"outcomeId",key:"outcomeId",sorter:(e,t)=>e.outcomeId.localeCompare(t.outcomeId),defaultSortOrder:"ascend"},{title:"Outcome",dataIndex:"outcomeId",key:"outcomeStatement",render:e=>d(e)},{title:"Opp",dataIndex:"opp",key:"opp",render:e=>((e,t)=>{const s=Math.pow(10,t);return Math.round((e+Number.EPSILON)*s)/s})(e,1).toFixed(1),sorter:(e,t)=>e.opp-t.opp}],d=e=>{const t=r.find(t=>t.id===e);return null===t||void 0===t?void 0:t.outcome};return(0,h.jsxs)("div",{className:"vc-insights-section",children:[(0,h.jsx)("h5",{children:s}),(0,h.jsxs)("ul",{children:[o.includes("Appropriately served")&&(0,h.jsxs)("li",{children:["Appropriately Served Outcomes: ",l.appropriatelyServed]}),o.includes("Underserved")&&(0,h.jsxs)("li",{children:["Underserved Outcomes: ",l.underserved,l.underservedTableStakes>0&&(0,h.jsx)("ul",{children:(0,h.jsxs)("li",{children:["Underserved table stakes:"," ",l.underservedTableStakes]})})]}),o.includes("Overserved")&&(0,h.jsxs)("li",{children:["Overserved Outcomes: ",l.overserved,l.overservedTableStakes>0&&(0,h.jsx)("ul",{children:(0,h.jsxs)("li",{children:["Overserved table stakes:"," ",l.overservedTableStakes]})})]})]}),i.length>0&&(0,h.jsx)("div",{style:{maxHeight:"270px",overflowY:"auto",marginBottom:"12px"},children:(0,h.jsx)(W.A,{rowKey:"outcomeId",className:"vc-insights-table",size:"small",bordered:!0,columns:c,cellSpace:16,dataSource:i,pagination:!1,onRow:e=>({className:D(e)})},`insights-table-${t}`)})]},`insights-section-${t}`)},K=e=>{let{elemKey:t,analytics:s,outcomesList:n,filters:i,filtersUsed:o}=e;const r=()=>{if(!o||0===o.length)return null;const e=new Map(i.map(e=>[`${e.filterId}|${e.optId}`,e])),t=o.map(t=>{const s=e.get(`${t.profileQId}|${t.profileOptionId}`);return s?`${s.filterId} ${s.filterDesc}: ${s.optDesc}`:`[${t.profileQId}:${t.profileOptionId}]`}).filter(e=>e.length>0);return t.length>0?t.join(" | "):null};return(0,h.jsxs)("div",{className:"vc-insights-content",children:[s.market?(0,h.jsx)(q,{elemKey:`asi-market-${t}`,title:r()||"Total Market",usedOutcomes:s.market,categoriesCovered:s.categoriesCovered,outcomesList:n}):null,Object.entries(s.segments).map(e=>{let[i,o]=e;if(o){const e=r(),l=e?`Segment ${i} | ${e}`:`Segment ${i}`;return(0,h.jsx)(q,{elemKey:`asi-segment-${t}-${i||Math.random()}`,title:l,usedOutcomes:o,categoriesCovered:s.categoriesCovered,outcomesList:n},`breakdown-section-${t}-${i||Math.random()}`)}return null})]},`area-specific-insights-${t}`)},J=e=>{let{elemKey:t,title:s,oppSpaces:n,category:i,outcomesList:o,visibleOutcomes:r}=e;const l=[{title:"ID",dataIndex:"outcomeId",key:"outcomeId",sorter:(e,t)=>e.outcomeId.localeCompare(t.outcomeId),defaultSortOrder:"ascend"},{title:"Outcome",dataIndex:"outcomeId",key:"outcomeStatement",render:e=>a(e)},{title:"Segments",dataIndex:"segments",key:"segments"}],a=e=>{const t=o.find(t=>t.id===e);return null===t||void 0===t?void 0:t.outcome},c=e=>{switch(e){case"Underserved":return"vc-row-underserved";case"Overserved":return"vc-row-overserved"}},d=(e,s)=>{const n=r?Object.entries(e).filter(e=>{let[t]=e;return r.includes(t)}):Object.entries(e);if(0===n.length)return"None";const o=n.map(e=>{let[t,s]=e;return{outcomeId:t,segments:s.join(", ")}});return(0,h.jsx)("div",{style:{maxHeight:"270px",overflowY:"auto",marginBottom:"12px"},children:(0,h.jsx)(W.A,{rowKey:"outcomeId",className:"vc-insights-table",size:"small",bordered:!0,columns:l,cellSpace:16,dataSource:o,pagination:!1,onRow:()=>({className:c(i)})},`table-osi-${t}-${i}-${s}`)})};return(0,h.jsxs)("div",{className:"vc-insights-section",children:[(0,h.jsx)("h5",{children:s}),(0,h.jsxs)("ul",{children:[(0,h.jsxs)("li",{children:["High-Leverage Opportunities:"," ",d(n.highLeverageUnmet,"high-leverage")]}),(0,h.jsxs)("li",{children:["Cross-Segment Opportunities:"," ",d(n.crossSegmentUnmet,"cross-segment")
1]}),(0,h.jsxs)("li",{children:["Segment-Specific Opportunities:",d(n.segmentSpecificUnmet,"segment-specific")]})]})]})},Y=e=>{let{elemKey:t,analytics:s,outcomesList:n,visibleOutcomes:i}=e;const{underserved:o,overserved:r}=s;return(0,h.jsxs)("div",{className:"vc-insights-content",children:[o&&(0,h.jsx)(J,{elemKey:t,title:"Opportunity Based Unmet Needs - Underserved",oppSpaces:o,category:"Underserved",outcomesList:n,visibleOutcomes:i}),r&&(0,h.jsx)(J,{elemKey:t,title:"Opportunity Based Unmet Needs - Overserved",oppSpaces:r,category:"Overserved",outcomesList:n,visibleOutcomes:i})]},`opp-specific-insights-${t}`)},Z={Overserved:"#FFEEED",Underserved:"#EFF9EA","Appropriately served":"#EEEEEE","Underserved Tablestakes":"#FAF8CF","Overserved Tablestakes":"#FAF8CF",Tablestakes:"#FAF8CF"},X=e=>({text:e,fillColor:"5656A5",textColor:"FFFFFF",bold:!0}),ee=e=>({text:e,fillColor:"5656A5",textColor:"FFFFFF",bold:!0}),te={market:"#8a1a77",g1:"#2C2C8E",g2:"#33727F",g3:"#9C9CE0",g4:"#83A0A7",g5:"#932B83",g6:"#FF7B80",g7:"#FDC741",g8:"#39D2D5",g9:"#686991",g10:"#95AC4F",default:"#808080"},se=e=>te[e]||te.default,ne=e=>{var t;let{analytics:s,filtersList:n,visibleOutcomes:i}=e;const o=i?new Set(i):null,r=e=>!o||o.has(e),l=[];if(s.market){const e=s.market.outcomes.filter(e=>r(e.outcomeId)).length;l.push({key:"market",label:`Total Sample (${e})`,color:se("market")})}return null===(t=s.dataGroups)||void 0===t||t.forEach(e=>{const t=`g${e.oneBasedIndex}`,s=e.outcomes.filter(e=>r(e.outcomeId)).length;l.push({key:t,label:`${P(e,n)} (${s})`,color:se(t)})}),l},ie="Outcomes and Jobs Statements",oe="Opportunity scores by selected variables",re="Outcomes",le="Opportunity Landscape",ae="Visual depiction of the quantified opportunities.",ce="Landscape",de="Profiling Data",ue="Relationship between selected variables",he="Profiling",pe=Z,me={higher:"#fff3d6",lower:"#e9f3fb"},fe=[{label:"Overserved",color:pe.Overserved},{label:"Underserved",color:pe.Underserved},{label:"Appropriately Served",color:pe["Appropriately served"]},{label:"Table Stakes",color:pe.Tablestakes}],ve=[{label:'Significantly > "all others"',color:me.higher},{label:'Significantly < "all others"',color:me.lower}],ge=e=>{const{filterCut:t}=e.groupParameter;return Array.isArray(t)&&t.length>0},ye=e=>null===e||void 0===e?"\u2014":"number"===typeof e?e.toFixed(1):e,xe=e=>{let{analytics:t,filtersList:s,outcomesList:n,visibleOutcomes:i,visibleSegments:o,metricColumnMode:r="none"}=e;const l=((e,t)=>{const s=[];e.market&&s.push({key:"market",label:"Total Sample",showToggle:!0}),e.dataGroups&&[...e.dataGroups].sort((e,t)=>{const s=Boolean(e.groupParameter.segment);return s===Boolean(t.groupParameter.segment)?0:s?-1:1}).forEach(e=>{s.push({key:`group-${e.oneBasedIndex.toString()}`,label:P(e,t),showToggle:!ge(e)})});return s})(t,s).filter(e=>{var t;return!e.showToggle||null===(t=null===o||void 0===o?void 0:o[e.key])||void 0===t||t}),a=n.filter(e=>!i||i.includes(e.id)).map(e=>{const s=Object.fromEntries(l.map(s=>{var n;if("market"===s.key){var i;const n=null===(i=t.market)||void 0===i?void 0:i.outcomes.find(t=>t.outcomeId===e.id),o=null!==n&&void 0!==n&&n.category?pe[n.category].replace("#",""):void 0;return[s.key,{opp:ye(null===n||void 0===n?void 0:n.opp),imp:ye(null===n||void 0===n?void 0:n.imp),sat:ye(null===n||void 0===n?void 0:n.sat),fillColor:o}]}const o=Number(s.key.replace("group-","")),r=null===(n=t.dataGroups)||void 0===n?void 0:n.find(e=>e.oneBasedIndex===o),l=null===r||void 0===r?void 0:r.outcomes.find(t=>t.outcomeId===e.id),a=null!==l&&void 0!==l&&l.category?pe[l.category].replace("#",""):void 0;return[s.key,{opp:ye(null===l||void 0===l?void 0:l.opp),imp:ye(null===l||void 0===l?void 0:l.imp),sat:ye(null===l||void 0===l?void 0:l.sat),fillColor:a}]}));return{id:e.id,outcome:e.outcome,values:s}});return(e=>{let{columns:t,rows:s,metricColumnMode:n="none"}=e;const i=Math.max(t.length,1);if("groupedOppImpSat"===n){const e=Number(((12.3-1.1-3.8)/i).toFixed(2)),n=Math.max(.65,Number((e/3).toFixed(2))),o=[X("ID"),X("Outcome/Job"),...t.flatMap(e=>[X(e.label),X(""),X("")])],r=[{text:"",fillColor:"5656A5",textColor:"FFFFFF",bold:!0},{text:"",fillColor:"5656A5",textColor:"FFFFFF",bold:!0},...t.flatMap(()=>[X("Imp"),X("Sat"),X("Opp")])],l=s.map(e=>[{text:e.id},{text:e.outcome},...t.flatMap(t=>{const s=e.values[t.key];return[{text:(null===s||void 0===s?void 0:s.imp)||"\u2014"},{text:(null===s||void 0===s?void 0:s.sat)||"\u2014"},{text:(null===s||void 0===s?void 0:s.opp)||"\u2014",fillColor:null===s||void 0===s?void 0:s.fillColor}]})]),a=[{fromRow:1,fromCol:1,toRow:2,toCol:1},{fromRow:1,fromCol:2,toRow:2,toCol:2},...t.map((e,t)=>{const s=3+3*t;return{fromRow:1,fromCol:s,toRow:1,toCol:s+2}})];return{rows:[o,r,...l],colWidths:[1.1,3.8,...Array(3*i).fill(n)],rowsPerSlide:10,rowHeight:.29,defaultBodyFillC
1olor:()=>"FFFFFF",xlsxMerges:a}}const o=Math.max(.9,Number(((12.3-1.1-3.8)/i).toFixed(2)));return{rows:[[X("ID"),X("Outcome/Job"),...t.map(e=>X(e.label))],...s.map(e=>[{text:e.id},{text:e.outcome},...t.map(t=>{var s,n;return{text:(null===(s=e.values[t.key])||void 0===s?void 0:s.opp)||"\u2014",fillColor:null===(n=e.values[t.key])||void 0===n?void 0:n.fillColor}})])],colWidths:[1.1,3.8,...Array(Math.max(t.length,1)).fill(o)],rowsPerSlide:10,rowHeight:.29,defaultBodyFillColor:(e,s)=>s<2||s>=2+Math.max(t.length,1)?"FFFFFF":"FAFAFA"}})({columns:l.map(e=>({key:e.key,label:e.label})),rows:a,metricColumnMode:r})},be=e=>{var t,s;let{analytics:n,profileList:i,visibleProfiles:o,visibleSegments:r}=e;const l=[],a=[],c=[],d=new Set,u=(e,t,s)=>{if(d.has(e))return;d.add(e);const n={key:e,label:t,showToggle:s};s?a.push(n):c.push(n)};null!==(t=n.market)&&void 0!==t&&t.profiles&&n.market.profiles.length>0&&u("totalSample","Total Sample",!0),null===(s=n.dataGroups)||void 0===s||s.forEach(e=>{if(e.groupParameter.segment&&!e.groupParameter.filterCut&&e.profiles.length>0&&u(e.groupParameter.segment,`Segment ${e.groupParameter.segment}`,!0),e.groupParameter.filterCut&&e.profiles.length>0){const t=e.groupParameter.filterCut.map(e=>`${e.profileQId}|${e.profileOptionId}`).join("+"),s=z(e.groupParameter.filterCut,i);u(t,s||`${t}`,!1)}}),l.push(...a,...c);const h=l.filter(e=>{var t;return!e.showToggle||null===(t=null===r||void 0===r?void 0:r[e.key])||void 0===t||t}),p=Array.from(new Set(i.map(e=>e.filterId))).flatMap(e=>{var t,s,r;if(!o.includes(e))return[];const l=i.filter(t=>t.filterId===e),a=(null===(t=n.market)||void 0===t||null===(s=t.profiles)||void 0===s?void 0:s.filter(t=>t.filterItem.profileQId===e))||[];if(0===a.length)return[];const c=a.map(e=>{var t;return{key:`${e.filterItem.profileQId}|${e.filterItem.profileOptionId}`,label:(null===(t=l.find(t=>t.optId===e.filterItem.profileOptionId))||void 0===t?void 0:t.optDesc)||"",values:{totalSample:Math.round(100*e.percentage)},significance:{}}}),d=[];return null===(r=n.dataGroups)||void 0===r||r.forEach(t=>{if(t.groupParameter.filterCut)d.push(t);else if(t.groupParameter.segment&&!t.groupParameter.filterCut&&t.profiles.length>0){const s=t.groupParameter.segment;t.profiles.filter(t=>t.filterItem.profileQId===e).forEach(e=>{const t=c.find(t=>t.key===`${e.filterItem.profileQId}|${e.filterItem.profileOptionId}`);t&&(t.values[s]=Math.round(100*e.filterItemPercentage),t.significance[s]=1===e.significanceLevel?"higher":-1===e.significanceLevel?"lower":null)})}}),d.forEach(t=>{const{filterCut:s}=t.groupParameter;if(!s)return;const n=s.map(e=>`${e.profileQId}|${e.profileOptionId}`).join("+");t.profiles.filter(t=>t.filterItem.profileQId===e).forEach(e=>{const t=c.find(t=>t.key===`${e.filterItem.profileQId}|${e.filterItem.profileOptionId}`);t&&(t.values[n]=Math.round(100*e.filterItemPercentage),t.significance[n]=1===e.significanceLevel?"higher":-1===e.significanceLevel?"lower":null)})}),c.map((t,s)=>{var n;return{questionId:e,questionLabel:(null===(n=l[0])||void 0===n?void 0:n.filterDesc)||e,optionLabel:t.label,values:Object.fromEntries(h.map(e=>{const s=t.significance[e.key];return[e.key,{text:(n=t.values[e.key],null===n||void 0===n?"\u2014":`${n}%`),fillColor:s&&me[s]?me[s].replace("#",""):void 0}];var n})),isFirstOption:0===s}})});return(e=>{let{columns:t,rows:s}=e;const n=[ee("ID"),ee("Label"),ee("Option"),...t.map(e=>ee(e.label))],i=s.map(e=>[{text:e.isFirstOption?e.questionId:""},{text:e.isFirstOption?e.questionLabel:""},{text:e.optionLabel},...t.map(t=>{var s,n;return{text:(null===(s=e.values[t.key])||void 0===s?void 0:s.text)||"\u2014",fillColor:null===(n=e.values[t.key])||void 0===n?void 0:n.fillColor}})]),o=Math.max(.85,Number((4.4/Math.max(t.length,1)).toFixed(2)));return{rows:[n,...i],colWidths:[1,4.4,2.5,...Array(Math.max(t.length,1)).fill(o)],rowsPerSlide:10,rowHeight:.29,defaultBodyFillC
1olor:(e,t)=>e%2===0?t<3?"FFFFFF":"FAFAFA":"FFFFFF"}})({columns:h.map(e=>({key:e.key,label:e.label})),rows:p})};var Ie=s(5341);const we=(e,t)=>e.map((e,s)=>e.map((e,n)=>({text:e.text,options:{bold:Boolean(e.bold),color:e.textColor||"51595C",fill:{color:e.fillColor||(0===s?"5656A5":t(s-1,n))},valign:"middle",align:0===n?"center":"left",fontFace:"Arial"}}))),je=async e=>{if(!e.table&&!e.chartImageDataUrl)throw new Error("Either table data or chart image is required for export.");await Ae({coverQuestion:e.coverQuestion,coverLabel:e.coverLabel,coverSubtitle:e.coverSubtitle,fileNamePrefix:e.fileNamePrefix,sections:[{slideTitle:e.slideTitle,slideSubtitle:e.slideSubtitle,table:e.table,chartImageDataUrl:e.chartImageDataUrl,legends:e.legends}]})},Se=e=>{let{pptx:t,slide:s,legends:n,startX:i=.5,startY:o,itemWidth:r=2.95}=e,l=i;const a=o;n.forEach(e=>{const n=(e.color||"#E6E6ED").replace("#","");s.addShape(t.ShapeType.rect,{x:l,y:a+.07,w:.12,h:.12,line:{color:"D4D6D7",pt:.5},fill:{color:n}}),s.addText(e.label,{x:l+.16,y:a,w:r-.45,h:.26,fontSize:8,color:"7C8385",fontFace:"Arial"}),l+=r})},Ce=async(e,t)=>{if(!t.chartImageDataUrl)return;const s=e.addSlide();s.background={color:"FFFFFF"},s.addText(t.slideTitle,{x:.5,y:.3,w:11.3,h:.4,fontSize:15,color:"51595C",bold:!0,fontFace:"Arial"}),s.addText(t.slideSubtitle,{x:.5,y:.72,w:11.3,h:.3,fontSize:9,color:"7C8385",fontFace:"Arial"});const n=Boolean(t.legends&&t.legends.length>0),i=n?8.3:12.3,o=await(r=t.chartImageDataUrl,new Promise((e,t)=>{const s=new Image;s.onload=()=>{e({width:s.naturalWidth||s.width,height:s.naturalHeight||s.height})},s.onerror=()=>t(new Error("Unable to read image dimensions.")),s.src=r}));var r;const l=((e,t,s,n)=>{if(!e||!t)return{width:s,height:n};const i=e/t;let o=s,r=o/i;return r>n&&(r=n,o=r*i),{width:o,height:r}})(o.width,o.height,i,5.8),a=function(e,t,s){const n=s/(arguments.length>3&&void 0!==arguments[3]?arguments[3]:96),i=Math.max(e-n,.5);return{width:i,height:t*(i/e)}}(l.width,l.height,100),c=1.2+(5.8-a.height)/2;if(s.addImage({data:t.chartImageDataUrl,x:.5,y:c,w:a.width,h:a.height}),n&&t.legends){const n=.5+i+0;(e=>{let{pptx:t,slide:s,legends:n,startX:i,startY:o,rowHeight:r=.3,textWidth:l=2.35}=e;n.forEach((e,n)=>{const a=o+n*r,c=(e.color||"#E6E6ED").replace("#","");s.addShape(t.ShapeType.rect,{x:i,y:a+.07,w:.12,h:.12,line:{color:"D4D6D7",pt:.5},fill:{color:c}}),s.addText(e.label,{x:i+.16,y:a,w:l,h:.26,fontSize:8,color:"7C8385",fontFace:"Arial"})})})({pptx:e,slide:s,legends:t.legends,startX:n,startY:1.6,textWidth:3.7})}},ke=(e,t)=>{if(!t.table)return;const s=t.table.rows[0]||[],n=t.table.rows.slice(1),i=Math.max(1,Math.ceil(n.length/t.table.rowsPerSlide));for(let o=0;o<i;o+=1){const r=[s,...n.slice(o*t.table.rowsPerSlide,(o+1)*t.table.rowsPerSlide)],l=we(r,t.table.defaultBodyFillC
1olor),a=e.addSlide();a.background={color:"FFFFFF"},a.addText(t.slideTitle,{x:.5,y:.3,w:11.3,h:.4,fontSize:15,color:"51595C",bold:!0,fontFace:"Arial"}),a.addText(`${t.slideSubtitle}${i>1?` (Page ${o+1} of ${i})`:""}`,{x:.5,y:.72,w:11.3,h:.3,fontSize:9,color:"7C8385",fontFace:"Arial"});let c=1.2,d=5.2;t.legends&&t.legends.length>0&&(Se({pptx:e,slide:a,legends:t.legends,startY:1.02}),c=1.45,d=4.95),a.addTable(l,{x:.5,y:c,w:12.3,h:d,colW:t.table.colWidths,rowH:Array(r.length).fill(t.table.rowHeight),fontSize:9.5,border:{pt:.5,color:"E6E6ED"}})}},Ae=async e=>{var t;if(!e.sections||0===e.sections.length)throw new Error("At least one section is required for export.");const s=new Ie.A;s.layout="LAYOUT_WIDE",s.author="Strategyn";const n=(null===(t=e.sections[0])||void 0===t?void 0:t.slideTitle)||"Insights Export";s.subject=n,s.title=n,((e,t)=>{const s=e.addSlide();s.background={color:"FFFFFF"},s.addText(t.coverLabel,{x:1.2,y:2.5,w:11,h:.35,align:"center",valign:"middle",fontFace:"Arial",fontSize:12,color:"7C8385"}),s.addText(t.coverQuestion,{x:1.2,y:2.5,w:11,h:2.1,align:"center",valign:"middle",fontFace:"Arial",bold:!0,fontSize:24,color:"5E2569"}),s.addText(t.coverSubtitle,{x:1.2,y:6.8,w:11,h:.6,align:"center",valign:"middle",fontFace:"Arial",fontSize:8,color:"7C8385"})})(s,e);for(const o of e.sections)o.chartImageDataUrl?await Ce(s,o):o.table&&ke(s,o);const i=(new Date).toISOString().replace(/[:.]/g,"-");await s.writeFile({fileName:`${e.fileNamePrefix}-${i}.pptx`})};var Ne=s(9264),Ee=s.n(Ne);const Fe=e=>{if(!e)return;const t=e.replace("#","").trim();return 3===t.length?`${t[0]}${t[0]}${t[1]}${t[1]}${t[2]}${t[2]}`.toUpperCase():t.length>=6?t.slice(0,6).toUpperCase():void 0},Oe=e=>{const t=Fe(e);return t?`FF${t}`:void 0},$e=async e=>{if(!e.table&&!e.chartImageDataUrl)throw new Error("Either table data or chart image is required for export.");await De({coverQuestion:e.coverQuestion,coverLabel:e.coverLabel,coverSubtitle:e.coverSubtitle,fileNamePrefix:e.fileNamePrefix,sections:[{sheetName:e.sheetName,table:e.table,chartImageDataUrl:e.chartImageDataUrl,legends:e.legends}]})},Te=async(e,t,s)=>{var n,i,o;const r=Boolean(s.chartImageDataUrl&&!s.table),l=r?4:Math.max((null===(n=s.table)||void 0===n||null===(i=n.rows[0])||void 0===i?void 0:i.length)||8,1);t.columns=r?Array.from({length:l}).map(()=>({width:18})):Array.from({length:l}).map((e,t)=>{var n,i;const o=null!==(n=null===(i=s.table)||void 0===i?void 0:i.colWidths[t])&&void 0!==n?n:10,r=Math.round(8.5*o);return{width:1===t?Math.max(r,64):Math.max(r,10)}}),t.getRow(1).values=[s.coverLabel],t.getRow(2).values=[s.coverQuestion],t.getRow(3).values=[s.coverSubtitle];const a=4+(s.table&&(null===(o=s.legends)||void 0===o?void 0:o.length)||0)+1;t.getRow(a-1).values=[""],t.getRow(1).height=22,t.getRow(2).height=30,t.getRow(3).height=18,t.getRow(a-1).height=10,t.mergeCells(1,1,1,l),t.mergeCells(2,1,2,l),t.mergeCells(3,1,3,l);const c={horizontal:"center",vertical:"middle"},d={horizontal:"left",vertical:"middle",wrapText:!0};if([1,2,3].forEach(e=>{t.getCell(e,1).alignment=c}),t.getCell(1,1).font={bold:!0,color:{argb:"FF7C8385"},size:11},t.getCell(2,1).font={bold:!0,color:{argb:"FF5E2569"},size:16},t.getCell(3,1).font={color:{argb:"FF7C8385"},size:10},s.table&&s.legends&&s.legends.length>0&&s.legends.forEach((e,s)=>{const n=4+s;t.getRow(n).height=18,l>1&&t.mergeCells(n,2,n,l);const i=t.getCell(n,1),o=t.getCell(n,2);i.value="",i.fill={type:"pattern",pattern:"solid",fgColor:{argb:Oe(e.color)||"FFE6E6ED"}},i.border={top:{style:"thin",color:{argb:"FFD4D6D7"}},right:{style:"thin",color:{argb:"FFD4D6D7"}},bottom:{style:"thin",color:{argb:"FFD4D6D7"}},left:{style:"thin",color:{argb:"FFD4D6D7"}}},o.value=e.label,o.font={color:{argb:"FF7C8385"},size:10},o.alignment=d}),s.chartImageDataUrl){const n=await(u=s.chartImageDataUrl,new Promise((e,t)=>{const s=new Image;s.onload=()=>{e({width:s.naturalWidth||s.width,height:s.naturalHeight||s.height})},s.onerror=()=>t(new Error("Unable to read image dimensions.")),s.src=u})),i=((e,t,s,n)=>{if(!e||!t)return{width:s,height:n};const i=e/t;let o=s,r=o/i;return r>n&&(r=n,o=r*i),{width:o,height:r}})(n.width,n.height,920,460),o=((e,t,s)=>{const n=Math.max(e-s,100);return{width:n,height:t*(n/e)}})(i.width,i.height,50),r=e.addImage({base64:s.chartImageDataUrl,extension:"png"});if(t.addImage(r,{tl:{col:0,row:a+.5},ext:{width:o.width,height:o.height}}),s.legends&&s.legends.length>0){const e=Math.ceil(o.height/20)+1,n=a+e;s.legends.forEach((e,s)=>{const i=n+s;t.getRow(i).height=18,l>1&&t.mergeCells(i,2,i,l);const o=t.getCell(i,1),r=t.getCell(i,2);o.value="",o.fill={type:"pattern",pattern:"solid",fgColor:{argb:Oe(e.color)||"FFE6E6ED"}},o.border={top:{style:"thin",color:{argb:"FFD4D6D7"}},right:{style:"thin",color:{argb:"FFD4D6D7"}},bottom:{style:"thin",color:{argb:"FFD4D6D7"}},left:{style:"thin",color:{argb:"FFD4D6D7"}}},r.value=e.label,r.font={color:{argb:"FF7C8385"},size:10},r.alignment=d})}}else if(s.table){const e=/^-?\d+(\.\d+)?$/,n=/^-?\d+(\.\d+)?%$/;s.table.rows.forEach((i,o)=>{const r=t.getRow(a+o);
1r.height=20,i.forEach((t,i)=>{const l=Boolean(t.bold)||0===o,a=o-1,u=l?"5656A5":Fe(s.table.defaultBodyFillColor(a,i)),h=Oe(t.fillColor)||(u?`FF${u}`:void 0),p=Oe(t.textColor)||(l?"FFFFFFFF":"FF51595C"),m=r.getCell(i+1),f=`${t.text||""}`.trim(),v=n.test(f),g=!l&&i>1&&e.test(f);if(!l&&i>1&&v){const e=Number(f.replace("%",""));m.value=e/100,m.numFmt="0%"}else m.value=g?Number(f):t.text;m.font={bold:Boolean(t.bold||l),color:{argb:p},size:10},m.alignment=0===i?c:d,m.border={top:{style:"thin",color:{argb:"FFE6E6ED"}},right:{style:"thin",color:{argb:"FFE6E6ED"}},bottom:{style:"thin",color:{argb:"FFE6E6ED"}},left:{style:"thin",color:{argb:"FFE6E6ED"}}},h&&(m.fill={type:"pattern",pattern:"solid",fgColor:{argb:h}})})}),s.table.xlsxMerges&&s.table.xlsxMerges.length>0&&s.table.xlsxMerges.forEach(e=>{t.mergeCells(a+e.fromRow-1,e.fromCol,a+e.toRow-1,e.toCol)})}var u},De=async e=>{if(!e.sections||0===e.sections.length)throw new Error("At least one section is required for export.");const t=new(Ee().Workbook);for(const l of e.sections){const s=t.addWorksheet(l.sheetName);await Te(t,s,{coverQuestion:e.coverQuestion,coverLabel:e.coverLabel,coverSubtitle:e.coverSubtitle,...l})}const s=(new Date).toISOString().replace(/[:.]/g,"-"),n=await t.xlsx.writeBuffer(),i=new Blob([n],{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),o=URL.createObjectURL(i),r=document.createElement("a");r.href=o,r.download=`${e.fileNamePrefix}-${s}.xlsx`,r.click(),URL.revokeObjectURL(o)},Re={Overserved:{color:Z.Overserved,className:"vc-segment-score--overserved"},Underserved:{color:Z.Underserved,className:"vc-segment-score--underserved"},"Appropriately served":{color:Z["Appropriately served"],className:"vc-segment-score--appropriately-served"},"Underserved Tablestakes":{color:Z["Underserved Tablestakes"],className:"vc-segment-score--table-stakes"},"Overserved Tablestakes":{color:Z["Overserved Tablestakes"],className:"vc-segment-score--table-stakes"},Tablestakes:{color:Z.Tablestakes,className:"vc-segment-score--table-stakes"}},Pe="An outcome that is very or extremely important to customers and poorly satisfied with currently available solutions.",ze="An outcome that is unimportant to customers and very or extremely satisfied with currently available solutions.",Le="An outcome that is very important to customers and very well satisfied with currently available solutions.",_e="An outcome that is important to customers and adequately satisfied with currently available solutions.",Me=e=>({content:e,placement:"top",trigger:"hover",getPopupContainer:()=>document.body,overlayClassName:"vc-legend-tooltip",overlayStyle:{maxWidth:420,zIndex:2e3}}),Qe=e=>{let{analytics:t,filtersList:s,outcomesList:i,visibleOutcomes:a,exportQuestion:c}=e;
1const[d,u]=(0,n.useState)([]),[p,m]=(0,n.useState)({}),[f,v]=(0,n.useState)([]),[g,y]=(0,n.useState)([]),[x,b]=(0,n.useState)(!1),I=(0,n.useMemo)(()=>d.map(e=>e.key),[d]);(0,n.useEffect)(()=>{const e=e=>{const{filterCut:t}=e.groupParameter;return Array.isArray(t)&&t.length>0};(t=>{const n=[];if(t.market&&(n.push({key:"market",label:"Total Sample",showToggle:!0}),m(e=>({...e,market:!0}))),t.dataGroups){[...t.dataGroups].sort((e,t)=>{const s=Boolean(e.groupParameter.segment);return s===Boolean(t.groupParameter.segment)?0:s?-1:1}).forEach(t=>{const i=`group-${t.oneBasedIndex.toString()}`;n.push({key:i,label:P(t,s),showToggle:!e(t)}),m(e=>({...e,[i]:!0}))})}y(n)})(t)},[t,s]),(0,n.useEffect)(()=>{u([]);const{market:e,dataGroups:s}=t,n=e=>e?{value:e.opp,status:e.category}:null,o=[];i.forEach(t=>{if(a&&!a.includes(t.id))return;const i={};if(e){const s=n(e.outcomes.find(e=>e.outcomeId===t.id));s&&(i.market=s)}s&&s.forEach(e=>{const s=n(e.outcomes.find(e=>e.outcomeId===t.id));s&&(i[`group-${e.oneBasedIndex.toString()}`]=s)}),Object.keys(i).length>0&&o.push({key:t.id,outcome:t.outcome,scores:i})}),u(o)},[t,i,a]),(0,n.useEffect)(()=>{if(0===f.length)return;const e=new Set(I);v(t=>{const s=t.filter(t=>e.has(t));return s.length===t.length?t:s})},[I,f]);const w=e=>null===e||void 0===e?"\u2014":"number"===typeof e?e.toFixed(1):e,S=e=>{const{value:t,statusHint:s}=(e=>{var t,s,n;if(null===e||void 0===e)return{value:null,statusHint:null};if("number"===typeof e||"string"===typeof e)return{value:e,statusHint:"string"===typeof e?e:null};const i=e.status||e.label||null;return{value:null!==(t=null!==(s=null!==(n=e.value)&&void 0!==n?n:e.label)&&void 0!==s?s:e.status)&&void 0!==t?t:null,statusHint:i}})(e),n=(e=>{if(!e)return null;const t=e.trim().toLowerCase();return Object.keys(Re).find(e=>t===e.toLowerCase())||null})(null!==s&&void 0!==s?s:"string"===typeof t?t:null),i=(e=>{if(!e)return{style:void 0,className:void 0};const t=Re[e];return{style:{backgroundColor:t.color},className:`vc-segment-score ${t.className}`}})(n);return{value:t,decor:i}},C=I.length>0&&f.length>=I.length,k=e=>g.filter(t=>!t.showToggle||e[t.key]).map(e=>({title:e.label,dataIndex:e.key,key:e.key,align:"left",onHeaderCell:()=>({title:e.label}),onCell:t=>{const s=S(t[e.key]).decor;return{className:s.className,style:s.style}},render:e=>(e=>{const{value:t}=S(e);return(0,h.jsx)("span",{children:w(t)})})(e)})),A=(0,h.jsxs)(V.Ay,{style:{minWidth:130},children:[(0,h.jsx)(V.Ay.Item,{onClick:async()=>{if(!x){b(!0);try{const e=xe({analytics:t,filtersList:s,outcomesList:i,visibleOutcomes:a,visibleSegments:p}),n=(c||"").trim();await je({coverQuestion:n.length>0?n:"Insights Export",coverLabel:"QUESTION",coverSubtitle:"Exported Insights via Sia",slideTitle:"Outcomes and Jobs Statements",slideSubtitle:"Opportunity scores by selected variables",fileNamePrefix:"outcomes-and-jobs",table:e,legends:fe})}catch(e){console.error("Failed to export outcomes PowerPoint:",e)}finally{b(!1)}}},disabled:x,children:(0,h.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:8},children:[(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-file-powerpoint"}),"PowerPoint"]})},"pptx"),(0,h.jsx)(V.Ay.Item,{onClick:async()=>{if(!x){b(!0);try{const e=xe({analytics:t,filtersList:s,outcomesList:i,visibleOutcomes:a,visibleSegments:p,metricColumnMode:"groupedOppImpSat"}),n=(c||"").trim();await $e({coverQuestion:n.length>0?n:"Insights Export",coverLabel:"QUESTION",coverSubtitle:"Exported Insights via Sia",sheetName:"Outcomes",fileNamePrefix:"outcomes-and-jobs",table:e,legends:fe})}catch(e){console.error("Failed to export outcomes Excel:",e),l.A.show({content:"Unable to export Excel right now.",type:"error"})}finally{b(!1)}}},children:(0,h.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:8},children:[(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-file-excel"}),"Excel"]})},"xlsx")]}),N=[{title:(0,h.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:8,paddingLeft:8},children:[(0,h.jsx)("span",{className:"expand-icon vc-expandable-insights-switch",role:"button",tabIndex:0===I.length?void 0:0,style:{cursor:0===I.length?"not-allowed":"pointer",opacity:0===I.length?.5:1,pointerEvents:0===I.length?"none":"auto"},onClick:()=>{v(C?[]:I)},children:(0,h.jsx)(r.A,{type:"regular",size:"12",icon:C?"fa-minus":"fa-plus"})}),(0,h.jsx)("span",{children:"ID"})]}),dataIndex:"key",key:"key",width:100,render:(e,t)=>{const s=f.includes(t.key);return(0,h.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:8,cursor:"pointer"},onClick:e=>{var s;e.stopPropagation(),s=t.key,v(e=>e.includes(s)?e.filter(e=>e!==s):[...e,s])},children:[(0,h.jsx)("span",{className:"expand-icon"+(s?" expanded":""),children:(0,h.jsx)(r.A,{type:"regular",size:"12",icon:s?"fa-minus":"fa-plus"})}),(0,h.jsx)("span",{children:e})]})}},{title:(0,h.jsx)("span",{title:"A statement that describes what a group of people is trying to achieve or accomplish in a given situation.",style:{cursor:"help"},children:"Outcome/Job"}),dataIndex:"outcome",key:"outcome",render:(e,t)=>{const s=f.includes(t.key);return(0,h.jsxs)("div",{children:[(0,h.jsx)("span",{className:"vc-expandable-insights-outcome",children:t.outcome}),s?(0,h.jsx)("div",{style:{marginTop:8},children:(0,h.jsx)(W.A,{rowKey:"key",className:"vc-expandable-insights-inner-table",size:"small",cellSpace:8,pagination:!1,bordered:!0,columns:k(p),dataSource:[{key:`${t.key}-scores`,...t.scores}]})}):null]})}}];return(0,h.jsxs)("div",{className:"vc-expandable-insights outcomes-data",
1style:{position:"relative"},children:[(0,h.jsx)("h5",{children:"Outcomes and Jobs Statements"}),(0,h.jsx)("p",{className:"vc-insights-meta",children:"Opportunity scores for selected variables based on importance and satisfaction ratings in the survey."}),(0,h.jsx)("div",{style:{position:"absolute",right:0,top:0,display:"inline-flex",alignItems:"center"},children:(0,h.jsx)(Q.A,{overlay:A,trigger:["click"],placement:"bottomRight",arrow:!0,overlayClassName:"vc-export-dropdown",getPopupContainer:e=>e.closest(".vc-insights-container")||document.body,children:(0,h.jsxs)(o.A,{type:"link",color:"secondary-1",size:"xsmall",disabled:x,style:{display:"inline-flex",alignItems:"center",gap:4},children:["Export",(0,h.jsx)(r.A,{type:"regular",size:"12",icon:"fa-arrow-right-from-bracket"})]})})}),(0,h.jsx)(W.A,{rowKey:"key",className:"vc-insights-table vc-expandable-insights-table",size:"small",bordered:!0,columns:N,dataSource:d,pagination:!1,title:()=>(0,h.jsx)("div",{className:"vc-expandable-insights-switches-overlay",children:g.filter(e=>e.showToggle).map(e=>(0,h.jsxs)("label",{className:"vc-expandable-insights-switch",style:{display:"inline-flex",gap:8,alignItems:"center"},children:[(0,h.jsx)(M.A,{size:"small",checked:p[e.key],onChange:t=>((e,t)=>{m(s=>({...s,[e]:t}))})(e.key,t)}),(0,h.jsx)("span",{children:e.label})]},e.key))})}),(0,h.jsxs)("div",{className:"vc-profile-legend",children:[(0,h.jsxs)("div",{className:"vc-profile-legend__item",children:[(0,h.jsx)("span",{className:"vc-profile-legend__swatch overserved"}),(0,h.jsx)(j.A,{...Me(ze),children:(0,h.jsx)("span",{style:{cursor:"help"},children:"Overserved"})})]}),(0,h.jsxs)("div",{className:"vc-profile-legend__item",children:[(0,h.jsx)("span",{className:"vc-profile-legend__swatch underserved"}),(0,h.jsx)(j.A,{...Me(Pe),children:(0,h.jsx)("span",{style:{cursor:"help"},children:"Underserved"})})]}),(0,h.jsxs)("div",{className:"vc-profile-legend__item",children:[(0,h.jsx)("span",{className:"vc-profile-legend__swatch appropriately-served"}),(0,h.jsx)(j.A,{...Me(_e),children:(0,h.jsx)("span",{style:{cursor:"help"},children:"Appropriately Served"})})]}),(0,h.jsxs)("div",{className:"vc-profile-legend__item",children:[(0,h.jsx)("span",{className:"vc-profile-legend__swatch table-stakes"}),(0,h.jsx)(j.A,{...Me(Le),children:(0,h.jsx)("span",{style:{cursor:"help"},children:"Table Stakes"})})]})]})]})},Ue={higher:{color:"#fff3d6",className:"vc-profile-segment--higher"},lower:{color:"#e9f3fb",className:"vc-profile-segment--lower"}},He="Datacut is significantly higher than all other datacuts combined",Be="Datacut is significantly lower than all other datacuts combined",Ge=e=>({content:e,placement:"top",trigger:"hover",getPopupContainer:()=>document.body,overlayClassName:"vc-legend-tooltip",overlayStyle:{maxWidth:420,zIndex:2e3}}),Ve=e=>{let{analytics:t,profileList:s,visibleProfiles:i,exportQuestion:a}=e;const[c,d]=(0,n.useState)({}),[u,p]=(0,n.useState)([]),[m,f]=(0,n.useState)([]),[v,g]=(0,n.useState)(!1);(0,n.useEffect)(()=>{var e,n;const i={},o=[],r=[],l=new Set,a=(e,t,s)=>{if(l.has(e))return;l.add(e),i[e]=!0;const n={key:e,label:t,showToggle:s};s?o.push(n):r.push(n)};null!==(e=t.market)&&void 0!==e&&e.profiles&&t.market.profiles.length>0&&a("totalSample","Total Sample",!0),null===(n=t.dataGroups)||void 0===n||n.forEach(e=>{if(e.groupParameter.segment&&!e.groupParameter.filterCut&&e.profiles.length>0&&a(e.groupParameter.segment,`Segment ${e.groupParameter.segment}`,!0),e.groupParameter.filterCut&&e.profiles.length>0){const t=e.groupParameter.filterCut.map(e=>`${e.profileQId}|${e.profileOptionId}`).join("+"),n=z(e.groupParameter.filterCut,s);a(t,n||`${t}`,!1)}}),d(i),p([...o,...r])},[t,s]),(0,n.useEffect)(()=>{const e=(e,t)=>t.profiles.filter(t=>t.filterItem.profileQId===e),n=new Set;s.forEach(e=>{n.add(e.filterId)});const o=[];n.forEach(n=>{var r;if(!i.includes(n))return;const l=s.filter(e=>e.filterId===n),a=(e=>{var s,n;return(null===(s=t.market)||void 0===s||null===(n=s.profiles)||void 0===n?void 0:n.filter(t=>t.filterItem.profileQId===e))||[]})(n);if(0===a.length)return;const c={key:n,variable:n,label:l[0].filterDesc,options:[]};
1a.forEach(e=>{var t;const s={key:`${e.filterItem.profileQId}|${e.filterItem.profileOptionId}`,label:(null===(t=l.find(t=>t.optId===e.filterItem.profileOptionId))||void 0===t?void 0:t.optDesc)||"",values:{totalSample:Math.round(100*e.percentage)}};c.options.push(s)});const d=[];null===(r=t.dataGroups)||void 0===r||r.forEach(t=>{if(t.groupParameter.filterCut)d.push(t);else if(t.groupParameter.segment&&!t.groupParameter.filterCut&&t.profiles.length>0){const s=t.groupParameter.segment,i=e(n,t);if(0===i.length)return;i.forEach(e=>{const t=c.options.find(t=>t.key===`${e.filterItem.profileQId}|${e.filterItem.profileOptionId}`);t&&(t.values[s]=Math.round(100*e.filterItemPercentage),void 0===t.significance&&(t.significance={}),t.significance[s]=1===e.significanceLevel?"higher":-1===e.significanceLevel?"lower":void 0)})}}),d.forEach(t=>{const{filterCut:s}=t.groupParameter;if(!s)return;const i=s.map(e=>`${e.profileQId}|${e.profileOptionId}`).join("+");e(n,t).forEach(e=>{const t=c.options.find(t=>t.key===`${e.filterItem.profileQId}|${e.filterItem.profileOptionId}`);t&&(t.values[i]=Math.round(100*e.filterItemPercentage),void 0===t.significance&&(t.significance={}),t.significance[i]=1===e.significanceLevel?"higher":-1===e.significanceLevel?"lower":void 0)})}),o.push(c)}),f(o)},[t,s,i]);const[y,x]=(0,n.useState)([]),b=(0,n.useMemo)(()=>m.map(e=>e.key),[m]),I=b.length>0&&y.length>=b.length,w=e=>[{title:"",dataIndex:"option",key:"option",align:"left",onHeaderCell:()=>({title:""})},...u.filter(t=>!t.showToggle||e[t.key]).map(e=>({title:e.label,dataIndex:e.key,key:e.key,align:"left",onHeaderCell:()=>({title:e.label}),onCell:t=>{var s;const n=(e=>{if(!e)return{style:void 0,className:void 0};const t=Ue[e];return{style:{backgroundColor:t.color},className:`vc-profile-segment ${t.className}`}})((null===(s=t.__significance)||void 0===s?void 0:s[e.key])||null);return{className:n.className,style:n.style}},render:e=>{return null===(t=e)||void 0===t?"\u2014":`${t}%`;var t}}))],S=(0,h.jsxs)(V.Ay,{style:{minWidth:130},children:[(0,h.jsx)(V.Ay.Item,{onClick:async()=>{if(!v){g(!0);try{const e=be({analytics:t,profileList:s,visibleProfiles:i,visibleSegments:c}),n=(a||"").trim();await je({coverQuestion:n.length>0?n:"Insights Export",coverLabel:"QUESTION",coverSubtitle:"Exported Insights via Sia",slideTitle:"Profiling Data",slideSubtitle:"Relationship between selected variables",fileNamePrefix:"profiling-data",table:e,legends:ve})}catch(e){console.error("Failed to export profiling PowerPoint:",e)}finally{g(!1)}}},disabled:v,children:(0,h.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:8},children:[(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-file-powerpoint"}),"PowerPoint"]})},"pptx"),(0,h.jsx)(V.Ay.Item,{onClick:async()=>{if(!v){g(!0);try{const e=be({analytics:t,profileList:s,visibleProfiles:i,visibleSegments:c}),n=(a||"").trim();await $e({coverQuestion:n.length>0?n:"Insights Export",coverLabel:"QUESTION",coverSubtitle:"Exported Insights via Sia",sheetName:"Profiling",fileNamePrefix:"profiling-data",table:e,legends:ve})}catch(e){console.error("Failed to export profiling Excel:",e),l.A.show({content:"Unable to export Excel right now.",type:"error"})}finally{g(!1)}}},children:(0,h.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:8},children:[(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-file-excel"}),"Excel"]})},"xlsx")]}),C=[{title:(0,h.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:8,paddingLeft:8},children:[(0,h.jsx)("span",{className:"expand-icon vc-expandable-insights-switch",role:"button",tabIndex:0===b.length?void 0:0,style:{cursor:0===b.length?"not-allowed":"pointer",opacity:0===b.length?.5:1,pointerEvents:0===b.length?"none":"auto"},onClick:()=>x(I?[]:b),children:(0,h.jsx)(r.A,{type:"regular",size:"12",icon:I?"fa-minus":"fa-plus"})}),(0,h.jsx)("span",{children:"ID"})]}),dataIndex:"variable",key:"variable",width:90,render:(e,t)=>{const s=y.includes(t.key);return(0,h.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:8,cursor:"pointer"},onClick:e=>{var s;e.stopPropagation(),s=t.key,x(e=>e.includes(s)?e.filter(e=>e!==s):[...e,s])},children:[(0,h.jsx)("span",{className:"expand-icon"+(s?" expanded":""),children:(0,h.jsx)(r.A,{type:"regular",size:"12",icon:s?"fa-minus":"fa-plus"})}),(0,h.jsx)("span",{children:e})]})}},{title:"Label",dataIndex:"label",key:"label",render:(e,t)=>{const s=y.includes(t.key),n=w(c),i=t.options.map(e=>({key:e.key,option:e.label,__significance:e.significance,...e.values}));return(0,h.jsxs)("div",{children:[(0,h.jsx)("span",{className:"vc-expandable-insights-outcome",children:t.label}),s?(0,h.jsx)("div",{style:{marginTop:8},children:i.length>0?(0,h.jsx)(W.A,{rowKey:"key",className:"vc-expandable-insights-inner-table",size:"small",cellSpace:8,pagination:!1,bordered:!0,columns:n,dataSource:i}):(0,h.jsx)("div",{style:{padding:"12px 8px",color:"var(--neutral-7)",background:"var(--neutral-2)",borderRadius:6},children:"No profile details available."})}):null]})}}];return(0,h.jsxs)("div",{className:"vc-expandable-insights profiling-data",style:{position:"relative"},children:[(0,h.jsx)("h5",{children:"Profiling Data"}),(0,h.jsx)("p",{className:"vc-insights-meta",children:"Relationship between selected variables based on the screening and profiling questions in the survey."}),(0,h.jsx)("div",{style:{position:"absolute",right:0,top:0,display:"inline-flex",alignItems:"center"},children:(0,h.jsx)(Q.A,{overlay:S,trigger:["click"],placement:"bottomRight",arrow:!0,overlayClassName:"vc-export-dropdown",getPopupContainer:e=>e.closest(".vc-insights-container")||document.body,children:(0,h.jsxs)(o.A,{type:"link",color:"secondary-1",size:"xsmall",disabled:v,style:{display:"inline-flex",alignItems:"center",gap:4},children:["Export",(0,h.jsx)(r.A,{type:"regular",size:"12",icon:"fa-arrow-right-from-bracket"})]})})}),(0,h.jsx)(W.A,{rowKey:"key",className:"vc-insights-table vc-expandable-insights-table",size:"small",bordered:!0,columns:C,dataSource:m,pagination:!1,title:()=>(0,h.jsx)("div",{className:"vc-expandable-insights-switches-overlay",children:u.filter(e=>e.showToggle).map(e=>(0,h.jsxs)("label",{className:"vc-expandable-insights-switch",style:{display:"inline-flex",gap:8,alignItems:"center"},children:[(0,h.jsx)(M.A,{size:"small",checked:c[e.key],onChange:t=>((e,t)=>{d(s=>({...s,[e]:t}))})(e.key,t)}),(0,h.jsx)("span",{children:e.label})]},e.key))})}),(0,h.jsxs)("div",{className:"vc-profile-legend",children:[(0,h.jsxs)("div",{className:"vc-profile-legend__item",children:[(0,h.jsx)("span",{className:"vc-profile-legend__swatch higher"}),(0,h.jsx)(j.A,{...Ge(He),children:(0,h.jsx)("span",{style:{cursor:"help"},children:'Significantly > "all others"'})})]}),(0,h.jsxs)("div",{className:"vc-profile-legend__item",children:[(0,h.jsx)("span",{className:"vc-profile-legend__swatch lower"}),(0,h.jsx)(j.A,{...Ge(Be),children:(0,h.jsx)("span",{style:{cursor:"help"},children:'Significantly < "all others"'})})]})]})]})},We=()=>(0,h.jsx)("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"400px",
1width:"100%"},children:(0,h.jsx)(r.A,{type:"solid",size:"20",icon:"fa-spinner",style:{color:"var(--tertiary3-5)",animation:"spin 3s linear infinite"}})});var qe=s(6659),Ke=s(6464),Je=s(7666),Ye=s(3229),Ze=s(9367),Xe=s(2981),et=s(7751);const tt=async e=>{if(!e)throw new Error("Export target is not ready.");return(0,et.$E)(e,{cacheBust:!0,pixelRatio:2,backgroundColor:"#ffffff",style:{marginTop:"0",marginBottom:"0"}})},st=(e,t,s,n)=>[t,e,`(${s}, ${n})`].join("\n"),nt=e=>{let{analytics:t,filters:s,outcomesList:i,visibleOutcomes:a,exportQuestion:c,onExportLegendsChange:d}=e;const[u,p]=(0,n.useState)([]),[m,f]=(0,n.useState)([]),[v,g]=(0,n.useState)({}),[y,x]=(0,n.useState)(!1),b=(0,n.useRef)(null);(0,n.useEffect)(()=>{const e=e=>Math.round(10*e)/10,n=new Map(i.map(e=>[e.id,e.outcome])),o=e=>n.get(e)||e,r=[],l=[],c=ne({analytics:t,filtersList:s,visibleOutcomes:a});if(t.market){const s=[];t.market.outcomes.forEach(t=>{a&&!a.includes(t.outcomeId)||s.push({id:t.outcomeId,legendKey:"market",x:e(t.imp),y:e(t.sat),outcome:o(t.outcomeId),tooltipLabel:st(o(t.outcomeId),"Total Sample",e(t.imp),e(t.sat)),color:se("market")})}),r.push(...s)}t.dataGroups&&t.dataGroups.forEach(t=>{const n=[],i=`g${t.oneBasedIndex}`,l=se(i),c=P(t,s);t.outcomes.forEach(t=>{a&&!a.includes(t.outcomeId)||n.push({id:t.outcomeId,legendKey:i,x:t.imp,y:t.sat,outcome:o(t.outcomeId),tooltipLabel:st(o(t.outcomeId),c,e(t.imp),e(t.sat)),color:l})}),r.push(...n)}),l.push(...c.map(e=>({key:e.key,name:e.label,symbol:{fill:e.color,type:"circle"}}))),p(r),f(l)},[t,s,i,a]),(0,n.useEffect)(()=>{g(e=>{const t={};return m.forEach(s=>{var n;t[s.key]=null===(n=e[s.key])||void 0===n||n}),t})},[m]);const I=u.filter(e=>{var t;return null===(t=v[e.legendKey])||void 0===t||t});(0,n.useEffect)(()=>{if(!d)return;const e=m.filter(e=>{var t;return null===(t=v[e.key])||void 0===t||t}).map(e=>({label:e.name,color:e.symbol.fill}));d(e)},[m,v,d]);const w=async e=>{if(!y){x(!0);try{const t=await(async()=>tt(b.current))(),s=m.filter(e=>{var t;return null===(t=v[e.key])||void 0===t||t}).map(e=>({label:e.name,color:e.symbol.fill})),n=(c||"").trim(),i=n.length>0?n:"Insights Export";"pptx"===e?await je({coverQuestion:i,coverLabel:"QUESTION",coverSubtitle:"Exported Insights via Sia",slideTitle:le,slideSubtitle:ae,fileNamePrefix:"outcome-landscape",chartImageDataUrl:t,legends:s}):await $e({coverQuestion:i,coverLabel:"QUESTION",coverSubtitle:"Exported Insights via Sia",sheetName:ce,fileNamePrefix:"outcome-landscape",chartImageDataUrl:t,legends:s})}catch(t){console.error(`Failed to export landscape ${e}:`,t),l.A.show({content:"pptx"===e?"Unable to export PowerPoint right now.":"Unable to export Excel right now.",type:"error"})}finally{x(!1)}}},S=(0,h.jsxs)(V.Ay,{style:{minWidth:130},children:[(0,h.jsx)(V.Ay.Item,{onClick:async()=>w("pptx"),disabled:y,children:(0,h.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:8},children:[(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-file-powerpoint"}),"PowerPoint"]})},"pptx"),(0,h.jsx)(V.Ay.Item,{onClick:async()=>w("xlsx"),disabled:y,children:(0,h.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:8},children:[(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-file-excel"}),"Excel"]})},"xlsx")]});return(0,h.jsxs)("div",{className:"vc-insights-landscape",role:"img","aria-label":"Outcome scatter landscape",style:{position:"relative"},children:[(0,h.jsx)("h5",{children:"Opportunity Landscape"}),(0,h.jsx)("p",{className:"vc-insights-meta",children:"Visual depiction of the quantified opportunities."}),(0,h.jsx)("div",{style:{position:"absolute",right:0,top:0,display:"inline-flex",alignItems:"center"},children:(0,h.jsx)(Q.A,{overlay:S,trigger:["click"],placement:"bottomRight",arrow:!0,overlayClassName:"vc-export-dropdown",getPopupContainer:e=>e.closest(".vc-insights-container")||document.body,children:(0,h.jsxs)(o.A,{type:"link",color:"secondary-1",size:"xsmall",disabled:y,style:{display:"inline-flex",alignItems:"center",gap:4},children:["Export",(0,h.jsx)(r.A,{type:"regular",size:"12",icon:"fa-arrow-right-from-bracket"})]})})}),(0,h.jsxs)("div",{className:"vc-insights-landscape__export-target",children:[(0,h.jsx)("div",{ref:b,className:"vc-insights-landscape__chart",children:(0,h.jsxs)(Ke.t,{domain:{x:[0,10],y:[0,10]},padding:{top:0,bottom:0,left:0,right:0},containerComponent:(0,h.jsx)(Je.EL,{voronoiPadding:0,radius:12,labels:e=>{let{datum:t}=e;return(s=null===t||void 0===t?void 0:t.tooltipLabel)?s.split("\n").map(e=>
1{const t=e.split(/\s+/).filter(Boolean);if(0===t.length)return"";const s=[];let n=t[0];for(let i=1;i<t.length;i++){const e=`${n} ${t[i]}`;e.length>56?(s.push(n),n=t[i]):n=e}return s.push(n),s.join("\n")}).join("\n"):"";var s},labelComponent:(0,h.jsx)(Ye.A,{flyoutStyle:{fill:"#ffffff",stroke:"rgba(0, 0, 0, 0.08)"},style:{fontSize:10,fill:"#4a4a55",fontFamily:"Gibson",textAnchor:"start",lineHeight:1.2},lineHeight:1.2,flyoutPadding:{top:4,bottom:4,left:8,right:8},cornerRadius:6,pointerLength:4,constrainToVisibleArea:!0})}),children:[(0,h.jsx)(Ze.O,{tickFormat:()=>"",style:{axis:{stroke:"transparent"},ticks:{stroke:"transparent"},tickLabels:{fill:"transparent"},grid:{stroke:"transparent"}}}),(0,h.jsx)(Ze.O,{dependentAxis:!0,tickFormat:()=>"",style:{axis:{stroke:"transparent"},ticks:{stroke:"transparent"},tickLabels:{fill:"transparent"},grid:{stroke:"transparent"}}}),(0,h.jsx)(Xe.J,{size:4,style:{data:{fill:e=>{let{datum:t}=e;return t.color},stroke:"white",strokeWidth:.4,strokeOpacity:.5,opacity:.92}},data:I})]})}),m.length>0&&(0,h.jsx)("div",{className:"vc-insights-landscape__legend",children:(0,h.jsx)("div",{className:"vc-insights-landscape__legend-list",children:m.map(e=>{var t,s;return(0,h.jsxs)("div",{className:"vc-insights-landscape__legend-item",children:[(0,h.jsx)(qe.A,{checked:null===(t=v[e.key])||void 0===t||t,onChange:t=>{var s;const n=Boolean(null===t||void 0===t||null===(s=t.target)||void 0===s?void 0:s.checked);g(t=>({...t,[e.key]:n}))},className:"vc-insights-landscape__legend-checkbox"}),(0,h.jsx)("span",{className:"vc-insights-landscape__legend-dot",style:{backgroundColor:e.symbol.fill}}),(0,h.jsx)(j.A,{...(s=e.name,{content:s,placement:"top",trigger:"hover",getPopupContainer:()=>document.body,overlayClassName:"vc-legend-tooltip",overlayStyle:{maxWidth:420,zIndex:2e3}}),children:(0,h.jsx)("span",{className:"vc-insights-landscape__legend-label",style:{cursor:"help"},children:e.name})})]},e.key)})})})]})]})},it=e=>{let{elemKey:t,onClose:s,message:i,sessionId:a,outcomesList:c,filters:d}=e;
1const u=(0,n.useRef)(null),[p,m]=(0,n.useState)(!0),[f,v]=(0,n.useState)(null),[g,y]=(0,n.useState)(!1),[x,b]=(0,n.useState)([]),[I,j]=(0,n.useState)({opportunitySpaces:!1,marketAndGroups:!1,respondentsProfile:!1}),[S,k]=(0,n.useState)(void 0),[A,N]=(0,n.useState)([]);if((0,n.useEffect)(()=>{var e,t,s;const n={opportunitySpaces:!1,marketAndGroups:!1,respondentsProfile:!1};if(null!==(e=i.attribution)&&void 0!==e&&e.usedProfileIds&&i.attribution.usedProfileIds.length>0){const e=new Set;i.attribution.usedProfileIds.forEach(t=>{e.add(t)}),N(Array.from(e)),n.respondentsProfile=!0}else N([]),n.respondentsProfile=!1;if(null!==(t=i.attribution)&&void 0!==t&&t.usedOutcomeIds&&i.attribution.usedOutcomeIds.length>0){const e=new Set;i.attribution.usedOutcomeIds.forEach(t=>{e.add(t)}),k(Array.from(e)),n.marketAndGroups=!0}else n.marketAndGroups=!1,k(void 0);null===(s=i.attribution)||void 0===s||s.items.forEach(e=>{e.opportunitySpaces&&(n.opportunitySpaces=!0)}),j(n)},[i.attribution]),(0,n.useEffect)(()=>{(async()=>{m(!0);try{if(i.analytics){const e=await(0,C.x7)(i.analytics);e.exists()?v(e.data()):v(null)}else if(null===i.analytics){const e=await async function(e){return(await w("fetchAnalytics")(e)).data}({sessionId:a,interactionId:i.interactionId});v(e)}else v(null)}catch(e){console.error("fs - exp fetch analytics",e),v(null)}finally{m(!1)}})()},[i.analytics,i.interactionId,a]),(0,n.useEffect)(()=>{const e=e=>{"Escape"===e.key&&s()};return window.addEventListener("keydown",e),()=>{window.removeEventListener("keydown",e)}},[s]),(0,n.useEffect)(()=>{I.marketAndGroups||b([])},[I.marketAndGroups]),"completed_pending_attribution"===i.status)return null;const E=()=>f?"dynamic_group_hierarchy"===f.analyticsType?f:"composite"===f.analyticsType?f.groupsAndCrosstab:null:null,F=async e=>{const t=[],s=[];if(I.marketAndGroups){const n=xe({analytics:e,filtersList:d,outcomesList:c,visibleOutcomes:S});n.rows.length>1&&t.push({slideTitle:ie,slideSubtitle:oe,table:n,legends:fe});const i=xe({analytics:e,filtersList:d,outcomesList:c,visibleOutcomes:S,metricColumnMode:"groupedOppImpSat"});i.rows.length>1&&s.push({sheetName:re,table:i,legends:fe});const o=await(async()=>{var e;const t=null===(e=u.current)||void 0===e?void 0:e.querySelector(".vc-insights-landscape__chart");return tt(t)})(),r=x.length>0?x:(e=>{let{analytics:t,filtersList:s,visibleOutcomes:n}=e;return ne({analytics:t,filtersList:s,visibleOutcomes:n}).map(e=>({label:e.label,color:e.color}))})({analytics:e,filtersList:d,visibleOutcomes:S});t.push({slideTitle:le,slideSubtitle:ae,chartImageDataUrl:o,legends:r}),s.push({sheetName:ce,chartImageDataUrl:o,legends:r})}if(I.respondentsProfile){const n=be({analytics:e,profileList:d,visibleProfiles:A});n.rows.length>1&&(t.push({slideTitle:de,slideSubtitle:ue,table:n,legends:ve}),s.push({sheetName:he,table:n,legends:ve}))}return{deckSections:t,workbookSections:s}},O=(0,h.jsxs)(V.Ay,{style:{minWidth:130},children:[(0,h.jsx)(V.Ay.Item,{onClick:async()=>{if(g)return;const e=E();if(e){y(!0);try{const{deckSections:t}=await F(e);if(0===t.length)return void l.A.show({content:"No exportable insights sections are available yet.",type:"warning"});const s=(i.userQuery||"").trim();await Ae({coverQuestion:s.length>0?s:"Insights Export",coverLabel:"QUESTION",coverSubtitle:"Exported Insights via Sia",fileNamePrefix:"insights-export",sections:t})}catch(t){console.error("Failed to export full insights PowerPoint:",t),l.A.show({content:"Unable to export PowerPoint right now.",type:"error"})}finally{y(!1)}}else l.A.show({content:"No exportable insights sections are available yet.",type:"warning"})},disabled:g,children:(0,h.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:8},children:[(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-file-powerpoint"}),"PowerPoint"]})},"pptx"),(0,h.jsx)(V.Ay.Item,{onClick:async()=>{if(g)return;const e=E();if(e){y(!0);try{const{workbookSections:t}=await F(e);if(0===t.length)return void l.A.show({content:"No exportable insights sections are available yet.",type:"warning"});const s=(i.userQuery||"").trim();await De({coverQuestion:s.length>
10?s:"Insights Export",coverLabel:"QUESTION",coverSubtitle:"Exported Insights via Sia",fileNamePrefix:"insights-export",sections:t})}catch(t){console.error("Failed to export full insights Excel:",t),l.A.show({content:"Unable to export Excel right now.",type:"error"})}finally{y(!1)}}else l.A.show({content:"No exportable insights sections are available yet.",type:"warning"})},disabled:g,children:(0,h.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:8},children:[(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-file-excel"}),"Excel"]})},"xlsx")]});return(0,h.jsx)("div",{className:"vc-insights-overlay",role:"dialog","aria-modal":"true","aria-label":"Insights drawer",onClick:s,children:(0,h.jsxs)("div",{className:"vc-insights-container",ref:u,onClick:e=>e.stopPropagation(),children:[(0,h.jsxs)("div",{className:"vc-insights-header",children:[(0,h.jsxs)("div",{className:"vc-insights-title",children:[(0,h.jsx)(r.A,{type:"regular",size:"12",icon:"fa-bar-chart",style:{marginRight:4}}),"Data Panel"]}),(0,h.jsxs)("div",{className:"vc-insights-actions",children:[(0,h.jsx)(Q.A,{overlay:O,trigger:["click"],placement:"bottomRight",arrow:!0,overlayClassName:"vc-export-dropdown",getPopupContainer:e=>e.closest(".vc-insights-container")||document.body,children:(0,h.jsxs)(o.A,{type:"alternative",color:"secondary-1",size:"small",disabled:g,children:[(0,h.jsx)(r.A,{type:"solid",size:"14",icon:"fa-arrow-right-from-bracket"}),"Export All"]})}),(0,h.jsx)(o.A,{type:"link",color:"neutral",size:"small",onClick:s,children:(0,h.jsx)(r.A,{type:"solid",size:"14",icon:"fa-xmark"})})]})]}),p?(0,h.jsx)(We,{}):f?(0,h.jsxs)(h.Fragment,{children:[void 0===f.analyticsType&&f.marketSegments?(0,h.jsx)(K,{elemKey:`asi-${t}-${i.interactionId}`,analytics:f.marketSegments,outcomesList:c,filters:d}):null,void 0===f.analyticsType&&f.strategicOpportunities?(0,h.jsx)(Y,{elemKey:`osi-${t}-${i.interactionId}`,analytics:f.strategicOpportunities,outcomesList:c}):null,"strategic_opportunities"===f.analyticsType?(0,h.jsx)(Y,{elemKey:`osi-${t}-${i.interactionId}`,analytics:f.strategicOpportunities,outcomesList:c,visibleOutcomes:S}):null,"dynamic_group_hierarchy"===f.analyticsType?(0,h.jsxs)(h.Fragment,{children:[I.marketAndGroups&&(0,h.jsx)(Qe,{analytics:f,filtersList:d,outcomesList:c,visibleOutcomes:S,exportQuestion:i.userQuery}),I.marketAndGroups&&(0,h.jsx)(nt,{analytics:f,filters:d,outcomesList:c,visibleOutcomes:S,exportQuestion:i.userQuery,onExportLegendsChange:b}),I.respondentsProfile&&(0,h.jsx)(Ve,{analytics:f,profileList:d,visibleProfiles:A,exportQuestion:i.userQuery})]}):null,"composite"===f.analyticsType?(0,h.jsxs)(h.Fragment,{children:[I.marketAndGroups&&(0,h.jsx)(Qe,{analytics:f.groupsAndCrosstab,filtersList:d,outcomesList:c,visibleOutcomes:S,exportQuestion:i.userQuery}),I.respondentsProfile&&(0,h.jsx)(Ve,{analytics:f.groupsAndCrosstab,profileList:d,visibleProfiles:A,exportQuestion:i.userQuery}),I.opportunitySpaces&&(0,h.jsx)(Y,{elemKey:`comp-osi-${t}-${i.interactionId}`,analytics:f.strategicOpportunities,outcomesList:c,visibleOutcomes:S}),I.marketAndGroups&&(0,h.jsx)(nt,{analytics:f.groupsAndCrosstab,filters:d,outcomesList:c,visibleOutcomes:S,exportQuestion:i.userQuery,onExportLegendsChange:b})]}):null]}):(0,h.jsx)("div",{className:"vc-insights-empty-state",children:"No insights available."})]})},`insights-drawer-${t}`)},ot="vcChatSessions",rt="interactions";class lt extends k.A{getInteractionCollectionRef(e){const t=(0,C.H9)(this.getUserDocRef(),ot,e);return(0,C.rJ)(t,rt)}async loadChatSession(e){if(!e)return null;try{const r=(0,C.H9)(this.getUserDocRef(),ot,e),l=await(0,C.x7)(r);if(l.exists()&&l.data()){var t,s,n,i,o;const e=l.data();if(!e.studyIds)throw new m.Q("cen/doc-loading-error","No studyIds in chat session");return{sessionId:e.sessionId,updatedAt:e.updatedAt,showInsightsSummary:null===(t=e.showInsightsSummary)||void 0===t||t,showRecommendations:null!==(s=e.showRecommendations)&&void 0!==s&&s,disableRecommendations:null!==(n=e.disableRecommendations)&&void 0!==n&&n,selectedRecommendations:null!==(i=e.selectedRecommendations)&&void 0!==i?i:[],createdAt:e.createdAt,studyIds:e.studyIds,sharedInsights:null!==(o=e.sharedInsights)&&void 0!==o?o:[]}}return null}catch(r){throw r}}async updateDocFields(e,t){try{const s=(0,C.H9)(this.getUserDocRef(),ot,e);await(0,C.mZ)(s,t);const n=await this.loadChatSession(e);if(!n)throw new m.Q("cen/internal-error");return n}catch(s){throw s}}updateInsightRulesForChat(e,t,s,n){const i=(0,C.H9)(this.getUserDocRef(),ot,t);e.update(i,s,n)}async updateInsightRulesForInteraction(e,t,s,n,i){const o=(0,C.rJ)(this.getUserDocRef(),ot,t,rt),r=(0,C.P)(o,(0,C._M)("interactionId","==",s),(0,C.AB)(1)),l=await(0,C.GG)(r);
1if(l.empty)throw new m.Q("cen/doc-not-found","Response not found");const a=l.docs[0].ref;e.update(a,n,i)}async deleteChatSession(e){try{const t=(0,C.H9)(this.getUserDocRef(),ot,e);await(0,C.kd)(t)}catch(t){throw t}}async deleteInteraction(e,t){try{const[s]=await this.getChatThread(e),n=(0,C.P)((0,C.rJ)(s,rt),(0,C._M)("interactionId","==",t),(0,C.AB)(1)),i=await(0,C.GG)(n);if(0===i.docs.length)throw new m.Q("cen/doc-not-found");await(0,C.kd)(i.docs[0].ref)}catch(s){throw s}}getNewChatSessionHeader(e){return{docRef:(0,C.H9)(this.getUserDocRef(),ot,e),createdAt:C.Dc.now(),updatedAt:C.Dc.now()}}async getChatThread(e){const t=(0,C.H9)(this.getUserDocRef(),ot,e),s=await(0,C.x7)(t);if(s.exists())return[t,s.data()];throw new Error("Document does not exist")}}class at{async fetchStudy(e,t){try{const t=(0,C.rJ)(g.A.getInstance().db,"vc/globalUserAssets/studies").withConverter(ct),s=await(0,C.x7)((0,C.H9)(t,e));return s.exists()?s.data():null}catch(s){if(m.A.is("permission-denied",s)){if(t)throw s;return null}throw s}}}const ct={toFirestore:e=>({}),fromFirestore(e){const t=e.data();return{id:e.id,name:t.name,description:t.description,createdAt:t.createdAt,updatedAt:t.updatedAt,datasets:t.datasets,jobExecutor:t.jobExecutor,jtbd:t.jtbd,productArea:t.productArea,orgName:t.orgName,executorInfo:t.executorInfo,segmentSolution:t.segmentSolution,thrUnderservedMinOpp:t.thrUnderservedMinOpp,thrTablestakesMinOpp:t.thrTablestakesMinOpp,thrTablestakesMinSat:t.thrTablestakesMinSat,thrOverservedMaxOpp:t.thrOverservedMaxOpp,recommendations:t.recommendations,siaIntro:t.siaIntro}}},dt=e=>{let{busy:t,open:s,onConfirm:n,onDecline:i,heading:r,messageText:l,confirmButtonText:a,declineButtonText:u,width:p}=e;return(0,h.jsx)(c.A,{width:p||380,visible:s,destroyOnClose:!0,footer:null,onCancel:i,children:(0,h.jsxs)(d.A,{direction:"vertical",size:24,style:{width:"100%"},children:[(0,h.jsx)(d.A,{direction:"vertical",size:8,children:(0,h.jsx)("h3",{children:r||""})}),(0,h.jsx)("p",{children:l}),(0,h.jsxs)(d.A,{direction:"vertical",size:12,children:[(0,h.jsx)(o.A,{block:!0,onClick:n,disabled:t,loading:t,children:a||"Yes"}),(0,h.jsx)(o.A,{block:!0,type:"link",onClick:i,disabled:t,children:u||"No"})]})]})})};var ut=s(4014);const ht="sharedData/vc",pt="insights";class mt extends k.A{async createInsightsDoc(e){const t=(0,C.wP)(this.db),s=await(new ut.A).getCurrentUser(),[,n]=this.getInsightRef(),i={id:n.id,title:e.title.trim(),savedBy:{uid:s.id,email:s.email,name:(0,T.Ii)(s)||s.email},savedAt:C.Dc.now(),insightType:e.insightType,studyId:e.sourceStudyId,sourceSessionId:e.sourceSessionId,sourceInteractionId:e.sourceInteractionId};t.set(n,i);const o=new lt;return o.updateInsightRulesForChat(t,e.sourceSessionId,"sharedInsights",(0,C.hq)(n)),e.sourceInteractionId&&await o.updateInsightRulesForInteraction(t,e.sourceSessionId,e.sourceInteractionId,"sharedInsights",(0,C.hq)(n)),await t.commit(),[i,n]}async deleteInsightsDoc(e){const t=(0,C.wP)(this.db),[,s]=this.getInsightRef(e.id);(await this.fetchCommentsList(e.id)).forEach(s=>{const n=this.getInsightCommentRef(e.id,s.id);t.delete(n)});(await this.fetchVotesList(e.id)).forEach(s=>{const n=this.getInsightVoteRef(e.id,s.author.id);t.delete(n)}),t.delete(s);const n=new lt;(new lt).updateInsightRulesForChat(t,e.sourceSessionId,"sharedInsights",(0,C.C3)(s)),e.sourceInteractionId&&await n.updateInsightRulesForInteraction(t,e.sourceSessionId,e.sourceInteractionId,"sharedInsights",(0,C.C3)(s)),await t.commit()}async fetchInsightsList(e){const t=(0,C.rJ)(this.getDomainDocRef(),`${ht}/${pt}`),s=(0,C.P)(t,(0,C._M)("studyId","==",e));return(await(0,C.GG)(s)).docs.map(e=>e.data())}async addComment(e,t){const s=(0,C.H9)(this.getInsightCommentsRef(e)),n={...t,id:s.id};return await(0,C.BN)(s,n),n}async removeComment(e,t){const s=this.getInsightCommentRef(e,t.id);await(0,C.kd)(s)}async fetchCommentsList(e){const t=this.getInsightCommentsRef(e);return(await(0,C.GG)((0,C.P)(t,(0,C.My)("timestamp")))).docs.map(e=>e.data())}async addVote(e,t){const s=this.getInsightVoteRef(e,t.author.id);await(0,C.BN)(s,t)}async removeVote(e,t){const s=this.getInsightVoteRef(e,t.author.id);await(0,C.kd)(s)}
1async updateVote(e,t,s){const n=(0,C.wP)(this.db);t.author.id!==s.author.id&&n.delete(this.getInsightVoteRef(e,t.author.id)),n.set(this.getInsightVoteRef(e,s.author.id),s),await n.commit()}async fetchVotesList(e){const t=this.getInsightVotesRef(e);return(await(0,C.GG)(t)).docs.map(e=>e.data())}getInsightRef(e){const t=(0,C.rJ)(this.getDomainDocRef(),`${ht}/${pt}`);return[t,e?(0,C.H9)(t,e):(0,C.H9)(t)]}getInsightCommentsRef(e){const[,t]=this.getInsightRef(e);return(0,C.rJ)(t,"comments")}getInsightCommentRef(e,t){return(0,C.H9)(this.getInsightCommentsRef(e),t)}getInsightVotesRef(e){const[,t]=this.getInsightRef(e);return(0,C.rJ)(t,"votes")}getInsightVoteRef(e,t){return(0,C.H9)(this.getInsightVotesRef(e),t)}}var ft=s(6951),vt=s(8628),gt=s(1863);gt.xI.use({breaks:!1,gfm:!0});const yt=e=>{let{children:t,className:s="",breaks:i=!1}=e;const[o,r]=(0,n.useState)("");if((0,n.useEffect)(()=>{if("string"!==typeof t||!t)return void r("");const e=e=>(i?e:e.replace(/<br\s*\/?>/gi,'<span class="vc-markdown-br"></span>')).replace(/<hr\s*\/?>/gi,'<span class="vc-markdown-hr"></span>').replace(/(^|>\s*)---(\s*<|$)/g,'$1<span class="vc-markdown-hr"></span>$2');let s=!0;const n=gt.xI.parse(t,{breaks:i});return n instanceof Promise?n.then(t=>{s&&r(e(t))}):r(e(n)),()=>{s=!1}},[t,i]),!o)return null;const l=s?`vc-markdown-content ${s}`.trim():"vc-markdown-content";return(0,h.jsx)("div",{className:l,dangerouslySetInnerHTML:{__html:o}})},xt=e=>e.replace(/(\*\*[^*\n]+\*\*)([.,!?:;]?)[ \t]*(\*[^*\n]+\*)/,"$1$2\n$3"),bt=e=>{let{iconClass:t,markdown:s}=e;
1const i=(0,n.useRef)(null),[o,l]=(0,n.useState)(!0);return(0,n.useLayoutEffect)(()=>{const e=i.current;if(!e)return;const t=2*(parseFloat(getComputedStyle(e).lineHeight)||21)+1,s=()=>l(e.offsetHeight<=t);s();const n=new ResizeObserver(s);return n.observe(e),()=>n.disconnect()},[s]),(0,h.jsxs)("div",{className:"strategy-summary-intro-pointer"+(o?" short":""),children:[(0,h.jsx)("span",{className:"strategy-summary-intro-pointer-icon",children:(0,h.jsx)(r.A,{type:"solid",size:"15",icon:t})}),(0,h.jsx)("div",{className:"strategy-summary-intro-pointer-body",ref:i,children:(0,h.jsx)(yt,{breaks:!0,children:xt(s)})})]})},It=e=>{let{disableCTAs:t,showRecommendationList:s,disableRecommendationList:i,recommendations:l,selectedRecommendations:a,updateThreadSettings:c,jobStepsCount:d,needsCount:u,respondentsCount:p,segmentsCount:f,siaIntro:v,studyId:x,onSessionTitleGenerated:b}=e;const[w,j]=(0,n.useState)(null),[S,C]=(0,n.useState)(!1),[k,A]=(0,n.useState)(!1),[N,E]=(0,n.useState)(!1);(0,n.useEffect)(()=>{j(a.length>0?a[0]:null)},[a]);const F=(()=>{if(!v)return[];
1const e=v.replace(/\\n/g,"\n").replace(/\s*(\[icon:[^\]]+\]|<i\s+class\s*=\s*["'][^"']+["']\s*>\s*<\/i>)/gi,"\n\n$1").split(/\n{2,}/).map(e=>e.trim()).filter(e=>e.length>0);return e.length>0&&/^hi\b/i.test(e[0])?e.slice(1):e})(),O=async e=>{try{C(!0),await c({showRecommendations:e})}finally{C(!1)}},$=l.length>0&&!(i&&!w),T=(0,h.jsxs)(o.A,{type:"link",size:"medium",onClick:()=>E(e=>!e),disabled:t,children:[(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-chart-line"}),N?"Hide Data Summary":"Explore Data Summary"]});return(0,h.jsxs)("div",{style:{paddingBottom:"24px"},children:[(0,h.jsxs)("div",{className:"strategy-summary-card",children:[(0,h.jsxs)("div",{className:"strategy-summary-header",children:[(0,h.jsx)("div",{className:"strategy-summary-icon",children:(0,h.jsx)("img",{src:vt.A,alt:"Sia",style:{height:32,width:32,objectFit:"contain"}})}),(0,h.jsxs)("div",{className:"strategy-summary-title",children:["Hi ",(()=>{var e;const t=g.A.getInstance().auth.currentUser;return(null===t||void 0===t||null===(e=t.email)||void 0===e?void 0:e.split("@")[0])||"there"})(),", I'm Sia \ud83d\udc4b"]})]}),F.length>0&&(0,h.jsx)("div",{className:"strategy-summary-intro",children:F.map((e,t)=>{const{iconClass:s,text:n}=(e=>{const t=e.match(/^\s*\[icon:\s*([^\]]+)\]\s*/i);if(t)return{iconClass:t[1].trim(),text:e.slice(t[0].length)};const s=e.match(/^\s*<i\s+class\s*=\s*["']([^"']+)["']\s*>\s*<\/i>\s*/i);return s?{iconClass:s[1].trim(),text:e.slice(s[0].length)}:{iconClass:null,text:e}})(e);return s?(0,h.jsx)(bt,{iconClass:s,markdown:n},t):(0,h.jsx)(yt,{breaks:!0,children:xt(e)},t)})}),N&&(0,h.jsxs)("div",{className:"strategy-summary-metrics",children:[(0,h.jsxs)("div",{className:"strategy-summary-metric",children:[(0,h.jsx)("div",{className:"metric-label",children:"JOB STEPS"}),(0,h.jsx)("div",{className:"metric-value",children:d||"..."})]}),(0,h.jsxs)("div",{className:"strategy-summary-metric",children:[(0,h.jsx)("div",{className:"metric-label",children:"NEEDS"}),(0,h.jsx)("div",{className:"metric-value",children:u||"..."})]}),(0,h.jsxs)("div",{className:"strategy-summary-metric",children:[(0,h.jsx)("div",{className:"metric-label",children:"RESPONDENTS"}),(0,h.jsx)("div",{className:"metric-value",children:p||"..."})]}),(0,h.jsxs)("div",{className:"strategy-summary-metric",children:[(0,h.jsx)("div",{className:"metric-label",children:"SEGMENTS"}),(0,h.jsx)("div",{className:"metric-value",children:f||"..."})]})]}),$?(0,h.jsxs)("div",{className:"strategy-summary-cta",children:[(0,h.jsx)("div",{className:"strategy-summary-cta-title",children:"Not sure where to start?"}),(0,h.jsx)("div",{className:"strategy-summary-cta-body",children:"I've already looked at your data and picked out the biggest opportunity areas worth digging into."}),(0,h.jsxs)("div",{className:"strategy-summary-cta-body",children:["Hit ",(0,h.jsx)("strong",{children:"See Recommendations"})," below and I'll walk you through what I found."]}),(0,h.jsxs)("div",{className:"strategy-summary-cta-actions",children:[(0,h.jsxs)(o.A,{type:"primary",size:"medium",onClick:()=>O(!s),loading:S,disabled:t,children:[(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-clipboard-list"}),s?"Hide Recommendations":"See Recommendations"]}),T]})]}):(0,h.jsxs)("div",{className:"strategy-summary-actions",children:[s&&(0,h.jsxs)(o.A,{type:"link",size:"medium",onClick:()=>O(!1),loading:S,disabled:t,children:[(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-clipboard-list"}),"Hide Recommendations"]}),T]})]}),s&&(0,h.jsx)("div",{className:"strategy-summary-card recommendations "+(s?"visible":""),children:(0,h.jsxs)("div",{className:"strategy-summary-recommendations",children:[(0,h.jsx)("div",{className:"strategy-summary-title",children:"Based on these insights, Sia recommends:"}),(0,h.jsx)("div",{className:"recommendations-grid",children:l.map(e=>(0,h.jsxs)("div",{className:"recommendation-item "+(w===e.id?"checked":""),onClick:()=>{var t;i||(t=e.id,j(t))},style:{cursor:i?"default":"pointer"},children:[(0,h.jsxs)("label",{style:{cursor:i?"default":"pointer"},children:[(0,h.jsx)(ft.Ay,{name:"recommendations",checked:w===e.id,disabled:i}),(0,h.jsx)("span",{className:"recommendation-label",children:e.text})]}),(0,h.jsxs)("div",{className:"recommendation-info",children:[(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-info-circle"}),e.description]})]},e.id))}),(0,h.jsxs)(o.A,{type:"primary",size:"medium",onClick:async()=>
1{if(w)try{A(!0);const t=await c({disableRecommendations:!0,selectedRecommendations:[w]});if(setTimeout(()=>{window.scrollTo({top:document.documentElement.scrollHeight,behavior:"smooth"})},50),t){var e;const s=null===(e=l.find(e=>e.id===w))||void 0===e?void 0:e.description;s&&(await y({userQuery:s,sessionId:t,cohorts:[]}),I({studyId:x,sessionId:t}).then(e=>{e.title&&b(t,e.title)}).catch(e=>{console.error("fs - rec-title-exp:",e)}))}}catch(t){m.A.handle(t)}finally{A(!1)}},disabled:i||!w,loading:k,children:[(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-lightbulb"}),"Explore selected recommendation"]})]})})]})},wt=e=>{let{vcMessage:t,sessionId:s,studyId:i,setShowInsights:a,setInsightsMessage:c,filters:d,onSaveInsight:u}=e;const[v,g]=(0,n.useState)(null),[y,x]=(0,n.useState)(!1),[I,w]=(0,n.useState)(!1),[j,S]=(0,n.useState)(!1),C=(0,n.useRef)(null),k=(0,n.useMemo)(()=>{var e;const s=t.vcResponse,n=t.attribution;if(!s||"string"!==typeof s||null===n||void 0===n||null===(e=n.items)||void 0===e||!e.length)return s;const i=(e,t)=>{const s=null===t||void 0===t?void 0:t.trim();if(!s)return null;const n=e.indexOf(s);return-1!==n?{start:n,end:n+s.length,matchedText:e.slice(n,n+s.length)}:null},o=e=>{const t=[];return e.opportunitySpaces&&t.push("Opportunity Data"),e.marketAndGroups&&t.push("Opportunity Data"),e.respondentsProfile&&t.push("Profiling Data"),t},r=new Map,l=new Set;for(const t of n.items){if(null===t||void 0===t||!t.chunk)continue;const e=t.chunk.trim();if(!e||l.has(e))continue;const n=o(t);if(!n.length)continue;const a=i(s,t.chunk);if(!a)continue;const c=s.slice(a.end);if(/^\s*(?:<br\s*\/?>\s*)*<sub\b/i.test(c))continue;l.add(e);const d=`${a.start}:${a.end}`,u=r.get(d);if(u)for(const t of n)u.sources.add(t);else r.set(d,{start:a.start,end:a.end,matchedText:a.matchedText,sources:new Set(n)})}if(0===r.size)return s;const a=Array.from(r.values()).map(e=>{let{start:t,end:s,matchedText:n,sources:i}=e;return{start:t,end:s,html:`${n}${Array.from(i).map(e=>`<sub class="vc-attrib-src">${e}</sub>`).join("")}`}}).sort((e,t)=>t.start-e.start);let c=s;for(const{start:t,end:d,html:u}of a)c=c.slice(0,t)+u+c.slice(d);return c},[t.vcResponse,t.attribution]);(0,n.useEffect)(()=>{t.thumbs?(g(t.thumbs),S(!0)):S(!1)},[t.thumbs]);const A=e=>{g(e),null!==e&&x(!0)},N=()=>{c(t),a(!0)};return(0,h.jsxs)("div",{children:[(0,h.jsxs)("div",{className:"vc-msg",style:{whiteSpace:"pre-line",overflowX:"auto"},children:[t.vcResponse?(0,h.jsxs)("div",{className:"vc-msg-header assistant",children:[(0,h.jsx)("img",{src:vt.A,alt:"Sia",style:{width:"28px",height:"28px"}}),(0,h.jsxs)("div",{className:"vc-msg-header-info",children:[(0,h.jsx)("span",{className:"vc-msg-header-name",children:"Sia"}),(0,h.jsx)("span",{className:"vc-msg-header-time",children:(e=>{try{return(0,T.y)(new Date(e).toISOString(),!0)}catch(t){return""}})(t.timestampIndex.toMillis())})]}),"completed"===t.status&&(t.analytics||null===t.analytics)&&(0,h.jsxs)(o.A,{type:"link",className:"vc-insights-tag",style:{position:"absolute",right:"0",top:"0"},onClick:N,children:["Explore data",(0,h.jsx)(r.A,{type:"regular",size:"10",icon:"fa-arrow-up-right"})]})]}):null,(0,h.jsx)("div",{ref:C,onClick:e=>{const s=e.target;if(!s)return;s.closest(".vc-attrib-src")&&("completed"!==t.status||!t.analytics&&null!==t.analytics||N())},children:k?(0,h.jsx)(yt,{children:k}):null}),k?(0,h.jsxs)("div",{className:"vc-msg-footer",children:[(0,h.jsx)("div",{className:"vc-msg-footer-feedback "+(j?"disabled":""),children:(0,h.jsx)(p,{value:v,onChange:A,disabled:j})}),(0,h.jsx)(o.A,{type:"default",className:"vc-msg-footer-copy-btn",onClick:async()=>{var e;const s=null===(e=t.vcResponse)||void 0===e?void 0:e.trim();if(!s)return;try{var n,i,o,r,a;const e=null===(n=C.current)||void 0===n?void 0:n.querySelector(".vc-markdown-content"),t=null===e||void 0===e||null===(i=e.innerHTML)||void 0===i?void 0:i.trim(),c=(null===e||void 0===e||null===(o=e.innerText)||void 0===o?void 0:o.trim())||s;t&&null!==(r=navigator.clipboard)&&void 0!==r&&r.write&&"undefined"!==typeof ClipboardItem?await navigator.clipboard.write([new ClipboardItem({"text/html":new Blob([t],{type:"text/html"}
1),"text/plain":new Blob([c],{type:"text/plain"})})]):null!==(a=navigator.clipboard)&&void 0!==a&&a.writeText?await navigator.clipboard.writeText(c):(e=>{const t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.left="-9999px",document.body.appendChild(t),t.focus(),t.select();const s=document.execCommand("copy");if(document.body.removeChild(t),!s)throw new Error("copy command failed")})(c),l.A.show({content:"Response copied.",type:"success"})}catch(c){l.A.show({content:"Unable to copy response.",type:"error"})}},"aria-label":"Copy response",title:"Copy response",children:(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-copy"})}),(0,h.jsx)(o.A,{type:"default",className:"vc-msg-footer-copy-btn",onClick:()=>w(!0),"aria-label":"Save insight",title:"Save response as insight",children:(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-floppy-disk"})})]}):null]}),(0,h.jsx)(f,{open:y,onClose:()=>{x(!1)},onCancel:()=>{x(!1),g(null)},onChange:A,onSubmit:async(e,n)=>{try{if(!s)throw new m.Q("cen/internal-error",`fs: send feedback - invalid id: ${s}`);await b({feedbackType:"sia_response_feedback",feedbackText:e,studyId:i,threadId:s,interactionId:t.interactionId,thumbs:n})?S(!0):(l.A.show({content:"Failed to process feedback. Please try again later.",type:"error"}),g(null))}catch(o){m.A.handle(o)}},title:"How did this response work for you?",description:"Please help us understand your rating.",initialThumb:v}),(0,h.jsx)(H,{studyId:i,sessionId:s,interactionId:t.interactionId,open:I,onClose:()=>w(!1),insightType:"response",onSave:u})]})};var jt=s(7274),St=s(7965),Ct=s(7732);const kt="profile-filter",At="filter:",Nt=e=>{if("string"===typeof e){const t=e.trim();return t.length>0?t:null}return"number"===typeof e&&Number.isFinite(e)?String(e):null},Et=e=>{if(!e)return null;let t;try{t=JSON.parse(e)}catch(r){return null}if("object"!==typeof(s=t)||null===s||Array.isArray(s))return null;var s;if(t.type!==kt)return null;const n=Nt(t.profileId),i=Nt(t.optionId),o=Nt(t.label);return n&&i&&o?{type:kt,profileId:n,optionId:i,label:o}:null},Ft=(e,t)=>`${e}|${t}`,Ot=e=>{if(!e.startsWith(At))return null;const t=e.slice(7),s=t.indexOf("|");if(s<1||s===t.length-1)return null;const n=t.slice(0,s).trim(),i=t.slice(s+1).trim();return n&&i?{profileId:n,optionId:i}:null},$t=(e,t)=>{let s=0,n=!1,i=!1;for(let o=t;o<e.length;o+=1){const t=e[o];if(n){if(i){i=!1;continue}if("\\"===t){i=!0;continue}'"'===t&&(n=!1)}else if('"'!==t)if("{"!==t){if("}"===t){if(s-=1,0===s)return o;if(s<0)return-1}}else s+=1;else n=!0}return-1},Tt=e=>{if(!e)return[];const t=(e=>{if(!e)return[];const t=[];for(let s=0;s<e.length;s+=1){if("{"!==e[s])continue;const n=$t(e,s);if(-1===n)continue;const i=e.slice(s,n+1),o=Et(i);o&&(t.push({token:o,raw:i,start:s,end:n+1}),s=n)}return t})(e);if(0===t.length)return[{type:"text",text:e}];const s=[];let n=0;return t.forEach(t=>{t.start>n&&s.push({type:"text",text:e.slice(n,t.start)}),s.push({type:"profile-filter",token:t.token,raw:t.raw}),n=t.end}),n<e.length&&s.push({type:"text",text:e.slice(n)}),s},Dt=e=>/^[a-zA-Z0-9]+$/.test(e),Rt=Ct.bP.create({name:"filterPill",group:"inline",inline:!0,atom:!0,selectable:!0,addAttributes:()=>({id:{default:""},label:{default:""},profileId:{default:""},optionId:{default:""}}),parseHTML:()=>[{tag:"span[data-filter-pill]"}],renderHTML(e){let{HTMLAttributes:t}=e;return["span",(0,Ct.KV)(t,{"data-filter-pill":"true",class:"vc-chatbox-inline-pill"}),t.label||""]}}),Pt=e=>"string"===typeof e?e.trim():"number"===typeof e&&Number.isFinite(e)?String(e):"",zt=e=>{const t=Pt(null===e||void 0===e?void 0:e.profileId),s=Pt(null===e||void 0===e?void 0:e.optionId),n=Pt(null===e||void 0===e?void 0:e.label);return t&&s&&n?(i={type:kt,profileId:t,optionId:s,label:n},JSON.stringify(i)):n;var i},Lt=e=>{if(!e)return"";if("text"===e.type)return e.text||"";if("hardBreak"===e.type)return"\n";if("filterPill"===e.type)return zt(e.attrs);const t=(e.content||[]).map(Lt).join("");return"paragraph"===e.type?`${t}\n`:t},_t=e=>{var t,s,n,i;if(!e)return"";if(e.isText||"text"===(null===(t=e.type)||void 0===t?void 0:t.name))return e.text||"";if("hardBreak"===(null===(s=e.type)||void 0===s?void 0:s.name))return"\n";if("filterPill"===(null===(n=e.type)||void 0===n?void 0:n.name))return zt(e.attrs);const o=e.content;if(null===o||void 0===o||!o.childCount)return"";let r="";for(let l=0;l<o.childCount;l+=1)r+=_t(o.child(l));return"paragraph"===(null===(i=e.type)||void 0===i?void 0:i.name)?`${r}\n`:r},Mt=e=>{var t,s,n;if(!e)return!1;if("filterPill"===(null===(t=e.type)||void 0===t?void 0:t.name)&&null!==(s=e.attrs)&&void 0!==s&&s.profileId&&null!==(n=e.attrs)&&void 0!==n&&n.optionId)return!0;const i=e.content;if(null===i||void 0===i||!i.childCount)return!1;for(let o=0;o<i.childCount;o+=1)if(Mt(i.child(o)))return!0;return!1},Qt=(e,t)=>
1{if(!t)return;const s=t.split("\n");s.forEach((t,n)=>{t.length>0&&e.push({type:"text",text:t}),n<s.length-1&&e.push({type:"hardBreak"})})},Ut=(0,n.forwardRef)((e,t)=>{let{disabled:s,enterHint:i,groupsAvailable:l=!1,groupsVisible:a=!1,onSend:c,onToggleGroups:d,onClearGroups:u,suggestions:p=[],onSuggestionSelected:m,onActivePillIdsChange:f,onInputChange:v}=e;const[g,y]=(0,n.useState)(!1),[x,b]=(0,n.useState)(null),[I,w]=(0,n.useState)(0),[j,S]=(0,n.useState)(""),[C,k]=(0,n.useState)(!0),[A,N]=(0,n.useState)({left:12,top:12}),E=(0,n.useRef)(null),F=(0,n.useRef)(null),O=(0,n.useRef)(!1),$=(0,n.useCallback)(e=>{f&&f((e=>{const t=[];return e.descendants(e=>{"filterPill"===e.type.name&&e.attrs.id&&t.push(e.attrs.id)}),t})(e.state.doc))},[f]),T=(0,n.useMemo)(()=>[],[]),D=p.length?p:T,R=(0,n.useMemo)(()=>{const e=new Map;return D.forEach(t=>{const s=t.profileId&&t.optionId?{profileId:t.profileId,optionId:t.optionId}:Ot(t.id);if(!s)return;const n=(t.pillLabel||t.label).trim();n&&e.set(Ft(s.profileId,s.optionId),n)}),e},[D]),P=(0,n.useCallback)(e=>Lt(e.getJSON()).replace(/\n{2,}/g,"\n").trim(),[]),z=(0,n.useCallback)(e=>{const[t,...s]=e.split(":"),n=(s.join(":")||e).trim(),i=(t||"").trim(),[o,...r]=i.split(/\s+/);return{idText:o||"",filterText:(r.join(" ").trim()||i||e).trim(),valueText:n}},[]),L=(0,n.useCallback)(e=>{const{idText:t,filterText:s,valueText:n}=z(e.label),i=[e.id,e.label,e.pillLabel,e.profileId,e.optionId,t,s,n],o=Ot(e.id);return o?i.push(o.profileId,o.optionId):e.id.startsWith("segment:")&&i.push(e.id.slice(8)),i.filter(e=>Boolean(null===e||void 0===e?void 0:e.trim())).join(" ").toLowerCase()},[z]),_=(0,n.useMemo)(()=>{const e=j.trim();if(e.length<1||!Dt(e))return[];const t=e.toLowerCase();return D.filter(e=>L(e).includes(t))},[L,D,j]),M=()=>{y(!1),b(null),S(""),w(0)},Q=(0,jt.hG)({extensions:[St.A,Rt],content:"",editable:!s,autofocus:!s&&"end",editorProps:{attributes:{class:"vc-chatbox-editor"}},onUpdate:e=>{let{editor:t}=e;k(t.isEmpty),O.current?O.current=!1:($(t),null===v||void 0===v||v(P(t)))},onSelectionUpdate:e=>{let{editor:t}=e;k(t.isEmpty)}}),U=(0,n.useCallback)(e=>{if(!Q||!E.current)return;const t=Q.view.coordsAtPos(e),s=E.current.getBoundingClientRect(),n=Math.min(Math.max(t.left-s.left,8),Math.max(s.width-360-8,8)),i=Math.max(t.top-s.top,8);N({left:n,top:i})},[Q]),H=(0,n.useCallback)(()=>{var e;if(!Q)return;const{selection:t}=Q.state;if(!t.empty)return void M();const s=t.$from;if(!s.parent.isTextblock)return void M();const n=s.parent.textBetween(0,s.parentOffset,"\n","\n"),i=n.match(/(^|\s)([^\s]+)$/);if(!i)return void M();const o=(null===(e=i[1])||void 0===e?void 0:e.length)||0,r=n.length-i[0].length+o,l=t.from-s.parentOffset+r,a=i[2]||"";if(a.trim().length<1||!Dt(a))return void M();const c=!g||x!==l||j!==a;b(l),S(a),U(t.from),c&&w(0),y(!0)},[Q,g,x,j,U]);(0,n.useEffect)(()=>{if(Q)return Q.on("update",H),Q.on("selectionUpdate",H),()=>{Q.off("update",H),Q.off("selectionUpdate",H)}},[Q,H]),(0,n.useEffect)(()=>{Q&&(Q.setEditable(!s),s||setTimeout(()=>{Q.commands.focus("end")},0))},[s,Q]),(0,n.useEffect)(()=>{const e=e=>{E.current&&(E.current.contains(e.target)||M())};return document.addEventListener("mousedown",e),()=>{document.removeEventListener("mousedown",e)}},[]),(0,n.useEffect)(()=>{if(!g)return;const e=F.current,t=null===e||void 0===e?void 0:e.querySelector(".vc-chatbox-suggestion-item.active");if(!e||!t)return;const s=t.offsetTop,n=s+t.offsetHeight,i=e.scrollTop,o=i+e.clientHeight;s<i?e.scrollTop=s:n>o&&(e.scrollTop=n-e.clientHeight)},[I,g]);const B=(0,n.useCallback)(()=>{if(!Q)return;const e=P(Q);if(""===e)return;const t=c(e);M(),!1!==t&&(O.current=!0,Q.commands.clearContent(!0),k(!0))},[Q,P,c]),G=(0,n.useCallback)(()=>{Q?(O.current=!0,Q.commands.clearContent(!0),k(!0),M(),null===u||void 0===u||u()):null===u||void 0===u||u()},[Q,u]);(0,n.useImperativeHandle)(t,()=>({send:B}));const V=(0,n.useCallback)(e=>{const t=e.profileId&&e.optionId?{profileId:e.profileId,optionId:e.optionId}:Ot(e.id),s=(e.pillLabel||e.label).trim();return t?{id:e.id,label:s,profileId:t.profileId,optionId:t.optionId}:{id:e.id,label:s}},[]),W=(0,n.useCallback)(e=>{const t=Tt(e),s=[];
1return 0===t.length?(Qt(s,e),s):(t.forEach(e=>{if("text"===e.type)return void Qt(s,e.text);const t=Ft(e.token.profileId,e.token.optionId),n=R.get(t)||e.token.label;var i,o;s.push({type:"filterPill",attrs:{id:(i=e.token.profileId,o=e.token.optionId,`${At}${i}|${o}`),label:n,profileId:e.token.profileId,optionId:e.token.optionId}})}),s)},[R]),q=e=>{if(!Q||null===x)return;if(!_[e])return;const t=_[e],s=Q.state.selection.from,n=V(t);Q.chain().focus().deleteRange({from:x,to:s}).insertContent([{type:"filterPill",attrs:n},{type:"text",text:" "}]).run(),M(),null===m||void 0===m||m(t.id),k(Q.isEmpty),$(Q)},K=(0,n.useCallback)(e=>{if(!Q)return!1;const{selection:t,doc:s}=Q.state;if(t.empty)return!1;const n=s.slice(t.from,t.to);if(!(e=>{if(null===e||void 0===e||!e.childCount)return!1;for(let t=0;t<e.childCount;t+=1)if(Mt(e.child(t)))return!0;return!1})(n.content))return!1;const i=(e=>{if(null===e||void 0===e||!e.childCount)return"";let t="";for(let s=0;s<e.childCount;s+=1)t+=_t(e.child(s));return t})(n.content).replace(/\n{2,}/g,"\n");return!!i.trim()&&(e.preventDefault(),e.clipboardData.setData("text/plain",i),!0)},[Q]),J=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:25;if(!e)return"";const s=e.trim(),n=2*t+3;if(s.length<=n)return s;return`${s.slice(0,t)}...${s.slice(-t)}`},Y=i&&!C&&!(g&&_.length>0);return(0,h.jsxs)("div",{className:"vc-chat-input-wrapper",ref:E,children:[(l||Y)&&(0,h.jsxs)("div",{className:"vc-chatbox-meta-row",children:[l?(0,h.jsxs)("div",{className:"vc-chatbox-group-actions",children:[(0,h.jsx)(o.A,{type:"link",size:"small",className:"vc-chatbox-group-action",disabled:s,onClick:d,children:a?(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-eye-slash"})," Hide Groups"]}):(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-eye"})," View Groups"]})}),(0,h.jsxs)(o.A,{type:"link",size:"small",className:"vc-chatbox-group-action",disabled:s,onClick:G,children:[(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-xmark"})," Clear Groups"]})]}):null,Y&&(0,h.jsxs)("div",{className:"vc-chatbox-enter-hint","aria-live":"polite",children:[(0,h.jsx)(r.A,{type:"solid",size:"10",icon:"fa-arrow-turn-down-left"}),(0,h.jsx)("span",{children:"Press Enter again to send this query"})]},i)]}),(0,h.jsxs)("div",{className:"vc-chatbox",onKeyDownCapture:e=>{if(g&&_.length>0){if("ArrowDown"===e.key)return e.preventDefault(),e.stopPropagation(),void w(e=>(e+1)%Math.max(_.length,1));if("ArrowUp"===e.key)return e.preventDefault(),e.stopPropagation(),void w(e=>0===e?_.length-1:e-1);if("Enter"===e.key||"Tab"===e.key)return e.preventDefault(),e.stopPropagation(),void q(I)}if(g&&"Escape"===e.key)return e.preventDefault(),e.stopPropagation(),void M();"Enter"!==e.key||e.shiftKey||(e.preventDefault(),e.stopPropagation(),B())},onPasteCapture:e=>{if(!Q)return;const t=e.clipboardData.getData("text/plain");if(!t)return;if(!Tt(t).some(e=>"profile-filter"===e.type))return;const s=W(t);0!==s.length&&(e.preventDefault(),Q.chain().focus().insertContent(s).run())},onCopyCapture:e=>{K(e)},onCutCapture:e=>{Q&&K(e)&&Q.chain().focus().deleteSelection().run()},children:[(0,h.jsx)(jt.$Z,{editor:Q}),C&&(0,h.jsx)("div",{className:"vc-chatbox-placeholder",onMouseDown:e=>{e.preventDefault(),null===Q||void 0===Q||Q.commands.focus("end")},children:"Type here to chat with Sia..."})]}),g&&_.length>0&&(0,h.jsx)("div",{className:"vc-chatbox-suggestions",style:{left:A.left,top:A.top},children:(0,h.jsx)("div",{className:"vc-chatbox-suggestions-list",role:"listbox",ref:F,children:_.map((e,t)=>(0,h.jsx)("button",{type:"button",className:"vc-chatbox-suggestion-item "+(t===I?"active":""),onMouseDown:e=>{e.preventDefault(),q(t)},children:(()=>{const{idText:t,filterText:s,valueText:n}=z(e.label),i=Ot(e.id);return(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)("span",{className:"vc-chatbox-suggestion-pill",title:n,children:J(n)}),(0,h.jsxs)("span",{className:"vc-chatbox-suggestion-meta",children:[(t||(null===i||void 0===i?void 0:i.profileId))&&(0,h.jsx)("span",{className:"vc-chatbox-suggestion-id",title:(null===i||void 0===i?void 0:i.profileId)||t,children:J((null===i||void 0===i?void 0:i.profileId)||t)}),s&&(0,h.jsx)("span",{className:"vc-chatbox-suggestion-filter-text",title:s,children:J(s)})]})]})})()},e.id))})})]})}),Ht=Ut;var Bt=s(7943);const Gt=e=>{let{label:t,className:s=""}=e;return(0,h.jsx)("span",{className:`vc-tag-filter small ${s}`.trim(),children:(0,h.jsx)("span",{className:"vc-tag-filter__label",children:t})})};var Vt=s(7956);const Wt=e=>e.filterOptionSubset.map(e=>`${e.profileQId}|${e.profileOptionId}`).sort().join(","),qt=(e,t,s)=>{const n=Kt({filterOptions:e.map(e=>
1({profileQId:e.filterId,optionId:e.optId,option:e.optDesc}))},t);return(s.length>0?ms(null!==n&&void 0!==n?n:[],s):null!==n&&void 0!==n?n:[]).map(e=>e.id?e:{...e,id:(0,Vt.A)()})},Kt=(e,t)=>{if(0===t.length)return null;if(1===t.length)return[{intersectionCriteria:[{filterOptionSubset:[t[0]]}],unionCriteria:[]}];if(ts(t)){const s=t[0].profileQId,n=t.map(e=>e.profileOptionId);return ss(t,e)?is(s,new Map([[s,t]])):[ns(s,n)]}return Jt(t,e)},Jt=(e,t)=>{if(0===e.length)return[];const s=es(e),n=new Map;for(const[i,o]of s.entries())ss(o,t)&&n.set(i,o);if(0===n.size)return[{intersectionCriteria:Yt(s),unionCriteria:[]}];if(1===n.size&&s.size>1){const e=n.keys().next().value||"";return Zt(e,s)}if(n.size>1){const e=Array.from(n.keys());return Xt(e,s)}throw new Error("getGroupsFromDifferentProfiles: No case found")},Yt=e=>{const t=[];for(const s of e.values())0!==s.length&&t.push({filterOptionSubset:s});return t},Zt=(e,t)=>{const s=is(e,t),n=os([e],t);for(const i of s)for(const e of n.values())i.intersectionCriteria.push({filterOptionSubset:e});return s},Xt=(e,t)=>{const s=[];for(const i of e)s.push(...is(i,t));const n=os(e,t);for(const i of s)for(const e of n.values())i.intersectionCriteria.push({filterOptionSubset:e});return s},es=e=>{const t=new Map,s=new Set;for(const n of e)s.add(n.profileQId);for(const n of s)t.set(n,e.filter(e=>e.profileQId===n));return t},ts=e=>0===e.length||e.every(t=>t.profileQId===e[0].profileQId),ss=(e,t)=>{if(!ts(e))return!1;const s=e[0].profileQId,{filterOptions:n}=t;return n.filter(e=>e.profileQId===s).every(t=>e.some(e=>e.profileOptionId===t.optionId))},ns=(e,t)=>({intersectionCriteria:[{filterOptionSubset:t.map(t=>({profileQId:e,profileOptionId:t}))}],unionCriteria:[]}),is=(e,t)=>{var s,n;const i=[],o=null!==(s=null===(n=t.get(e))||void 0===n?void 0:n.map(e=>e.profileOptionId))&&void 0!==s?s:[];for(const r of o)i.push({intersectionCriteria:[{filterOptionSubset:[{profileQId:e,profileOptionId:r}]}],unionCriteria:[]});return i},os=(e,t)=>{const s=new Map;for(const[n,i]of t.entries())e.includes(n)||s.set(n,i);return s},rs=e=>`${e.profileQId}|${e.profileOptionId}`,ls=(e,t)=>"union"===t?e.unionCriteria:e.intersectionCriteria,as=(e,t,s)=>"union"===t?{...e,unionCriteria:s}:{...e,intersectionCriteria:s},cs=(e,t)=>[...e.intersectionCriteria,...e.unionCriteria].some(e=>e.filterOptionSubset.some(e=>rs(e)===rs(t))),ds=(e,t)=>{const s=new Set,n=[];for(const i of t){const t=rs(i);s.has(t)||cs(e,i)||(s.add(t),n.push(i))}return n},us=(e,t)=>{const s=[...e],n=s.findIndex(e=>((e,t)=>0===e.filterOptionSubset.length||ts(e.filterOptionSubset)&&e.filterOptionSubset[0].profileQId===t.profileQId)(e,t));if(n>=0){const e=s[n];return s[n]={...e,filterOptionSubset:[...e.filterOptionSubset,t]},s}return s.push({filterOptionSubset:[t]}),s},hs=e=>{const t=new Set,s=[];for(const n of e)for(const e of[...n.intersectionCriteria,...n.unionCriteria])for(const n of e.filterOptionSubset){const e=rs(n);t.has(e)||(t.add(e),s.push(n))}return s}
1,ps=e=>{const t=new Set;for(const s of e)s.segment&&t.add(s.segment);return Array.from(t)},ms=(e,t)=>{const s=[];for(const n of e)for(const e of t)s.push({...n,segment:e});return s};var fs=s(8041),vs=s(9291);const gs="ease-out",ys=()=>{const e=(0,n.useMemo)(()=>({duration:180,easing:gs}),[]);return(0,vs.Q)(e)},xs={display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,width:13,height:13,marginLeft:6,padding:0,border:0,borderRadius:999,background:"var(--tertiary3-5)",color:"var(--neutral-1)",cursor:"pointer"},bs={display:"inline-block",fontSize:9,fontWeight:400,lineHeight:1,color:"var(--neutral-1)"},Is=e=>{let{placement:t,onClick:s}=e;const n="union"===t?"intersection":"union",i="union"===n?"Move to Union":"Move to Intersection";return(0,h.jsx)("button",{type:"button",style:xs,title:i,"aria-label":i,onClick:e=>{e.stopPropagation(),s()},children:(0,h.jsx)("span",{style:{...bs,transform:"intersection"===n?"scaleY(-1)":void 0},"aria-hidden":!0,children:"U"})})},ws=e=>{let{operands:t,placement:s,onRemovePill:n,onMovePlacement:i,onPillClick:o,className:l}=e;const a=e=>{const t=(0,h.jsxs)("span",{className:"vc-tag-filter small cohort-criterion-pill"+(o?" cohort-criterion-pill--clickable":""),children:[(0,h.jsxs)("span",{className:"vc-tag-filter__label",children:[e.filterDesc,": ",(0,h.jsx)("b",{children:e.optDesc})]}),i&&s&&(0,h.jsx)(Is,{placement:s,onClick:i}),n&&(l=`Remove ${e.label}`,a=()=>n({type:"filter",profileQId:e.profileQId,profileOptionId:e.profileOptionId}),(0,h.jsx)("button",{type:"button",className:"vc-tag-filter__close","aria-label":l,onClick:e=>{e.stopPropagation(),a()},children:(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-xmark"})}))]});var l,a;return o?(0,h.jsx)("button",{type:"button",className:"cohort-criterion-pill-button","aria-label":`Add ${e.label}`,onClick:()=>o(e),children:t}):t};return(0,h.jsx)("div",{className:"cohort-criterion-filter-list"+(l?` ${l}`:""),children:t.map(e=>(0,h.jsx)(j.A,{content:e.label,placement:"top",trigger:"hover",children:(0,h.jsx)("span",{className:"cohort-criterion-pill-host",children:a(e)})},e.key))})},js=(e,t)=>(0,h.jsx)("button",{type:"button",className:"vc-tag-filter__close","aria-label":e,onClick:e=>{e.stopPropagation(),t()},children:(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-xmark"})}),Ss=e=>{let{criterion:t,filters:s,showRespondentsSubsetAs:n,placement:i,onRemovePill:o,onMovePlacement:r}=e;const l=((e,t)=>e.map(e=>{const s=t.find(t=>t.filterId===e.profileQId&&t.optId===e.profileOptionId);return s?{key:`${e.profileQId}-${e.profileOptionId}`,label:`${s.filterDesc}: ${s.optDesc}`,filterDesc:s.filterDesc,optDesc:s.optDesc,profileQId:e.profileQId,profileOptionId:e.profileOptionId}:null}).filter(e=>null!==e))(t.filterOptionSubset,s),a=t.filterOptionSubset.length>1,c=e=>(0,h.jsxs)("span",{className:"vc-tag-filter small cohort-criterion-pill",children:[(0,h.jsxs)("span",{className:"vc-tag-filter__label",children:[e.filterDesc,": ",(0,h.jsx)("b",{children:e.optDesc})]}),o&&js(`Remove ${e.label}`,()=>o({type:"filter",profileQId:e.profileQId,profileOptionId:e.profileOptionId}))]});if(a){if("SINGLE_PILL"===n&&l.length>1){var d,u;const e=null!==(d=null===(u=l[0])||void 0===u?void 0:u.filterDesc)&&void 0!==d?d:"",t=l.length,s=(0,h.jsx)("div",{className:"cohort-criterion-options-popover",children:l.map(e=>(0,h.jsx)("span",{className:"cohort-criterion-pill-host",children:c(e)},e.key))});return(0,h.jsx)("div",{className:"cohort-criterion-card",children:(0,h.jsx)("span",{className:"cohort-criterion-pill-host",children:(0,h.jsxs)("span",{className:"vc-tag-filter small cohort-criterion-pill cohort-criterion-union-pill",children:[(0,h.jsxs)("span",{className:"cohort-criterion-union-pill__content",children:[(0,h.jsx)(j.A,{content:e,placement:"top",trigger:"hover",children:(0,h.jsx)("span",{className:"vc-tag-filter__label cohort-criterion-union-pill__label",children:e})}),(0,h.jsx)(fs.A,{content:s,placement:"top",trigger:"click",overlayClassName:"vc-cohort-filter-option-popover",children:(0,h.jsx)("button",{type:"button",className:"vc-cohort-filter-option-count","aria-label":`${t} selected options. Click to view and remove.`,children:t})})]}),r&&(0,h.jsx)(Is,{placement:i,onClick:r}),o&&js(`Remove ${e}`,()=>o({type:"criterion"}))]})})})}return(0,h.jsx)("div",{className:"cohort-criterion-card",children:(0,h.jsx)(ws,{operands:l,placement:i,onRemovePill:o,onMovePlacement:r})})}return(0,h.jsx)("div",{className:"cohort-criterion-card",children:(0,h.jsx)(ws,{operands:l,placement:i,onRemovePill:o,onMovePlacement:r})})},Cs=e=>{let{addableFilters:t,filters:s,onRestore:n}=e;return(0,h.jsx)("div",{className:"vc-add-filter-popover-list",role:"listbox","aria-label":"Addable filters",children:t.map(e=>{const t=s.find(t=>t.filterId===e.profileQId&&t.optId===e.profileOptionId);if(!t)return null;const i=`${t.filterDesc}: ${t.optDesc}`,o=`${e.profileQId}|${e.profileOptionId}`;return(0,h.jsxs)("div",{className:"vc-add-filter-popover-item",role:"option","aria-selected":!1,children:[(0,h.jsx)(j.A,{content:i,placement:"top",trigger:"hover",children:(0,h.jsx)("span",{className:"cohort-criterion-pill-host vc-add-filter-popover-pill-host",children:(0,h.jsx)("span",{className:"vc-tag-filter small cohort-criterion-pill",children:(0,h.jsxs)("span",{className:"vc-tag-filter__label",children:[t.filterDesc,": ",(0,h.jsx)("b",{children:t.optDesc})]})})})}),(0,h.jsxs)("span",{className:"vc-add-filter-popover-item-actions",children:[(0,h.jsx)("button",{type:"button",className:"vc-add-filter-placement-btn vc-add-filter-placement-btn--union",title:"Add as Union","aria-label":"Add as Union",onClick:()=>n(e.profileQId,e.profileOptionId,"union"),children:(0,h.jsx)("span",{className:"vc-add-filter-placement-letter","aria-hidden":!0,
1children:"U"})}),(0,h.jsx)("button",{type:"button",className:"vc-add-filter-placement-btn vc-add-filter-placement-btn--intersection",title:"Add as Intersection","aria-label":"Add as Intersection",onClick:()=>n(e.profileQId,e.profileOptionId,"intersection"),children:(0,h.jsx)("span",{className:"vc-add-filter-placement-letter vc-add-filter-placement-letter--reverse","aria-hidden":!0,children:"U"})})]})]},o)})})},ks="Total Sample",As="__total_sample__",Ns=e=>`Segment ${e}`,Es=e=>{const t=[];for(let s=0;s<e&&s<5;s++)t.push(String.fromCharCode(65+s));return t},Fs=e=>{let{cohort:t,filters:s,selectedFilters:i,showRespondentsSubsetAs:l,readOnly:a=!1,onRemove:c,onRemoveCriterionPill:d,onMoveCriterionPlacement:u,onRestoreFilter:p,availableSegments:m,onSegmentChange:f}=e;const[v]=ys(),[g,y]=(0,n.useState)(!1),x=ds(t,i),b=x.length>0;(0,n.useEffect)(()=>{b||y(!1)},[b]);const I=t.segment?Ns(t.segment):ks,w=t.unionCriteria.map((e,t)=>({criterion:e,stepIndex:t})),j=t.intersectionCriteria.map((e,t)=>({criterion:e,stepIndex:t})),S=0===w.length,C=(0,h.jsx)(Cs,{addableFilters:x,filters:s,onRestore:(e,t,s)=>{null===p||void 0===p||p(e,t,s),x.length<=1&&y(!1)}});return(0,h.jsx)("div",{className:"group-card-wrapper",children:(0,h.jsxs)("div",{className:"filter-card",children:[(0,h.jsx)("div",{className:"segment-select-anchor",children:a?(0,h.jsx)("span",{className:"segment-select-trigger segment-select-trigger--readonly",children:(0,h.jsx)(o.A,{color:"primary",type:"alternative",className:"segment-select-button",size:"small",tabIndex:-1,children:I})}):(0,h.jsx)(Q.A,{overlay:(0,h.jsxs)(V.Ay,{style:{minWidth:130},onClick:e=>{let{key:t}=e;return null===f||void 0===f?void 0:f(t===As?void 0:t)},children:[(0,h.jsx)(V.Ay.Item,{children:ks},As),m.map(e=>(0,h.jsx)(V.Ay.Item,{children:Ns(e)},e))]}),trigger:["click"],placement:"bottomCenter",overlayClassName:"st-dropdown-menu vc-segment-select-dropdown",getPopupContainer:()=>document.body,children:(0,h.jsx)("span",{className:"segment-select-trigger",children:(0,h.jsxs)(o.A,{color:"primary",type:"alternative",className:"segment-select-button",size:"small",children:[I," ",(0,h.jsx)(r.A,{type:"solid",size:"10",icon:"fa-angle-down"})]})})})}),a?null:(0,h.jsxs)("div",{className:"filter-card-header",children:[(0,h.jsx)(fs.A,{content:C,placement:"topLeft",trigger:"click",visible:g,onVisibleChange:e=>{e&&!b||y(e)},overlayClassName:"vc-add-filter-popover-overlay",children:(0,h.jsx)("span",{className:"add-filter-button-anchor",children:(0,h.jsxs)(o.A,{color:"primary",type:"link",className:"add-filter-button",size:"xsmall",disabled:!b,children:[(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-plus-circle"})," Add Filter"]})})}),(0,h.jsx)(o.A,{color:"danger",type:"link",className:"group-remove","aria-label":"Remove Group",onClick:c,children:(0,h.jsx)(r.A,{type:"solid",size:"10",icon:"fa-trash"})})]}),(0,h.jsxs)("div",{ref:v,className:"filter-card-criteria-list",children:[!S&&(0,h.jsx)("div",{className:"cohort-criterion-card cohort-criterion-card--union",children:(0,h.jsxs)("div",{className:"cohort-criterion-union-box",children:[(0,h.jsx)("span",{className:"cohort-criterion-union-box__tag",children:"Union"}),(0,h.jsx)("div",{className:"cohort-criterion-union-box__content",children:w.map(e=>{let{criterion:t,stepIndex:n}=e;return(0,h.jsx)(Ss,{criterion:t,filters:s,showRespondentsSubsetAs:l,placement:"union",onRemovePill:d?e=>d({placement:"union",criterionIndex:n},e):void 0,onMovePlacement:u?()=>u({placement:"union",criterionIndex:n}):void 0},`union:${n}:${Wt(t)}`)})})]})}),j.map(e=>{let{criterion:t,stepIndex:n}=e;return(0,h.jsx)(Ss,{criterion:t,filters:s,showRespondentsSubsetAs:l,placement:"intersection",onRemovePill:d?e=>d({placement:"intersection",criterionIndex:n},e):void 0,onMovePlacement:u?()=>u({placement:"intersection",criterionIndex:n}):void 0},`intersection:${n}:${Wt(t)}`)})]})]})})},Os=e=>{let{onClick:t}=e;return(0,h.jsx)("div",{className:"add-cohort-button-wrapper",children:(0,h.jsxs)("div",{className:"add-cohort-button",children:[(0,h.jsx)(o.A,{type:"default",color:"primary",size:"medium",icononly:!0,className:"add-cohort-button-icon",onClick:t,"aria-label":"Add cohort",children:(0,h.jsx)(r.A,{type:"solid",size:"16",icon:"fa-plus"})}),(0,h.jsx)("span",{className:"add-cohort-button-label",children:"Add cohort"})]})})},$s=e=>{var t;const{cohorts:s,filters:n,showRespondentsSubsetAs:i="SINGLE_PILL",onRemoveCriterionPill:o,onMoveCriterionPlacement:r,onRestoreFilter:l,readOnly:a=!1}=e,c=null!==(t=e.selectedFilters)&&void 0!==t?t:[],[d]=ys();return s.length?(0,h.jsx)("div",{className:"filters-module",children:(0,h.jsxs)("div",{ref:d,className:"filters-cards",children:[s.map((t,s)=>{var d;return(0,h.jsx)(Fs,{cohort:t,index:s,filters:n,selectedFilters:c,showRespondentsSubsetAs:i,readOnly:a,onRemove:a?void 0:()=>e.onRemoveCohort(s),availableSegments:a?[]:null!==(d=e.availableSegments)&&void 0!==d?d:[],onSegmentChange:a?void 0:t=>e.onCohortSegmentChange(s,t),onRemoveCriterionPill:a||!o?void 0:(e,t)=>o(s,e,t),onMoveCriterionPlacement:a||!r?void 0:e=>r(s,e),onRestoreFilter:a||!l?void 0:(e,t,n)=>l(s,e,t,n)},(e=>{var t;return e.id?e.id:`${null!==(t=e.segment)&&void 0!==t?t:"_"}|i:${e.intersectionCriteria.map(Wt).join("::")}|u:${e.unionCriteria.map(Wt).join("::")}`})(t))}),!a&&e.onAddCohort?(0,h.jsx)(Os,{onClick:e.onAddCohort}):null]})}):null},Ts=e=>{var t,s,i;let{message:l,disabled:a,onDelete:c,filters:d=[]}=e;
1const[u,p]=(0,n.useState)(""),[m,f]=(0,n.useState)(!1),[v]=ys(),y=(null===(t=g.A.getInstance().auth.currentUser)||void 0===t?void 0:t.email)||"anonymous";(0,n.useEffect)(()=>{"pending"===l.status?p("Generating Response..."):"completed_pending_attribution"===l.status?p("Preparing Attribution... "):p("")},[l.status]);const x=(0,n.useMemo)(()=>(e=>new Map(e.map(e=>[Ft(e.filterId,e.optId),e])))(d),[d]),b=(0,n.useMemo)(()=>Tt(l.userQuery||""),[l.userQuery]),I=(0,n.useMemo)(()=>b.some(e=>"profile-filter"===e.type),[b]),w=(null!==(s=null===(i=l.cohorts)||void 0===i?void 0:i.length)&&void 0!==s?s:0)>0;return(0,h.jsxs)("div",{style:{position:"relative"},children:[(0,h.jsxs)("div",{className:"vc-user-msg",children:[(0,h.jsx)("span",{className:"vc-user-msg-inline",onCopy:e=>{I&&(e.preventDefault(),e.clipboardData.setData("text/plain",l.userQuery||""))},children:I?b.map((e,t)=>{if("text"===e.type)return(0,h.jsx)(n.Fragment,{children:e.text},`txt-${l.interactionId}-${t}`);const s=((e,t)=>{const s=t.get(Ft(e.profileId,e.optionId));return s?(n=s.filterDesc,i=s.optDesc,`${n}: ${i}`):e.label;var n,i})(e.token,x);return(0,h.jsx)(Gt,{label:s},`pill-${l.interactionId}-${e.token.profileId}-${e.token.optionId}-${t}`)}):l.userQuery}),(0,h.jsx)("span",{className:"delete-user-chat",children:c&&(e=>{var t,s;if(!c)return null;const n=(null!==(t=null===(s=l.sharedInsights)||void 0===s?void 0:s.length)&&void 0!==t?t:0)>0,i=(0,h.jsx)(o.A,{type:"link",size:"small",disabled:a||"pending"===l.status||n,onClick:()=>c(e),children:(0,h.jsx)(r.A,{type:"solid",size:"10",icon:"fa-trash"})});return n?(0,h.jsx)(j.A,{content:"Delete the associated Insights before deleting this item.",placement:"top",trigger:"hover",children:(0,h.jsx)("span",{style:{display:"inline-block"},children:i})}):i})(l.interactionId)})]}),w?(0,h.jsxs)("div",{ref:v,className:"vc-user-msg-cohorts",children:[(0,h.jsx)(o.A,{type:"link",size:"small",className:"vc-user-msg-groups-toggle",onClick:()=>f(e=>!e),children:m?(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-eye-slash"})," Hide Groups"]}):(0,h.jsxs)(h.Fragment,{children:[(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-eye"})," View Groups"]})}),m?(0,h.jsx)($s,{readOnly:!0,cohorts:l.cohorts,filters:d}):null]}):null,u?(0,h.jsxs)("p",{className:"vc-user-pending",children:[(0,h.jsx)(r.A,{type:"solid",size:"16",icon:"fa-spinner",style:{animation:"spin 2s linear infinite"}}),(0,h.jsx)("span",{className:"vc-user-pending-text",children:u})]}):null,(0,h.jsxs)("div",{className:"vc-msg-header user",children:[(0,h.jsx)(Bt.A,{shape:"circle",style:{backgroundColor:"#5E2569"},children:(S=y,S.split("@")[0].split(/[._-]/).map(e=>{var t;return(null===(t=e[0])||void 0===t?void 0:t.toUpperCase())||""}).join("").slice(0,2))}),(0,h.jsxs)("div",{className:"vc-msg-header-info",children:[(0,h.jsx)("span",{className:"vc-msg-header-name",children:y.split("@")[0]}),(0,h.jsx)("span",{className:"vc-msg-header-time",children:(e=>{try{return(0,T.y)(new Date(e).toISOString(),!0)}catch(t){return""}})(l.timestampIndex.toMillis())})]})]})]},`${l.interactionId}-user`);var S},Ds=()=>(0,h.jsxs)("div",{className:"old-dataset-alert",children:[(0,h.jsx)(r.A,{type:"solid",size:"14",icon:"fa-exclamation-circle"}),(0,h.jsx)("span",{className:"alert-text",children:"The above responses were generated with an older dataset."})]});class Rs extends k.A{getInsightInteractionCollectionRef(e,t){const s=this.getInsightSessionDocRef(e,t);return(0,C.rJ)(s,"interactions")}async loadInsightChatSession(e,t){if(!e)return null;try{const l=this.getInsightSessionDocRef(e,t),a=await(0,C.x7)(l);if(a.exists()&&a.data()){var s,n,i,o,r;const e=a.data();if(!e.studyIds)throw new m.Q("cen/doc-loading-error","No studyIds in chat session");return{sessionId:e.sessionId,updatedAt:e.updatedAt,showInsightsSummary:null===(s=e.showInsightsSummary)||void 0===s||s,showRecommendations:null!==(n=e.showRecommendations)&&void 0!==n&&n,disableRecommendations:null!==(i=e.disableRecommendations)&&void 0!==i&&i,selectedRecommendations:null!==(o=e.selectedRecommendations)&&void 0!==o?o:[],createdAt:e.createdAt,studyIds:e.studyIds,sharedInsights:null!==(r=e.sharedInsights)&&void 0!==r?r:[]}}return null}catch(l){throw l}}getInsightSessionDocRef(e,t){var s,n;const i=null===(s=this.auth.currentUser)||void 0===s||null===(n=s.email)||void 0===n?void 0:n.split("@")[1];if(!i||!t)throw new m.Q("cen/sign-in-required");return(0,C.H9)(this.db,`domains/${i}/users/${t}
1/vcChatSessions/${e}`)}}const Ps="filter:",zs="segment:",Ls=e=>e.startsWith(Ps),_s=e=>e.startsWith(zs),Ms=e=>{if(!_s(e))return null;const t=e.replace(zs,"");return t||null},Qs=e=>{const t=(e=>Ls(e)?e.replace(Ps,""):null)(e);if(!t)return null;const[s,n]=t.split("|");return s&&n?{profileQId:s,profileOptionId:n}:null},Us=e=>`${e.profileQId}|${e.profileOptionId}`,Hs=(e,t)=>{const s=new Set(e.map(Us));return t.filter(e=>!s.has(Us(e)))},Bs=e=>{let{filters:t,isSavedMode:s,segmentsCount:i,sessionId:o,initialSelectionState:r=null}=e;const[l,a]=(0,n.useState)([]),[c,d]=(0,n.useState)([]),[u,h]=(0,n.useState)([]),p=(0,n.useRef)([]),m=(0,n.useRef)([]),f=(0,n.useRef)([]),v=(0,n.useRef)([]),g=(0,n.useRef)([]),y=(0,n.useRef)(null),x=(0,n.useMemo)(()=>((e,t)=>{const s=new Set,n=e.filter(e=>{const t=`${e.filterId}|${e.optId}`;return!s.has(t)&&(s.add(t),!0)}).map(e=>({id:`filter:${e.filterId}|${e.optId}`,label:`${e.filterId} ${e.filterDesc}: ${e.optDesc}`,pillLabel:`${e.filterDesc}: ${e.optDesc}`,profileId:e.filterId,optionId:e.optId}));return[...Es(t).map(e=>({id:`segment:${e}`,label:Ns(e),pillLabel:Ns(e)})),...n]})(t,i),[t,i]),b=(0,n.useMemo)(()=>Es(i),[i]),I=(0,n.useCallback)(()=>{f.current=[],v.current=[],g.current=[],p.current=[],m.current=[],h([]),d([]),a([])},[]),w=(0,n.useCallback)(e=>{const s=f.current;f.current=e;if(s.length===e.length&&s.every(t=>e.includes(t)))return;const{filters:n,segments:i}=(e=>{const t=[],s=[],n=new Set,i=new Set;for(const o of e){const e=Qs(o);if(e){const s=`${e.profileQId}|${e.profileOptionId}`;n.has(s)||(n.add(s),t.push({profileQId:e.profileQId,profileOptionId:e.profileOptionId}));continue}const r=Ms(o);r&&!i.has(r)&&(i.add(r),s.push(r))}return{filters:t,segments:s}})(e),o=p.current,r=m.current,l=v.current,c=g.current,u=Hs(n,l),y=Hs(l,n),x=c.filter(e=>!i.includes(e)),b=i.filter(e=>!c.includes(e)),I=function(){const e=new Set,t=[];for(var s=arguments.length,n=new Array(s),i=0;i<s;i++)n[i]=arguments[i];for(const o of n)for(const s of o){const n=`${s.profileQId}|${s.profileOptionId}`;e.has(n)||(e.add(n),t.push(s))}return t}(((e,t)=>{if(0===t.length)return e;const s=new Set(t.map(Us));return e.filter(e=>!s.has(Us(e)))})(o,u),y),w=[...r.filter(e=>!x.includes(e)),...b];v.current=n,g.current=i;const j=!((e,t)=>{if(e.length!==t.length)return!1;const s=new Set(e.map(Us));return t.every(e=>s.has(Us(e)))})(o,I),S=(k=w,!((C=r).length===k.length&&C.every(e=>k.includes(e))));var C,k;(j||S)&&(j&&(p.current=I,h(I)),S&&(m.current=w,d(w)),a(qt(t,I,w)))},[t]),j=(0,n.useCallback)(e=>{if(Ls(e)){const s=Qs(e);if(!s)return;const n={profileQId:s.profileQId,profileOptionId:s.profileOptionId},i=p.current;if(i.some(e=>e.profileQId===n.profileQId&&e.profileOptionId===n.profileOptionId))return;const o=[...i,n];return p.current=o,h(o),void a(qt(t,o,m.current))}if(!_s(e))return;const s=Ms(e);if(!s)return;const n=m.current;if(n.includes(s))return;const i=[...n,s];m.current=i,d(i),a(qt(t,p.current,i))},[t]),S=(0,n.useCallback)(()=>{a(e=>[...e,{id:(0,Vt.A)(),intersectionCriteria:[],unionCriteria:[]}])},[]),C=(0,n.useCallback)(e=>{a(t=>t.filter((t,s)=>s!==e))},[]),k=(0,n.useCallback)((e,t)=>{a(s=>((e,t,s)=>e.map((e,n)=>n===t?{...e,segment:s}:e))(s,e,t))},[]),A=(0,n.useCallback)((e,t,s)=>{a(n=>e<0||e>=n.length?n:((e,t,s,n)=>e.map((e,i)=>{if(i!==t)return e;const o=ls(e,s.placement).flatMap((e,t)=>{if(t!==s.criterionIndex)return[e];if("criterion"===n.type)return[];const i=e.filterOptionSubset.filter(e=>!(e.profileQId===n.profileQId&&e.profileOptionId===n.profileOptionId));return 0===i.length?[]:[{...e,filterOptionSubset:i}]});return as(e,s.placement,o)}))(n,e,t,s))},[]),N=(0,n.useCallback)((e,t)=>{a(s=>e<0||e>=s.length?s:((e,t,s)=>e.map((e,n)=>{if(n!==t)return e;const i=ls(e,s.placement),o=i[s.criterionIndex];if(!o)return e;const r="union"===s.placement?"intersection":"union",l=i.filter((e,t)=>t!==s.criterionIndex),a=[...ls(e,r),o];let c=as(e,s.placement,l);return c=as(c,r,a),c}))(s,e,t))},[]),E=(0,n.useCallback)((e,t,s,n)=>{a(i=>{if(e<0||e>=i.length)return i;const o=i[e],r={profileQId:t,profileOptionId:s};return ds(o,p.current).some(e=>e.profileQId===t&&e.profileOptionId===s)?((e,t,s,n)=>e.map((e,i)=>{if(i!==t)return e;if(cs(e,s))return e;const o=ls(e,n),r=us(o,s);return as(e,n,r)}))(i,e,r,n):i})},[]),F=(0,n.useCallback)(()=>{f.current=[],v.current=[],g.current=[]},[]),O=(0,n.useCallback)(()=>{I()},[I]);return(0,n.useEffect)(()=>
1{if(s||!o||!r)return y.current=null,void I();y.current!==r.key&&(y.current=r.key,a(r.cohorts),p.current=r.selectedFilters,h(r.selectedFilters),m.current=r.selectedSegments,d(r.selectedSegments))},[r,s,I,o]),(0,n.useEffect)(()=>{p.current=u},[u]),(0,n.useEffect)(()=>{m.current=c},[c]),{cohorts:l,quickSuggestions:x,selectedFilters:u,onAddCohort:S,onRemoveCohort:C,onRemoveCriterionPill:A,onMoveCriterionPlacement:N,onRestoreFilter:E,onCohortSegmentChange:k,availableSegments:b,onActivePillIdsChange:w,onSuggestionSelected:j,onClearGroups:O,resetTrackedPillIds:F}},Gs=e=>{let{studyId:t,readOnly:s,chatSession:i,segmentsCount:a=0,sessionId:c,setShowInsights:d,setInsightsMessage:u,activeInsightsId:p,filters:f,sessionAdded:v,sessionUpdated:g,onCreatingSession:b,onQueryProcessing:w,dsFingerprint:j,isMobile:S=!1,onNewChat:k,onSaveInsight:A,onSessionMessagesChange:N,isSavedMode:E=!1,savedInsight:F=null,sessionIdOverride:O=null,renderSavedInsightComments:$,onDeleteInsight:D}=e;const[R,P]=(0,n.useState)([]),[z,L]=(0,n.useState)(!1),[_,M]=(0,n.useState)(null),[Q,U]=(0,n.useState)(!1),[G,V]=(0,n.useState)(!1),[W,q]=(0,n.use
1State)(!1),[K,J]=(0,n.useState)({x:0,y:0}),[Y,Z]=(0,n.useState)(null),[X,ee]=(0,n.useState)(!1),te=n.useRef(null),se=n.useRef(null),ne=n.useRef(null),ie=null!==O&&void 0!==O?O:c,oe=(new B.A).getCurrentUserId(),re=E?null===F||void 0===F?void 0:F.savedBy.uid:void 0,le=E&&"response"===(null===F||void 0===F?void 0:F.insightType)&&!!F.sourceInteractionId,ae=(0,n.useMemo)(()=>{var e;if(!R.length||E)return null;const t=[...R].sort((e,t)=>e.timestampIndex.toMillis()-t.timestampIndex.toMillis());return null!==(e=t[t.length-1])&&void 0!==e?e:null},[R,E]),ce=(0,n.useMemo)(()=>{const e=null===ae||void 0===ae?void 0:ae.cohorts;return null!==ae&&void 0!==ae&&ae.interactionId&&null!==e&&void 0!==e&&e.length?{key:ae.interactionId,cohorts:e,selectedFilters:hs(e),selectedSegments:ps(e)}:null},[ae]),{cohorts:de,quickSuggestions:ue,selectedFilters:he,onAddCohort:pe,onRemoveCohort:me,onRemoveCriterionPill:fe,onMoveCriterionPlacement:ve,onRestoreFilter:ge,onCohortSegmentChange:ye,availableSegments:xe,onActivePillIdsChange:be,onSuggestionSelected:Ie,onClearGroups:we,resetTrackedPillIds:je}=Bs({filters:f,isSavedMode:E,segmentsCount:a,sessionId:c,initialSelectionState:ce}),Se=E||(null===i||void 0===i?void 0:i.showRecommendations)&&!i.disableRecommendations||s;(0,n.useEffect)(()=>{U(!1)},[ie]);const Ce=n.useRef(null),[ke]=ys(),{clearancePx:Ae,clearanceRef:Ne}=((e,t)=>{const[s,i]=(0,n.useState)(0),o=(0,n.useRef)(0);return(0,n.useLayoutEffect)(()=>{if(!t)return o.current=0,void i(0);const s=e.current;if(!s)return;const n=()=>{const e=Math.ceil(s.getBoundingClientRect().height);o.current=e,i(e)};n();const r=new ResizeObserver(n);return r.observe(s),()=>r.disconnect()},[e,t]),{clearancePx:s,clearanceRef:o}})(Ce,!Se),Ee=(0,n.useCallback)(e=>{try{const t=new Date(Date.now()-3e5);return e.timestampIndex.toDate().getTime()>t.getTime()}catch{return!1}},[]),Fe=(0,n.useCallback)(e=>{const t=document.querySelectorAll(".vc-user-msg");if(t.length>0){const s=t[t.length-1].getBoundingClientRect(),n=Ne.current||86,i=window.scrollY+s.top-n;window.scrollTo({top:i,behavior:e||"smooth"})}else window.scrollTo({top:document.documentElement.scrollHeight,behavior:e||"smooth"})},[Ne]);(0,n.useEffect)(()=>{if(P([]),M(null),!ie)return;const e=new lt,t=new Rs,s=re?t.getInsightInteractionCollectionRef(ie,re):e.getInteractionCollectionRef(ie),n=(0,C.aQ)(s,e=>
1{e.docChanges().forEach(e=>{if("added"===e.type){const t=e.doc.data();P(e=>[...e,t]),M(null);const s=0===e.newIndex&&Ee(t)?"smooth":"instant";setTimeout(()=>{Fe(s)},10)}else if("removed"===e.type)P(t=>t.filter(t=>t.interactionId!==e.doc.id));else if("modified"===e.type){const t=e.doc.data();P(e=>{const s=e.find(e=>e.interactionId===t.interactionId);return t.thumbs===(null===s||void 0===s?void 0:s.thumbs)&&t.attribution===(null===s||void 0===s?void 0:s.attribution)&&setTimeout(()=>{Fe()},10),e.map(e=>e.interactionId===t.interactionId?t:e)})}})});return()=>{n()}},[ie,re,Ee,Fe]),(0,n.useEffect)(()=>{null===N||void 0===N||N(R)},[R,N]);const Oe=(0,n.useCallback)(function(){var e;let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"smooth";const s=ne.current||(null===(e=se.current)||void 0===e?void 0:e.querySelector(".vc-interaction-block--context-active"));return!!s&&(s.scrollIntoView({behavior:t,block:"start",inline:"nearest"}),!0)},[]),$e=(0,n.useCallback)(()=>{if(!le)return void ee(!1);const e=se.current,t=ne.current||(null===e||void 0===e?void 0:e.querySelector(".vc-interaction-block--context-active"));if(!e||!t)return void ee(!1);const s=t.getBoundingClientRect(),n=e.getBoundingClientRect(),i=Math.max(n.top+70,70),o=Math.min(n.bottom,window.innerHeight),r=s.bottom>i&&s.top<o;ee(!r)},[le]);(0,n.useEffect)(()=>{if(!le)return void ee(!1);const e=se.current;if(!e)return void ee(!1);const t=()=>$e();return t(),window.requestAnimationFrame(t),e.addEventListener("scroll",t,{passive:!0}),window.addEventListener("scroll",t,!0),window.addEventListener("resize",t),()=>{e.removeEventListener("scroll",t),window.removeEventListener("scroll",t,!0),window.removeEventListener("resize",t)}},[le,null===F||void 0===F?void 0:F.sourceInteractionId,R.length,$e]),(0,n.useEffect)(()=>{if(!le)return;let e=0;const t=()=>{const s=Oe("auto");$e(),e+=1,!s&&e<8&&window.setTimeout(t,120)};t()},[le,E,null===F||void 0===F?void 0:F.id,null===F||void 0===F?void 0:F.insightType,null===F||void 0===F?void 0:F.sourceInteractionId,R.length,Oe,$e]),(0,n.useEffect)(()=>{if(!W)return;const e=()=>{q(!1),Z(null)};return window.addEventListener("click",e),window.addEventListener("resize",e),window.addEventListener("scroll",e,!0),()=>{window.removeEventListener("click",e),window.removeEventListener("resize",e),window.removeEventListener("scroll",e,!0)}},[W]);const Te=async e=>{if(!s)try{const s=void 0!==e?e:"";if(z||""===s.trim())return;if(U(!1),L(!0),w(!0),setTimeout(()=>{Fe()}),ie)M(s),await y({userQuery:s,cohorts:de,sessionId:ie}),0===R.length?I({studyId:t,sessionId:ie}).then(e=>{e.title&&g(ie,e.title)}).catch(e=>{console.error("fs - sess-title-exp:",e)}):g(ie);else{b(!0),M(s);const e=(await x({studyId:t,editableFields:{disableRecommendations:!0,showRecommendations:!1}})).sessionId;try{await y({userQuery:s,cohorts:de,sessionId:e}),I({studyId:t,sessionId:e}).then(t=>{t.title&&g(e,t.title)}).catch(e=>{console.error("fs - sess-title-exp:",e)})}catch(n){throw n}finally{v(e)}}}catch(n){m.A.handle(n)}finally{L(!1),w(!1),M(null),b(!1),setTimeout(()=>{Fe()})}},De=(0,n.useCallback)(async e=>{try{if(E||null===i||void 0===i||!i.sessionId)return;await(new lt).deleteInteraction(i.sessionId,e),P(t=>t.filter(t=>t.interactionId!==e)),l.A.show({content:"Message removed",type:"success"})}catch(t){m.A.handle(t)}},[E,null===i||void 0===i?void 0:i.sessionId]),Re=Q,Pe=Q&&de.length>0?"send-query":void 0;return(0,h.jsxs)("div",{children:[(0,h.jsxs)("div",{children:[(0,h.jsx)("div",{ref:se,className:`vc-conversation ${E?"vc-conversation--saved-insight":""} ${E&&"chat"===(null===F||void 0===F?void 0:F.insightType)?"vc-conversation--saved-chat":""} ${Se?"":"vc-conversation--has-chatbox"}`,style:Se?void 0:{"--vc-chatbox-clearance":Ae?`${Ae}px`:void 0,"--vc-motion-duration":"180ms","--vc-motion-easing":gs},children:(()=>{const e=j?R.reduce((e,t,s)=>{var n;return(null===(n=t.usedSources[0])||void 0===n?void 0:n.datasetFingerprint)!==j?s:e},-1):-1;return(0,h.jsxs)(h.Fragment,{children:[ie&&R.sort((e,t)=>e.timestampIndex.toMillis()-t.timestampIndex.toMillis()).map((n,i)=>{const l=E&&"response"===(null===F||void 0===F?void 0:F.insightType)&&F.sourceInteractionId===n.interactionId,a=p===n.interactionId;return(0,h.jsxs)("div",{children:[(0,h.jsxs)("div",{ref:l?ne:null,onContextMenu:e=>{E||(e.preventDefault(),Z(n.interactionId),J({x:e.clientX,y:e.clientY}),q(!0))},"aria-selected":Y===n.interactionId,className:`vc-interaction-block ${Y===n.interactionId&&W||l?"vc-interaction-block--context-active":""} ${a?"vc-interaction-block--active-insights":""}`,children:[l?(0,h.jsxs)("span",{className:"vc-interaction-block__saved-tag",children:[F.savedBy.uid===oe?"You":F.savedBy.name," ","saved it as Insight on"," ",(0,T.dl)(F.savedAt),D&&F.savedBy.uid===oe?(0,h.jsxs)(h.Fragment,{children:[" ",(0,h.jsx)(o.A,{type:"link",size:"small",onClick:()=>D(F),children:(0,h.jsx)(r.A,{type:"solid",size:"10",icon:"fa-trash"})})]}):null]}):null,(0,h.jsx)(Ts,{message:n,disabled:E||s||z,onDelete:De,filters:f}),(0,h.jsx)(wt,{vcMessage:n,sessionId:ie,studyId:t,setShowInsights:d,setInsightsMessage:u,filters:f,onSaveInsight:A})]}),i===e&&(0,h.jsx)(Ds,{})]},n.interactionId)}),_&&(0,h.jsxs)("div",{className:"vc-interaction-block",children:[(0,h.jsx)(Ts,{message:{interactionId:"pending-query",userQuery:_,status:"pending",timestampIndex:C.Dc.now(),vcResponse:"",usedSources:[],sharedInsights:[]},disabled:!0,filters:f}
1),(0,h.jsx)(wt,{vcMessage:{interactionId:"pending-query",userQuery:_,status:"pending",timestampIndex:C.Dc.now(),vcResponse:"",usedSources:[],sharedInsights:[]},sessionId:"",studyId:t,setShowInsights:()=>{},setInsightsMessage:()=>{},filters:[]})]})]})})()}),Se?null:(0,h.jsx)("div",{ref:Ce,className:"vc-chatbox-container "+(z?"busy":""),children:(0,h.jsxs)("div",{ref:ke,className:"vc-chatbox-body",children:[Re&&de.length>0?(0,h.jsx)($s,{cohorts:de,filters:f,selectedFilters:he,showRespondentsSubsetAs:"SINGLE_PILL",onAddCohort:pe,onRemoveCohort:me,onRemoveCriterionPill:fe,onMoveCriterionPlacement:ve,onRestoreFilter:ge,availableSegments:xe,onCohortSegmentChange:ye}):null,(0,h.jsx)(Ht,{ref:te,disabled:z||s,enterHint:Pe,groupsAvailable:de.length>0,groupsVisible:Re,onToggleGroups:()=>{U(!Re)},onClearGroups:()=>{we(),U(!1)},onSend:e=>0===de.length?(je(),Te(e),!0):Q?(je(),Te(e),U(!1),!0):(U(!0),!1),suggestions:ue,onActivePillIdsChange:be,onSuggestionSelected:Ie,onInputChange:()=>{Q&&U(!1)}}),(0,h.jsx)("div",{className:"vc-chatbox-actions",children:(0,h.jsx)(o.A,{type:"primary",className:"vc-chatbox-send-btn",disabled:z,onClick:()=>{var e;null===(e=te.current)||void 0===e||e.send()},children:(0,h.jsx)(r.A,{type:"solid",size:"14",icon:"fa-arrow-up"})})})]})})]}),!E&&W?(0,h.jsx)("div",{className:"vc-markdown-context-menu",role:"menu",style:{left:K.x,top:K.y},onClick:e=>e.stopPropagation(),children:(0,h.jsxs)(o.A,{type:"link",size:"small",className:"vc-markdown-context-menu__item",role:"menuitem",onClick:()=>{q(!1),V(!0)},children:[(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-floppy-disk"}),"Save as Insight"]})}):null,c&&(0,h.jsx)(H,{studyId:t,sessionId:c,interactionId:Y,open:G,onClose:()=>{V(!1),Z(null)},insightType:"response",onSave:A}),E&&F&&$?$({showScrollToInsightButton:"response"===F.insightType&&X,onScrollToInsight:()=>{Oe("smooth")}}):null]},c||"new-chat-session")},Vs=e=>{let{insightId:t,author:s,comments:i,votes:l,onVote:a,onCommentsChange:c,showScrollToInsightButton:d=!1,onScrollToInsight:u}=e;const[p,f]=(0,n.useState)(""),[v,g]=(0,n.useState)(!1),y=(0,n.useRef)(!1),[x,b]=(0,n.useState)(new Set),I=(0,n.useRef)(new Set),[w,j]=(0,n.useState)(i),S=(0,n.useRef)(i);(0,n.useEffect)(()=>{S.current=i,j(i)},[i]);const k=async()=>{try{var e,n;if(y.current)return;const i=p.trim();if(!i)return;y.current=!0,g(!0);const o={author:{id:s.id,email:s.email,firstName:null!==(e=s.firstName)&&void 0!==e?e:"",lastName:null!==(n=s.lastName)&&void 0!==n?n:""},text:i,timestamp:C.Dc.now()},r=await(new mt).addComment(t,o),l=[...S.current,r];S.current=l,j(l),null===c||void 0===c||c(l),f("")}catch(i){m.A.handle(i)}finally{y.current=!1,g(!1)}};return(0,h.jsxs)("div",{className:"vc-saved-insight-comments",children:[(0,h.jsx)(L,{author:s,votes:l,onVote:a}),d?(0,h.jsxs)(o.A,{type:"link",size:"small",className:"vc-saved-insight-comments__scroll-btn",onClick:u,children:[(0,h.jsx)(r.A,{type:"solid",size:"10",icon:"fa-angles-up"}),"SCROLL TO INSIGHT"]}):null,(0,h.jsx)("div",{className:"vc-saved-insight-modal__comments",children:w.length>0?w.map((e,n)=>(0,h.jsxs)("div",{className:"vc-saved-insight-modal__comment",children:[(0,h.jsx)(Bt.A,{size:18,style:{backgroundColor:"#2D2D8E",fontSize:"10px"},children:(0,T.Vd)(e.author)}),(0,h.jsxs)("div",{className:"vc-saved-insight-modal__comment-body",children:[(0,h.jsxs)("div",{className:"vc-saved-insight-modal__comment-author-row",children:[(0,h.jsx)("span",{className:"vc-saved-insight-modal__comment-author",children:(0,T.Ii)(e.author)}),(0,h.jsx)("span",{className:"vc-msg-header-time",children:(0,T.dl)(e.timestamp,!0)}),s.id===e.author.id&&(0,h.jsx)(o.A,{type:"link",icononly:!0,size:"xsmall",className:"vc-saved-insight-modal__comment-delete",title:"Delete comment",onClick:()=>(async e=>{try{if(I.current.has(e.id))return;I.current=new Set(I.current),I.current.add(e.id),b(I.current),await(new mt).removeComment(t,e);const s=S.current.filter(t=>t.id!==e.id);S.current=s,j(s),null===c||void 0===c||c(s)}catch(s){m.A.handle(s)}finally{I.current=new Set(I.current),I.current.delete(e.id),b(I.current)}})(e),disabled:x.has(e.id),children:(0,h.jsx)(r.A,{type:"solid",size:"10",icon:"fa-trash"})})]}),(0,h.jsx)("span",{className:"vc-saved-insight-modal__comment-text",children:e.text})]})]},`${t}-${e.author}-${e.text}-${n}`)):(0,h.jsx)("div",{className:"vc-saved-insight-modal__empty-comments",children:"No comments yet."})}),(0,h.jsxs)("div",{className:"vc-saved-insight-modal__input-row",children:[(0,h.jsx)(Bt.A,{size:32,style:{backgroundColor:"#2D2D8E",fontSize:"16px"},children:(0,T.Vd)(s)}),(0,h.jsx)(U.A,{className:"vc-saved-insight-modal__input",placeholder:"Comment on this insight",style:{borderRadius:20,height:34,fontSize:13},value:p,disabled:v,onChange:e=>f(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),k())}}),(0,h.jsx)(o.A,{icononly:!0,className:"vc-saved-insight-modal__send",title:"Send comment",onClick:k,disabled:!p.trim()||v,children:(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-paper-plane"})})]})]})},Ws=e=>{var t;let{studyId:s,readOnly:n,chatSession:i,filters:o,sessionId:r,setShowInsights:l,setInsightsMessage:a,activeInsightsId:c,onCreatingSession:d,onQueryProcessing:u,dsFingerprint:p,isMobile:m,onNewChat:f,onSaveInsight:v,disableCTAs:g,recommendations:y,updateThreadSett
1ings:x,jobStepsCount:b,needsCount:I,segmentsCount:w,respondentsCount:j,onSessionTitleGenerated:S,onSessionAdded:C,onSessionUpdated:k,siaIntro:A}=e;return(0,h.jsxs)(h.Fragment,{children:[(null===(t=null===i||void 0===i?void 0:i.showInsightsSummary)||void 0===t||t)&&(0,h.jsx)(It,{siaIntro:A,disableCTAs:g,showRecommendationList:null!==i&&(y.length>0&&i.showRecommendations),disableRecommendationList:null!==i&&i.disableRecommendations,recommendations:y,selectedRecommendations:(null===i||void 0===i?void 0:i.selectedRecommendations)||[],updateThreadSettings:x,jobStepsCount:b,needsCount:I,segmentsCount:w,respondentsCount:j,studyId:s,onSessionTitleGenerated:S}),(0,h.jsx)(Gs,{studyId:s,segmentsCount:w,readOnly:n,chatSession:i,filters:o,sessionId:r,setShowInsights:l,setInsightsMessage:a,activeInsightsId:c,sessionAdded:C,sessionUpdated:k,onCreatingSession:d,onQueryProcessing:u,dsFingerprint:p,isMobile:m,onNewChat:f,onSaveInsight:v},r)]})},qs=e=>{let{studyId:t,readOnly:s,chatSession:n,filters:i,setShowInsights:o,setInsightsMessage:r,activeInsightsId:l,onCreatingSession:a,onQueryProcessing:c,dsFingerprint:d,isMobile:u,onNewChat:p,onSaveInsight:m,onDeleteInsight:f,insightAuthor:v,savedInsight:g,savedInsightComments:y,savedInsightVotes:x,onSavedInsightVote:b,onSavedInsightCommentsChange:I}=e;return(0,h.jsx)(Gs,{studyId:t,readOnly:s,chatSession:n,filters:i,sessionId:g.sourceSessionId,sessionIdOverride:g.sourceSessionId,setShowInsights:o,setInsightsMessage:r,activeInsightsId:l,sessionAdded:()=>{},sessionUpdated:()=>{},onCreatingSession:a,onQueryProcessing:c,dsFingerprint:d,isMobile:u,onNewChat:p,onSaveInsight:m,isSavedMode:!0,savedInsight:g,renderSavedInsightComments:e=>{let{showScrollToInsightButton:t,onScrollToInsight:s}=e;return(0,h.jsx)(Vs,{insightId:g.id,author:v,comments:y,votes:x,onVote:b,onCommentsChange:I,showScrollToInsightButton:t,onScrollToInsight:s})},onDeleteInsight:f},`saved-${g.id}`)},Ks=e=>{var t,s,a,c,d,u,p,f,v,g,y,b,I,j;let{currentUser:S}=e;const k=(0,i.Zp)(),{studyId:A,sessionId:E,insightId:O}=(0,i.g)(),[$,T]=(0,n.useState)([]),[D,R]=(0,n.useState)(!1),[P,z]=(0,n.useState)(null),[L,M]=(0,n.useState)(null),[Q,U]=(0,n.useState)(!0),[H,B]=(0,n.useState)(!1),[V,W]=(0,n.useState)(!1),[q,K]=(0,n.useState)(!1),[J,Y]=(0,n.use
1State)([]),[Z,X]=(0,n.useState)(null),[ee,te]=(0,n.useState)(null),[se,ne]=(0,n.useState)(new Map),ie=(0,n.useRef)(se),[oe,re]=(0,n.useState)(!1),[le,ae]=(0,n.useState)(!1),[ce,de]=(0,n.useState)(null),[ue,he]=(0,n.useState)(!1),[pe,me]=(0,n.useState)(!1),[fe,ve]=(0,n.useState)(!0),[ge,ye]=(0,n.useState)(["recent","savedInsights"]),xe=null===Z||void 0===Z?void 0:Z.id,be=null===Z||void 0===Z||null===(t=Z.datasets[0])||void 0===t?void 0:t.fingerprint,Ie=!!O,we=(0,n.useCallback)(e=>{A&&k(`${F.du.VC}/${A}/insights/${e.id}`)},[k,A]),{savedInsights:je,savedInsightComments:Se,savedInsightVotes:Ce,loadingSavedInsights:ke,loadedSavedInsightsStudyId:Ae,handleSaveInsight:Ne,handleDeleteInsight:Ee,handleSavedInsightVote:Fe,handleSavedInsightCommentsChange:Oe,refetchSavedInsights:$e}=function(e){let{studyId:t,onInsightCreated:s}=e;const[i,o]=(0,n.useState)([]),[r,l]=(0,n.useState)({}),[a,c]=(0,n.useState)({}),[d,u]=(0,n.useState)(!1),[h,p]=(0,n.useState)(null),f=(0,n.useCallback)(async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:()=>!0;if(e)try{u(!0),p(null);const s=await(new mt).fetchInsightsList(e),n=await Promise.all(s.map(async e=>[e.id,await(new mt).fetchCommentsList(e.id)])),i=await Promise.all(s.map(async e=>[e.id,await(new mt).fetchVotesList(e.id)]));t()&&(o(s),l(Object.fromEntries(n)),c(Object.fromEntries(i)),p(e))}catch(s){m.A.handle(s)}finally{t()&&u(!1)}else t()&&(o([]),l({}),c({}),u(!1),p(null))},[]);(0,n.useEffect)(()=>{let e=!1;return f(t,()=>!e),()=>{e=!0}},[f,t]);const v=(0,n.useCallback)(async()=>{await f(t)},[f,t]),g=(0,n.useCallback)(async e=>{if(e.sourceStudyId!==t)return;const[n]=await(new mt).createInsightsDoc(e);o(e=>[n,...e]),l(e=>({...e,[n.id]:[]})),c(e=>({...e,[n.id]:[]})),null===s||void 0===s||s(n)},[s,t]),y=(0,n.useCallback)(async e=>{try{return await(new mt).deleteInsightsDoc(e),o(t=>t.filter(t=>t.id!==e.id)),l(t=>{const{[e.id]:s,...n}=t;return n}),c(t=>{const{[e.id]:s,...n}=t;return n}),!0}catch(t){return m.A.handle(t),!1}},[]),x=(0,n.useCallback)(async(e,t,s)=>{var n;if(!i.find(t=>t.id===e))throw new m.Q("cen/doc-not-found");const o=null!==(n=a[e])&&void 0!==n?n:[],r=o.find(e=>e.author.id===t.id),l=new mt,d=o.filter(e=>e.author.id!==t.id);if(null===s)r&&await l.removeVote(e,r);else{const n={author:t,thumb:s};d.push(n),r?await l.updateVote(e,r,n):await l.addVote(e,n)}c(t=>({...t,[e]:d}))},[i,a]),b=(0,n.useCallback)((e,t)=>{l(s=>({...s,[e]:t}))},[]);return{savedInsights:i,savedInsightComments:r,savedInsightVotes:a,loadingSavedInsights:d,loadedSavedInsightsStudyId:h,handleSaveInsight:g,handleDeleteInsight:y,handleSavedInsightVote:x,handleSavedInsightCommentsChange:b,refetchSavedInsights:v}}({studyId:xe,onInsightCreated:we}),Te=(0,n.useMemo)(()=>O&&je.find(e=>e.id===O)||null,[O,je]),De=Ae===xe,Re=(null===Te||void 0===Te?void 0:Te.sourceSessionId)||E,Pe=Te?Te.savedBy.uid:void 0;(0,n.useEffect)(()=>{!function(){const e=navigator.userAgent||navigator.vendor;/android/i.test(e)||/iPad|iPhone|iPod/.test(e)&&!window.MSStream?me(!0):me(!1)}()},[]),(0,n.useEffect)(()=>{if("undefined"!==typeof window)return window.dispatchEvent(new CustomEvent("sia-mobile-header-visibility",{detail:{hidden:fe}})),()=>{window.dispatchEvent(new CustomEvent("sia-mobile-header-visibility",{detail:{hidden:!1}}))}},[fe]),(0,n.useEffect)(()=>{ye(["recent","savedInsights"])},[A]),(0,n.useEffect)(()=>{const e=async()=>{try{if(!A)return;T([]),te(null),Y([]),X(null),R(!1),z(null);const[e,t]=await Promise.all([(new N).fetchStudyHeader(A),(new at).fetchStudy(A)]),s=(null===e||void 0===e?void 0:e.sessionList)||[];if(T(s),te(e),Y((null===t||void 0===t?void 0:t.recommendations)||[]),X(t),t)re(!1),e&&(async(e,t)=>{try{t&&null!==e&&void 0!==e&&e.name&&(t.studyName!==e.name||t.studyDescription!==(e.description||""))&&(console.log("fs: vc-auto-upd:",e.id),ae(!0))}catch(s){console.log("fs: vc-auto-upd-cnd-err:",s)}})(t,e);else{if(0===s.length)return l.A.show({content:"Workspace not found",type:"error"}),void k(`${F.du.HOME}`,{replace:!0});re(!0)}}catch(e){m.A.handle(e)}};A?(null===Z||void 0===Z?void 0:Z.id)!==A&&e():(async()=>{try{if(A)return;const e=await(new N).fetchDefaultStudyHeader();e?k(`${F.du.VC}/${e.studyId}`):(l.A.show({content:"You don't have access to Sia Workspace.",type:"info"}),k(`${F.du.HOME}`,{replace:!0}))}catch(e){m.A.handle(e)}})()},[A,k,null===Z||void 0===Z?void 0:Z.id]),(0,n.useEffect)(()=>{ie.current=se},[se]),(0,n.useEffect)(()=>{xe&&(async e=>{try{const t=ie.current.get(e);if(t&&t.fingerprint===be)return;const s=await async function(e){return(await w("getVCDatasetSummary")(e)).data}({studyId:e});ne(e=>{const t=new Map(e);return t.set(s.studyId,{studyId:s.studyId,fingerprint:s.fingerprint,outcomes:s.outcomes,respondentsCount:s.respondentsCount,filters:s.filters}),t})}catch(t){m.A.handle(t)}})(xe)},[xe,be]),(0,n.useEffect)(()=>
1{if(M(null),A&&Re){U(!0);const e=Pe?(async(e,t)=>{try{const s=new Rs;return await s.loadInsightChatSession(e,t)}catch(s){return null}})(Re,Pe):(async e=>{try{const t=new lt,s=await t.loadChatSession(e);return M(s),s}catch(t){return m.A.handle(t),null}})(Re);e.then(e=>{M(e),e||($e(),k(`${F.du.VC}/${A}`,{replace:!0}))}).finally(()=>{U(!1)})}else U(!1)},[Re,k,Pe,A,$e]),(0,n.useEffect)(()=>{A&&Ie&&!ke&&De&&!Te&&(l.A.show({content:"Insight not found",type:"error"}),k(`${F.du.VC}/${A}`,{replace:!0}))},[Ie,ke,k,De,Te,A]);const ze=(0,n.useCallback)(e=>{A?(z(null),R(!1),k(e?`${F.du.VC}/${A}/${e}`:`${F.du.VC}/${A}`)):m.A.handle(new m.Q("cen/internal-error",`fs: change thread id - invalid study id: ${A}`))},[A,k]),Le=(0,n.useCallback)(async e=>{try{if(!Z)return;const t=async()=>(W(!0),(await x({studyId:Z.id})).sessionId),s=E||await t(),n=await(new lt).updateDocFields(s,e);return M(n),E||(ze(s),$.some(e=>e.docRef.id===s)||T([(new lt).getNewChatSessionHeader(s),...$])),s}catch(t){m.A.handle(t)}finally{W(!1)}},[E,Z,ze,$]),_e=(0,n.useCallback)(async e=>{var t;if(!await Ee(e))return!1;const s=je.findIndex(t=>t.id===e.id),n=s>0?je[s-1]:null!==(t=je[s+1])&&void 0!==t?t:null;return k(n?`${F.du.VC}/${A}/insights/${n.id}`:`${F.du.VC}/${A}`),!0},[k,A,je,Ee]);return A&&se.has(A)&&(!Ie||!ke&&De&&Te)?(0,h.jsx)(h.Fragment,{children:(0,h.jsxs)("div",{style:{display:"flex",width:"100%",paddingLeft:pe?"0":"10px"},children:[(0,h.jsx)(_,{disableCTAs:V,sessionList:$,interviewId:E||"",setInterviewId:e=>{e&&e!==E&&(U(!0),B(!0),setTimeout(()=>{B(!1)},200)),ze(e)},workspaceTitle:(null===ee||void 0===ee?void 0:ee.studyName)||"",readOnly:oe,initialCollapsed:pe,mobileHeaderHidden:pe&&fe,savedInsights:je,savedInsightVotes:Ce,selectedSavedInsightId:null===Te||void 0===Te?void 0:Te.id,onSelectSavedInsight:e=>{R(!1),z(null),k(`${F.du.VC}/${A}/insights/${e.id}`)},openGroups:ge,setOpenGroups:ye}),Q||!ee?(0,h.jsx)(We,{}):(0,h.jsxs)("div",{className:"vc-chat-container "+(pe&&fe?"mobile-header-hidden":""),children:[pe&&(0,h.jsxs)(h.Fragment,{children:[(0,h.jsxs)("div",{className:"sia-mobile-header "+(fe?"is-hidden":""),children:[(0,h.jsx)("h3",{children:"Sia"}),(0,h.jsxs)(o.A,{color:"neutral",type:"link",size:"small",className:"sia-mobile-header__toggle",onClick:()=>ve(!0),children:[(0,h.jsx)(r.A,{type:"solid",size:"10",icon:"fa-chevron-up"}),(0,h.jsx)("span",{children:"Hide"})]}),(0,h.jsxs)("span",{className:"workspace-title",children:[(0,h.jsx)(r.A,{type:"solid",size:"12",icon:"fa-grid-2"}),(null===ee||void 0===ee?void 0:ee.studyName)&&`${ee.studyName}`]})]}),fe&&(0,h.jsxs)(o.A,{type:"default",size:"small",className:"sia-mobile-header__show",onClick:()=>ve(!1),children:[(0,h.jsx)(r.A,{type:"solid",size:"10",icon:"fa-chevron-down"}),"Show"]})]}),(0,h.jsx)(G,{studyId:A,disableCTAs:V,disableDelete:q||!!Te,readOnly:oe,workspaceTitle:ee.studyName,sessionHeader:$.find(e=>e.docRef.id===((null===Te||void 0===Te?void 0:Te.sourceSessionId)||E))||null,showSummary:null===(s=null===L||void 0===L?void 0:L.showInsightsSummary)||void 0===s||s,updateThreadSettings:Le,isMobile:pe,onNewChat:()=>ze(""),onDeleteChat:async()=>{try{if(!E||V||q)return;await(new lt).deleteChatSession(E);const e=$.filter(e=>e.docRef.id!==E);if(T(e),e.length>0){const t=$.findIndex(e=>e.docRef.id===E),s=e[t>0?t-1:e.length-1].docRef.id;ze(s)}else ze("")}catch(e){m.A.handle(e)}},onSaveInsight:Ne,onDeleteInsight:de,selectedSavedInsight:Te,chatHasSharedInsights:(null!==(a=null===L||void 0===L||null===(c=L.sharedInsights)||void 0===c?void 0:c.length)&&void 0!==a?a:0)>0}),(0,h.jsx)("div",{style:{opacity:H?0:1},children:Te?(0,h.jsx)(qs,{studyId:A,readOnly:oe,chatSession:L,filters:(null===(d=se.get((null===Z||void 0===Z?void 0:Z.id)||""))||void 0===d?void 0:d.filters)||[],setShowInsights:R,setInsightsMessage:z,activeInsightsId:(null===P||void 0===P?void 0:P.interactionId)||null,onCreatingSession:W,onQueryProcessing:K,dsFingerprint:(null===Z||void 0===Z||null===(u=Z.datasets[0])||void 0===u?void 0:u.fingerprint)||"",isMobile:pe,onNewChat:()=>ze(""),onSaveInsight:Ne,savedInsight:Te,savedInsightComments:null!==(p=Se[Te.id])&&void 0!==p?p:[],savedInsightVotes:null!==(f=Ce[Te.id])&&void 0!==f?f:[],onSavedInsightVote:e=>{var t,s;return Fe(Te.id,{id:S.id,email:S.email,firstName:null!==(t=S.firstName)&&void 0!==t?t:"",lastName:null!==(s=S.lastName)&&void 0!==s?s:""},e)},onSavedInsightCommentsChange:e=>Oe(Te.id,e),onDeleteInsight:de,insightAuthor:S}):(0,h.jsx)(Ws,{studyId:A,readOnly:oe,chatSession:L,filters:(null===(v=se.get((null===Z||void 0===Z?void 0:Z.id)||""))||void 0===v?void 0:v.filters)||[],sessionId:E||"",setShowInsights:R,setInsightsMessage:z,activeInsightsId:(null===P||void 0===P?void 0:P.interactionId)||null,onCreatingSession:W,onQueryProcessing:K,dsFingerprint:(null===Z||void 0===Z||null===(g=Z.datasets[0])||void 0===g?void 0:g.fingerprint)||"",isMobile:pe,onNewChat:()=>ze(""),onSaveInsight:Ne,disableCTAs:V,recommendations:J,updateThreadSett
1ings:Le,jobStepsCount:(()=>{var e;const t=(null===(e=se.get((null===Z||void 0===Z?void 0:Z.id)||""))||void 0===e?void 0:e.outcomes.map(e=>e.step))||[];return new Set(t).size})(),needsCount:(null===(y=se.get((null===Z||void 0===Z?void 0:Z.id)||""))||void 0===y?void 0:y.outcomes.length)||0,segmentsCount:(null===Z||void 0===Z?void 0:Z.segmentSolution)||0,respondentsCount:(null===(b=se.get((null===Z||void 0===Z?void 0:Z.id)||""))||void 0===b?void 0:b.respondentsCount)||0,siaIntro:null===Z||void 0===Z?void 0:Z.siaIntro,onSessionTitleGenerated:(e,t)=>{T(s=>s.map(s=>s.docRef.id===e?{...s,customTitle:t}:s))},onSessionAdded:e=>{T(t=>t.some(t=>t.docRef.id===e)?t:[(new lt).getNewChatSessionHeader(e),...t]),E||ze(e)},onSessionUpdated:(e,t)=>{T(s=>s.map(s=>s.docRef.id===e?{...s,updatedAt:C.Dc.now(),customTitle:t||s.customTitle}:s))}})})]}),D&&P&&(0,h.jsx)(it,{elemKey:`${A}-${E||Math.random()}`,onClose:()=>{R(!1),z(null)},message:P,sessionId:Re||"",outcomesList:(null===(I=se.get((null===Z||void 0===Z?void 0:Z.id)||""))||void 0===I?void 0:I.outcomes)||[],filters:(null===(j=se.get((null===Z||void 0===Z?void 0:Z.id)||""))||void 0===j?void 0:j.filters)||[]}),(0,h.jsx)(dt,{heading:"Delete Insight?",messageText:"Are you sure you want to delete this Insight? This action cannot be undone.",open:!!ce,busy:ue,confirmButtonText:"Delete",declineButtonText:"Cancel",onConfirm:async()=>{if(ce&&!ue)try{he(!0);await _e(ce)&&de(null)}finally{he(!1)}},onDecline:()=>{ue||de(null)}}),(0,h.jsx)(dt,{heading:"Update Study Info?",messageText:"An admin updated the study name/description. Do you want to sync the changes?",open:le,confirmButtonText:(0,h.jsxs)(h.Fragment,{children:["Yes"," ",(0,h.jsx)("span",{style:{fontSize:12,opacity:.7,paddingLeft:4},children:"(Recommended)"})]}),declineButtonText:"Later",onConfirm:async()=>{try{if(!Z||!ee)return;await(new N).updateStudyMetadata(Z.id,Z.name,Z.description||""),te({...ee,studyName:Z.name,studyDescription:Z.description||""})}catch(e){console.log("fs: vc-auto-upd-err:",e),m.A.handle(e)}finally{ae(!1)}},onDecline:()=>ae(!1)})]},`vc-container-${A}-${O||E||"new-session"}`)}):(0,h.jsx)(We,{})}},9912(){},908(){}}]);
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.